hexsha
stringlengths 40
40
| size
int64 5
1.05M
| ext
stringclasses 98
values | lang
stringclasses 21
values | max_stars_repo_path
stringlengths 3
945
| max_stars_repo_name
stringlengths 4
118
| max_stars_repo_head_hexsha
stringlengths 40
78
| max_stars_repo_licenses
listlengths 1
10
| max_stars_count
int64 1
368k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 3
945
| max_issues_repo_name
stringlengths 4
118
| max_issues_repo_head_hexsha
stringlengths 40
78
| max_issues_repo_licenses
listlengths 1
10
| max_issues_count
int64 1
134k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 3
945
| max_forks_repo_name
stringlengths 4
135
| max_forks_repo_head_hexsha
stringlengths 40
78
| max_forks_repo_licenses
listlengths 1
10
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 5
1.05M
| avg_line_length
float64 1
1.03M
| max_line_length
int64 2
1.03M
| alphanum_fraction
float64 0
1
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
63ae6c14874c7602653fc59719423b7eb216be6c
| 6,497
|
lua
|
Lua
|
CartTrainer.lua
|
lukeha/torch-decisiontree
|
d73f150487745cc7eefe161eaebae233d236d526
|
[
"Apache-2.0"
] | null | null | null |
CartTrainer.lua
|
lukeha/torch-decisiontree
|
d73f150487745cc7eefe161eaebae233d236d526
|
[
"Apache-2.0"
] | null | null | null |
CartTrainer.lua
|
lukeha/torch-decisiontree
|
d73f150487745cc7eefe161eaebae233d236d526
|
[
"Apache-2.0"
] | null | null | null |
local dt = require "decisiontree._env"
local _ = require "moses"
local CartTrainer = torch.class("dt.CartTrainer", dt)
-- Generic CART trainer
function CartTrainer:__init(dataset, minLeafSize, maxLeafNodes)
assert(torch.isTypeOf(dataset, 'dt.DataSet'))
self.dataset = dataset
self.minLeafSize = assert(minLeafSize) -- min examples per leaf
self.maxLeafNodes = assert(maxLeafNodes) -- max leaf nodes in tree
-- by default, single thread
self.parallelMode = 'singlethread'
end
function CartTrainer:train(rootTreeState, activeFeatures)
assert(torch.isTypeOf(rootTreeState, 'dt.TreeState'))
assert(torch.isTensor(activeFeatures))
local root = dt.CartNode()
root.id = 0
root.score = rootTreeState:score(self.dataset)
local nleaf = 1
-- TODO : nodeparallel: parallelize here. The queue is a workqueue.
local queue = {}
table.insert(queue, 1, {cartNode=root, treeState=rootTreeState})
while #queue > 0 and nleaf < self.maxLeafNodes do
local treeGrowerArgs = table.remove(queue, #queue)
local currentTreeState = treeGrowerArgs.treeState
-- Note: if minLeafSize = 1 and maxLeafNode = inf, then each example will be its own leaf...
if self:hasEnoughTrainingExamplesToSplit(currentTreeState.exampleIds:size(1)) then
nleaf = self:processNode(nleaf, queue, treeGrowerArgs.cartNode, currentTreeState, activeFeatures)
end
end
-- CartTree with random branching (when feature is missing)
local branchleft = function() return math.random() < 0.5 end
return dt.CartTree(root, branchleft), nleaf
end
function CartTrainer:processNode(nleaf, queue, node, treeState, activeFeatures)
local bestSplit
if self.parallelMode == 'singlethread' then
bestSplit = self:findBestSplitForAllFeatures(treeState, activeFeatures)
elseif self.parallelMode == 'featureparallel' then
bestSplit = self:findBestSplitForAllFeaturesFP(treeState, activeFeatures)
else
error("Unrecognized parallel mode: " .. self.parallelMode)
end
if bestSplit then
local leftTreeState, rightTreeState = treeState:branch(bestSplit, self.dataset)
assert(bestSplit.leftChildSize + bestSplit.rightChildSize == leftTreeState.exampleIds:size(1) + rightTreeState.exampleIds:size(1), "The left and right subtrees don't match the split found!")
self:setValuesAndCreateChildrenForNode(node, bestSplit, leftTreeState, rightTreeState, nleaf)
table.insert(queue, 1, {cartNode=node.leftChild, treeState=leftTreeState})
table.insert(queue, 1, {cartNode=node.rightChild, treeState=rightTreeState})
return nleaf + 1
end
return nleaf
end
function CartTrainer:findBestSplitForAllFeatures(treeState, activeFeatures)
local timer = torch.Timer()
local bestSplit = treeState:findBestSplit(self.dataset, activeFeatures, self.minLeafSize, -1, -1)
if bestSplit then
assert(torch.type(bestSplit) == 'table')
end
if dt.PROFILE then
print("findBestSplitForAllFeatures time="..timer:time().real)
end
return bestSplit
end
-- Updates the parentNode with the bestSplit information by creates left/right child Nodes.
function CartTrainer:setValuesAndCreateChildrenForNode(parentNode, bestSplit, leftState, rightState, nleaf)
assert(torch.isTypeOf(parentNode, 'dt.CartNode'))
assert(torch.type(bestSplit) == 'table')
assert(torch.isTypeOf(leftState, 'dt.TreeState'))
assert(torch.isTypeOf(rightState, 'dt.TreeState'))
assert(torch.type(nleaf) == 'number')
local leftChild = dt.CartNode()
leftChild.score = leftState:score(self.dataset)
leftChild.nodeId = 2 * nleaf - 1
local rightChild = dt.CartNode()
rightChild.score = rightState:score(self.dataset)
rightChild.nodeId = 2 * nleaf
parentNode.splitFeatureId = bestSplit.splitId
parentNode.splitFeatureValue = bestSplit.splitValue
parentNode.leftChild = leftChild
parentNode.rightChild = rightChild
parentNode.splitGain = bestSplit.splitGain
end
-- We minimally need 2 * N examples in the parent to satisfy >= N examples per child
function CartTrainer:hasEnoughTrainingExamplesToSplit(count)
return count >= 2 * self.minLeafSize
end
-- call before training to enable feature-parallelization
function CartTrainer:featureParallel(workPool)
assert(self.parallelMode == 'singlethread', self.parallelMode)
self.parallelMode = 'featureparallel'
self.workPool = torch.type(workPool) == 'number' and dt.WorkPool(workPool) or workPool
assert(torch.isTypeOf(self.workPool, 'dt.WorkPool'))
-- this deletes all SparseTensor hash maps so that they aren't serialized
self.dataset:deleteIndex()
-- require the dt package
self.workPool:update('require', {libname='decisiontree',varname='dt'})
-- setup worker store (each worker will have its own copy)
local store = {
dataset=self.dataset,
minLeafSize=self.minLeafSize
}
self.workPool:update('storeKeysValues', store)
end
-- feature parallel
function CartTrainer:findBestSplitForAllFeaturesFP(treeState, activeFeatures)
local timer = torch.Timer()
local bestSplit
if treeState.findBestSplitFP then
bestSplit = treeState:findBestSplitFP(self.dataset, activeFeatures, self.minLeafSize, self.workPool.nThread)
end
if not bestSplit then
for i=1,self.workPool.nThread do
-- upvalues
local treeState = treeState
local shardId = i
local nShard = self.workPool.nThread
local featureIds = activeFeatures
-- closure
local task = function(store)
assert(store.dataset)
assert(store.minLeafSize)
if treeState.threadInitialize then
treeState:threadInitialize()
end
local bestSplit = treeState:findBestSplit(store.dataset, featureIds, store.minLeafSize, shardId, nShard)
return bestSplit
end
self.workPool:writeup('execute', task)
end
for i=1,self.workPool.nThread do
local taskname, candidateSplit = self.workPool:read()
assert(taskname == 'execute')
if candidateSplit then
if ((not bestSplit) or candidateSplit.splitGain < bestSplit.splitGain) then
bestSplit = candidateSplit
end
end
end
end
if bestSplit then
assert(torch.type(bestSplit) == 'table')
end
if dt.PROFILE then
print("findBestSplitForAllFeaturesFP time="..timer:time().real)
end
return bestSplit
end
| 35.895028
| 196
| 0.720179
|
45a27a3546768593bd1d753cdff48074da35f8c3
| 1,047
|
py
|
Python
|
aiida/cmdline/tests/common.py
|
astamminger/aiida_core
|
b01ad8236f21804f273c9d2a0365ecee62255cbb
|
[
"BSD-2-Clause"
] | null | null | null |
aiida/cmdline/tests/common.py
|
astamminger/aiida_core
|
b01ad8236f21804f273c9d2a0365ecee62255cbb
|
[
"BSD-2-Clause"
] | null | null | null |
aiida/cmdline/tests/common.py
|
astamminger/aiida_core
|
b01ad8236f21804f273c9d2a0365ecee62255cbb
|
[
"BSD-2-Clause"
] | null | null | null |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida_core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
"""Common code to be used in cli testing"""
import sys
from contextlib import contextmanager
from StringIO import StringIO
@contextmanager
def captured_output():
new_out, new_err = StringIO(), StringIO()
old_out, old_err = sys.stdout, sys.stderr
try:
sys.stdout, sys.stderr = new_out, new_err
yield sys.stdout, sys.stderr
finally:
sys.stdout, sys.stderr = old_out, old_err
| 41.88
| 75
| 0.501433
|
8ea5ea8626304308244b01535fe4c93d7e66a847
| 1,024
|
rb
|
Ruby
|
metadata.rb
|
devops-consultants/cookbooks-base-server
|
61dbea0882da55e17c027af497a1357d81cc5c9a
|
[
"Apache-2.0"
] | null | null | null |
metadata.rb
|
devops-consultants/cookbooks-base-server
|
61dbea0882da55e17c027af497a1357d81cc5c9a
|
[
"Apache-2.0"
] | 6
|
2018-11-22T14:30:24.000Z
|
2021-06-25T15:17:00.000Z
|
metadata.rb
|
devops-consultants/cookbooks-base-server
|
61dbea0882da55e17c027af497a1357d81cc5c9a
|
[
"Apache-2.0"
] | null | null | null |
name 'base_server'
maintainer 'Rob Coward'
maintainer_email 'rob.coward@devops-consultants.co.uk'
license 'Apache-2.0'
description 'Installs/Configures base_server'
long_description 'Installs/Configures base_server'
version '0.1.6'
chef_version '>= 12.1' if respond_to?(:chef_version)
# The `issues_url` points to the location where issues for this cookbook are
# tracked. A `View Issues` link will be displayed on this cookbook's page when
# uploaded to a Supermarket.
#
issues_url 'https://github.com/devops-consultants/cookbooks-base-server/issues'
# The `source_url` points to the development repository for this cookbook. A
# `View Source` link will be displayed on this cookbook's page when uploaded to
# a Supermarket.
#
source_url 'https://github.com/devops-consultants/cookbooks-base-server'
depends 'users'
depends 'os-hardening'
depends 'chef-client'
depends 'sudo'
depends 'openssh'
depends 'rsyslog'
depends 'logrotate'
depends 'postfix', '~> 5.1'
depends 'logwatch', '~> 2.1'
depends 'fail2ban', '~> 4.0'
| 32
| 79
| 0.766602
|
ef5ff36d188f726c50428ee8584b6eadfc5cc8ab
| 176
|
js
|
JavaScript
|
pages/utils/card/card.js
|
Asuis/wexin-app
|
e8cf72964ac8a026f14611cf6660d4dfca1f1a51
|
[
"MIT"
] | null | null | null |
pages/utils/card/card.js
|
Asuis/wexin-app
|
e8cf72964ac8a026f14611cf6660d4dfca1f1a51
|
[
"MIT"
] | null | null | null |
pages/utils/card/card.js
|
Asuis/wexin-app
|
e8cf72964ac8a026f14611cf6660d4dfca1f1a51
|
[
"MIT"
] | null | null | null |
// pages/utils/card/card.js
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
}
})
| 7.333333
| 27
| 0.403409
|
b7828e490770598d7cbe06bfad2e50233ce92d64
| 1,838
|
hpp
|
C++
|
src/backnocles/utils/disablewarnings.hpp
|
dsiroky/backnocles
|
889ab5f65fc1beb27f6dfff36d5fcda8544a9be2
|
[
"MIT"
] | 3
|
2017-10-22T17:57:10.000Z
|
2017-11-06T12:33:31.000Z
|
src/backnocles/utils/disablewarnings.hpp
|
dsiroky/backnocles
|
889ab5f65fc1beb27f6dfff36d5fcda8544a9be2
|
[
"MIT"
] | null | null | null |
src/backnocles/utils/disablewarnings.hpp
|
dsiroky/backnocles
|
889ab5f65fc1beb27f6dfff36d5fcda8544a9be2
|
[
"MIT"
] | null | null | null |
/// Place this include above thirdparty includes. Pair with enablewarnings.hpp.
///
/// Project has very restrictive warnings and lots of libraries does not
/// conform to that. MSVC++ does not have "-isystem" equivalent.
///
/// @file
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4244)
#pragma warning(disable: 4245)
#pragma warning(disable: 4251)
#pragma warning(disable: 4290)
#pragma warning(disable: 4913)
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-align"
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor"
#pragma GCC diagnostic ignored "-Wdeprecated"
#pragma GCC diagnostic ignored "-Wfloat-equal"
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#pragma GCC diagnostic ignored "-Wshadow"
#pragma GCC diagnostic ignored "-Wsign-compare"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wsign-promo"
#pragma GCC diagnostic ignored "-Wswitch-default"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#ifndef __APPLE__
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#ifdef __clang__
#ifndef __APPLE__
#pragma GCC diagnostic ignored "-Winconsistent-missing-override"
#endif
#pragma GCC diagnostic ignored "-Wfloat-conversion"
#pragma GCC diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
#pragma GCC diagnostic ignored "-Wparentheses-equality"
#if __clang_major__ * 100 + __clang_minor__ >= 309
#ifndef __APPLE__
#pragma GCC diagnostic ignored "-Wexpansion-to-defined"
#endif
#pragma GCC diagnostic ignored "-Wnull-dereference"
#endif
#endif
#endif
| 37.510204
| 79
| 0.73667
|
bf074c98507a4cf4d10b60f3b0bce3be36116599
| 961
|
sh
|
Shell
|
deploy/istio-helm/deploy.sh
|
fossabot/curiefense
|
6941f8aa08bcac1b0cf87c36ddb0037917a38c5a
|
[
"Apache-2.0"
] | null | null | null |
deploy/istio-helm/deploy.sh
|
fossabot/curiefense
|
6941f8aa08bcac1b0cf87c36ddb0037917a38c5a
|
[
"Apache-2.0"
] | null | null | null |
deploy/istio-helm/deploy.sh
|
fossabot/curiefense
|
6941f8aa08bcac1b0cf87c36ddb0037917a38c5a
|
[
"Apache-2.0"
] | 1
|
2021-01-07T20:51:48.000Z
|
2021-01-07T20:51:48.000Z
|
#!/bin/bash
if [ -z "$DOCKER_TAG" ]; then
if ! GITTAG="$(git describe --tag --long --exact-match 2> /dev/null)"; then
GITTAG="$(git describe --tag --long --dirty)"
echo "This commit is not tagged; use this for testing only"
fi
DOCKER_DIR_HASH="$(git rev-parse --short=12 HEAD:curiefense)"
DOCKER_TAG="$GITTAG-$DOCKER_DIR_HASH"
fi
if ! kubectl api-resources|grep -q config.istio.io; then
for i in crds/crd-*yaml; do kubectl apply -f "$i"; done
echo "CRDs created, waiting 5s for them to be registered..."
sleep 5
fi
PARAMS=()
if [ -n "$NOPULL" ]; then
PARAMS+=("--set" "global.imagePullPolicy=Never")
fi
helm upgrade --install --namespace istio-system --reuse-values --debug \
-f chart/custom/enable-waf-ingress.yaml \
--set "global.proxy.gw_image=curiefense/curieproxy-istio:$DOCKER_TAG" \
--set "global.proxy.curiesync_image=curiefense/curiesync:$DOCKER_TAG" \
${PARAMS[@]} istio-cf chart/
| 32.033333
| 79
| 0.662851
|
2a329bb76734a284f92825ad782a135d94c6d661
| 149,056
|
rs
|
Rust
|
sdk/ecr/src/output.rs
|
a-xp/aws-sdk-rust
|
6feb50dd219ec5bf8cb7527d6142e46ec5311b9e
|
[
"Apache-2.0"
] | 1
|
2022-03-02T02:19:58.000Z
|
2022-03-02T02:19:58.000Z
|
sdk/ecr/src/output.rs
|
a-xp/aws-sdk-rust
|
6feb50dd219ec5bf8cb7527d6142e46ec5311b9e
|
[
"Apache-2.0"
] | null | null | null |
sdk/ecr/src/output.rs
|
a-xp/aws-sdk-rust
|
6feb50dd219ec5bf8cb7527d6142e46ec5311b9e
|
[
"Apache-2.0"
] | null | null | null |
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UploadLayerPartOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The upload ID associated with the request.</p>
pub upload_id: std::option::Option<std::string::String>,
/// <p>The integer value of the last byte received in the request.</p>
pub last_byte_received: std::option::Option<i64>,
}
impl UploadLayerPartOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The upload ID associated with the request.</p>
pub fn upload_id(&self) -> std::option::Option<&str> {
self.upload_id.as_deref()
}
/// <p>The integer value of the last byte received in the request.</p>
pub fn last_byte_received(&self) -> std::option::Option<i64> {
self.last_byte_received
}
}
impl std::fmt::Debug for UploadLayerPartOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UploadLayerPartOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("upload_id", &self.upload_id);
formatter.field("last_byte_received", &self.last_byte_received);
formatter.finish()
}
}
/// See [`UploadLayerPartOutput`](crate::output::UploadLayerPartOutput)
pub mod upload_layer_part_output {
/// A builder for [`UploadLayerPartOutput`](crate::output::UploadLayerPartOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) upload_id: std::option::Option<std::string::String>,
pub(crate) last_byte_received: std::option::Option<i64>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The upload ID associated with the request.</p>
pub fn upload_id(mut self, input: impl Into<std::string::String>) -> Self {
self.upload_id = Some(input.into());
self
}
/// <p>The upload ID associated with the request.</p>
pub fn set_upload_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.upload_id = input;
self
}
/// <p>The integer value of the last byte received in the request.</p>
pub fn last_byte_received(mut self, input: i64) -> Self {
self.last_byte_received = Some(input);
self
}
/// <p>The integer value of the last byte received in the request.</p>
pub fn set_last_byte_received(mut self, input: std::option::Option<i64>) -> Self {
self.last_byte_received = input;
self
}
/// Consumes the builder and constructs a [`UploadLayerPartOutput`](crate::output::UploadLayerPartOutput)
pub fn build(self) -> crate::output::UploadLayerPartOutput {
crate::output::UploadLayerPartOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
upload_id: self.upload_id,
last_byte_received: self.last_byte_received,
}
}
}
}
impl UploadLayerPartOutput {
/// Creates a new builder-style object to manufacture [`UploadLayerPartOutput`](crate::output::UploadLayerPartOutput)
pub fn builder() -> crate::output::upload_layer_part_output::Builder {
crate::output::upload_layer_part_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct UntagResourceOutput {}
impl std::fmt::Debug for UntagResourceOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("UntagResourceOutput");
formatter.finish()
}
}
/// See [`UntagResourceOutput`](crate::output::UntagResourceOutput)
pub mod untag_resource_output {
/// A builder for [`UntagResourceOutput`](crate::output::UntagResourceOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {}
impl Builder {
/// Consumes the builder and constructs a [`UntagResourceOutput`](crate::output::UntagResourceOutput)
pub fn build(self) -> crate::output::UntagResourceOutput {
crate::output::UntagResourceOutput {}
}
}
}
impl UntagResourceOutput {
/// Creates a new builder-style object to manufacture [`UntagResourceOutput`](crate::output::UntagResourceOutput)
pub fn builder() -> crate::output::untag_resource_output::Builder {
crate::output::untag_resource_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct TagResourceOutput {}
impl std::fmt::Debug for TagResourceOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("TagResourceOutput");
formatter.finish()
}
}
/// See [`TagResourceOutput`](crate::output::TagResourceOutput)
pub mod tag_resource_output {
/// A builder for [`TagResourceOutput`](crate::output::TagResourceOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {}
impl Builder {
/// Consumes the builder and constructs a [`TagResourceOutput`](crate::output::TagResourceOutput)
pub fn build(self) -> crate::output::TagResourceOutput {
crate::output::TagResourceOutput {}
}
}
}
impl TagResourceOutput {
/// Creates a new builder-style object to manufacture [`TagResourceOutput`](crate::output::TagResourceOutput)
pub fn builder() -> crate::output::tag_resource_output::Builder {
crate::output::tag_resource_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct StartLifecyclePolicyPreviewOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The JSON repository policy text.</p>
pub lifecycle_policy_text: std::option::Option<std::string::String>,
/// <p>The status of the lifecycle policy preview request.</p>
pub status: std::option::Option<crate::model::LifecyclePolicyPreviewStatus>,
}
impl StartLifecyclePolicyPreviewOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The JSON repository policy text.</p>
pub fn lifecycle_policy_text(&self) -> std::option::Option<&str> {
self.lifecycle_policy_text.as_deref()
}
/// <p>The status of the lifecycle policy preview request.</p>
pub fn status(&self) -> std::option::Option<&crate::model::LifecyclePolicyPreviewStatus> {
self.status.as_ref()
}
}
impl std::fmt::Debug for StartLifecyclePolicyPreviewOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("StartLifecyclePolicyPreviewOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("lifecycle_policy_text", &self.lifecycle_policy_text);
formatter.field("status", &self.status);
formatter.finish()
}
}
/// See [`StartLifecyclePolicyPreviewOutput`](crate::output::StartLifecyclePolicyPreviewOutput)
pub mod start_lifecycle_policy_preview_output {
/// A builder for [`StartLifecyclePolicyPreviewOutput`](crate::output::StartLifecyclePolicyPreviewOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) lifecycle_policy_text: std::option::Option<std::string::String>,
pub(crate) status: std::option::Option<crate::model::LifecyclePolicyPreviewStatus>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The JSON repository policy text.</p>
pub fn lifecycle_policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.lifecycle_policy_text = Some(input.into());
self
}
/// <p>The JSON repository policy text.</p>
pub fn set_lifecycle_policy_text(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.lifecycle_policy_text = input;
self
}
/// <p>The status of the lifecycle policy preview request.</p>
pub fn status(mut self, input: crate::model::LifecyclePolicyPreviewStatus) -> Self {
self.status = Some(input);
self
}
/// <p>The status of the lifecycle policy preview request.</p>
pub fn set_status(
mut self,
input: std::option::Option<crate::model::LifecyclePolicyPreviewStatus>,
) -> Self {
self.status = input;
self
}
/// Consumes the builder and constructs a [`StartLifecyclePolicyPreviewOutput`](crate::output::StartLifecyclePolicyPreviewOutput)
pub fn build(self) -> crate::output::StartLifecyclePolicyPreviewOutput {
crate::output::StartLifecyclePolicyPreviewOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
lifecycle_policy_text: self.lifecycle_policy_text,
status: self.status,
}
}
}
}
impl StartLifecyclePolicyPreviewOutput {
/// Creates a new builder-style object to manufacture [`StartLifecyclePolicyPreviewOutput`](crate::output::StartLifecyclePolicyPreviewOutput)
pub fn builder() -> crate::output::start_lifecycle_policy_preview_output::Builder {
crate::output::start_lifecycle_policy_preview_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct StartImageScanOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub image_id: std::option::Option<crate::model::ImageIdentifier>,
/// <p>The current state of the scan.</p>
pub image_scan_status: std::option::Option<crate::model::ImageScanStatus>,
}
impl StartImageScanOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub fn image_id(&self) -> std::option::Option<&crate::model::ImageIdentifier> {
self.image_id.as_ref()
}
/// <p>The current state of the scan.</p>
pub fn image_scan_status(&self) -> std::option::Option<&crate::model::ImageScanStatus> {
self.image_scan_status.as_ref()
}
}
impl std::fmt::Debug for StartImageScanOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("StartImageScanOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("image_id", &self.image_id);
formatter.field("image_scan_status", &self.image_scan_status);
formatter.finish()
}
}
/// See [`StartImageScanOutput`](crate::output::StartImageScanOutput)
pub mod start_image_scan_output {
/// A builder for [`StartImageScanOutput`](crate::output::StartImageScanOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) image_id: std::option::Option<crate::model::ImageIdentifier>,
pub(crate) image_scan_status: std::option::Option<crate::model::ImageScanStatus>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub fn image_id(mut self, input: crate::model::ImageIdentifier) -> Self {
self.image_id = Some(input);
self
}
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub fn set_image_id(
mut self,
input: std::option::Option<crate::model::ImageIdentifier>,
) -> Self {
self.image_id = input;
self
}
/// <p>The current state of the scan.</p>
pub fn image_scan_status(mut self, input: crate::model::ImageScanStatus) -> Self {
self.image_scan_status = Some(input);
self
}
/// <p>The current state of the scan.</p>
pub fn set_image_scan_status(
mut self,
input: std::option::Option<crate::model::ImageScanStatus>,
) -> Self {
self.image_scan_status = input;
self
}
/// Consumes the builder and constructs a [`StartImageScanOutput`](crate::output::StartImageScanOutput)
pub fn build(self) -> crate::output::StartImageScanOutput {
crate::output::StartImageScanOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
image_id: self.image_id,
image_scan_status: self.image_scan_status,
}
}
}
}
impl StartImageScanOutput {
/// Creates a new builder-style object to manufacture [`StartImageScanOutput`](crate::output::StartImageScanOutput)
pub fn builder() -> crate::output::start_image_scan_output::Builder {
crate::output::start_image_scan_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct SetRepositoryPolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The JSON repository policy text applied to the repository.</p>
pub policy_text: std::option::Option<std::string::String>,
}
impl SetRepositoryPolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The JSON repository policy text applied to the repository.</p>
pub fn policy_text(&self) -> std::option::Option<&str> {
self.policy_text.as_deref()
}
}
impl std::fmt::Debug for SetRepositoryPolicyOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("SetRepositoryPolicyOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("policy_text", &self.policy_text);
formatter.finish()
}
}
/// See [`SetRepositoryPolicyOutput`](crate::output::SetRepositoryPolicyOutput)
pub mod set_repository_policy_output {
/// A builder for [`SetRepositoryPolicyOutput`](crate::output::SetRepositoryPolicyOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) policy_text: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The JSON repository policy text applied to the repository.</p>
pub fn policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.policy_text = Some(input.into());
self
}
/// <p>The JSON repository policy text applied to the repository.</p>
pub fn set_policy_text(mut self, input: std::option::Option<std::string::String>) -> Self {
self.policy_text = input;
self
}
/// Consumes the builder and constructs a [`SetRepositoryPolicyOutput`](crate::output::SetRepositoryPolicyOutput)
pub fn build(self) -> crate::output::SetRepositoryPolicyOutput {
crate::output::SetRepositoryPolicyOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
policy_text: self.policy_text,
}
}
}
}
impl SetRepositoryPolicyOutput {
/// Creates a new builder-style object to manufacture [`SetRepositoryPolicyOutput`](crate::output::SetRepositoryPolicyOutput)
pub fn builder() -> crate::output::set_repository_policy_output::Builder {
crate::output::set_repository_policy_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct PutReplicationConfigurationOutput {
/// <p>The contents of the replication configuration for the registry.</p>
pub replication_configuration: std::option::Option<crate::model::ReplicationConfiguration>,
}
impl PutReplicationConfigurationOutput {
/// <p>The contents of the replication configuration for the registry.</p>
pub fn replication_configuration(
&self,
) -> std::option::Option<&crate::model::ReplicationConfiguration> {
self.replication_configuration.as_ref()
}
}
impl std::fmt::Debug for PutReplicationConfigurationOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("PutReplicationConfigurationOutput");
formatter.field("replication_configuration", &self.replication_configuration);
formatter.finish()
}
}
/// See [`PutReplicationConfigurationOutput`](crate::output::PutReplicationConfigurationOutput)
pub mod put_replication_configuration_output {
/// A builder for [`PutReplicationConfigurationOutput`](crate::output::PutReplicationConfigurationOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) replication_configuration:
std::option::Option<crate::model::ReplicationConfiguration>,
}
impl Builder {
/// <p>The contents of the replication configuration for the registry.</p>
pub fn replication_configuration(
mut self,
input: crate::model::ReplicationConfiguration,
) -> Self {
self.replication_configuration = Some(input);
self
}
/// <p>The contents of the replication configuration for the registry.</p>
pub fn set_replication_configuration(
mut self,
input: std::option::Option<crate::model::ReplicationConfiguration>,
) -> Self {
self.replication_configuration = input;
self
}
/// Consumes the builder and constructs a [`PutReplicationConfigurationOutput`](crate::output::PutReplicationConfigurationOutput)
pub fn build(self) -> crate::output::PutReplicationConfigurationOutput {
crate::output::PutReplicationConfigurationOutput {
replication_configuration: self.replication_configuration,
}
}
}
}
impl PutReplicationConfigurationOutput {
/// Creates a new builder-style object to manufacture [`PutReplicationConfigurationOutput`](crate::output::PutReplicationConfigurationOutput)
pub fn builder() -> crate::output::put_replication_configuration_output::Builder {
crate::output::put_replication_configuration_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct PutRegistryPolicyOutput {
/// <p>The registry ID.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The JSON policy text for your registry.</p>
pub policy_text: std::option::Option<std::string::String>,
}
impl PutRegistryPolicyOutput {
/// <p>The registry ID.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The JSON policy text for your registry.</p>
pub fn policy_text(&self) -> std::option::Option<&str> {
self.policy_text.as_deref()
}
}
impl std::fmt::Debug for PutRegistryPolicyOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("PutRegistryPolicyOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("policy_text", &self.policy_text);
formatter.finish()
}
}
/// See [`PutRegistryPolicyOutput`](crate::output::PutRegistryPolicyOutput)
pub mod put_registry_policy_output {
/// A builder for [`PutRegistryPolicyOutput`](crate::output::PutRegistryPolicyOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) policy_text: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The registry ID.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The JSON policy text for your registry.</p>
pub fn policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.policy_text = Some(input.into());
self
}
/// <p>The JSON policy text for your registry.</p>
pub fn set_policy_text(mut self, input: std::option::Option<std::string::String>) -> Self {
self.policy_text = input;
self
}
/// Consumes the builder and constructs a [`PutRegistryPolicyOutput`](crate::output::PutRegistryPolicyOutput)
pub fn build(self) -> crate::output::PutRegistryPolicyOutput {
crate::output::PutRegistryPolicyOutput {
registry_id: self.registry_id,
policy_text: self.policy_text,
}
}
}
}
impl PutRegistryPolicyOutput {
/// Creates a new builder-style object to manufacture [`PutRegistryPolicyOutput`](crate::output::PutRegistryPolicyOutput)
pub fn builder() -> crate::output::put_registry_policy_output::Builder {
crate::output::put_registry_policy_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct PutLifecyclePolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The JSON repository policy text.</p>
pub lifecycle_policy_text: std::option::Option<std::string::String>,
}
impl PutLifecyclePolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The JSON repository policy text.</p>
pub fn lifecycle_policy_text(&self) -> std::option::Option<&str> {
self.lifecycle_policy_text.as_deref()
}
}
impl std::fmt::Debug for PutLifecyclePolicyOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("PutLifecyclePolicyOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("lifecycle_policy_text", &self.lifecycle_policy_text);
formatter.finish()
}
}
/// See [`PutLifecyclePolicyOutput`](crate::output::PutLifecyclePolicyOutput)
pub mod put_lifecycle_policy_output {
/// A builder for [`PutLifecyclePolicyOutput`](crate::output::PutLifecyclePolicyOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) lifecycle_policy_text: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The JSON repository policy text.</p>
pub fn lifecycle_policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.lifecycle_policy_text = Some(input.into());
self
}
/// <p>The JSON repository policy text.</p>
pub fn set_lifecycle_policy_text(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.lifecycle_policy_text = input;
self
}
/// Consumes the builder and constructs a [`PutLifecyclePolicyOutput`](crate::output::PutLifecyclePolicyOutput)
pub fn build(self) -> crate::output::PutLifecyclePolicyOutput {
crate::output::PutLifecyclePolicyOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
lifecycle_policy_text: self.lifecycle_policy_text,
}
}
}
}
impl PutLifecyclePolicyOutput {
/// Creates a new builder-style object to manufacture [`PutLifecyclePolicyOutput`](crate::output::PutLifecyclePolicyOutput)
pub fn builder() -> crate::output::put_lifecycle_policy_output::Builder {
crate::output::put_lifecycle_policy_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct PutImageTagMutabilityOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The image tag mutability setting for the repository.</p>
pub image_tag_mutability: std::option::Option<crate::model::ImageTagMutability>,
}
impl PutImageTagMutabilityOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The image tag mutability setting for the repository.</p>
pub fn image_tag_mutability(&self) -> std::option::Option<&crate::model::ImageTagMutability> {
self.image_tag_mutability.as_ref()
}
}
impl std::fmt::Debug for PutImageTagMutabilityOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("PutImageTagMutabilityOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("image_tag_mutability", &self.image_tag_mutability);
formatter.finish()
}
}
/// See [`PutImageTagMutabilityOutput`](crate::output::PutImageTagMutabilityOutput)
pub mod put_image_tag_mutability_output {
/// A builder for [`PutImageTagMutabilityOutput`](crate::output::PutImageTagMutabilityOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) image_tag_mutability: std::option::Option<crate::model::ImageTagMutability>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The image tag mutability setting for the repository.</p>
pub fn image_tag_mutability(mut self, input: crate::model::ImageTagMutability) -> Self {
self.image_tag_mutability = Some(input);
self
}
/// <p>The image tag mutability setting for the repository.</p>
pub fn set_image_tag_mutability(
mut self,
input: std::option::Option<crate::model::ImageTagMutability>,
) -> Self {
self.image_tag_mutability = input;
self
}
/// Consumes the builder and constructs a [`PutImageTagMutabilityOutput`](crate::output::PutImageTagMutabilityOutput)
pub fn build(self) -> crate::output::PutImageTagMutabilityOutput {
crate::output::PutImageTagMutabilityOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
image_tag_mutability: self.image_tag_mutability,
}
}
}
}
impl PutImageTagMutabilityOutput {
/// Creates a new builder-style object to manufacture [`PutImageTagMutabilityOutput`](crate::output::PutImageTagMutabilityOutput)
pub fn builder() -> crate::output::put_image_tag_mutability_output::Builder {
crate::output::put_image_tag_mutability_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct PutImageScanningConfigurationOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The image scanning configuration setting for the repository.</p>
pub image_scanning_configuration: std::option::Option<crate::model::ImageScanningConfiguration>,
}
impl PutImageScanningConfigurationOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The image scanning configuration setting for the repository.</p>
pub fn image_scanning_configuration(
&self,
) -> std::option::Option<&crate::model::ImageScanningConfiguration> {
self.image_scanning_configuration.as_ref()
}
}
impl std::fmt::Debug for PutImageScanningConfigurationOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("PutImageScanningConfigurationOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field(
"image_scanning_configuration",
&self.image_scanning_configuration,
);
formatter.finish()
}
}
/// See [`PutImageScanningConfigurationOutput`](crate::output::PutImageScanningConfigurationOutput)
pub mod put_image_scanning_configuration_output {
/// A builder for [`PutImageScanningConfigurationOutput`](crate::output::PutImageScanningConfigurationOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) image_scanning_configuration:
std::option::Option<crate::model::ImageScanningConfiguration>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The image scanning configuration setting for the repository.</p>
pub fn image_scanning_configuration(
mut self,
input: crate::model::ImageScanningConfiguration,
) -> Self {
self.image_scanning_configuration = Some(input);
self
}
/// <p>The image scanning configuration setting for the repository.</p>
pub fn set_image_scanning_configuration(
mut self,
input: std::option::Option<crate::model::ImageScanningConfiguration>,
) -> Self {
self.image_scanning_configuration = input;
self
}
/// Consumes the builder and constructs a [`PutImageScanningConfigurationOutput`](crate::output::PutImageScanningConfigurationOutput)
pub fn build(self) -> crate::output::PutImageScanningConfigurationOutput {
crate::output::PutImageScanningConfigurationOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
image_scanning_configuration: self.image_scanning_configuration,
}
}
}
}
impl PutImageScanningConfigurationOutput {
/// Creates a new builder-style object to manufacture [`PutImageScanningConfigurationOutput`](crate::output::PutImageScanningConfigurationOutput)
pub fn builder() -> crate::output::put_image_scanning_configuration_output::Builder {
crate::output::put_image_scanning_configuration_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct PutImageOutput {
/// <p>Details of the image uploaded.</p>
pub image: std::option::Option<crate::model::Image>,
}
impl PutImageOutput {
/// <p>Details of the image uploaded.</p>
pub fn image(&self) -> std::option::Option<&crate::model::Image> {
self.image.as_ref()
}
}
impl std::fmt::Debug for PutImageOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("PutImageOutput");
formatter.field("image", &self.image);
formatter.finish()
}
}
/// See [`PutImageOutput`](crate::output::PutImageOutput)
pub mod put_image_output {
/// A builder for [`PutImageOutput`](crate::output::PutImageOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) image: std::option::Option<crate::model::Image>,
}
impl Builder {
/// <p>Details of the image uploaded.</p>
pub fn image(mut self, input: crate::model::Image) -> Self {
self.image = Some(input);
self
}
/// <p>Details of the image uploaded.</p>
pub fn set_image(mut self, input: std::option::Option<crate::model::Image>) -> Self {
self.image = input;
self
}
/// Consumes the builder and constructs a [`PutImageOutput`](crate::output::PutImageOutput)
pub fn build(self) -> crate::output::PutImageOutput {
crate::output::PutImageOutput { image: self.image }
}
}
}
impl PutImageOutput {
/// Creates a new builder-style object to manufacture [`PutImageOutput`](crate::output::PutImageOutput)
pub fn builder() -> crate::output::put_image_output::Builder {
crate::output::put_image_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ListTagsForResourceOutput {
/// <p>The tags for the resource.</p>
pub tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl ListTagsForResourceOutput {
/// <p>The tags for the resource.</p>
pub fn tags(&self) -> std::option::Option<&[crate::model::Tag]> {
self.tags.as_deref()
}
}
impl std::fmt::Debug for ListTagsForResourceOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ListTagsForResourceOutput");
formatter.field("tags", &self.tags);
formatter.finish()
}
}
/// See [`ListTagsForResourceOutput`](crate::output::ListTagsForResourceOutput)
pub mod list_tags_for_resource_output {
/// A builder for [`ListTagsForResourceOutput`](crate::output::ListTagsForResourceOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) tags: std::option::Option<std::vec::Vec<crate::model::Tag>>,
}
impl Builder {
/// Appends an item to `tags`.
///
/// To override the contents of this collection use [`set_tags`](Self::set_tags).
///
/// <p>The tags for the resource.</p>
pub fn tags(mut self, input: impl Into<crate::model::Tag>) -> Self {
let mut v = self.tags.unwrap_or_default();
v.push(input.into());
self.tags = Some(v);
self
}
/// <p>The tags for the resource.</p>
pub fn set_tags(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Tag>>,
) -> Self {
self.tags = input;
self
}
/// Consumes the builder and constructs a [`ListTagsForResourceOutput`](crate::output::ListTagsForResourceOutput)
pub fn build(self) -> crate::output::ListTagsForResourceOutput {
crate::output::ListTagsForResourceOutput { tags: self.tags }
}
}
}
impl ListTagsForResourceOutput {
/// Creates a new builder-style object to manufacture [`ListTagsForResourceOutput`](crate::output::ListTagsForResourceOutput)
pub fn builder() -> crate::output::list_tags_for_resource_output::Builder {
crate::output::list_tags_for_resource_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ListImagesOutput {
/// <p>The list of image IDs for the requested repository.</p>
pub image_ids: std::option::Option<std::vec::Vec<crate::model::ImageIdentifier>>,
/// <p>The <code>nextToken</code> value to include in a future <code>ListImages</code>
/// request. When the results of a <code>ListImages</code> request exceed
/// <code>maxResults</code>, this value can be used to retrieve the next page of
/// results. This value is <code>null</code> when there are no more results to
/// return.</p>
pub next_token: std::option::Option<std::string::String>,
}
impl ListImagesOutput {
/// <p>The list of image IDs for the requested repository.</p>
pub fn image_ids(&self) -> std::option::Option<&[crate::model::ImageIdentifier]> {
self.image_ids.as_deref()
}
/// <p>The <code>nextToken</code> value to include in a future <code>ListImages</code>
/// request. When the results of a <code>ListImages</code> request exceed
/// <code>maxResults</code>, this value can be used to retrieve the next page of
/// results. This value is <code>null</code> when there are no more results to
/// return.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
}
impl std::fmt::Debug for ListImagesOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ListImagesOutput");
formatter.field("image_ids", &self.image_ids);
formatter.field("next_token", &self.next_token);
formatter.finish()
}
}
/// See [`ListImagesOutput`](crate::output::ListImagesOutput)
pub mod list_images_output {
/// A builder for [`ListImagesOutput`](crate::output::ListImagesOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) image_ids: std::option::Option<std::vec::Vec<crate::model::ImageIdentifier>>,
pub(crate) next_token: std::option::Option<std::string::String>,
}
impl Builder {
/// Appends an item to `image_ids`.
///
/// To override the contents of this collection use [`set_image_ids`](Self::set_image_ids).
///
/// <p>The list of image IDs for the requested repository.</p>
pub fn image_ids(mut self, input: impl Into<crate::model::ImageIdentifier>) -> Self {
let mut v = self.image_ids.unwrap_or_default();
v.push(input.into());
self.image_ids = Some(v);
self
}
/// <p>The list of image IDs for the requested repository.</p>
pub fn set_image_ids(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ImageIdentifier>>,
) -> Self {
self.image_ids = input;
self
}
/// <p>The <code>nextToken</code> value to include in a future <code>ListImages</code>
/// request. When the results of a <code>ListImages</code> request exceed
/// <code>maxResults</code>, this value can be used to retrieve the next page of
/// results. This value is <code>null</code> when there are no more results to
/// return.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <code>nextToken</code> value to include in a future <code>ListImages</code>
/// request. When the results of a <code>ListImages</code> request exceed
/// <code>maxResults</code>, this value can be used to retrieve the next page of
/// results. This value is <code>null</code> when there are no more results to
/// return.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// Consumes the builder and constructs a [`ListImagesOutput`](crate::output::ListImagesOutput)
pub fn build(self) -> crate::output::ListImagesOutput {
crate::output::ListImagesOutput {
image_ids: self.image_ids,
next_token: self.next_token,
}
}
}
}
impl ListImagesOutput {
/// Creates a new builder-style object to manufacture [`ListImagesOutput`](crate::output::ListImagesOutput)
pub fn builder() -> crate::output::list_images_output::Builder {
crate::output::list_images_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InitiateLayerUploadOutput {
/// <p>The upload ID for the layer upload. This parameter is passed to further <a>UploadLayerPart</a> and <a>CompleteLayerUpload</a>
/// operations.</p>
pub upload_id: std::option::Option<std::string::String>,
/// <p>The size, in bytes, that Amazon ECR expects future layer part uploads to be.</p>
pub part_size: std::option::Option<i64>,
}
impl InitiateLayerUploadOutput {
/// <p>The upload ID for the layer upload. This parameter is passed to further <a>UploadLayerPart</a> and <a>CompleteLayerUpload</a>
/// operations.</p>
pub fn upload_id(&self) -> std::option::Option<&str> {
self.upload_id.as_deref()
}
/// <p>The size, in bytes, that Amazon ECR expects future layer part uploads to be.</p>
pub fn part_size(&self) -> std::option::Option<i64> {
self.part_size
}
}
impl std::fmt::Debug for InitiateLayerUploadOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InitiateLayerUploadOutput");
formatter.field("upload_id", &self.upload_id);
formatter.field("part_size", &self.part_size);
formatter.finish()
}
}
/// See [`InitiateLayerUploadOutput`](crate::output::InitiateLayerUploadOutput)
pub mod initiate_layer_upload_output {
/// A builder for [`InitiateLayerUploadOutput`](crate::output::InitiateLayerUploadOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) upload_id: std::option::Option<std::string::String>,
pub(crate) part_size: std::option::Option<i64>,
}
impl Builder {
/// <p>The upload ID for the layer upload. This parameter is passed to further <a>UploadLayerPart</a> and <a>CompleteLayerUpload</a>
/// operations.</p>
pub fn upload_id(mut self, input: impl Into<std::string::String>) -> Self {
self.upload_id = Some(input.into());
self
}
/// <p>The upload ID for the layer upload. This parameter is passed to further <a>UploadLayerPart</a> and <a>CompleteLayerUpload</a>
/// operations.</p>
pub fn set_upload_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.upload_id = input;
self
}
/// <p>The size, in bytes, that Amazon ECR expects future layer part uploads to be.</p>
pub fn part_size(mut self, input: i64) -> Self {
self.part_size = Some(input);
self
}
/// <p>The size, in bytes, that Amazon ECR expects future layer part uploads to be.</p>
pub fn set_part_size(mut self, input: std::option::Option<i64>) -> Self {
self.part_size = input;
self
}
/// Consumes the builder and constructs a [`InitiateLayerUploadOutput`](crate::output::InitiateLayerUploadOutput)
pub fn build(self) -> crate::output::InitiateLayerUploadOutput {
crate::output::InitiateLayerUploadOutput {
upload_id: self.upload_id,
part_size: self.part_size,
}
}
}
}
impl InitiateLayerUploadOutput {
/// Creates a new builder-style object to manufacture [`InitiateLayerUploadOutput`](crate::output::InitiateLayerUploadOutput)
pub fn builder() -> crate::output::initiate_layer_upload_output::Builder {
crate::output::initiate_layer_upload_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetRepositoryPolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The JSON repository policy text associated with the repository.</p>
pub policy_text: std::option::Option<std::string::String>,
}
impl GetRepositoryPolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The JSON repository policy text associated with the repository.</p>
pub fn policy_text(&self) -> std::option::Option<&str> {
self.policy_text.as_deref()
}
}
impl std::fmt::Debug for GetRepositoryPolicyOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetRepositoryPolicyOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("policy_text", &self.policy_text);
formatter.finish()
}
}
/// See [`GetRepositoryPolicyOutput`](crate::output::GetRepositoryPolicyOutput)
pub mod get_repository_policy_output {
/// A builder for [`GetRepositoryPolicyOutput`](crate::output::GetRepositoryPolicyOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) policy_text: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The JSON repository policy text associated with the repository.</p>
pub fn policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.policy_text = Some(input.into());
self
}
/// <p>The JSON repository policy text associated with the repository.</p>
pub fn set_policy_text(mut self, input: std::option::Option<std::string::String>) -> Self {
self.policy_text = input;
self
}
/// Consumes the builder and constructs a [`GetRepositoryPolicyOutput`](crate::output::GetRepositoryPolicyOutput)
pub fn build(self) -> crate::output::GetRepositoryPolicyOutput {
crate::output::GetRepositoryPolicyOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
policy_text: self.policy_text,
}
}
}
}
impl GetRepositoryPolicyOutput {
/// Creates a new builder-style object to manufacture [`GetRepositoryPolicyOutput`](crate::output::GetRepositoryPolicyOutput)
pub fn builder() -> crate::output::get_repository_policy_output::Builder {
crate::output::get_repository_policy_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetRegistryPolicyOutput {
/// <p>The ID of the registry.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The JSON text of the permissions policy for a registry.</p>
pub policy_text: std::option::Option<std::string::String>,
}
impl GetRegistryPolicyOutput {
/// <p>The ID of the registry.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The JSON text of the permissions policy for a registry.</p>
pub fn policy_text(&self) -> std::option::Option<&str> {
self.policy_text.as_deref()
}
}
impl std::fmt::Debug for GetRegistryPolicyOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetRegistryPolicyOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("policy_text", &self.policy_text);
formatter.finish()
}
}
/// See [`GetRegistryPolicyOutput`](crate::output::GetRegistryPolicyOutput)
pub mod get_registry_policy_output {
/// A builder for [`GetRegistryPolicyOutput`](crate::output::GetRegistryPolicyOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) policy_text: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The ID of the registry.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The ID of the registry.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The JSON text of the permissions policy for a registry.</p>
pub fn policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.policy_text = Some(input.into());
self
}
/// <p>The JSON text of the permissions policy for a registry.</p>
pub fn set_policy_text(mut self, input: std::option::Option<std::string::String>) -> Self {
self.policy_text = input;
self
}
/// Consumes the builder and constructs a [`GetRegistryPolicyOutput`](crate::output::GetRegistryPolicyOutput)
pub fn build(self) -> crate::output::GetRegistryPolicyOutput {
crate::output::GetRegistryPolicyOutput {
registry_id: self.registry_id,
policy_text: self.policy_text,
}
}
}
}
impl GetRegistryPolicyOutput {
/// Creates a new builder-style object to manufacture [`GetRegistryPolicyOutput`](crate::output::GetRegistryPolicyOutput)
pub fn builder() -> crate::output::get_registry_policy_output::Builder {
crate::output::get_registry_policy_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetLifecyclePolicyPreviewOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The JSON lifecycle policy text.</p>
pub lifecycle_policy_text: std::option::Option<std::string::String>,
/// <p>The status of the lifecycle policy preview request.</p>
pub status: std::option::Option<crate::model::LifecyclePolicyPreviewStatus>,
/// <p>The <code>nextToken</code> value to include in a future
/// <code>GetLifecyclePolicyPreview</code> request. When the results of a
/// <code>GetLifecyclePolicyPreview</code> request exceed <code>maxResults</code>, this
/// value can be used to retrieve the next page of results. This value is <code>null</code>
/// when there are no more results to return.</p>
pub next_token: std::option::Option<std::string::String>,
/// <p>The results of the lifecycle policy preview request.</p>
pub preview_results:
std::option::Option<std::vec::Vec<crate::model::LifecyclePolicyPreviewResult>>,
/// <p>The list of images that is returned as a result of the action.</p>
pub summary: std::option::Option<crate::model::LifecyclePolicyPreviewSummary>,
}
impl GetLifecyclePolicyPreviewOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The JSON lifecycle policy text.</p>
pub fn lifecycle_policy_text(&self) -> std::option::Option<&str> {
self.lifecycle_policy_text.as_deref()
}
/// <p>The status of the lifecycle policy preview request.</p>
pub fn status(&self) -> std::option::Option<&crate::model::LifecyclePolicyPreviewStatus> {
self.status.as_ref()
}
/// <p>The <code>nextToken</code> value to include in a future
/// <code>GetLifecyclePolicyPreview</code> request. When the results of a
/// <code>GetLifecyclePolicyPreview</code> request exceed <code>maxResults</code>, this
/// value can be used to retrieve the next page of results. This value is <code>null</code>
/// when there are no more results to return.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
/// <p>The results of the lifecycle policy preview request.</p>
pub fn preview_results(
&self,
) -> std::option::Option<&[crate::model::LifecyclePolicyPreviewResult]> {
self.preview_results.as_deref()
}
/// <p>The list of images that is returned as a result of the action.</p>
pub fn summary(&self) -> std::option::Option<&crate::model::LifecyclePolicyPreviewSummary> {
self.summary.as_ref()
}
}
impl std::fmt::Debug for GetLifecyclePolicyPreviewOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetLifecyclePolicyPreviewOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("lifecycle_policy_text", &self.lifecycle_policy_text);
formatter.field("status", &self.status);
formatter.field("next_token", &self.next_token);
formatter.field("preview_results", &self.preview_results);
formatter.field("summary", &self.summary);
formatter.finish()
}
}
/// See [`GetLifecyclePolicyPreviewOutput`](crate::output::GetLifecyclePolicyPreviewOutput)
pub mod get_lifecycle_policy_preview_output {
/// A builder for [`GetLifecyclePolicyPreviewOutput`](crate::output::GetLifecyclePolicyPreviewOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) lifecycle_policy_text: std::option::Option<std::string::String>,
pub(crate) status: std::option::Option<crate::model::LifecyclePolicyPreviewStatus>,
pub(crate) next_token: std::option::Option<std::string::String>,
pub(crate) preview_results:
std::option::Option<std::vec::Vec<crate::model::LifecyclePolicyPreviewResult>>,
pub(crate) summary: std::option::Option<crate::model::LifecyclePolicyPreviewSummary>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The JSON lifecycle policy text.</p>
pub fn lifecycle_policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.lifecycle_policy_text = Some(input.into());
self
}
/// <p>The JSON lifecycle policy text.</p>
pub fn set_lifecycle_policy_text(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.lifecycle_policy_text = input;
self
}
/// <p>The status of the lifecycle policy preview request.</p>
pub fn status(mut self, input: crate::model::LifecyclePolicyPreviewStatus) -> Self {
self.status = Some(input);
self
}
/// <p>The status of the lifecycle policy preview request.</p>
pub fn set_status(
mut self,
input: std::option::Option<crate::model::LifecyclePolicyPreviewStatus>,
) -> Self {
self.status = input;
self
}
/// <p>The <code>nextToken</code> value to include in a future
/// <code>GetLifecyclePolicyPreview</code> request. When the results of a
/// <code>GetLifecyclePolicyPreview</code> request exceed <code>maxResults</code>, this
/// value can be used to retrieve the next page of results. This value is <code>null</code>
/// when there are no more results to return.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <code>nextToken</code> value to include in a future
/// <code>GetLifecyclePolicyPreview</code> request. When the results of a
/// <code>GetLifecyclePolicyPreview</code> request exceed <code>maxResults</code>, this
/// value can be used to retrieve the next page of results. This value is <code>null</code>
/// when there are no more results to return.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// Appends an item to `preview_results`.
///
/// To override the contents of this collection use [`set_preview_results`](Self::set_preview_results).
///
/// <p>The results of the lifecycle policy preview request.</p>
pub fn preview_results(
mut self,
input: impl Into<crate::model::LifecyclePolicyPreviewResult>,
) -> Self {
let mut v = self.preview_results.unwrap_or_default();
v.push(input.into());
self.preview_results = Some(v);
self
}
/// <p>The results of the lifecycle policy preview request.</p>
pub fn set_preview_results(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::LifecyclePolicyPreviewResult>>,
) -> Self {
self.preview_results = input;
self
}
/// <p>The list of images that is returned as a result of the action.</p>
pub fn summary(mut self, input: crate::model::LifecyclePolicyPreviewSummary) -> Self {
self.summary = Some(input);
self
}
/// <p>The list of images that is returned as a result of the action.</p>
pub fn set_summary(
mut self,
input: std::option::Option<crate::model::LifecyclePolicyPreviewSummary>,
) -> Self {
self.summary = input;
self
}
/// Consumes the builder and constructs a [`GetLifecyclePolicyPreviewOutput`](crate::output::GetLifecyclePolicyPreviewOutput)
pub fn build(self) -> crate::output::GetLifecyclePolicyPreviewOutput {
crate::output::GetLifecyclePolicyPreviewOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
lifecycle_policy_text: self.lifecycle_policy_text,
status: self.status,
next_token: self.next_token,
preview_results: self.preview_results,
summary: self.summary,
}
}
}
}
impl GetLifecyclePolicyPreviewOutput {
/// Creates a new builder-style object to manufacture [`GetLifecyclePolicyPreviewOutput`](crate::output::GetLifecyclePolicyPreviewOutput)
pub fn builder() -> crate::output::get_lifecycle_policy_preview_output::Builder {
crate::output::get_lifecycle_policy_preview_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetLifecyclePolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The JSON lifecycle policy text.</p>
pub lifecycle_policy_text: std::option::Option<std::string::String>,
/// <p>The time stamp of the last time that the lifecycle policy was run.</p>
pub last_evaluated_at: std::option::Option<aws_smithy_types::DateTime>,
}
impl GetLifecyclePolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The JSON lifecycle policy text.</p>
pub fn lifecycle_policy_text(&self) -> std::option::Option<&str> {
self.lifecycle_policy_text.as_deref()
}
/// <p>The time stamp of the last time that the lifecycle policy was run.</p>
pub fn last_evaluated_at(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.last_evaluated_at.as_ref()
}
}
impl std::fmt::Debug for GetLifecyclePolicyOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetLifecyclePolicyOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("lifecycle_policy_text", &self.lifecycle_policy_text);
formatter.field("last_evaluated_at", &self.last_evaluated_at);
formatter.finish()
}
}
/// See [`GetLifecyclePolicyOutput`](crate::output::GetLifecyclePolicyOutput)
pub mod get_lifecycle_policy_output {
/// A builder for [`GetLifecyclePolicyOutput`](crate::output::GetLifecyclePolicyOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) lifecycle_policy_text: std::option::Option<std::string::String>,
pub(crate) last_evaluated_at: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The JSON lifecycle policy text.</p>
pub fn lifecycle_policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.lifecycle_policy_text = Some(input.into());
self
}
/// <p>The JSON lifecycle policy text.</p>
pub fn set_lifecycle_policy_text(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.lifecycle_policy_text = input;
self
}
/// <p>The time stamp of the last time that the lifecycle policy was run.</p>
pub fn last_evaluated_at(mut self, input: aws_smithy_types::DateTime) -> Self {
self.last_evaluated_at = Some(input);
self
}
/// <p>The time stamp of the last time that the lifecycle policy was run.</p>
pub fn set_last_evaluated_at(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.last_evaluated_at = input;
self
}
/// Consumes the builder and constructs a [`GetLifecyclePolicyOutput`](crate::output::GetLifecyclePolicyOutput)
pub fn build(self) -> crate::output::GetLifecyclePolicyOutput {
crate::output::GetLifecyclePolicyOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
lifecycle_policy_text: self.lifecycle_policy_text,
last_evaluated_at: self.last_evaluated_at,
}
}
}
}
impl GetLifecyclePolicyOutput {
/// Creates a new builder-style object to manufacture [`GetLifecyclePolicyOutput`](crate::output::GetLifecyclePolicyOutput)
pub fn builder() -> crate::output::get_lifecycle_policy_output::Builder {
crate::output::get_lifecycle_policy_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetDownloadUrlForLayerOutput {
/// <p>The pre-signed Amazon S3 download URL for the requested layer.</p>
pub download_url: std::option::Option<std::string::String>,
/// <p>The digest of the image layer to download.</p>
pub layer_digest: std::option::Option<std::string::String>,
}
impl GetDownloadUrlForLayerOutput {
/// <p>The pre-signed Amazon S3 download URL for the requested layer.</p>
pub fn download_url(&self) -> std::option::Option<&str> {
self.download_url.as_deref()
}
/// <p>The digest of the image layer to download.</p>
pub fn layer_digest(&self) -> std::option::Option<&str> {
self.layer_digest.as_deref()
}
}
impl std::fmt::Debug for GetDownloadUrlForLayerOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetDownloadUrlForLayerOutput");
formatter.field("download_url", &self.download_url);
formatter.field("layer_digest", &self.layer_digest);
formatter.finish()
}
}
/// See [`GetDownloadUrlForLayerOutput`](crate::output::GetDownloadUrlForLayerOutput)
pub mod get_download_url_for_layer_output {
/// A builder for [`GetDownloadUrlForLayerOutput`](crate::output::GetDownloadUrlForLayerOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) download_url: std::option::Option<std::string::String>,
pub(crate) layer_digest: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The pre-signed Amazon S3 download URL for the requested layer.</p>
pub fn download_url(mut self, input: impl Into<std::string::String>) -> Self {
self.download_url = Some(input.into());
self
}
/// <p>The pre-signed Amazon S3 download URL for the requested layer.</p>
pub fn set_download_url(mut self, input: std::option::Option<std::string::String>) -> Self {
self.download_url = input;
self
}
/// <p>The digest of the image layer to download.</p>
pub fn layer_digest(mut self, input: impl Into<std::string::String>) -> Self {
self.layer_digest = Some(input.into());
self
}
/// <p>The digest of the image layer to download.</p>
pub fn set_layer_digest(mut self, input: std::option::Option<std::string::String>) -> Self {
self.layer_digest = input;
self
}
/// Consumes the builder and constructs a [`GetDownloadUrlForLayerOutput`](crate::output::GetDownloadUrlForLayerOutput)
pub fn build(self) -> crate::output::GetDownloadUrlForLayerOutput {
crate::output::GetDownloadUrlForLayerOutput {
download_url: self.download_url,
layer_digest: self.layer_digest,
}
}
}
}
impl GetDownloadUrlForLayerOutput {
/// Creates a new builder-style object to manufacture [`GetDownloadUrlForLayerOutput`](crate::output::GetDownloadUrlForLayerOutput)
pub fn builder() -> crate::output::get_download_url_for_layer_output::Builder {
crate::output::get_download_url_for_layer_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct GetAuthorizationTokenOutput {
/// <p>A list of authorization token data objects that correspond to the
/// <code>registryIds</code> values in the request.</p>
pub authorization_data: std::option::Option<std::vec::Vec<crate::model::AuthorizationData>>,
}
impl GetAuthorizationTokenOutput {
/// <p>A list of authorization token data objects that correspond to the
/// <code>registryIds</code> values in the request.</p>
pub fn authorization_data(&self) -> std::option::Option<&[crate::model::AuthorizationData]> {
self.authorization_data.as_deref()
}
}
impl std::fmt::Debug for GetAuthorizationTokenOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("GetAuthorizationTokenOutput");
formatter.field("authorization_data", &self.authorization_data);
formatter.finish()
}
}
/// See [`GetAuthorizationTokenOutput`](crate::output::GetAuthorizationTokenOutput)
pub mod get_authorization_token_output {
/// A builder for [`GetAuthorizationTokenOutput`](crate::output::GetAuthorizationTokenOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) authorization_data:
std::option::Option<std::vec::Vec<crate::model::AuthorizationData>>,
}
impl Builder {
/// Appends an item to `authorization_data`.
///
/// To override the contents of this collection use [`set_authorization_data`](Self::set_authorization_data).
///
/// <p>A list of authorization token data objects that correspond to the
/// <code>registryIds</code> values in the request.</p>
pub fn authorization_data(
mut self,
input: impl Into<crate::model::AuthorizationData>,
) -> Self {
let mut v = self.authorization_data.unwrap_or_default();
v.push(input.into());
self.authorization_data = Some(v);
self
}
/// <p>A list of authorization token data objects that correspond to the
/// <code>registryIds</code> values in the request.</p>
pub fn set_authorization_data(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::AuthorizationData>>,
) -> Self {
self.authorization_data = input;
self
}
/// Consumes the builder and constructs a [`GetAuthorizationTokenOutput`](crate::output::GetAuthorizationTokenOutput)
pub fn build(self) -> crate::output::GetAuthorizationTokenOutput {
crate::output::GetAuthorizationTokenOutput {
authorization_data: self.authorization_data,
}
}
}
}
impl GetAuthorizationTokenOutput {
/// Creates a new builder-style object to manufacture [`GetAuthorizationTokenOutput`](crate::output::GetAuthorizationTokenOutput)
pub fn builder() -> crate::output::get_authorization_token_output::Builder {
crate::output::get_authorization_token_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeRepositoriesOutput {
/// <p>A list of repository objects corresponding to valid repositories.</p>
pub repositories: std::option::Option<std::vec::Vec<crate::model::Repository>>,
/// <p>The <code>nextToken</code> value to include in a future
/// <code>DescribeRepositories</code> request. When the results of a
/// <code>DescribeRepositories</code> request exceed <code>maxResults</code>, this value
/// can be used to retrieve the next page of results. This value is <code>null</code> when
/// there are no more results to return.</p>
pub next_token: std::option::Option<std::string::String>,
}
impl DescribeRepositoriesOutput {
/// <p>A list of repository objects corresponding to valid repositories.</p>
pub fn repositories(&self) -> std::option::Option<&[crate::model::Repository]> {
self.repositories.as_deref()
}
/// <p>The <code>nextToken</code> value to include in a future
/// <code>DescribeRepositories</code> request. When the results of a
/// <code>DescribeRepositories</code> request exceed <code>maxResults</code>, this value
/// can be used to retrieve the next page of results. This value is <code>null</code> when
/// there are no more results to return.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
}
impl std::fmt::Debug for DescribeRepositoriesOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeRepositoriesOutput");
formatter.field("repositories", &self.repositories);
formatter.field("next_token", &self.next_token);
formatter.finish()
}
}
/// See [`DescribeRepositoriesOutput`](crate::output::DescribeRepositoriesOutput)
pub mod describe_repositories_output {
/// A builder for [`DescribeRepositoriesOutput`](crate::output::DescribeRepositoriesOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) repositories: std::option::Option<std::vec::Vec<crate::model::Repository>>,
pub(crate) next_token: std::option::Option<std::string::String>,
}
impl Builder {
/// Appends an item to `repositories`.
///
/// To override the contents of this collection use [`set_repositories`](Self::set_repositories).
///
/// <p>A list of repository objects corresponding to valid repositories.</p>
pub fn repositories(mut self, input: impl Into<crate::model::Repository>) -> Self {
let mut v = self.repositories.unwrap_or_default();
v.push(input.into());
self.repositories = Some(v);
self
}
/// <p>A list of repository objects corresponding to valid repositories.</p>
pub fn set_repositories(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Repository>>,
) -> Self {
self.repositories = input;
self
}
/// <p>The <code>nextToken</code> value to include in a future
/// <code>DescribeRepositories</code> request. When the results of a
/// <code>DescribeRepositories</code> request exceed <code>maxResults</code>, this value
/// can be used to retrieve the next page of results. This value is <code>null</code> when
/// there are no more results to return.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <code>nextToken</code> value to include in a future
/// <code>DescribeRepositories</code> request. When the results of a
/// <code>DescribeRepositories</code> request exceed <code>maxResults</code>, this value
/// can be used to retrieve the next page of results. This value is <code>null</code> when
/// there are no more results to return.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// Consumes the builder and constructs a [`DescribeRepositoriesOutput`](crate::output::DescribeRepositoriesOutput)
pub fn build(self) -> crate::output::DescribeRepositoriesOutput {
crate::output::DescribeRepositoriesOutput {
repositories: self.repositories,
next_token: self.next_token,
}
}
}
}
impl DescribeRepositoriesOutput {
/// Creates a new builder-style object to manufacture [`DescribeRepositoriesOutput`](crate::output::DescribeRepositoriesOutput)
pub fn builder() -> crate::output::describe_repositories_output::Builder {
crate::output::describe_repositories_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeRegistryOutput {
/// <p>The ID of the registry.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The replication configuration for the registry.</p>
pub replication_configuration: std::option::Option<crate::model::ReplicationConfiguration>,
}
impl DescribeRegistryOutput {
/// <p>The ID of the registry.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The replication configuration for the registry.</p>
pub fn replication_configuration(
&self,
) -> std::option::Option<&crate::model::ReplicationConfiguration> {
self.replication_configuration.as_ref()
}
}
impl std::fmt::Debug for DescribeRegistryOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeRegistryOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("replication_configuration", &self.replication_configuration);
formatter.finish()
}
}
/// See [`DescribeRegistryOutput`](crate::output::DescribeRegistryOutput)
pub mod describe_registry_output {
/// A builder for [`DescribeRegistryOutput`](crate::output::DescribeRegistryOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) replication_configuration:
std::option::Option<crate::model::ReplicationConfiguration>,
}
impl Builder {
/// <p>The ID of the registry.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The ID of the registry.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The replication configuration for the registry.</p>
pub fn replication_configuration(
mut self,
input: crate::model::ReplicationConfiguration,
) -> Self {
self.replication_configuration = Some(input);
self
}
/// <p>The replication configuration for the registry.</p>
pub fn set_replication_configuration(
mut self,
input: std::option::Option<crate::model::ReplicationConfiguration>,
) -> Self {
self.replication_configuration = input;
self
}
/// Consumes the builder and constructs a [`DescribeRegistryOutput`](crate::output::DescribeRegistryOutput)
pub fn build(self) -> crate::output::DescribeRegistryOutput {
crate::output::DescribeRegistryOutput {
registry_id: self.registry_id,
replication_configuration: self.replication_configuration,
}
}
}
}
impl DescribeRegistryOutput {
/// Creates a new builder-style object to manufacture [`DescribeRegistryOutput`](crate::output::DescribeRegistryOutput)
pub fn builder() -> crate::output::describe_registry_output::Builder {
crate::output::describe_registry_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeImageScanFindingsOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub image_id: std::option::Option<crate::model::ImageIdentifier>,
/// <p>The current state of the scan.</p>
pub image_scan_status: std::option::Option<crate::model::ImageScanStatus>,
/// <p>The information contained in the image scan findings.</p>
pub image_scan_findings: std::option::Option<crate::model::ImageScanFindings>,
/// <p>The <code>nextToken</code> value to include in a future
/// <code>DescribeImageScanFindings</code> request. When the results of a
/// <code>DescribeImageScanFindings</code> request exceed <code>maxResults</code>, this
/// value can be used to retrieve the next page of results. This value is null when there
/// are no more results to return.</p>
pub next_token: std::option::Option<std::string::String>,
}
impl DescribeImageScanFindingsOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub fn image_id(&self) -> std::option::Option<&crate::model::ImageIdentifier> {
self.image_id.as_ref()
}
/// <p>The current state of the scan.</p>
pub fn image_scan_status(&self) -> std::option::Option<&crate::model::ImageScanStatus> {
self.image_scan_status.as_ref()
}
/// <p>The information contained in the image scan findings.</p>
pub fn image_scan_findings(&self) -> std::option::Option<&crate::model::ImageScanFindings> {
self.image_scan_findings.as_ref()
}
/// <p>The <code>nextToken</code> value to include in a future
/// <code>DescribeImageScanFindings</code> request. When the results of a
/// <code>DescribeImageScanFindings</code> request exceed <code>maxResults</code>, this
/// value can be used to retrieve the next page of results. This value is null when there
/// are no more results to return.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
}
impl std::fmt::Debug for DescribeImageScanFindingsOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeImageScanFindingsOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("image_id", &self.image_id);
formatter.field("image_scan_status", &self.image_scan_status);
formatter.field("image_scan_findings", &self.image_scan_findings);
formatter.field("next_token", &self.next_token);
formatter.finish()
}
}
/// See [`DescribeImageScanFindingsOutput`](crate::output::DescribeImageScanFindingsOutput)
pub mod describe_image_scan_findings_output {
/// A builder for [`DescribeImageScanFindingsOutput`](crate::output::DescribeImageScanFindingsOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) image_id: std::option::Option<crate::model::ImageIdentifier>,
pub(crate) image_scan_status: std::option::Option<crate::model::ImageScanStatus>,
pub(crate) image_scan_findings: std::option::Option<crate::model::ImageScanFindings>,
pub(crate) next_token: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub fn image_id(mut self, input: crate::model::ImageIdentifier) -> Self {
self.image_id = Some(input);
self
}
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub fn set_image_id(
mut self,
input: std::option::Option<crate::model::ImageIdentifier>,
) -> Self {
self.image_id = input;
self
}
/// <p>The current state of the scan.</p>
pub fn image_scan_status(mut self, input: crate::model::ImageScanStatus) -> Self {
self.image_scan_status = Some(input);
self
}
/// <p>The current state of the scan.</p>
pub fn set_image_scan_status(
mut self,
input: std::option::Option<crate::model::ImageScanStatus>,
) -> Self {
self.image_scan_status = input;
self
}
/// <p>The information contained in the image scan findings.</p>
pub fn image_scan_findings(mut self, input: crate::model::ImageScanFindings) -> Self {
self.image_scan_findings = Some(input);
self
}
/// <p>The information contained in the image scan findings.</p>
pub fn set_image_scan_findings(
mut self,
input: std::option::Option<crate::model::ImageScanFindings>,
) -> Self {
self.image_scan_findings = input;
self
}
/// <p>The <code>nextToken</code> value to include in a future
/// <code>DescribeImageScanFindings</code> request. When the results of a
/// <code>DescribeImageScanFindings</code> request exceed <code>maxResults</code>, this
/// value can be used to retrieve the next page of results. This value is null when there
/// are no more results to return.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <code>nextToken</code> value to include in a future
/// <code>DescribeImageScanFindings</code> request. When the results of a
/// <code>DescribeImageScanFindings</code> request exceed <code>maxResults</code>, this
/// value can be used to retrieve the next page of results. This value is null when there
/// are no more results to return.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// Consumes the builder and constructs a [`DescribeImageScanFindingsOutput`](crate::output::DescribeImageScanFindingsOutput)
pub fn build(self) -> crate::output::DescribeImageScanFindingsOutput {
crate::output::DescribeImageScanFindingsOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
image_id: self.image_id,
image_scan_status: self.image_scan_status,
image_scan_findings: self.image_scan_findings,
next_token: self.next_token,
}
}
}
}
impl DescribeImageScanFindingsOutput {
/// Creates a new builder-style object to manufacture [`DescribeImageScanFindingsOutput`](crate::output::DescribeImageScanFindingsOutput)
pub fn builder() -> crate::output::describe_image_scan_findings_output::Builder {
crate::output::describe_image_scan_findings_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeImagesOutput {
/// <p>A list of <a>ImageDetail</a> objects that contain data about the
/// image.</p>
pub image_details: std::option::Option<std::vec::Vec<crate::model::ImageDetail>>,
/// <p>The <code>nextToken</code> value to include in a future <code>DescribeImages</code>
/// request. When the results of a <code>DescribeImages</code> request exceed
/// <code>maxResults</code>, this value can be used to retrieve the next page of
/// results. This value is <code>null</code> when there are no more results to
/// return.</p>
pub next_token: std::option::Option<std::string::String>,
}
impl DescribeImagesOutput {
/// <p>A list of <a>ImageDetail</a> objects that contain data about the
/// image.</p>
pub fn image_details(&self) -> std::option::Option<&[crate::model::ImageDetail]> {
self.image_details.as_deref()
}
/// <p>The <code>nextToken</code> value to include in a future <code>DescribeImages</code>
/// request. When the results of a <code>DescribeImages</code> request exceed
/// <code>maxResults</code>, this value can be used to retrieve the next page of
/// results. This value is <code>null</code> when there are no more results to
/// return.</p>
pub fn next_token(&self) -> std::option::Option<&str> {
self.next_token.as_deref()
}
}
impl std::fmt::Debug for DescribeImagesOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeImagesOutput");
formatter.field("image_details", &self.image_details);
formatter.field("next_token", &self.next_token);
formatter.finish()
}
}
/// See [`DescribeImagesOutput`](crate::output::DescribeImagesOutput)
pub mod describe_images_output {
/// A builder for [`DescribeImagesOutput`](crate::output::DescribeImagesOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) image_details: std::option::Option<std::vec::Vec<crate::model::ImageDetail>>,
pub(crate) next_token: std::option::Option<std::string::String>,
}
impl Builder {
/// Appends an item to `image_details`.
///
/// To override the contents of this collection use [`set_image_details`](Self::set_image_details).
///
/// <p>A list of <a>ImageDetail</a> objects that contain data about the
/// image.</p>
pub fn image_details(mut self, input: impl Into<crate::model::ImageDetail>) -> Self {
let mut v = self.image_details.unwrap_or_default();
v.push(input.into());
self.image_details = Some(v);
self
}
/// <p>A list of <a>ImageDetail</a> objects that contain data about the
/// image.</p>
pub fn set_image_details(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ImageDetail>>,
) -> Self {
self.image_details = input;
self
}
/// <p>The <code>nextToken</code> value to include in a future <code>DescribeImages</code>
/// request. When the results of a <code>DescribeImages</code> request exceed
/// <code>maxResults</code>, this value can be used to retrieve the next page of
/// results. This value is <code>null</code> when there are no more results to
/// return.</p>
pub fn next_token(mut self, input: impl Into<std::string::String>) -> Self {
self.next_token = Some(input.into());
self
}
/// <p>The <code>nextToken</code> value to include in a future <code>DescribeImages</code>
/// request. When the results of a <code>DescribeImages</code> request exceed
/// <code>maxResults</code>, this value can be used to retrieve the next page of
/// results. This value is <code>null</code> when there are no more results to
/// return.</p>
pub fn set_next_token(mut self, input: std::option::Option<std::string::String>) -> Self {
self.next_token = input;
self
}
/// Consumes the builder and constructs a [`DescribeImagesOutput`](crate::output::DescribeImagesOutput)
pub fn build(self) -> crate::output::DescribeImagesOutput {
crate::output::DescribeImagesOutput {
image_details: self.image_details,
next_token: self.next_token,
}
}
}
}
impl DescribeImagesOutput {
/// Creates a new builder-style object to manufacture [`DescribeImagesOutput`](crate::output::DescribeImagesOutput)
pub fn builder() -> crate::output::describe_images_output::Builder {
crate::output::describe_images_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DescribeImageReplicationStatusOutput {
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub image_id: std::option::Option<crate::model::ImageIdentifier>,
/// <p>The replication status details for the images in the specified repository.</p>
pub replication_statuses:
std::option::Option<std::vec::Vec<crate::model::ImageReplicationStatus>>,
}
impl DescribeImageReplicationStatusOutput {
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub fn image_id(&self) -> std::option::Option<&crate::model::ImageIdentifier> {
self.image_id.as_ref()
}
/// <p>The replication status details for the images in the specified repository.</p>
pub fn replication_statuses(
&self,
) -> std::option::Option<&[crate::model::ImageReplicationStatus]> {
self.replication_statuses.as_deref()
}
}
impl std::fmt::Debug for DescribeImageReplicationStatusOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DescribeImageReplicationStatusOutput");
formatter.field("repository_name", &self.repository_name);
formatter.field("image_id", &self.image_id);
formatter.field("replication_statuses", &self.replication_statuses);
formatter.finish()
}
}
/// See [`DescribeImageReplicationStatusOutput`](crate::output::DescribeImageReplicationStatusOutput)
pub mod describe_image_replication_status_output {
/// A builder for [`DescribeImageReplicationStatusOutput`](crate::output::DescribeImageReplicationStatusOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) image_id: std::option::Option<crate::model::ImageIdentifier>,
pub(crate) replication_statuses:
std::option::Option<std::vec::Vec<crate::model::ImageReplicationStatus>>,
}
impl Builder {
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub fn image_id(mut self, input: crate::model::ImageIdentifier) -> Self {
self.image_id = Some(input);
self
}
/// <p>An object with identifying information for an image in an Amazon ECR repository.</p>
pub fn set_image_id(
mut self,
input: std::option::Option<crate::model::ImageIdentifier>,
) -> Self {
self.image_id = input;
self
}
/// Appends an item to `replication_statuses`.
///
/// To override the contents of this collection use [`set_replication_statuses`](Self::set_replication_statuses).
///
/// <p>The replication status details for the images in the specified repository.</p>
pub fn replication_statuses(
mut self,
input: impl Into<crate::model::ImageReplicationStatus>,
) -> Self {
let mut v = self.replication_statuses.unwrap_or_default();
v.push(input.into());
self.replication_statuses = Some(v);
self
}
/// <p>The replication status details for the images in the specified repository.</p>
pub fn set_replication_statuses(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ImageReplicationStatus>>,
) -> Self {
self.replication_statuses = input;
self
}
/// Consumes the builder and constructs a [`DescribeImageReplicationStatusOutput`](crate::output::DescribeImageReplicationStatusOutput)
pub fn build(self) -> crate::output::DescribeImageReplicationStatusOutput {
crate::output::DescribeImageReplicationStatusOutput {
repository_name: self.repository_name,
image_id: self.image_id,
replication_statuses: self.replication_statuses,
}
}
}
}
impl DescribeImageReplicationStatusOutput {
/// Creates a new builder-style object to manufacture [`DescribeImageReplicationStatusOutput`](crate::output::DescribeImageReplicationStatusOutput)
pub fn builder() -> crate::output::describe_image_replication_status_output::Builder {
crate::output::describe_image_replication_status_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeleteRepositoryPolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The JSON repository policy that was deleted from the repository.</p>
pub policy_text: std::option::Option<std::string::String>,
}
impl DeleteRepositoryPolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The JSON repository policy that was deleted from the repository.</p>
pub fn policy_text(&self) -> std::option::Option<&str> {
self.policy_text.as_deref()
}
}
impl std::fmt::Debug for DeleteRepositoryPolicyOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeleteRepositoryPolicyOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("policy_text", &self.policy_text);
formatter.finish()
}
}
/// See [`DeleteRepositoryPolicyOutput`](crate::output::DeleteRepositoryPolicyOutput)
pub mod delete_repository_policy_output {
/// A builder for [`DeleteRepositoryPolicyOutput`](crate::output::DeleteRepositoryPolicyOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) policy_text: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The JSON repository policy that was deleted from the repository.</p>
pub fn policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.policy_text = Some(input.into());
self
}
/// <p>The JSON repository policy that was deleted from the repository.</p>
pub fn set_policy_text(mut self, input: std::option::Option<std::string::String>) -> Self {
self.policy_text = input;
self
}
/// Consumes the builder and constructs a [`DeleteRepositoryPolicyOutput`](crate::output::DeleteRepositoryPolicyOutput)
pub fn build(self) -> crate::output::DeleteRepositoryPolicyOutput {
crate::output::DeleteRepositoryPolicyOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
policy_text: self.policy_text,
}
}
}
}
impl DeleteRepositoryPolicyOutput {
/// Creates a new builder-style object to manufacture [`DeleteRepositoryPolicyOutput`](crate::output::DeleteRepositoryPolicyOutput)
pub fn builder() -> crate::output::delete_repository_policy_output::Builder {
crate::output::delete_repository_policy_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeleteRepositoryOutput {
/// <p>The repository that was deleted.</p>
pub repository: std::option::Option<crate::model::Repository>,
}
impl DeleteRepositoryOutput {
/// <p>The repository that was deleted.</p>
pub fn repository(&self) -> std::option::Option<&crate::model::Repository> {
self.repository.as_ref()
}
}
impl std::fmt::Debug for DeleteRepositoryOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeleteRepositoryOutput");
formatter.field("repository", &self.repository);
formatter.finish()
}
}
/// See [`DeleteRepositoryOutput`](crate::output::DeleteRepositoryOutput)
pub mod delete_repository_output {
/// A builder for [`DeleteRepositoryOutput`](crate::output::DeleteRepositoryOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) repository: std::option::Option<crate::model::Repository>,
}
impl Builder {
/// <p>The repository that was deleted.</p>
pub fn repository(mut self, input: crate::model::Repository) -> Self {
self.repository = Some(input);
self
}
/// <p>The repository that was deleted.</p>
pub fn set_repository(
mut self,
input: std::option::Option<crate::model::Repository>,
) -> Self {
self.repository = input;
self
}
/// Consumes the builder and constructs a [`DeleteRepositoryOutput`](crate::output::DeleteRepositoryOutput)
pub fn build(self) -> crate::output::DeleteRepositoryOutput {
crate::output::DeleteRepositoryOutput {
repository: self.repository,
}
}
}
}
impl DeleteRepositoryOutput {
/// Creates a new builder-style object to manufacture [`DeleteRepositoryOutput`](crate::output::DeleteRepositoryOutput)
pub fn builder() -> crate::output::delete_repository_output::Builder {
crate::output::delete_repository_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeleteRegistryPolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The contents of the registry permissions policy that was deleted.</p>
pub policy_text: std::option::Option<std::string::String>,
}
impl DeleteRegistryPolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The contents of the registry permissions policy that was deleted.</p>
pub fn policy_text(&self) -> std::option::Option<&str> {
self.policy_text.as_deref()
}
}
impl std::fmt::Debug for DeleteRegistryPolicyOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeleteRegistryPolicyOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("policy_text", &self.policy_text);
formatter.finish()
}
}
/// See [`DeleteRegistryPolicyOutput`](crate::output::DeleteRegistryPolicyOutput)
pub mod delete_registry_policy_output {
/// A builder for [`DeleteRegistryPolicyOutput`](crate::output::DeleteRegistryPolicyOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) policy_text: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The contents of the registry permissions policy that was deleted.</p>
pub fn policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.policy_text = Some(input.into());
self
}
/// <p>The contents of the registry permissions policy that was deleted.</p>
pub fn set_policy_text(mut self, input: std::option::Option<std::string::String>) -> Self {
self.policy_text = input;
self
}
/// Consumes the builder and constructs a [`DeleteRegistryPolicyOutput`](crate::output::DeleteRegistryPolicyOutput)
pub fn build(self) -> crate::output::DeleteRegistryPolicyOutput {
crate::output::DeleteRegistryPolicyOutput {
registry_id: self.registry_id,
policy_text: self.policy_text,
}
}
}
}
impl DeleteRegistryPolicyOutput {
/// Creates a new builder-style object to manufacture [`DeleteRegistryPolicyOutput`](crate::output::DeleteRegistryPolicyOutput)
pub fn builder() -> crate::output::delete_registry_policy_output::Builder {
crate::output::delete_registry_policy_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct DeleteLifecyclePolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The JSON lifecycle policy text.</p>
pub lifecycle_policy_text: std::option::Option<std::string::String>,
/// <p>The time stamp of the last time that the lifecycle policy was run.</p>
pub last_evaluated_at: std::option::Option<aws_smithy_types::DateTime>,
}
impl DeleteLifecyclePolicyOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The JSON lifecycle policy text.</p>
pub fn lifecycle_policy_text(&self) -> std::option::Option<&str> {
self.lifecycle_policy_text.as_deref()
}
/// <p>The time stamp of the last time that the lifecycle policy was run.</p>
pub fn last_evaluated_at(&self) -> std::option::Option<&aws_smithy_types::DateTime> {
self.last_evaluated_at.as_ref()
}
}
impl std::fmt::Debug for DeleteLifecyclePolicyOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("DeleteLifecyclePolicyOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("lifecycle_policy_text", &self.lifecycle_policy_text);
formatter.field("last_evaluated_at", &self.last_evaluated_at);
formatter.finish()
}
}
/// See [`DeleteLifecyclePolicyOutput`](crate::output::DeleteLifecyclePolicyOutput)
pub mod delete_lifecycle_policy_output {
/// A builder for [`DeleteLifecyclePolicyOutput`](crate::output::DeleteLifecyclePolicyOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) lifecycle_policy_text: std::option::Option<std::string::String>,
pub(crate) last_evaluated_at: std::option::Option<aws_smithy_types::DateTime>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The JSON lifecycle policy text.</p>
pub fn lifecycle_policy_text(mut self, input: impl Into<std::string::String>) -> Self {
self.lifecycle_policy_text = Some(input.into());
self
}
/// <p>The JSON lifecycle policy text.</p>
pub fn set_lifecycle_policy_text(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.lifecycle_policy_text = input;
self
}
/// <p>The time stamp of the last time that the lifecycle policy was run.</p>
pub fn last_evaluated_at(mut self, input: aws_smithy_types::DateTime) -> Self {
self.last_evaluated_at = Some(input);
self
}
/// <p>The time stamp of the last time that the lifecycle policy was run.</p>
pub fn set_last_evaluated_at(
mut self,
input: std::option::Option<aws_smithy_types::DateTime>,
) -> Self {
self.last_evaluated_at = input;
self
}
/// Consumes the builder and constructs a [`DeleteLifecyclePolicyOutput`](crate::output::DeleteLifecyclePolicyOutput)
pub fn build(self) -> crate::output::DeleteLifecyclePolicyOutput {
crate::output::DeleteLifecyclePolicyOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
lifecycle_policy_text: self.lifecycle_policy_text,
last_evaluated_at: self.last_evaluated_at,
}
}
}
}
impl DeleteLifecyclePolicyOutput {
/// Creates a new builder-style object to manufacture [`DeleteLifecyclePolicyOutput`](crate::output::DeleteLifecyclePolicyOutput)
pub fn builder() -> crate::output::delete_lifecycle_policy_output::Builder {
crate::output::delete_lifecycle_policy_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CreateRepositoryOutput {
/// <p>The repository that was created.</p>
pub repository: std::option::Option<crate::model::Repository>,
}
impl CreateRepositoryOutput {
/// <p>The repository that was created.</p>
pub fn repository(&self) -> std::option::Option<&crate::model::Repository> {
self.repository.as_ref()
}
}
impl std::fmt::Debug for CreateRepositoryOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CreateRepositoryOutput");
formatter.field("repository", &self.repository);
formatter.finish()
}
}
/// See [`CreateRepositoryOutput`](crate::output::CreateRepositoryOutput)
pub mod create_repository_output {
/// A builder for [`CreateRepositoryOutput`](crate::output::CreateRepositoryOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) repository: std::option::Option<crate::model::Repository>,
}
impl Builder {
/// <p>The repository that was created.</p>
pub fn repository(mut self, input: crate::model::Repository) -> Self {
self.repository = Some(input);
self
}
/// <p>The repository that was created.</p>
pub fn set_repository(
mut self,
input: std::option::Option<crate::model::Repository>,
) -> Self {
self.repository = input;
self
}
/// Consumes the builder and constructs a [`CreateRepositoryOutput`](crate::output::CreateRepositoryOutput)
pub fn build(self) -> crate::output::CreateRepositoryOutput {
crate::output::CreateRepositoryOutput {
repository: self.repository,
}
}
}
}
impl CreateRepositoryOutput {
/// Creates a new builder-style object to manufacture [`CreateRepositoryOutput`](crate::output::CreateRepositoryOutput)
pub fn builder() -> crate::output::create_repository_output::Builder {
crate::output::create_repository_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct CompleteLayerUploadOutput {
/// <p>The registry ID associated with the request.</p>
pub registry_id: std::option::Option<std::string::String>,
/// <p>The repository name associated with the request.</p>
pub repository_name: std::option::Option<std::string::String>,
/// <p>The upload ID associated with the layer.</p>
pub upload_id: std::option::Option<std::string::String>,
/// <p>The <code>sha256</code> digest of the image layer.</p>
pub layer_digest: std::option::Option<std::string::String>,
}
impl CompleteLayerUploadOutput {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(&self) -> std::option::Option<&str> {
self.registry_id.as_deref()
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(&self) -> std::option::Option<&str> {
self.repository_name.as_deref()
}
/// <p>The upload ID associated with the layer.</p>
pub fn upload_id(&self) -> std::option::Option<&str> {
self.upload_id.as_deref()
}
/// <p>The <code>sha256</code> digest of the image layer.</p>
pub fn layer_digest(&self) -> std::option::Option<&str> {
self.layer_digest.as_deref()
}
}
impl std::fmt::Debug for CompleteLayerUploadOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("CompleteLayerUploadOutput");
formatter.field("registry_id", &self.registry_id);
formatter.field("repository_name", &self.repository_name);
formatter.field("upload_id", &self.upload_id);
formatter.field("layer_digest", &self.layer_digest);
formatter.finish()
}
}
/// See [`CompleteLayerUploadOutput`](crate::output::CompleteLayerUploadOutput)
pub mod complete_layer_upload_output {
/// A builder for [`CompleteLayerUploadOutput`](crate::output::CompleteLayerUploadOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) registry_id: std::option::Option<std::string::String>,
pub(crate) repository_name: std::option::Option<std::string::String>,
pub(crate) upload_id: std::option::Option<std::string::String>,
pub(crate) layer_digest: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>The registry ID associated with the request.</p>
pub fn registry_id(mut self, input: impl Into<std::string::String>) -> Self {
self.registry_id = Some(input.into());
self
}
/// <p>The registry ID associated with the request.</p>
pub fn set_registry_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.registry_id = input;
self
}
/// <p>The repository name associated with the request.</p>
pub fn repository_name(mut self, input: impl Into<std::string::String>) -> Self {
self.repository_name = Some(input.into());
self
}
/// <p>The repository name associated with the request.</p>
pub fn set_repository_name(
mut self,
input: std::option::Option<std::string::String>,
) -> Self {
self.repository_name = input;
self
}
/// <p>The upload ID associated with the layer.</p>
pub fn upload_id(mut self, input: impl Into<std::string::String>) -> Self {
self.upload_id = Some(input.into());
self
}
/// <p>The upload ID associated with the layer.</p>
pub fn set_upload_id(mut self, input: std::option::Option<std::string::String>) -> Self {
self.upload_id = input;
self
}
/// <p>The <code>sha256</code> digest of the image layer.</p>
pub fn layer_digest(mut self, input: impl Into<std::string::String>) -> Self {
self.layer_digest = Some(input.into());
self
}
/// <p>The <code>sha256</code> digest of the image layer.</p>
pub fn set_layer_digest(mut self, input: std::option::Option<std::string::String>) -> Self {
self.layer_digest = input;
self
}
/// Consumes the builder and constructs a [`CompleteLayerUploadOutput`](crate::output::CompleteLayerUploadOutput)
pub fn build(self) -> crate::output::CompleteLayerUploadOutput {
crate::output::CompleteLayerUploadOutput {
registry_id: self.registry_id,
repository_name: self.repository_name,
upload_id: self.upload_id,
layer_digest: self.layer_digest,
}
}
}
}
impl CompleteLayerUploadOutput {
/// Creates a new builder-style object to manufacture [`CompleteLayerUploadOutput`](crate::output::CompleteLayerUploadOutput)
pub fn builder() -> crate::output::complete_layer_upload_output::Builder {
crate::output::complete_layer_upload_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct BatchGetImageOutput {
/// <p>A list of image objects corresponding to the image references in the request.</p>
pub images: std::option::Option<std::vec::Vec<crate::model::Image>>,
/// <p>Any failures associated with the call.</p>
pub failures: std::option::Option<std::vec::Vec<crate::model::ImageFailure>>,
}
impl BatchGetImageOutput {
/// <p>A list of image objects corresponding to the image references in the request.</p>
pub fn images(&self) -> std::option::Option<&[crate::model::Image]> {
self.images.as_deref()
}
/// <p>Any failures associated with the call.</p>
pub fn failures(&self) -> std::option::Option<&[crate::model::ImageFailure]> {
self.failures.as_deref()
}
}
impl std::fmt::Debug for BatchGetImageOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("BatchGetImageOutput");
formatter.field("images", &self.images);
formatter.field("failures", &self.failures);
formatter.finish()
}
}
/// See [`BatchGetImageOutput`](crate::output::BatchGetImageOutput)
pub mod batch_get_image_output {
/// A builder for [`BatchGetImageOutput`](crate::output::BatchGetImageOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) images: std::option::Option<std::vec::Vec<crate::model::Image>>,
pub(crate) failures: std::option::Option<std::vec::Vec<crate::model::ImageFailure>>,
}
impl Builder {
/// Appends an item to `images`.
///
/// To override the contents of this collection use [`set_images`](Self::set_images).
///
/// <p>A list of image objects corresponding to the image references in the request.</p>
pub fn images(mut self, input: impl Into<crate::model::Image>) -> Self {
let mut v = self.images.unwrap_or_default();
v.push(input.into());
self.images = Some(v);
self
}
/// <p>A list of image objects corresponding to the image references in the request.</p>
pub fn set_images(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Image>>,
) -> Self {
self.images = input;
self
}
/// Appends an item to `failures`.
///
/// To override the contents of this collection use [`set_failures`](Self::set_failures).
///
/// <p>Any failures associated with the call.</p>
pub fn failures(mut self, input: impl Into<crate::model::ImageFailure>) -> Self {
let mut v = self.failures.unwrap_or_default();
v.push(input.into());
self.failures = Some(v);
self
}
/// <p>Any failures associated with the call.</p>
pub fn set_failures(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ImageFailure>>,
) -> Self {
self.failures = input;
self
}
/// Consumes the builder and constructs a [`BatchGetImageOutput`](crate::output::BatchGetImageOutput)
pub fn build(self) -> crate::output::BatchGetImageOutput {
crate::output::BatchGetImageOutput {
images: self.images,
failures: self.failures,
}
}
}
}
impl BatchGetImageOutput {
/// Creates a new builder-style object to manufacture [`BatchGetImageOutput`](crate::output::BatchGetImageOutput)
pub fn builder() -> crate::output::batch_get_image_output::Builder {
crate::output::batch_get_image_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct BatchDeleteImageOutput {
/// <p>The image IDs of the deleted images.</p>
pub image_ids: std::option::Option<std::vec::Vec<crate::model::ImageIdentifier>>,
/// <p>Any failures associated with the call.</p>
pub failures: std::option::Option<std::vec::Vec<crate::model::ImageFailure>>,
}
impl BatchDeleteImageOutput {
/// <p>The image IDs of the deleted images.</p>
pub fn image_ids(&self) -> std::option::Option<&[crate::model::ImageIdentifier]> {
self.image_ids.as_deref()
}
/// <p>Any failures associated with the call.</p>
pub fn failures(&self) -> std::option::Option<&[crate::model::ImageFailure]> {
self.failures.as_deref()
}
}
impl std::fmt::Debug for BatchDeleteImageOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("BatchDeleteImageOutput");
formatter.field("image_ids", &self.image_ids);
formatter.field("failures", &self.failures);
formatter.finish()
}
}
/// See [`BatchDeleteImageOutput`](crate::output::BatchDeleteImageOutput)
pub mod batch_delete_image_output {
/// A builder for [`BatchDeleteImageOutput`](crate::output::BatchDeleteImageOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) image_ids: std::option::Option<std::vec::Vec<crate::model::ImageIdentifier>>,
pub(crate) failures: std::option::Option<std::vec::Vec<crate::model::ImageFailure>>,
}
impl Builder {
/// Appends an item to `image_ids`.
///
/// To override the contents of this collection use [`set_image_ids`](Self::set_image_ids).
///
/// <p>The image IDs of the deleted images.</p>
pub fn image_ids(mut self, input: impl Into<crate::model::ImageIdentifier>) -> Self {
let mut v = self.image_ids.unwrap_or_default();
v.push(input.into());
self.image_ids = Some(v);
self
}
/// <p>The image IDs of the deleted images.</p>
pub fn set_image_ids(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ImageIdentifier>>,
) -> Self {
self.image_ids = input;
self
}
/// Appends an item to `failures`.
///
/// To override the contents of this collection use [`set_failures`](Self::set_failures).
///
/// <p>Any failures associated with the call.</p>
pub fn failures(mut self, input: impl Into<crate::model::ImageFailure>) -> Self {
let mut v = self.failures.unwrap_or_default();
v.push(input.into());
self.failures = Some(v);
self
}
/// <p>Any failures associated with the call.</p>
pub fn set_failures(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::ImageFailure>>,
) -> Self {
self.failures = input;
self
}
/// Consumes the builder and constructs a [`BatchDeleteImageOutput`](crate::output::BatchDeleteImageOutput)
pub fn build(self) -> crate::output::BatchDeleteImageOutput {
crate::output::BatchDeleteImageOutput {
image_ids: self.image_ids,
failures: self.failures,
}
}
}
}
impl BatchDeleteImageOutput {
/// Creates a new builder-style object to manufacture [`BatchDeleteImageOutput`](crate::output::BatchDeleteImageOutput)
pub fn builder() -> crate::output::batch_delete_image_output::Builder {
crate::output::batch_delete_image_output::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct BatchCheckLayerAvailabilityOutput {
/// <p>A list of image layer objects corresponding to the image layer references in the
/// request.</p>
pub layers: std::option::Option<std::vec::Vec<crate::model::Layer>>,
/// <p>Any failures associated with the call.</p>
pub failures: std::option::Option<std::vec::Vec<crate::model::LayerFailure>>,
}
impl BatchCheckLayerAvailabilityOutput {
/// <p>A list of image layer objects corresponding to the image layer references in the
/// request.</p>
pub fn layers(&self) -> std::option::Option<&[crate::model::Layer]> {
self.layers.as_deref()
}
/// <p>Any failures associated with the call.</p>
pub fn failures(&self) -> std::option::Option<&[crate::model::LayerFailure]> {
self.failures.as_deref()
}
}
impl std::fmt::Debug for BatchCheckLayerAvailabilityOutput {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("BatchCheckLayerAvailabilityOutput");
formatter.field("layers", &self.layers);
formatter.field("failures", &self.failures);
formatter.finish()
}
}
/// See [`BatchCheckLayerAvailabilityOutput`](crate::output::BatchCheckLayerAvailabilityOutput)
pub mod batch_check_layer_availability_output {
/// A builder for [`BatchCheckLayerAvailabilityOutput`](crate::output::BatchCheckLayerAvailabilityOutput)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) layers: std::option::Option<std::vec::Vec<crate::model::Layer>>,
pub(crate) failures: std::option::Option<std::vec::Vec<crate::model::LayerFailure>>,
}
impl Builder {
/// Appends an item to `layers`.
///
/// To override the contents of this collection use [`set_layers`](Self::set_layers).
///
/// <p>A list of image layer objects corresponding to the image layer references in the
/// request.</p>
pub fn layers(mut self, input: impl Into<crate::model::Layer>) -> Self {
let mut v = self.layers.unwrap_or_default();
v.push(input.into());
self.layers = Some(v);
self
}
/// <p>A list of image layer objects corresponding to the image layer references in the
/// request.</p>
pub fn set_layers(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::Layer>>,
) -> Self {
self.layers = input;
self
}
/// Appends an item to `failures`.
///
/// To override the contents of this collection use [`set_failures`](Self::set_failures).
///
/// <p>Any failures associated with the call.</p>
pub fn failures(mut self, input: impl Into<crate::model::LayerFailure>) -> Self {
let mut v = self.failures.unwrap_or_default();
v.push(input.into());
self.failures = Some(v);
self
}
/// <p>Any failures associated with the call.</p>
pub fn set_failures(
mut self,
input: std::option::Option<std::vec::Vec<crate::model::LayerFailure>>,
) -> Self {
self.failures = input;
self
}
/// Consumes the builder and constructs a [`BatchCheckLayerAvailabilityOutput`](crate::output::BatchCheckLayerAvailabilityOutput)
pub fn build(self) -> crate::output::BatchCheckLayerAvailabilityOutput {
crate::output::BatchCheckLayerAvailabilityOutput {
layers: self.layers,
failures: self.failures,
}
}
}
}
impl BatchCheckLayerAvailabilityOutput {
/// Creates a new builder-style object to manufacture [`BatchCheckLayerAvailabilityOutput`](crate::output::BatchCheckLayerAvailabilityOutput)
pub fn builder() -> crate::output::batch_check_layer_availability_output::Builder {
crate::output::batch_check_layer_availability_output::Builder::default()
}
}
| 45.905759
| 151
| 0.640511
|
23c30a2fd65acf3a01d83a7bf2a398a24c9a1f40
| 351
|
js
|
JavaScript
|
src/js/socket-io/server.js
|
moyea/front-end-experience
|
0593154481408a7c43a28838ffed5ae607404bee
|
[
"MIT"
] | 1
|
2016-05-17T11:32:23.000Z
|
2016-05-17T11:32:23.000Z
|
src/js/socket-io/server.js
|
librey/front-end-experience
|
0593154481408a7c43a28838ffed5ae607404bee
|
[
"MIT"
] | null | null | null |
src/js/socket-io/server.js
|
librey/front-end-experience
|
0593154481408a7c43a28838ffed5ae607404bee
|
[
"MIT"
] | null | null | null |
var server = require('http').createServer();
var io = require('socket.io')(server);
io.on('connection', function (socket) {
socket.on('event', function (data) {
});
socket.on('disconnect', function () {
});
});
server.listen(3000);
io.clients(function (error,clients) {
if(error) throw error;
console.log(clients);
});
| 15.954545
| 44
| 0.615385
|
33f2f92429df015b5f9fc852ffc86a752250b497
| 12,502
|
h
|
C
|
include/click/libdivide.h
|
MacWR/Click-changed-for-ParaGraph
|
18285e5da578fbb7285d10380836146e738dee6e
|
[
"Apache-2.0"
] | 32
|
2017-11-02T12:33:21.000Z
|
2022-02-07T22:25:58.000Z
|
include/click/libdivide.h
|
MacWR/Click-changed-for-ParaGraph
|
18285e5da578fbb7285d10380836146e738dee6e
|
[
"Apache-2.0"
] | 2
|
2019-02-18T08:47:16.000Z
|
2019-05-24T14:41:23.000Z
|
include/click/libdivide.h
|
MacWR/Click-changed-for-ParaGraph
|
18285e5da578fbb7285d10380836146e738dee6e
|
[
"Apache-2.0"
] | 10
|
2018-06-13T11:54:53.000Z
|
2020-09-08T06:52:43.000Z
|
// libdivide.h
// Copyright 2010 - 2016 ridiculous_fish
/*
libdivide
Copyright (C) 2010 ridiculous_fish
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
libdivide@ridiculousfish.com
*/
/* modified from https://github.com/ridiculousfish/libdivide for click */
#ifndef CLICK_LIBDIVIDE_H
#define CLICK_LIBDIVIDE_H
#include <click/glue.hh>
#include <click/integers.hh>
CLICK_DECLS
#ifndef __has_builtin
#define __has_builtin(x) 0 // Compatibility with non-clang compilers.
#endif
#if defined(__SIZEOF_INT128__)
#define HAS_INT128_T 1
#endif
#if defined(__x86_64__) || defined(_WIN64) || defined(_M_X64)
#define LIBDIVIDE_IS_X86_64 1
#endif
#if defined(__i386__)
#define LIBDIVIDE_IS_i386 1
#endif
#if __GNUC__ || __clang__
#define LIBDIVIDE_GCC_STYLE_ASM 1
#endif
#define LIBDIVIDE_ASSERT(x) assert(x)
// Explanation of "more" field: bit 6 is whether to use shift path. If we are
// using the shift path, bit 7 is whether the divisor is negative in the signed
// case; in the unsigned case it is 0. Bits 0-4 is shift value (for shift
// path or mult path). In 32 bit case, bit 5 is always 0. We use bit 7 as the
// "negative divisor indicator" so that we can use sign extension to
// efficiently go to a full-width -1.
//
// u32: [0-4] shift value
// [5] ignored
// [6] add indicator
// [7] shift path
//
// s32: [0-4] shift value
// [5] shift path
// [6] add indicator
// [7] indicates negative divisor
//
// u64: [0-5] shift value
// [6] add indicator
// [7] shift path
//
// s64: [0-5] shift value
// [6] add indicator
// [7] indicates negative divisor
// magic number of 0 indicates shift path (we ran out of bits!)
//
// In s32 and s64 branchfree modes, the magic number is negated according to
// whether the divisor is negated. In branchfree strategy, it is not negated.
enum {
LIBDIVIDE_32_SHIFT_MASK = 0x1F,
LIBDIVIDE_64_SHIFT_MASK = 0x3F,
LIBDIVIDE_ADD_MARKER = 0x40,
LIBDIVIDE_U32_SHIFT_PATH = 0x80,
LIBDIVIDE_U64_SHIFT_PATH = 0x80,
LIBDIVIDE_S32_SHIFT_PATH = 0x20,
LIBDIVIDE_NEGATIVE_DIVISOR = 0x80
};
struct libdivide_u32_t {
uint32_t magic;
uint8_t more;
};
struct libdivide_u32_branchfree_t {
uint32_t magic;
uint8_t more;
};
#ifndef LIBDIVIDE_API
#define LIBDIVIDE_API static inline
#endif
LIBDIVIDE_API struct libdivide_u32_t libdivide_u32_gen(uint32_t y);
LIBDIVIDE_API struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t y);
LIBDIVIDE_API uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom);
LIBDIVIDE_API uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom);
LIBDIVIDE_API uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom);
LIBDIVIDE_API uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom);
LIBDIVIDE_API int libdivide_u32_get_algorithm(const struct libdivide_u32_t *denom);
LIBDIVIDE_API uint32_t libdivide_u32_do_alg0(uint32_t numer, const struct libdivide_u32_t *denom);
LIBDIVIDE_API uint32_t libdivide_u32_do_alg1(uint32_t numer, const struct libdivide_u32_t *denom);
LIBDIVIDE_API uint32_t libdivide_u32_do_alg2(uint32_t numer, const struct libdivide_u32_t *denom);
//////// Internal Utility Functions
static inline uint32_t libdivide__mullhi_u32(uint32_t x, uint32_t y) {
uint64_t xl = x, yl = y;
uint64_t rl = xl * yl;
return (uint32_t)(rl >> 32);
}
static inline int32_t libdivide__count_leading_zeros32(uint32_t val) {
#if __GNUC__ || __has_builtin(__builtin_clz)
// Fast way to count leading zeros
return __builtin_clz(val);
#else
int32_t result = 0;
uint32_t hi = 1U << 31;
while (~val & hi) {
hi >>= 1;
result++;
}
return result;
#endif
}
static inline int32_t libdivide__count_leading_zeros64(uint64_t val) {
#if __GNUC__ || __has_builtin(__builtin_clzll)
// Fast way to count leading zeros
return __builtin_clzll(val);
#else
uint32_t hi = val >> 32;
uint32_t lo = val & 0xFFFFFFFF;
if (hi != 0) return libdivide__count_leading_zeros32(hi);
return 32 + libdivide__count_leading_zeros32(lo);
#endif
}
// libdivide_64_div_32_to_32: divides a 64 bit uint {u1, u0} by a 32 bit
// uint {v}. The result must fit in 32 bits.
// Returns the quotient directly and the remainder in *r
#if (LIBDIVIDE_IS_i386 || LIBDIVIDE_IS_X86_64) && LIBDIVIDE_GCC_STYLE_ASM
static uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, uint32_t *r) {
uint32_t result;
__asm__("divl %[v]"
: "=a"(result), "=d"(*r)
: [v] "r"(v), "a"(u0), "d"(u1)
);
return result;
}
#else
static uint32_t libdivide_64_div_32_to_32(uint32_t u1, uint32_t u0, uint32_t v, uint32_t *r) {
uint64_t n = (((uint64_t)u1) << 32) | u0;
uint32_t result = (uint32_t)int_divide(n, v);
*r = (uint32_t)(n - result * (uint64_t)v);
return result;
}
#endif
////////// UINT32
static inline struct libdivide_u32_t libdivide_internal_u32_gen(uint32_t d, int branchfree) {
// 1 is not supported with branchfree algorithm
LIBDIVIDE_ASSERT(!branchfree || d != 1);
struct libdivide_u32_t result;
const uint32_t floor_log_2_d = 31 - libdivide__count_leading_zeros32(d);
if ((d & (d - 1)) == 0) {
// Power of 2
if (! branchfree) {
result.magic = 0;
result.more = floor_log_2_d | LIBDIVIDE_U32_SHIFT_PATH;
} else {
// We want a magic number of 2**32 and a shift of floor_log_2_d
// but one of the shifts is taken up by LIBDIVIDE_ADD_MARKER, so we
// subtract 1 from the shift
result.magic = 0;
result.more = (floor_log_2_d-1) | LIBDIVIDE_ADD_MARKER;
}
} else {
uint8_t more;
uint32_t rem, proposed_m;
proposed_m = libdivide_64_div_32_to_32(1U << floor_log_2_d, 0, d, &rem);
LIBDIVIDE_ASSERT(rem > 0 && rem < d);
const uint32_t e = d - rem;
// This power works if e < 2**floor_log_2_d.
if (!branchfree && (e < (1U << floor_log_2_d))) {
// This power works
more = floor_log_2_d;
} else {
// We have to use the general 33-bit algorithm. We need to compute
// (2**power) / d. However, we already have (2**(power-1))/d and
// its remainder. By doubling both, and then correcting the
// remainder, we can compute the larger division.
// don't care about overflow here - in fact, we expect it
proposed_m += proposed_m;
const uint32_t twice_rem = rem + rem;
if (twice_rem >= d || twice_rem < rem) proposed_m += 1;
more = floor_log_2_d | LIBDIVIDE_ADD_MARKER;
}
result.magic = 1 + proposed_m;
result.more = more;
// result.more's shift should in general be ceil_log_2_d. But if we
// used the smaller power, we subtract one from the shift because we're
// using the smaller power. If we're using the larger power, we
// subtract one from the shift because it's taken care of by the add
// indicator. So floor_log_2_d happens to be correct in both cases.
}
return result;
}
struct libdivide_u32_t libdivide_u32_gen(uint32_t d) {
return libdivide_internal_u32_gen(d, 0);
}
struct libdivide_u32_branchfree_t libdivide_u32_branchfree_gen(uint32_t d) {
struct libdivide_u32_t tmp = libdivide_internal_u32_gen(d, 1);
struct libdivide_u32_branchfree_t ret = {tmp.magic, (uint8_t)(tmp.more & LIBDIVIDE_32_SHIFT_MASK)};
return ret;
}
uint32_t libdivide_u32_do(uint32_t numer, const struct libdivide_u32_t *denom) {
uint8_t more = denom->more;
if (more & LIBDIVIDE_U32_SHIFT_PATH) {
return numer >> (more & LIBDIVIDE_32_SHIFT_MASK);
}
else {
uint32_t q = libdivide__mullhi_u32(denom->magic, numer);
if (more & LIBDIVIDE_ADD_MARKER) {
uint32_t t = ((numer - q) >> 1) + q;
return t >> (more & LIBDIVIDE_32_SHIFT_MASK);
}
else {
return q >> more; // all upper bits are 0 - don't need to mask them off
}
}
}
uint32_t libdivide_u32_recover(const struct libdivide_u32_t *denom) {
uint8_t more = denom->more;
uint8_t shift = more & LIBDIVIDE_32_SHIFT_MASK;
if (more & LIBDIVIDE_U32_SHIFT_PATH) {
return 1U << shift;
} else if (! (more & LIBDIVIDE_ADD_MARKER)) {
// We compute q = n/d = n*m / 2^(32 + shift)
// Therefore we have d = 2^(32 + shift) / m
// We need to ceil it.
// We know d is not a power of 2, so m is not a power of 2,
// so we can just add 1 to the floor
uint32_t hi_dividend = 1U << shift;
uint32_t rem_ignored;
return 1 + libdivide_64_div_32_to_32(hi_dividend, 0, denom->magic, &rem_ignored);
} else {
// Here we wish to compute d = 2^(32+shift+1)/(m+2^32).
// Notice (m + 2^32) is a 33 bit number. Use 64 bit division for now
// Also note that shift may be as high as 31, so shift + 1 will
// overflow. So we have to compute it as 2^(32+shift)/(m+2^32), and
// then double the quotient and remainder.
// TODO: do something better than 64 bit math
uint64_t half_n = 1ULL << (32 + shift);
uint64_t d = (1ULL << 32) | denom->magic;
// Note that the quotient is guaranteed <= 32 bits, but the remainder
// may need 33!
uint32_t half_q = (uint32_t)int_divide(half_n, d);
uint64_t rem = half_n - half_q * d; // broken
// We computed 2^(32+shift)/(m+2^32)
// Need to double it, and then add 1 to the quotient if doubling th
// remainder would increase the quotient.
// Note that rem<<1 cannot overflow, since rem < d and d is 33 bits
uint32_t full_q = half_q + half_q + ((rem<<1) >= d);
// We rounded down in gen unless we're a power of 2 (i.e. in branchfree case)
// We can detect that by looking at m. If m zero, we're a power of 2
return full_q + (denom->magic != 0);
}
}
uint32_t libdivide_u32_branchfree_recover(const struct libdivide_u32_branchfree_t *denom) {
struct libdivide_u32_t denom_u32 = {denom->magic, (uint8_t)(denom->more | LIBDIVIDE_ADD_MARKER)};
return libdivide_u32_recover(&denom_u32);
}
int libdivide_u32_get_algorithm(const struct libdivide_u32_t *denom) {
uint8_t more = denom->more;
if (more & LIBDIVIDE_U32_SHIFT_PATH) return 0;
else if (! (more & LIBDIVIDE_ADD_MARKER)) return 1;
else return 2;
}
uint32_t libdivide_u32_do_alg0(uint32_t numer, const struct libdivide_u32_t *denom) {
return numer >> (denom->more & LIBDIVIDE_32_SHIFT_MASK);
}
uint32_t libdivide_u32_do_alg1(uint32_t numer, const struct libdivide_u32_t *denom) {
uint32_t q = libdivide__mullhi_u32(denom->magic, numer);
return q >> denom->more;
}
uint32_t libdivide_u32_do_alg2(uint32_t numer, const struct libdivide_u32_t *denom) {
// denom->add != 0
uint32_t q = libdivide__mullhi_u32(denom->magic, numer);
uint32_t t = ((numer - q) >> 1) + q;
// Note that this mask is typically free. Only the low bits are meaningful
// to a shift, so compilers can optimize out this AND.
return t >> (denom->more & LIBDIVIDE_32_SHIFT_MASK);
}
uint32_t libdivide_u32_branchfree_do(uint32_t numer, const struct libdivide_u32_branchfree_t *denom) {
// same as alg 2
uint32_t q = libdivide__mullhi_u32(denom->magic, numer);
uint32_t t = ((numer - q) >> 1) + q;
return t >> denom->more;
}
CLICK_ENDDECLS
#endif
| 36.44898
| 115
| 0.676452
|
76573c3db2cd0cc5f6f91ea52817462019bee4db
| 3,834
|
swift
|
Swift
|
CotEditor/Sources/DraggableArrayController.swift
|
GetToSet/CotEditor
|
95ccf52c22ae243f9bc9a5291062ba7cf1d298ce
|
[
"Apache-2.0"
] | 1
|
2021-12-24T02:55:33.000Z
|
2021-12-24T02:55:33.000Z
|
CotEditor/Sources/DraggableArrayController.swift
|
GetToSet/CotEditor
|
95ccf52c22ae243f9bc9a5291062ba7cf1d298ce
|
[
"Apache-2.0"
] | null | null | null |
CotEditor/Sources/DraggableArrayController.swift
|
GetToSet/CotEditor
|
95ccf52c22ae243f9bc9a5291062ba7cf1d298ce
|
[
"Apache-2.0"
] | null | null | null |
//
// DraggableArrayController.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2014-08-18.
//
// ---------------------------------------------------------------------------
//
// © 2014-2021 1024jp
//
// 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.
//
import Cocoa
final class DraggableArrayController: NSArrayController, NSTableViewDataSource {
// MARK: Table Data Source Protocol
/// start dragging
func tableView(_ tableView: NSTableView, pasteboardWriterForRow row: Int) -> NSPasteboardWriting? {
tableView.registerForDraggedTypes([.string])
let item = NSPasteboardItem()
item.setString(String(row), forType: .string)
return item
}
/// validate when dragged items come to tableView
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation {
// accept only self drag-and-drop
guard info.draggingSource as? NSTableView == tableView else { return [] }
if dropOperation == .on {
tableView.setDropRow(row, dropOperation: .above)
}
return .move
}
/// check acceptability of dragged items and insert them to table
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool {
// accept only self drag-and-drop
guard info.draggingSource as? NSTableView == tableView else { return false }
// obtain original rows from pasteboard
var sourceRows = IndexSet()
info.enumerateDraggingItems(options: .concurrent, for: tableView, classes: [NSPasteboardItem.self]) { (item, _, _) in
guard let string = (item.item as? NSPasteboardItem)?.string(forType: .string),
let row = Int(string)
else { return }
sourceRows.insert(row)
}
let draggingItems = (self.arrangedObjects as AnyObject).objects(at: sourceRows)
let destinationRow = row - sourceRows.count(in: 0...row) // real insertion point after removing items to move
let destinationRows = IndexSet(destinationRow..<(destinationRow + draggingItems.count))
// update
NSAnimationContext.runAnimationGroup({ _ in
// update UI
var sourceOffset = 0
var destinationOffset = 0
tableView.beginUpdates()
for sourceRow in sourceRows {
if sourceRow < row {
tableView.moveRow(at: sourceRow + sourceOffset, to: row - 1)
sourceOffset -= 1
} else {
tableView.moveRow(at: sourceRow, to: row + destinationOffset)
destinationOffset += 1
}
}
tableView.endUpdates()
}, completionHandler: {
// update data
self.remove(atArrangedObjectIndexes: sourceRows)
self.insert(contentsOf: draggingItems, atArrangedObjectIndexes: destinationRows)
})
return true
}
}
| 35.831776
| 186
| 0.605112
|
4da1b9e17b0fdec25bd9530508a9ffa5b16fd499
| 724
|
cs
|
C#
|
TankLib/Math/teUUID.cs
|
prophetl33t/OWLib
|
5f589c0acb43bf8178df73f2eb9f5e1a63744d76
|
[
"MIT"
] | 226
|
2017-04-28T12:40:41.000Z
|
2022-03-29T19:12:22.000Z
|
TankLib/Math/teUUID.cs
|
prophetl33t/OWLib
|
5f589c0acb43bf8178df73f2eb9f5e1a63744d76
|
[
"MIT"
] | 120
|
2017-04-29T12:11:03.000Z
|
2022-03-25T02:34:41.000Z
|
TankLib/Math/teUUID.cs
|
prophetl33t/OWLib
|
5f589c0acb43bf8178df73f2eb9f5e1a63744d76
|
[
"MIT"
] | 73
|
2017-04-30T13:22:24.000Z
|
2021-12-28T10:51:38.000Z
|
using System;
using System.Runtime.InteropServices;
namespace TankLib.Math {
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct teUUID {
public Guid Value;
public teUUID(Guid guid) {
Value = guid;
}
public static teUUID New() {
return new teUUID(Guid.NewGuid());
}
public bool Equals(teUUID other) {
return Value.Equals(other.Value);
}
public override bool Equals(object obj) {
if (obj is null) return false;
return obj is teUUID && Equals((teUUID) obj);
}
public override int GetHashCode() {
return Value.GetHashCode();
}
}
}
| 24.133333
| 57
| 0.553867
|
669bb11eed4656160ede56e476db66a37976fc2f
| 42
|
css
|
CSS
|
src/styles/vars/components/Layout/qonsoll/_layout.css
|
qonsoll/react-design
|
07d80ff4170db24830e2356287eb8994e8506aec
|
[
"MIT"
] | 3
|
2021-01-24T19:05:32.000Z
|
2021-01-25T17:27:50.000Z
|
src/styles/vars/components/Layout/qonsoll/_layout.css
|
qonsoll/react-design
|
07d80ff4170db24830e2356287eb8994e8506aec
|
[
"MIT"
] | 1
|
2022-01-28T12:50:59.000Z
|
2022-01-28T12:50:59.000Z
|
src/styles/vars/components/Layout/qonsoll/_layout.css
|
qonsoll/react-design
|
07d80ff4170db24830e2356287eb8994e8506aec
|
[
"MIT"
] | 1
|
2021-07-21T11:56:57.000Z
|
2021-07-21T11:56:57.000Z
|
:root {
--ql-layout-background: unset;
}
| 14
| 32
| 0.642857
|
d6aaf0f93ce843ff06350551908093a79d59124f
| 1,651
|
swift
|
Swift
|
Sources/XTerraPacket/Types/PacketTileEntityHatRackItemSync.swift
|
Xenoxiluna/XTerraPacket
|
61abd97c5e863bbe771e346c2bd11939e2271d1f
|
[
"MIT"
] | null | null | null |
Sources/XTerraPacket/Types/PacketTileEntityHatRackItemSync.swift
|
Xenoxiluna/XTerraPacket
|
61abd97c5e863bbe771e346c2bd11939e2271d1f
|
[
"MIT"
] | 2
|
2020-09-03T00:32:06.000Z
|
2020-09-03T00:35:47.000Z
|
Sources/XTerraPacket/Types/PacketTileEntityHatRackItemSync.swift
|
Xenoxiluna/XTerraPacket
|
61abd97c5e863bbe771e346c2bd11939e2271d1f
|
[
"MIT"
] | null | null | null |
//
// PacketTileEntityHatRackItemSync.swift
//
//
// Created by Quentin Berry on 5/22/20.
// Direction: Client <-> Server
import Foundation
import SwiftyBytes
/// Hat rack item sync
public struct PacketTileEntityHatRackItemSync: TerrariaPacket{
public var bytes: [UInt8] = []
public var length: UInt16 = 0
public var context: TerrariaPacketContext = .ServerToClient
public var packetType: TerrariaPacketType = .TileEntityHatRackItemSync
public var payload: [UInt8] = []
public var playerId: UInt8 = 0
public var tileEntityId: Int32 = 0
public var itemIndex: UInt8 = 0
public var itemId: UInt16 = 0
public var stack: UInt16 = 0
public var prefix: UInt8 = 0
public init(){}
public mutating func decodePayload() throws{
if self.payload.isEmpty{
try decodeHeader()
}
let data = BinaryData(data: self.payload)
let reader = BinaryReader(data)
self.playerId = try reader.readUInt8()
self.tileEntityId = try reader.readInt32()
self.itemIndex = try reader.readUInt8()
self.itemId = try reader.readUInt16()
self.stack = try reader.readUInt16()
self.prefix = try reader.readUInt8()
}
mutating public func encodePayload() throws{
self.resetPayload()
let writer = BinaryWriter()
try writer.writeUInt8(playerId)
try writer.writeInt32(tileEntityId)
try writer.writeUInt8(itemIndex)
try writer.writeUInt16(itemId)
try writer.writeUInt16(stack)
try writer.writeUInt8(prefix)
payload.append(contentsOf: writer.data.bytes)
}
}
| 31.75
| 74
| 0.66384
|
bf2aa2ef5eb7fb6fcf67a5cde7379b0d9f3f2005
| 886
|
dart
|
Dart
|
lib/html/input/controller_system.dart
|
KayZGames/gamejam_template
|
4b2a162776ab8b5aac7a841f46c82c00cc66f0fe
|
[
"MIT"
] | null | null | null |
lib/html/input/controller_system.dart
|
KayZGames/gamejam_template
|
4b2a162776ab8b5aac7a841f46c82c00cc66f0fe
|
[
"MIT"
] | null | null | null |
lib/html/input/controller_system.dart
|
KayZGames/gamejam_template
|
4b2a162776ab8b5aac7a841f46c82c00cc66f0fe
|
[
"MIT"
] | null | null | null |
import 'dart:html';
import 'package:dartemis/dartemis.dart';
import 'package:gamedev_helpers/gamedev_helpers.dart';
import '../../components/components.dart';
part 'controller_system.g.dart';
@Generate(
GenericInputHandlingSystem,
allOf: [
Controller,
],
)
class ControllerSystem extends _$ControllerSystem {
ControllerSystem() : super(<Element>[]);
@override
void processEntity(int entity) {
final c = controllerMapper[entity]..reset();
if (up) {
if (left) {
c.upleft = true;
} else if (right) {
c.upright = true;
} else {
c.up = true;
}
} else if (down) {
if (left) {
c.downleft = true;
} else if (right) {
c.downright = true;
} else {
c.down = true;
}
} else if (left) {
c.left = true;
} else if (right) {
c.right = true;
}
}
}
| 19.688889
| 54
| 0.565463
|
e83c6b069031e308b6fa2df46b96f6e822f4e541
| 2,478
|
cs
|
C#
|
Src/Pscx/Commands/InvokeApartmentCommand.cs
|
weloytty/Pscx
|
440990bf025483349acb998e14351e8289af1b5e
|
[
"MIT"
] | 557
|
2015-09-26T01:04:13.000Z
|
2022-03-28T20:21:15.000Z
|
Src/Pscx/Commands/InvokeApartmentCommand.cs
|
weloytty/Pscx
|
440990bf025483349acb998e14351e8289af1b5e
|
[
"MIT"
] | 70
|
2015-12-24T18:29:10.000Z
|
2022-03-22T10:57:42.000Z
|
Src/Pscx/Commands/InvokeApartmentCommand.cs
|
weloytty/Pscx
|
440990bf025483349acb998e14351e8289af1b5e
|
[
"MIT"
] | 57
|
2015-11-03T22:35:08.000Z
|
2022-02-09T13:36:32.000Z
|
using System;
using System.Management.Automation;
using System.Threading;
using System.Management.Automation.Runspaces;
using System.Collections.ObjectModel;
namespace Pscx.Commands
{
[Cmdlet(PscxVerbs.Invoke, PscxNouns.Apartment)]
[OutputType(new[]{typeof(PSObject[])})]
public sealed class InvokeApartmentCommand : PscxCmdlet
{
private ApartmentState _apartment;
private ScriptBlock _script;
private Runspace _runspace;
private Exception _exception;
private Collection<PSObject> _results;
[Parameter(Position = 0, Mandatory = true)]
[ValidateSet("MTA", "STA")]
public ApartmentState Apartment
{
get { return _apartment; }
set { _apartment = value; }
}
[Parameter(Position = 1, Mandatory = true)]
[ValidateNotNull]
public ScriptBlock Expression
{
get { return _script; }
set { _script = value; }
}
protected override void EndProcessing()
{
base.EndProcessing();
if (_apartment == Thread.CurrentThread.GetApartmentState())
{
WriteObject(_script.Invoke());
}
else
{
_runspace = Runspace.DefaultRunspace;
Thread thread = new Thread(WorkerThread);
thread.SetApartmentState(_apartment);
thread.Start();
thread.Join();
if (_exception != null)
{
IContainsErrorRecord errRecordContaier = (_exception as IContainsErrorRecord);
if (errRecordContaier != null)
{
ThrowTerminatingError(errRecordContaier.ErrorRecord);
}
else
{
ThrowTerminatingError(new ErrorRecord(_exception, _exception.GetType().Name, ErrorCategory.NotSpecified, null));
}
}
else
{
WriteObject(_results, true);
}
}
}
private void WorkerThread()
{
Runspace.DefaultRunspace = _runspace;
try
{
_results = _script.Invoke();
}
catch (Exception exc)
{
_exception = exc;
}
}
}
}
| 27.842697
| 136
| 0.510896
|
7b1970dc91e02fb65c97f2da2f34a31f05307d2c
| 1,005
|
ps1
|
PowerShell
|
smlets-98120/Main/Source/SMLets/SMLets/Test/get-IncidentPriority.ps1
|
veharshv/smlets
|
11a63af8535ff88740c3c0ce30639ae78cc43146
|
[
"MS-PL"
] | 16
|
2017-06-06T06:35:46.000Z
|
2022-03-12T02:43:40.000Z
|
smlets-98120/Main/Source/SMLets/SMLets/Test/get-IncidentPriority.ps1
|
veharshv/smlets
|
11a63af8535ff88740c3c0ce30639ae78cc43146
|
[
"MS-PL"
] | 17
|
2017-05-18T14:30:55.000Z
|
2022-03-14T07:54:31.000Z
|
smlets-98120/Main/Source/SMLets/SMLets/Test/get-IncidentPriority.ps1
|
veharshv/smlets
|
11a63af8535ff88740c3c0ce30639ae78cc43146
|
[
"MS-PL"
] | 10
|
2017-06-12T14:23:38.000Z
|
2021-11-03T09:13:53.000Z
|
$PriorityData = (get-scsmobject System.WorkItem.Incident.GeneralSetting).PriorityMatrix
if ( $PriorityData )
{
$matrix = [xml]$PriorityData
}
$Impact = Get-SCSMEnumeration System.WorkItem.TroubleTicket.ImpactEnum. | sort Ordinal
$Urgency = Get-SCSMEnumeration System.WorkItem.TroubleTicket.UrgencyEnum. | sort Ordinal
$count=1
foreach($U in $Urgency)
{
$UOrdinal = $U.Ordinal
foreach($I in $Impact)
{
$IOrdinal = $I.Ordinal
$UN = $U.DisplayName; $IN = $I.DisplayName
$UID = $U.ID; $IID = $I.ID
$xpath = "Matrix/U[@Id='$UID']/I[@Id='$IID']/P"
if ( $ProrityData )
{
$value = $Matrix.SelectSingleNode($xpath)."#text"
}
else
{
$Value = $count++
}
new-object psobject |
add-member -pass NoteProperty UrgencyImpact "${UN}${IN}" |
add-member -pass NoteProperty Value $value |
add-member -pass NoteProperty Ordinal ($UOrdinal * $IOrdinal)
}
}
| 31.40625
| 88
| 0.593035
|
d029db8f1e67ea83c4f02d187a9c7e822bed729e
| 10,375
|
cpp
|
C++
|
myodd/log/logfile.cpp
|
FFMG/myoddweb.piger
|
6c5e9dff6ab8e2e02d6990c1959450f087acf371
|
[
"MIT"
] | 18
|
2016-03-04T15:44:24.000Z
|
2021-12-31T11:06:25.000Z
|
myodd/log/logfile.cpp
|
FFMG/myoddweb.piger
|
6c5e9dff6ab8e2e02d6990c1959450f087acf371
|
[
"MIT"
] | 49
|
2016-02-29T17:59:52.000Z
|
2019-05-05T04:59:26.000Z
|
myodd/log/logfile.cpp
|
FFMG/myoddweb.piger
|
6c5e9dff6ab8e2e02d6990c1959450f087acf371
|
[
"MIT"
] | 2
|
2016-07-30T10:17:12.000Z
|
2016-08-11T20:31:46.000Z
|
#include "stdafx.h"
#include "log.h"
#include "logfile.h"
#include <io.h>
#include <chrono>
#include "../math/math.h"
#include "../files/files.h"
// the maxfile size we want to use.
static size_t MAX_FILE_SIZE_IN_MEGABYTES = 5;
static const MYODD_CHAR* LogFile_default_Prefix = _T("myodd");
static const MYODD_CHAR* LogFile_default_Extention = _T("log");
namespace myodd{ namespace log{
LogFile::LogFile() :
m_fp( NULL ),
m_uCurrentSize( 0 ),
m_bInOpenCall( false ),
_maxFileSizeInMegabytes(MAX_FILE_SIZE_IN_MEGABYTES)
{
}
LogFile::~LogFile()
{
// close the log file.
Close();
}
/**
* Check if the log file is open or not.
* @param none
* @return bool if the log file is open or not.
*/
bool LogFile::IsOpen() const
{
return ( m_fp != NULL && !m_bInOpenCall );
}
struct tm LogFile::GetCurrentTimeStruct() const
{
// the current time.
auto timeNow = std::chrono::system_clock::now();
// to a time_t struct
auto tTime = std::chrono::system_clock::to_time_t(timeNow);
// to a tm structure.
return *localtime(&tTime);
}
/**
* Updated the started time of the log file.
* this will set the _tStarted structure.
*/
void LogFile::UpdateStartedTime()
{
// update the started time with the current structure.
_tStarted = GetCurrentTimeStruct();
}
/**
* Create the log file given the prefix and extension
* We will check that the file size if within limit
* And the date/time is up to date.
*/
bool LogFile::Create()
{
// is the file open already.
if (IsOpen())
{
return true;
}
// lock the current
if( m_bInOpenCall )
{
return false;
}
// we are in open call
// that way we can log things ourselves.
m_bInOpenCall = true;
bool bResult = false;
try
{
// get the time now.
UpdateStartedTime();
// look for a file that matches
for ( unsigned int i = 0;; ++i )
{
// get the log file.
MYODD_CHAR szDateLogStarted[40] = {};
_tcsftime(szDateLogStarted, _countof(szDateLogStarted), _T("%Y-%m-%d"), &_tStarted );
// add a number if the file number is > 0
// so we will create more than one file for today if need be.
MYODD_CHAR szFileCount[10] = {};
if (i > 0)
{
swprintf(szFileCount, _T("-%u"), i);
}
// we have already added a back slash at the end of the directory.
// the file could exist already.
std::wstring proposedCurrentFile = m_sDirectory + m_sPrefix + szDateLogStarted + szFileCount + _T(".") + m_sExtention;
double fileSizeInMegabytes = myodd::math::BytesToMegabytes(myodd::files::GetFileSizeInBytes(proposedCurrentFile));
if (fileSizeInMegabytes < GetMaxFileSizeInMegabytes())
{
m_sCurrentFile = proposedCurrentFile;
break;
}
}
// try and open the new file.
m_fp = _tfsopen(m_sCurrentFile.c_str(), _T("a+b"), _SH_DENYWR);
// did the file open?
if( NULL == m_fp )
{
myodd::log::LogError( _T("Could not open log file : \"%s\"."), m_sCurrentFile.c_str() );
bResult = false;
}
else
{
myodd::log::LogSuccess( _T("Log file, \"%s\", opened."), m_sCurrentFile.c_str() );
// get the size of the file.
m_uCurrentSize = _filelengthi64(_fileno(m_fp));
// is it a brand new file?
if( m_uCurrentSize == 0 )
{
// add the unicode byte order format.
fputwc(0xFEFF, m_fp);
}
#ifdef _DEBUG
// just make sure that we have the right format.
// if the file was changed by the user, then something will go wrong at some stage.
// but we cannot go around and police user misbehaving
//
// so the debug version will make sure that the app is not misbehaving.
else if (m_uCurrentSize >= sizeof(WORD))
{
WORD wBOM;
if (fread(&wBOM, sizeof(wBOM), 1, m_fp) == 1)
{
assert( wBOM == 0xFEFF );
}
}
#endif // Check for the UNICODE param
// go to the end of the file.
(void)fseek(m_fp, 0, SEEK_END);
}
// if we made it here, then it worked.
bResult = true;
}
catch ( ... )
{
bResult = false;
}
// we are no longer in open call.
m_bInOpenCall = false;
// return if this worked.
return bResult;
}
/**
* Ensure that the file is not too big and not out of date.
*/
void LogFile::ValidateDateAndSize()
{
if (!IsOpen())
{
return;
}
// recreate?
bool bRecreate = false;
// check the size.
double fileSizeInMegabytes = myodd::math::BytesToMegabytes(myodd::files::GetFileSizeInBytes( GetCurrentLogFile()));
if (fileSizeInMegabytes > GetMaxFileSizeInMegabytes())
{
bRecreate = true;
}
else
{
// get the current time and check if the file is out of date.
auto tStarted = GetCurrentTimeStruct();
// compare it to the started time.
auto tm = GetStartedDate();
if (tm.tm_yday != tStarted.tm_yday)
{
// close the old one and force a re-open
// this will force a check to be done.
bRecreate = true;
}
}
if (bRecreate)
{
// close the old file
Close();
// create a new one.
Create();
}
}
/**
* Open the file for login.
* @param none
* @return none
*/
bool LogFile::Open()
{
// is the file open already.
if (IsOpen())
{
return true;
}
// lock the current
if( m_bInOpenCall )
{
return false;
}
// we are in open call
// that way we can log things ourselves.
m_bInOpenCall = true;
// assume an error.
bool bResult = false;
try
{
// do we already know the name of the file?
if( m_sCurrentFile.empty() )
{
if( !Create() )
{
// there was a problem.
m_bInOpenCall = true;
return false;
}
}
// try and open the new file.
m_fp = _tfsopen(m_sCurrentFile.c_str(), _T("a+b"), _SH_DENYWR);
// get the size of the file.
m_uCurrentSize = _filelengthi64(_fileno(m_fp));
// go to the end of the file.
(void)fseek(m_fp, 0, SEEK_END);
// if we made it here, then it worked.
bResult = true;
}
catch ( ... )
{
bResult = false;
}
// we are no longer in open call.
m_bInOpenCall = false;
return bResult;
}
/**
* Close a log file.
* @param none
* @return bool if the file was closed or not.
*/
bool LogFile::Close()
{
// is it open?
if (!IsOpen())
{
return true;
}
// close it.
bool bResult = (fclose(m_fp) == 0);
m_fp = NULL;
m_uCurrentSize = 0;
return bResult;
}
/**
* Log an entry to the file.
* @param unsigned int uiType the log type
* @param const MYODD_CHAR* the line we are adding.
* @return bool success or not.
*/
bool LogFile::LogToFile( unsigned int uiType, const MYODD_CHAR* pszLine )
{
// are we logging?
if (m_sCurrentFile.empty())
{
return false;
}
if (!Open())
{
return false;
}
// check the size and date
ValidateDateAndSize();
bool bResult = false;
try
{
// get the current date so we can add it to the log.
auto tStarted = GetCurrentTimeStruct();
MYODD_CHAR szDateLogStarted[40];
_tcsftime(szDateLogStarted, _countof(szDateLogStarted), _T("%Y/%m/%d %H:%M:%S"), &tStarted );
// build the return message.
MYODD_STRING stdMsg = szDateLogStarted;
stdMsg += _T(" ") + myodd::strings::ToString( uiType, _T("%04d") );
stdMsg += _T(" ");
stdMsg += (pszLine ? pszLine : _T(""));
stdMsg += _T("\r\n");
const MYODD_CHAR* pszMsg = stdMsg.c_str();
// get the total size of what we are about to write..
size_t uToWrite = _tcslen(pszMsg) * sizeof(MYODD_CHAR);
// then we can write to the file.
size_t uWritten = fwrite(pszMsg, 1, uToWrite, m_fp);
// did it work?
bResult = !ferror(m_fp);
// get the file size.
m_uCurrentSize += uWritten;
}
catch( ... )
{
}
Close();
return bResult;
}
/**
* Set the log path directory.
* If we pass a NULL argument then we want to stop/disable the logging.
* @param const std::wstring& wPath the log path we will be using.
* @param const std::wstring& wPrefix the prefix of the filename we will create, (default is blank).
* @param const std::wstring& wExtention the file extension.
* @param size_t maxFileSize the max file size in megabytes.
* @return bool success or not
*/
bool LogFile::Initialise(const std::wstring& wPath, const std::wstring& wPrefix, const std::wstring& wExtention, size_t maxFileSize)
{
// close the file
Close();
// is the new, given path valid?
// or is the user telling us that they want to close it?
if( wPath.length() == 0 )
{
m_sPrefix = m_sExtention = m_sDirectory = _T("");
return true;
}
// set the prefix and extension.
// if the user is giving us some silly values then there is nothing we can do about really.
m_sPrefix = wPrefix.length() > 0 ? wPrefix : LogFile_default_Prefix;
m_sExtention = wExtention.length() > 0 ? wExtention : LogFile_default_Extention;
// It seems to be valid, so we can set the path here.
m_sDirectory = wPath;
// expand the file name
if (!myodd::files::ExpandEnvironment(m_sDirectory, m_sDirectory))
{
return false;
}
// add a trailing backslash
myodd::files::AddTrailingBackSlash( m_sDirectory );
// expand the path, in case the user changes their path or something.
if( !myodd::files::GetAbsolutePath( m_sDirectory, m_sDirectory, _T(".") ))
{
return false;
}
// expand the path, in case the user changes their path or something.
if( !myodd::files::CreateFullDirectory( m_sDirectory.c_str(), false ) )
{
return false;
}
// simply open the next file
// if there is a problem then nothing will log.
return Create();
}
} // log
} // myodd
| 24.880096
| 134
| 0.586602
|
a48c4b829d7c14de7b459b62e49d58355f215a81
| 533
|
php
|
PHP
|
app/Model/HistoryOrder.php
|
adminsemy/orderCartridges
|
d430fbd829332cbece34d4046b249e5b8a3bab59
|
[
"MIT"
] | null | null | null |
app/Model/HistoryOrder.php
|
adminsemy/orderCartridges
|
d430fbd829332cbece34d4046b249e5b8a3bab59
|
[
"MIT"
] | 5
|
2021-02-02T18:13:41.000Z
|
2022-02-19T01:41:11.000Z
|
app/Model/HistoryOrder.php
|
adminsemy/orderCartridges
|
d430fbd829332cbece34d4046b249e5b8a3bab59
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class HistoryOrder extends Model
{
const NEW_CARTRIDGE = 'new';
const SEASONED_CARTRIDGE = 'seasoned';
const GIVE_NEW = 1;
const GIVE_SEASONED = 2;
const ORDER_COMPLITED = 1;
protected $table = 'web_zakaz';
public function cartridge()
{
return $this->belongsTo('App\Model\Cartridge', 'id_cartridge');
}
public function printer()
{
return $this->belongsTo('App\Model\Printers', 'id_tehniki');
}
}
| 19.740741
| 71
| 0.654784
|
25b87634fc250720b73c93e879373ab17e670769
| 1,814
|
js
|
JavaScript
|
theme.js
|
RodrigoWebDev/kate-joe-website
|
4a2ebaba5bcecb345685b8fd8cf99c20c25e7ec2
|
[
"MIT"
] | null | null | null |
theme.js
|
RodrigoWebDev/kate-joe-website
|
4a2ebaba5bcecb345685b8fd8cf99c20c25e7ec2
|
[
"MIT"
] | null | null | null |
theme.js
|
RodrigoWebDev/kate-joe-website
|
4a2ebaba5bcecb345685b8fd8cf99c20c25e7ec2
|
[
"MIT"
] | null | null | null |
export default {
space: Array.from(Array(11).keys()).map(x => x * 8),
breakpoints: ["768px", "1024px"],
colors: {
text: "#000000",
background: "#FFFFFF",
primary: "#1E488F",
muted: "#8F8F8F",
},
fonts: {
body: "'Playfair Display', serif",
heading: "'Poppins', sans-serif",
monospace: "Menlo, monospace",
},
fontWeights: {
body: 400,
heading: 700,
},
sizes: {
container: "1184px",
containerSmall: "735px",
},
lineHeights: {
body: 1.5,
heading: 1.125,
},
fontSizes: [14, 18, 24, 27, 32, 40, 48, 60, 72],
text: {
h1: {
fontSize: 72,
lineHeight: "98px",
},
h2: {
fontSize: 60,
lineHeight: "82px",
},
h3: {
fontSize: 48,
lineHeight: "65px",
},
h4: {
fontSize: 40,
lineHeight: "54px",
},
h5: {
fontSize: 32,
lineHeight: "44px",
},
h6: {
fontSize: 27,
lineHeight: "37px",
},
h7: {
fontSize: 24,
lineHeight: "34px",
},
body: {
fontSize: 18,
lineHeight: "22px",
fontWeight: "body",
},
bodySmall: {
fontSize: 14,
lineHeight: "20px",
},
},
styles: {
root: {
fontSize: 1,
lineHeight: "body",
fontWeight: "body",
fontFamily: "body",
},
p: {
m: 0,
fontSize: 18,
color: "muted",
lineHeight: "28px",
":not(:last-child)": {
mb: 4,
},
},
a: {
color: "primary",
},
},
links: {
nav: {
textDecoration: "none",
textTransform: "uppercase",
fontFamily: "heading",
color: "rgba(0, 0, 0, 0.30)",
"&:hover": {
color: "primary",
},
},
navActive: {
variant: "links.nav",
color: "primary",
},
},
}
| 17.61165
| 54
| 0.462514
|
1bba9664e2385c29a07ed23608ef107f89a747a8
| 972
|
rb
|
Ruby
|
spec/controllers/interest_spec.rb
|
tsteph11/Cocoa
|
8f1ed8e5a760d304a74212d0143b89c77111ca1b
|
[
"MIT"
] | 1
|
2020-03-01T00:37:10.000Z
|
2020-03-01T00:37:10.000Z
|
spec/controllers/interest_spec.rb
|
tsteph11/Cocoa
|
8f1ed8e5a760d304a74212d0143b89c77111ca1b
|
[
"MIT"
] | 5
|
2020-02-25T22:35:16.000Z
|
2020-03-04T15:16:40.000Z
|
spec/controllers/interest_spec.rb
|
tsteph11/Cocoa
|
8f1ed8e5a760d304a74212d0143b89c77111ca1b
|
[
"MIT"
] | null | null | null |
require 'rails_helper'
RSpec.describe InterestsController do
describe "GET index" do
it "assigns @interests" do
interest = Interest.create(image_name: "image.png", name: "test", description: "this is a test", long_description: "this is a test")
get :index
expect(assigns(:interests)).to eq([interest])
end
it "renders the index template" do
get :index
expect(response).to render_template("index")
end
end
describe "GET show" do
let(:interest){Interest.create(image_name: "image.png", name: "test", description: "this is a test", long_description: "this is a test")}
it "assigns @interest" do
get :show, params: { id: interest }
expect(assigns(:interest)).to eq interest
end
it "renders the show template" do
get :show, params: { id: interest }
expect(response).to render_template("show")
end
end
end
| 32.4
| 145
| 0.615226
|
a32e769d3d11077fb4c3f99a301b411b96ed4f6f
| 2,005
|
java
|
Java
|
src/main/java/com/mindata/blockchain/common/utils/UploadBlockUtil.java
|
PenfeiLiu/md_blockchain
|
355b31b13404afd0cb196ed5676336073eaba2b6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/mindata/blockchain/common/utils/UploadBlockUtil.java
|
PenfeiLiu/md_blockchain
|
355b31b13404afd0cb196ed5676336073eaba2b6
|
[
"Apache-2.0"
] | null | null | null |
src/main/java/com/mindata/blockchain/common/utils/UploadBlockUtil.java
|
PenfeiLiu/md_blockchain
|
355b31b13404afd0cb196ed5676336073eaba2b6
|
[
"Apache-2.0"
] | null | null | null |
package com.mindata.blockchain.common.utils;
import cn.hutool.core.collection.CollectionUtil;
import com.mindata.blockchain.block.Instruction;
import com.mindata.blockchain.block.Operation;
import com.mindata.blockchain.core.requestbody.BlockRequestBody;
import com.mindata.blockchain.core.requestbody.InstructionBody;
import com.mindata.blockchain.core.service.BlockService;
import com.mindata.blockchain.core.service.InstructionService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UploadBlockUtil {
@Value("${publicKey:A8WLqHTjcT/FQ2IWhIePNShUEcdCzu5dG+XrQU8OMu54}")
private String publicKey;
@Value("${privateKey:yScdp6fNgUU+cRUTygvJG4EBhDKmOMRrK4XJ9mKVQJ8=}")
private String privateKey;
@Resource
private InstructionService instructionService;
@Resource
private BlockService blockService;
public void uploadBlock(String json,byte operation,String tableName){
InstructionBody instructionBody = new InstructionBody();
instructionBody.setOperation(operation);
instructionBody.setTable(tableName);
instructionBody.setJson(json);
instructionBody.setPublicKey(publicKey);
instructionBody.setPrivateKey(privateKey);
Instruction instruction = null;
try {
instruction = instructionService.build(instructionBody);
} catch (Exception e) {
e.printStackTrace();
}
BlockRequestBody blockRequestBody = new BlockRequestBody();
blockRequestBody.setPublicKey(instructionBody.getPublicKey());
com.mindata.blockchain.block.BlockBody blockBody = new com.mindata.blockchain.block.BlockBody();
blockBody.setInstructions(CollectionUtil.newArrayList(instruction));
blockRequestBody.setBlockBody(blockBody);
blockService.addBlock(blockRequestBody);
}
}
| 37.12963
| 104
| 0.762594
|
4dc7761881c5e2b91b06c0c1c23a73c2be141c9a
| 537
|
cs
|
C#
|
AstroDroid.Core/Utils/Require.cs
|
michaelprosario/AstroDroid
|
b1304a51419926a5db2707c7d1470a069fe6e106
|
[
"MIT"
] | 1
|
2021-02-22T11:48:39.000Z
|
2021-02-22T11:48:39.000Z
|
AstroDroid.Core/Utils/Require.cs
|
michaelprosario/AstroDroid
|
b1304a51419926a5db2707c7d1470a069fe6e106
|
[
"MIT"
] | null | null | null |
AstroDroid.Core/Utils/Require.cs
|
michaelprosario/AstroDroid
|
b1304a51419926a5db2707c7d1470a069fe6e106
|
[
"MIT"
] | null | null | null |
using System;
namespace AstroDroid.Core.Utils
{
/// <summary>
/// Helper class to guard methods from invalid data
/// </summary>
public class Require
{
public static void ObjectNotNull(object currentObject, string message)
{
if (currentObject == null) throw new ArgumentNullException(message);
}
public static void NotNullOrEmpty(string input, string message)
{
if (string.IsNullOrEmpty(input)) throw new ArgumentException(message);
}
}
}
| 26.85
| 82
| 0.631285
|
d3ece8941f61387d2420ef1226520b071a08843f
| 9,617
|
rs
|
Rust
|
src/compound_select.rs
|
howard0su/nom-sql
|
01a055d264ce28e1a9f6ad9d91585fd3dee5ae63
|
[
"MIT"
] | 202
|
2016-10-24T14:24:26.000Z
|
2022-02-19T20:03:37.000Z
|
src/compound_select.rs
|
howard0su/nom-sql
|
01a055d264ce28e1a9f6ad9d91585fd3dee5ae63
|
[
"MIT"
] | 59
|
2017-07-25T23:04:15.000Z
|
2020-12-07T23:15:54.000Z
|
src/compound_select.rs
|
howard0su/nom-sql
|
01a055d264ce28e1a9f6ad9d91585fd3dee5ae63
|
[
"MIT"
] | 57
|
2017-01-13T10:47:05.000Z
|
2022-01-30T17:23:20.000Z
|
use nom::character::complete::{multispace0, multispace1};
use std::fmt;
use std::str;
use common::{opt_delimited, statement_terminator};
use nom::branch::alt;
use nom::bytes::complete::{tag, tag_no_case};
use nom::combinator::{map, opt};
use nom::multi::many1;
use nom::sequence::{delimited, preceded, tuple};
use nom::IResult;
use order::{order_clause, OrderClause};
use select::{limit_clause, nested_selection, LimitClause, SelectStatement};
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub enum CompoundSelectOperator {
Union,
DistinctUnion,
Intersect,
Except,
}
impl fmt::Display for CompoundSelectOperator {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CompoundSelectOperator::Union => write!(f, "UNION"),
CompoundSelectOperator::DistinctUnion => write!(f, "UNION DISTINCT"),
CompoundSelectOperator::Intersect => write!(f, "INTERSECT"),
CompoundSelectOperator::Except => write!(f, "EXCEPT"),
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub struct CompoundSelectStatement {
pub selects: Vec<(Option<CompoundSelectOperator>, SelectStatement)>,
pub order: Option<OrderClause>,
pub limit: Option<LimitClause>,
}
impl fmt::Display for CompoundSelectStatement {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (ref op, ref sel) in &self.selects {
if op.is_some() {
write!(f, " {}", op.as_ref().unwrap())?;
}
write!(f, " {}", sel)?;
}
if self.order.is_some() {
write!(f, " {}", self.order.as_ref().unwrap())?;
}
if self.limit.is_some() {
write!(f, " {}", self.order.as_ref().unwrap())?;
}
Ok(())
}
}
// Parse compound operator
fn compound_op(i: &[u8]) -> IResult<&[u8], CompoundSelectOperator> {
alt((
map(
preceded(
tag_no_case("union"),
opt(preceded(
multispace1,
alt((
map(tag_no_case("all"), |_| false),
map(tag_no_case("distinct"), |_| true),
)),
)),
),
|distinct| match distinct {
// DISTINCT is the default in both MySQL and SQLite
None => CompoundSelectOperator::DistinctUnion,
Some(d) => {
if d {
CompoundSelectOperator::DistinctUnion
} else {
CompoundSelectOperator::Union
}
}
},
),
map(tag_no_case("intersect"), |_| {
CompoundSelectOperator::Intersect
}),
map(tag_no_case("except"), |_| CompoundSelectOperator::Except),
))(i)
}
fn other_selects(i: &[u8]) -> IResult<&[u8], (Option<CompoundSelectOperator>, SelectStatement)> {
let (remaining_input, (_, op, _, select)) = tuple((
multispace0,
compound_op,
multispace1,
opt_delimited(
tag("("),
delimited(multispace0, nested_selection, multispace0),
tag(")"),
),
))(i)?;
Ok((remaining_input, (Some(op), select)))
}
// Parse compound selection
pub fn compound_selection(i: &[u8]) -> IResult<&[u8], CompoundSelectStatement> {
let (remaining_input, (first_select, other_selects, _, order, limit, _)) = tuple((
opt_delimited(tag("("), nested_selection, tag(")")),
many1(other_selects),
multispace0,
opt(order_clause),
opt(limit_clause),
statement_terminator,
))(i)?;
let mut selects = vec![(None, first_select)];
selects.extend(other_selects);
Ok((
remaining_input,
CompoundSelectStatement {
selects,
order,
limit,
},
))
}
#[cfg(test)]
mod tests {
use super::*;
use column::Column;
use common::{FieldDefinitionExpression, FieldValueExpression, Literal};
use table::Table;
#[test]
fn union() {
let qstr = "SELECT id, 1 FROM Vote UNION SELECT id, stars from Rating;";
let qstr2 = "(SELECT id, 1 FROM Vote) UNION (SELECT id, stars from Rating);";
let res = compound_selection(qstr.as_bytes());
let res2 = compound_selection(qstr2.as_bytes());
let first_select = SelectStatement {
tables: vec![Table::from("Vote")],
fields: vec![
FieldDefinitionExpression::Col(Column::from("id")),
FieldDefinitionExpression::Value(FieldValueExpression::Literal(
Literal::Integer(1).into(),
)),
],
..Default::default()
};
let second_select = SelectStatement {
tables: vec![Table::from("Rating")],
fields: vec![
FieldDefinitionExpression::Col(Column::from("id")),
FieldDefinitionExpression::Col(Column::from("stars")),
],
..Default::default()
};
let expected = CompoundSelectStatement {
selects: vec![
(None, first_select),
(Some(CompoundSelectOperator::DistinctUnion), second_select),
],
order: None,
limit: None,
};
assert_eq!(res.unwrap().1, expected);
assert_eq!(res2.unwrap().1, expected);
}
#[test]
fn union_strict() {
let qstr = "SELECT id, 1 FROM Vote);";
let qstr2 = "(SELECT id, 1 FROM Vote;";
let qstr3 = "SELECT id, 1 FROM Vote) UNION (SELECT id, stars from Rating;";
let res = compound_selection(qstr.as_bytes());
let res2 = compound_selection(qstr2.as_bytes());
let res3 = compound_selection(qstr3.as_bytes());
assert!(&res.is_err());
assert_eq!(
res.unwrap_err(),
nom::Err::Error(nom::error::Error::new(");".as_bytes(), nom::error::ErrorKind::Tag))
);
assert!(&res2.is_err());
assert_eq!(
res2.unwrap_err(),
nom::Err::Error(nom::error::Error::new(";".as_bytes(), nom::error::ErrorKind::Tag))
);
assert!(&res3.is_err());
assert_eq!(
res3.unwrap_err(),
nom::Err::Error(nom::error::Error::new(
") UNION (SELECT id, stars from Rating;".as_bytes(),
nom::error::ErrorKind::Tag
))
);
}
#[test]
fn multi_union() {
let qstr = "SELECT id, 1 FROM Vote \
UNION SELECT id, stars from Rating \
UNION DISTINCT SELECT 42, 5 FROM Vote;";
let res = compound_selection(qstr.as_bytes());
let first_select = SelectStatement {
tables: vec![Table::from("Vote")],
fields: vec![
FieldDefinitionExpression::Col(Column::from("id")),
FieldDefinitionExpression::Value(FieldValueExpression::Literal(
Literal::Integer(1).into(),
)),
],
..Default::default()
};
let second_select = SelectStatement {
tables: vec![Table::from("Rating")],
fields: vec![
FieldDefinitionExpression::Col(Column::from("id")),
FieldDefinitionExpression::Col(Column::from("stars")),
],
..Default::default()
};
let third_select = SelectStatement {
tables: vec![Table::from("Vote")],
fields: vec![
FieldDefinitionExpression::Value(FieldValueExpression::Literal(
Literal::Integer(42).into(),
)),
FieldDefinitionExpression::Value(FieldValueExpression::Literal(
Literal::Integer(5).into(),
)),
],
..Default::default()
};
let expected = CompoundSelectStatement {
selects: vec![
(None, first_select),
(Some(CompoundSelectOperator::DistinctUnion), second_select),
(Some(CompoundSelectOperator::DistinctUnion), third_select),
],
order: None,
limit: None,
};
assert_eq!(res.unwrap().1, expected);
}
#[test]
fn union_all() {
let qstr = "SELECT id, 1 FROM Vote UNION ALL SELECT id, stars from Rating;";
let res = compound_selection(qstr.as_bytes());
let first_select = SelectStatement {
tables: vec![Table::from("Vote")],
fields: vec![
FieldDefinitionExpression::Col(Column::from("id")),
FieldDefinitionExpression::Value(FieldValueExpression::Literal(
Literal::Integer(1).into(),
)),
],
..Default::default()
};
let second_select = SelectStatement {
tables: vec![Table::from("Rating")],
fields: vec![
FieldDefinitionExpression::Col(Column::from("id")),
FieldDefinitionExpression::Col(Column::from("stars")),
],
..Default::default()
};
let expected = CompoundSelectStatement {
selects: vec![
(None, first_select),
(Some(CompoundSelectOperator::Union), second_select),
],
order: None,
limit: None,
};
assert_eq!(res.unwrap().1, expected);
}
}
| 33.04811
| 97
| 0.529479
|
b11692128c7968bc55352d82dd7bbee2e70d3d49
| 391
|
py
|
Python
|
notecoin/huobi/dataset/upload.py
|
notechats/notecoin
|
57e1ed71567ce8864158f24c00ed47addbd9851f
|
[
"Apache-2.0"
] | null | null | null |
notecoin/huobi/dataset/upload.py
|
notechats/notecoin
|
57e1ed71567ce8864158f24c00ed47addbd9851f
|
[
"Apache-2.0"
] | null | null | null |
notecoin/huobi/dataset/upload.py
|
notechats/notecoin
|
57e1ed71567ce8864158f24c00ed47addbd9851f
|
[
"Apache-2.0"
] | 1
|
2022-03-26T11:42:18.000Z
|
2022-03-26T11:42:18.000Z
|
from notedrive.lanzou import LanZouCloud
from notetool.log import logger
from notetool.tool.secret import read_secret
downer = LanZouCloud()
downer.ignore_limits()
downer.login_by_cookie()
logger.info('begin')
#print(downer.sync_directory(path_root='/root/workspace/tmp/coin', folder_id='3358325'))
downer.upload_file('/root/workspace/tmp/coin/dbs/huobi-SHIBUSDT.db', folder_id='3907901')
| 32.583333
| 89
| 0.805627
|
45a46bef2590041f1a3c11a22a696e62579787da
| 2,914
|
py
|
Python
|
src/view/RoleListMediator.py
|
JulienGrv/puremvc-python-demo-PySide-employeeadmin
|
b076493ac34254e665b485259b0a7122fa9cfde4
|
[
"BSD-3-Clause"
] | 4
|
2017-08-26T10:18:10.000Z
|
2020-07-28T19:50:54.000Z
|
src/view/RoleListMediator.py
|
JulienGrv/puremvc-python-demo-PySide-employeeadmin
|
b076493ac34254e665b485259b0a7122fa9cfde4
|
[
"BSD-3-Clause"
] | null | null | null |
src/view/RoleListMediator.py
|
JulienGrv/puremvc-python-demo-PySide-employeeadmin
|
b076493ac34254e665b485259b0a7122fa9cfde4
|
[
"BSD-3-Clause"
] | 3
|
2020-09-22T12:17:14.000Z
|
2021-07-16T12:28:18.000Z
|
# -*- coding: utf-8 -*-
from puremvc.patterns.mediator import Mediator
from .. import ApplicationFacade, model
class RoleListMediator(Mediator):
"""
Role list component Mediator.
"""
NAME = 'RoleListMediator'
def __init__(self, mediatorName=None, viewComponent=None):
super(RoleListMediator, self).__init__(mediatorName, viewComponent)
def listNotificationInterests(self):
return [
ApplicationFacade.NEW_USER, ApplicationFacade.USER_ADDED,
ApplicationFacade.USER_UPDATED, ApplicationFacade.USER_DELETED,
ApplicationFacade.CANCEL_SELECTED, ApplicationFacade.USER_SELECTED,
ApplicationFacade.ADD_ROLE_RESULT
]
def handleNotification(self, notification):
name = notification.getName()
roleList = self.viewComponent
if name == ApplicationFacade.NEW_USER:
roleList.user = None
roleList.userRoles = None
roleList.setEnabled(False)
elif name == ApplicationFacade.USER_ADDED:
roleList.user = notification.getBody()
roleList.userRoles = None
role = model.vo.RoleVO(roleList.user.username)
self.roleProxy.addIem(role)
roleList.setEnabled(False)
elif name == ApplicationFacade.USER_UPDATED:
roleList.user = None
roleList.userRoles = None
roleList.setEnabled(False)
elif name == ApplicationFacade.USER_DELETED:
roleList.user = None
roleList.userRoles = None
roleList.setEnabled(False)
elif name == ApplicationFacade.CANCEL_SELECTED:
roleList.user = None
roleList.userRoles = None
roleList.setEnabled(False)
elif name == ApplicationFacade.USER_SELECTED:
roleList.user = notification.getBody()
roleList.userRoles = self.roleProxy.getUserRoles(
roleList.user.username)
roleList.setEnabled(True)
elif name == ApplicationFacade.ADD_ROLE_RESULT:
roleList.userRoles = self.roleProxy.getUserRoles(
roleList.user.username)
def onRegister(self):
self.viewComponent.roles = model.enum.RoleEnum()
self.roleProxy = self.facade.retrieveProxy(model.RoleProxy.NAME)
self.viewComponent.addEventListener(self.viewComponent.ADD,
self.onAddRole)
self.viewComponent.addEventListener(self.viewComponent.REMOVE,
self.onRemoveRole)
def onAddRole(self):
self.roleProxy.addRoleToUser(self.viewComponent.user,
self.viewComponent.selectedRole)
def onRemoveRole(self):
self.roleProxy.removeRoleFromUser(self.viewComponent.user,
self.viewComponent.selectedRole)
| 38.853333
| 79
| 0.631434
|
05647eb4f3250fee2cd189da86bc97aa7512aceb
| 1,130
|
rb
|
Ruby
|
app/presenters/houston/roadmaps/roadmap_presenter.rb
|
houston/houston-roadmaps
|
d8df0e26dc0f2a367f4699abe8aafa25881734cd
|
[
"MIT"
] | null | null | null |
app/presenters/houston/roadmaps/roadmap_presenter.rb
|
houston/houston-roadmaps
|
d8df0e26dc0f2a367f4699abe8aafa25881734cd
|
[
"MIT"
] | null | null | null |
app/presenters/houston/roadmaps/roadmap_presenter.rb
|
houston/houston-roadmaps
|
d8df0e26dc0f2a367f4699abe8aafa25881734cd
|
[
"MIT"
] | null | null | null |
class Houston::Roadmaps::RoadmapPresenter
def initialize(roadmaps)
@roadmaps = OneOrMany.new(roadmaps)
end
def as_json(*args)
@roadmaps.map(&method(:to_hash))
end
def to_hash(roadmap)
{ id: roadmap.id,
name: roadmap.name,
teams: roadmap.teams.map { |team| {
id: team.id,
name: team.name } },
projects: roadmap.projects.map { |project| {
id: project.id,
name: project.name,
color: project.color } },
milestones: present_milestones(roadmap.milestones) }
end
private
def present_milestones(milestones)
milestones.map do |milestone|
# TODO: optimize this: manually preload projects
klass = milestone.fetch("type", "Milestone").constantize
project = klass.unscope(where: :destroyed_at).find(milestone["id"]).project
{ id: milestone["id"],
name: milestone["name"],
projectId: project.id,
projectColor: project.color,
band: milestone["band"],
lanes: milestone["lanes"],
startDate: milestone["start_date"],
endDate: milestone["end_date"] }
end
end
end
| 26.27907
| 81
| 0.629204
|
da8f89b78771d75147b9e8dd13eab7e6b10d87fa
| 15,359
|
php
|
PHP
|
src/Generator/TypeDescriber.php
|
wapmorgan/OpenApiGenerator
|
3989faa16996ccdb3dacaf64f300c8d121af17eb
|
[
"MIT"
] | 3
|
2020-03-16T17:13:40.000Z
|
2020-06-12T05:20:46.000Z
|
src/Generator/TypeDescriber.php
|
wapmorgan/OpenApiGenerator
|
3989faa16996ccdb3dacaf64f300c8d121af17eb
|
[
"MIT"
] | null | null | null |
src/Generator/TypeDescriber.php
|
wapmorgan/OpenApiGenerator
|
3989faa16996ccdb3dacaf64f300c8d121af17eb
|
[
"MIT"
] | 1
|
2020-03-16T17:13:58.000Z
|
2020-03-16T17:13:58.000Z
|
<?php
namespace wapmorgan\OpenApiGenerator\Generator;
use OpenApi\Annotations\AbstractAnnotation;
use OpenApi\Annotations\Items;
use OpenApi\Annotations\Parameter;
use OpenApi\Annotations\Property;
use OpenApi\Annotations\Schema;
use ReflectionException;
use wapmorgan\OpenApiGenerator\ReflectionsCollection;
use const OpenApi\Annotations\UNDEFINED;
class TypeDescriber
{
public const PRIMITIVE_TYPE = 1;
public const COMPLEX_ABSTRACT_TYPE = 2;
public const COMPLEX_TYPE = 3;
/**
* @var DefaultGenerator
*/
protected $generator;
/**
* @var array <string, array<string>>
*/
protected $classesImports = [];
/**
* @var string[]
*/
public $primitiveTypes = ['void', 'null', 'string', 'bool', 'int', 'integer', 'float', 'boolean'];
/**
* @var string[]
*/
public $complexAbstractTypes = ['object', 'array', 'stdclass', 'mixed'];
/**
* TypeDescriber constructor.
* @param DefaultGenerator $generator
*/
public function __construct(DefaultGenerator $generator)
{
$this->generator = $generator;
}
/**
* @param string $declaringClass
* @param string|null $typeSpecification Тип (скалярный или сложный)
* @param string|array|null $defaultValue
* @param bool $isNullableType
* @param string|null $schemaType Parameter|Schema|Property|null
* @param null $kindOfType
* @return Schema|Property
* @throws ReflectionException
*/
public function generateSchemaForType(
string $declaringClass,
?string $typeSpecification,
$defaultValue,
&$isNullableType = false,
?string $schemaType = null,
&$kindOfType = null
): ?Schema
{
$is_iterable_type = false;
// Does not make sense to generate empty @OA\Schema
if ($typeSpecification === null || $typeSpecification === 'void') {
return null;
}
// case when bad type - only 'null'. Treat as like 'string|null'
if ($typeSpecification === 'null') {
$typeSpecification = 'string|null';
}
// multiple types - generate Schema for every type
if (strpos($typeSpecification, '|') !== false) {
return $this->generateSchemaForFewTypes(
$typeSpecification,
$declaringClass,
$defaultValue,
$isNullableType,
$schemaType,
$kindOfType);
}
// remove brackets from iterable specification
if (substr($typeSpecification, -2) === '[]') {
$typeSpecification = substr($typeSpecification, 0, -2);
$is_iterable_type = true;
}
if (in_array(strtolower($typeSpecification), $this->primitiveTypes, true)
|| in_array(strtolower($typeSpecification), ['true', 'false'], true)) {
$kindOfType = self::PRIMITIVE_TYPE;
$schema = $this->generateSchemaForPrimitiveType(strtolower($typeSpecification), $defaultValue, $is_iterable_type);
} else if (in_array(strtolower($typeSpecification), $this->complexAbstractTypes, true)) {
$kindOfType = self::COMPLEX_ABSTRACT_TYPE;
$schema = $this->generateSchemaForComplexAbstractType(strtolower($typeSpecification), $is_iterable_type);
} else {
$kindOfType = self::COMPLEX_TYPE;
$schema = $this->generateSchemaPartsForComplexType($this->resolveLocalName($declaringClass, $typeSpecification), $is_iterable_type);
}
$schema->nullable = $isNullableType;
if ($schemaType !== null && $schemaType !== Schema::class) {
if (!is_subclass_of($schemaType, Schema::class) && $schemaType !== Parameter::class)
throw new \RuntimeException('Invalid target Schema-class: '.$schemaType);
/** @var Schema $new_schema */
$new_schema = new $schemaType([]);
$this->transferOptions($schema, $new_schema);
return $new_schema;
}
return $schema;
}
/**
* @param string $declaringClass
* @param string|null $typeSpecification
* @return int|null
*/
public function getKindForType(
string $declaringClass,
?string $typeSpecification)
: ?int
{
// Does not make sense to generate empty @OA\Schema
if ($typeSpecification === null) {
return null;
}
// multiple types - generate Schema for every type
if (strpos($typeSpecification, '|') !== false) {
$kind = null;
foreach (explode('|', $typeSpecification) as $type_variant) {
$kind = max($kind, $this->getKindForType($declaringClass, $type_variant));
}
return $kind;
}
// remove brackets from iterable specification
if (substr($typeSpecification, -2) === '[]') {
$typeSpecification = substr($typeSpecification, 0, -2);
}
if (in_array(strtolower($typeSpecification), $this->primitiveTypes, true)) {
return self::PRIMITIVE_TYPE;
}
if (in_array(strtolower($typeSpecification), $this->complexAbstractTypes, true)) {
return self::COMPLEX_ABSTRACT_TYPE;
}
return self::COMPLEX_TYPE;
}
/**
* @param object $object
* @param bool $isIterable
* @param string|null $schemaType
* @return Schema|null
* @throws ReflectionException
*/
public function generateSchemaForObject(
object $object,
bool $isIterable = false,
?string $schemaType = null
): ?Schema
{
$schema = $this->generateSchemaPartsForObject($object, $isIterable);
if ($schemaType !== null && $schemaType !== Schema::class) {
if (!is_subclass_of($schemaType, Schema::class) && $schemaType !== Parameter::class)
throw new \RuntimeException('Invalid target Schema-class: '.$schemaType);
/** @var Schema $new_schema */
$new_schema = new $schemaType([]);
$this->transferOptions($schema, $new_schema);
return $new_schema;
}
return $schema;
}
/**
* @param string $typeSpecification
* @param $defaultValue
* @param bool $isIterable
* @return Schema
*/
public function generateSchemaForPrimitiveType(
?string $typeSpecification,
$defaultValue,
bool $isIterable): Schema
{
$type = $this->canonizePrimitiveType($typeSpecification);
if ($isIterable) {
$schema = new Schema([
'type' => 'array',
'items' => new Items([
'type' => $type,
])
]);
if (is_array($defaultValue) && !empty($defaultValue)) {
$schema->enum = $defaultValue;
}
} else {
$schema = new Schema([
'type' => $type,
]);
if (!empty($defaultValue)) {
$schema->default = $defaultValue;
}
}
return $schema;
}
/**
* @param string|null $typeSpecification
* @param bool $isIterable
* @return Schema
* @throws ReflectionException
*/
public function generateSchemaPartsForComplexType(
?string $typeSpecification,
bool $isIterable
): Schema
{
$schema = $this->generator->getClassDescriber()->generateSchemaForClass($typeSpecification);
if ($isIterable) {
$schema = new Schema([
'type' => 'array',
'items' => $schema,
]);
}
return $schema;
}
/**
* @param object $object
* @param bool $isIterable
* @return Schema|null
* @throws ReflectionException
*/
protected function generateSchemaPartsForObject(
object $object,
bool $isIterable
)
{
$schema = $this->generator->getClassDescriber()->generateSchemaForObject($object);
if ($isIterable) {
$schema = new Schema([
'type' => 'array',
'items' => $schema,
]);
}
return $schema;
}
/**
* @param string $type
* @return string
*/
public function canonizePrimitiveType(string $type): string
{
switch ($type) {
case 'float':
case 'int':
return 'integer';
case 'bool':
case 'true':
case 'false':
return 'boolean';
}
return $type;
}
/**
* @param $declaringClass
* @param $typeName
* @return string
* @throws ReflectionException
*/
public function resolveLocalName($declaringClass, $typeName)
{
$typeName = ltrim($typeName, '\\');
// If declaring class is not scanned
if (!isset($this->classesImports[$declaringClass])) {
$this->addImports([$declaringClass]);
}
if (isset($this->classesImports[$declaringClass][$typeName])) {
return $this->classesImports[$declaringClass][$typeName];
}
if (strpos($declaringClass, '\\') !== false && strpos($typeName, '\\') === false) {
$namespace = substr($declaringClass, 0, strrpos($declaringClass, '\\'));
return $namespace.'\\'.$typeName;
}
return $typeName;
}
/**
* @param array $addedClasses
* @throws ReflectionException
*/
public function addImports(array $addedClasses)
{
// array<string file, array<string localName, string fullName>
$cache = [];
foreach ($addedClasses as $addedClass) {
$class_reflection = ReflectionsCollection::getClass($addedClass);
if (!isset($cache[$class_reflection->getFileName()]))
$cache[$class_reflection->getFileName()] = $this->getImportsFromFile($class_reflection->getFileName());
$this->classesImports[$addedClass] = $cache[$class_reflection->getFileName()];
}
}
/**
* Глупый метод поиска импортов в файле, для разрешения сокращенных имён
*
* @param string $phpFile
* @return array
*/
public function getImportsFromFile(string $phpFile): array
{
$tokens = token_get_all(file_get_contents($phpFile));
$imports = [];
$t = count($tokens);
for ($i = 0; $i < $t; $i++) {
$token = $tokens[$i];
if (is_array($token) && $token[0] === T_USE) {
$import = null;
$i += 2;
while (is_array($tokens[$i]) && in_array($tokens[$i][0], [T_STRING, T_NS_SEPARATOR, T_WHITESPACE])) {
if ($tokens[$i][0] !== T_WHITESPACE) {
$import .= $tokens[$i][1];
}
$i++;
}
if (is_array($tokens[$i]) && $tokens[$i][0] == T_AS) {
$local_name = $tokens[$i + 2][1];
} else {
$local_name = strpos($import, '\\') ? substr(strrchr($import, '\\'), 1) : $import;
}
$imports[$local_name] = $import;
}
}
return $imports;
}
/**
* @param string $typeSpecification
* @param bool $isIterableType
* @return Schema
*/
public function generateSchemaForComplexAbstractType(string $typeSpecification, bool $isIterableType): Schema
{
// an array
if ($typeSpecification === 'array') {
$schema = new Schema([
'type' => 'array',
'items' => new Items([
'type' => 'object',
]),
]);
}
// an object
else if (in_array($typeSpecification, ['stdclass', 'object', 'mixed'], true)) {
$schema = new Schema([
'type' => 'object',
]);
}
if ($isIterableType) {
$schema = new Schema([
'type' => 'array',
'items' => $schema,
]);
}
return $schema;
}
/**
* @param Schema $schema
* @param AbstractAnnotation $new_schema
*/
public function transferOptions(Schema $schema, AbstractAnnotation $new_schema): void
{
if ($new_schema instanceof Parameter) {
foreach (['required', 'description', 'deprecated', 'example'] as $property) {
if ($schema->{$property} !== UNDEFINED) {
$new_schema->{$property} = $schema->{$property};
}
}
$new_schema->schema = $schema;
} else {
$new_schema->mergeProperties($schema);
}
}
/**
* @param string $typeSpecification
* @param string $declaringClass
* @param $defaultValue
* @param bool $isNullableType
* @param string|null $schemaType
* @return mixed|Property|Schema|null
* @throws ReflectionException
*/
protected function generateSchemaForFewTypes(
string $typeSpecification,
string $declaringClass,
$defaultValue,
bool &$isNullableType,
?string $schemaType,
&$kindOfType = null)
{
$type_specification_variants = explode('|', $typeSpecification);
if (in_array('null', $type_specification_variants, true)) {
$isNullableType = true;
unset($type_specification_variants[array_search('null', $type_specification_variants, true)]);
}
if (count($type_specification_variants) === 1) {
// if there really one type after "null" removing
$typeSpecification = current($type_specification_variants);
return $this->generateSchemaForType($declaringClass, current($type_specification_variants), $defaultValue, $isNullableType, $schemaType, $kindOfType);
}
// generate schemas for few types
$sub_type_schemas = [];
foreach ($type_specification_variants as $subtypeSpecification) {
$sub_type_schemas[] = $this->generateSchemaForType(
$declaringClass, $subtypeSpecification, $defaultValue, $isNullableType, $schemaType, $variantType);
if ($kindOfType === null || $kindOfType < $variantType) $kindOfType = $variantType;
}
if ($schemaType !== null && $schemaType !== Schema::class) {
if (!is_subclass_of($schemaType, Schema::class) && $schemaType !== Parameter::class)
throw new \RuntimeException('Invalid target Schema-class: ' . $schemaType);
switch ($schemaType) {
// case Property::class:
// return new Property([
// 'schema' => new Schema([
// 'oneOf' => $sub_type_schemas,
// ]),
// ]);
default:
return new $schemaType([
'oneOf' => $sub_type_schemas,
]);
}
} else {
return new Schema([
'oneOf' => $sub_type_schemas,
]);
}
}
}
| 31.931393
| 162
| 0.543655
|
c67ed6e0bd9b0429d3e14cc9f0b147b16cfcc8ea
| 1,725
|
py
|
Python
|
sensor_correction/gp_gpu.py
|
cheind/rgbd-correction
|
3cc6cae43d7393a58f9212167be90b1af0c67e39
|
[
"BSD-3-Clause"
] | 15
|
2017-09-15T14:39:29.000Z
|
2021-05-14T13:55:59.000Z
|
sensor_correction/gp_gpu.py
|
cheind/rgbd-correction
|
3cc6cae43d7393a58f9212167be90b1af0c67e39
|
[
"BSD-3-Clause"
] | 1
|
2020-11-05T19:57:40.000Z
|
2020-11-06T17:09:20.000Z
|
sensor_correction/gp_gpu.py
|
cheind/rgbd-correction
|
3cc6cae43d7393a58f9212167be90b1af0c67e39
|
[
"BSD-3-Clause"
] | 4
|
2018-11-15T06:34:52.000Z
|
2021-04-01T02:20:23.000Z
|
__author__ = 'Christoph Heindl'
__copyright__ = 'Copyright 2017, Profactor GmbH'
__license__ = 'BSD'
import numpy as np
import tensorflow as tf
class GPRegressorGPU:
'''Gaussian Process regressor on GPU.
Takes a pre-fitted Gaussian Process regressor (CPU) and prepares a TensorFlow graph for
prediction using pre-computed values.
'''
def __init__(self, gp_cpu, x):
'''Initialize regressor.
Params
------
gp_cpu : sensor_correction.GPRegressor
Pre-fitted Gaussing Process regressor
x : Nx4 tensor
Feature vectors on GPU.
'''
# Prepare constants
signal_var = tf.constant(gp_cpu.signal_std**2, dtype=tf.float32)
mean_y = tf.constant(gp_cpu.gpr.y_train_mean, dtype=tf.float32)
w = tf.constant(np.reciprocal(gp_cpu.length_scale), dtype=tf.float32)
# Pre-scale train and test
xtrain = tf.constant(gp_cpu.gpr.X_train_, dtype=tf.float32) * w
xtest = x * w
alpha = tf.expand_dims(tf.constant(gp_cpu.gpr.alpha_, dtype=tf.float32), -1)
# Compute pairwise squared distance
a = tf.matmul(
tf.expand_dims(tf.reduce_sum(tf.square(xtrain), 1), 1),
tf.ones(shape=(1, xtest.shape[0]))
)
b = tf.transpose(tf.matmul(
tf.reshape(tf.reduce_sum(tf.square(xtest), 1), shape=[-1, 1]),
tf.ones(shape=(xtrain.shape[0], 1)),
transpose_b=True
))
d = tf.add(a, b) - 2 * tf.matmul(xtrain, xtest, transpose_b=True)
# Eval kernel
k = signal_var * tf.exp(-0.5 * d)
# Predict
self.predict = tf.matmul(tf.transpose(k), alpha) + mean_y
| 30.803571
| 91
| 0.602319
|
b5e1fcad072554672ac9ee5284fdcc1d0ec3982f
| 92
|
dart
|
Dart
|
build.dart
|
Fulnir/dart-village
|
69231f68e721f075bf57c668bc5aaccd6c9c9df0
|
[
"MIT"
] | 3
|
2017-03-03T16:19:06.000Z
|
2018-05-25T11:01:57.000Z
|
build.dart
|
Fulnir/angular-dart-i18n-sample
|
d0e793763c906832e429ec8ecc51e10336cc4111
|
[
"MIT"
] | null | null | null |
build.dart
|
Fulnir/angular-dart-i18n-sample
|
d0e793763c906832e429ec8ecc51e10336cc4111
|
[
"MIT"
] | null | null | null |
import 'package:polymer/builder.dart';
main() {
build(entryPoints: ['web/index.html']);
}
| 18.4
| 41
| 0.684783
|
6d9c0ff34a3a640117132276b8d0a97f73a7596d
| 21,155
|
h
|
C
|
src/amuse/community/seba/src/SeBa/include/star/single_star.h
|
andrisdorozsmai/amuse
|
768d27ffe4acc21880f945199417589eabf0d600
|
[
"Apache-2.0"
] | null | null | null |
src/amuse/community/seba/src/SeBa/include/star/single_star.h
|
andrisdorozsmai/amuse
|
768d27ffe4acc21880f945199417589eabf0d600
|
[
"Apache-2.0"
] | null | null | null |
src/amuse/community/seba/src/SeBa/include/star/single_star.h
|
andrisdorozsmai/amuse
|
768d27ffe4acc21880f945199417589eabf0d600
|
[
"Apache-2.0"
] | null | null | null |
//=======================================================// _\|/_
// __ _____ ___ ___ // /|\
// / | ^ | \ | ^ | \ // _\|/_
// \__ | / \ |___/ | / \ |___/ // /|\
// \ | /___\ | \ | /___\ | \ // _\|/_
// ___/ | / \ | \ |____ / \ |___/ // /|\
// // _\|/_
//=======================================================// /|\
/*
* single_star.h: derived class for single star base element.
*
*.............................................................................
* version 1: Jan 1994 Simon F. Portegies Zwart
* version 2:
*.............................................................................
* This file includes:
* 1) definition of class estar
*
*.............................................................................
*/
#ifndef _SINGLE_STAR
# define _SINGLE_STAR
#include "star.h"
#include "star_state.h"
/*-----------------------------------------------------------------------------
* star -- the standard class for stellar evolution, with core and envelope
*-----------------------------------------------------------------------------
*/
class single_star : public star
{
protected:
int identity;
stellar_type star_type;
star_type_spec spec_type[no_of_spec_type];
real metalicity;
real current_time;
real relative_age;
real last_update_age;
real next_update_age;
// AMUSE
real time_offset;
// AMUSE
real relative_mass;
real envelope_mass;
real core_mass;
real COcore_mass;
real mzams;
real radius;
real core_radius;
real effective_radius;
real luminosity;
real velocity;
vec anomal_velocity;
real birth_mass;
real magnetic_field; //[log G]
real rotation_period; //[s]
real wind_constant;
real accreted_mass;
star_hist previous;
real beta_interpolated;
real k_interpolated;
real beta_array[19][25];
real timestamp_array[19][25];
real k_array[19][25];
real beta_array_SSO[14][15];
real timestamp_array_SSO[14][15];
real k_array_SSO[14][15];
public:
single_star(node*);
single_star(single_star&);
~single_star() {
get_seba_counters()->del_sstar++;
}
int no_of_elements() {return 1;}
star_type_spec get_spec_type(star_type_spec i) {
return spec_type[i];}
int get_identity() {return identity;}
real get_metalicity() {return metalicity;}
void set_metalicity(const real z) {metalicity = z;}
real get_previous_current_time() {return previous.current_time;}
real get_previous_total_mass() {return previous.envelope_mass
+ previous.core_mass;}
real get_current_time() {return current_time;}
real get_relative_age() {return relative_age;}
real get_effective_radius() {return effective_radius;}
real get_last_update_age() {return last_update_age;}
real get_next_update_age() {return next_update_age;}
real get_relative_mass() {return relative_mass;}
real get_envelope_mass() {return envelope_mass;}
real get_core_mass() {return core_mass;}
real get_COcore_mass() {return COcore_mass;}
real get_core_radius() {return core_radius;}
real get_radius() {return radius;}
real get_luminosity() {return luminosity;}
real get_velocity() {return velocity;}
vec get_anomal_velocity() {return anomal_velocity;}
real get_magnetic_field() {return magnetic_field;}
real get_rotation_period() {return rotation_period;}
real get_fallback(){return 0;}// only meaningful for BHs
stellar_type get_sep(){return star_type;}
real get_total_mass() {return envelope_mass + core_mass;}
real get_mzams() {return mzams;}
real get_beta_interpolated() {return beta_interpolated;}
real get_k_interpolated() {return k_interpolated;}
void set_current_time(real t) {current_time=t;}
void set_relative_age(real t) {relative_age=t;}
void set_luminosity(real l) {luminosity = l;}
void set_magnetic_field(real b){magnetic_field=b;}
void set_rotation_period(real p){rotation_period=p;}
void set_identity(int i) {identity=i;}
void set_envelope_mass(const real m) {envelope_mass = m;}
void set_core_mass(const real m) {core_mass = m;}
void set_COcore_mass(const real m) {COcore_mass = m;}
void set_spec_type(star_type_spec s, bool on=true);
void set_effective_radius(const real r) {effective_radius=r;}
void set_last_update_age(const real t) {last_update_age = t;}
void set_next_update_age(const real t) {next_update_age = t;}
void set_previous_radius(const real r) {previous.radius = r;}
void set_velocity(const real v) {velocity = v;}
void set_anomal_velocity(const vec v) {anomal_velocity = v;}
void set_beta_interpolated(real b) {beta_interpolated = b;}
void set_k_interpolated(real k) {k_interpolated = k;}
real magnitude();
real temperature();
real get_wind_constant();
// void clean();
// Replaced see below
// bool low_mass_star();
// bool medium_mass_star();
// bool high_mass_star();
void initialize(int id, real z, real t_cur,
real t_rel, real m_rel, real m_tot,
real m_core, real co_core);
// Time scales
real nucleair_evolution_timescale();
real kelvin_helmholds_timescale();
real dynamic_timescale();
real nucleair_evolution_time();
real nucleair_evolution_time(const real, const real, const real);
real get_evolve_timestep();
real mass_transfer_timescale(mass_transfer_type &type);
// Luminosities
real bolometric_correction();
bool remnant() {return false;} // default: not a remnant.
bool magnetic() {return false;} // default: no magnetic stellar wind.
bool hydrogen_envelope_star() {return true;}
bool giant_star() {return false;}
bool star_with_COcore() {return false;}
// real helium_core_radius();
void refresh_memory();
void recall_memory();
// stellar wind routines.
void update_wind_constant();
void stellar_wind(const real);
real wind_velocity();
real accrete_from_stellar_wind(const real, const real);
// Stability rourines.
real zeta_adiabatic();
real zeta_thermal();
real angular_momentum();
// radius change for donors/accretors
void adjust_donor_radius(const real);
void adjust_accretor_radius(const real, const real);
// Mass transfer routines.
// void add_mass_to_core(const real);
real add_mass_to_accretor(real, bool, const real = -1.);
// star* reduce_mass(const real);
real rejuvenation_fraction(const real);
void update_relative_mass(const real);
void lose_envelope_decent();
star* merge_elements(star*);
real mdot_limit(const real, real);
real mass_ratio_mdot_limit(real);
real accretion_limit(const real, const real);
real expansionA(const real);
real expansionB(const real);
real accretion_limit_eddington(const real, const real);
void update();
void detect_spectral_features();
// Input/Output
void read_element();
void put_element();
void dump(ostream&, bool brief = true);
void dump(char*, bool brief = true);
void print_status();
void print_roche();
void put_state();
void put_hrd(ostream &);
virtual void read_in_csv_table(real beta_array[19][25], char* filename);
virtual void read_in_csv_table(real beta_array[14][15], char* filename){};
virtual void determine_beta(const real mass, const real time);
//virtual void determine_beta_bd(const real mass, const real time);
//virtual void read_in_csv_table_bd(real beta_array_SSO[14][15], char* filename);
real tf2_energy_diss(const real);
real tf3_energy_diss(const real);
real potential_energy();
real kinetic_energy();
real total_energy();
void post_constructor();
void star_transformation_story(stellar_type);
void post_supernova_story();
void first_roche_lobe_contact_story(stellar_type);
virtual istream& scan_star_story(istream&);
virtual ostream& print_star_story(ostream&,
int short_output = 0);
real linear_function_inversion(real (single_star::*fptr)(real, const real),
const real x_guess, const real y_value, const real z = 0,
const real xmin = cnsts.parameters(minimum_main_sequence),
const real xmax = cnsts.parameters(maximum_main_sequence));
real update_core_and_envelope_mass(const real m_core);
real update_core_and_envelope_mass_TPAGB(const real m_core);
real update_COcore_mass(const real mco_core);
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// The new metalicity dependencies come here:
real get_zeta(const real z);
real helium_flash_mass(const real z);
real helium_ignition_mass(const real z);
real helium_ignition_luminosity(const real mass,
const real z);
real helium_ignition_radius(const real mass, const real mass_tot, const real z);
real helium_ignition_core_mass(const real mass,
const real z); // Eq.67
// real core_helium_burning_core_mass_from_helium_star(const real time,
// const real mass,
// const real z,
// const real mc);
// real core_helium_burning_core_mass_from_helium_star(const real mass,
// const real z);
bool low_mass_star(const real mass,
const real z);
bool low_mass_star();
bool medium_mass_star();
bool intermediate_mass_star(const real mass,
const real z);
bool high_mass_star(const real mass,
const real z);
bool high_mass_star();
real base_giant_branch_time(const real mass,
const real z);
// real base_giant_branch_time(const real mass);
real base_giant_branch_time();
real base_giant_branch_luminosity(const real mass,
const real z);
real base_giant_branch_luminosity(const real mass);
real base_giant_branch_luminosity();
real FGB_mass(const real z);
real get_hydrogen_fraction(const real z);
// real convective_envelope_mass(const real z);
real convective_envelope_mass(){return 0;}
real convective_envelope_radius(){return 0;}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// These functions are part of main_sequence.C
real main_sequence_hook_mass(const real z);
// friend main_sequence::main_sequence_hook_mass(const real z);
// real helium_flash_mass(const real z);
real main_sequence_time(const real mass,
const real z);
real main_sequence_time();
real main_sequence_hook_time(const real mass,
const real z);
real stars_without_main_sequence_hook(const real mass,
const real z);
real stars_with_main_sequence_hook(const real mass,
const real z);
real terminal_main_sequence_luminosity(const real mass,
const real z);
real terminal_main_sequence_radius(const real mass,
const real z);
//real base_main_sequence_radius(const real mass);
real base_main_sequence_radius(const real mass, const real z);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Hertzsprung-gap
real initial_hertzsprung_gap_core_mass(const real mass, const real z);
real terminal_hertzsprung_gap_core_mass(const real mass,
const real z);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++
//Functions for core helium burning
real giant_branch_radius(const real l_hb,
const real mass_tot,
const real z);
real minimum_blue_loop_radius(const real mass, const real mass_tot, const real z);
real base_horizontal_branch_luminosity(const real mass, const real z);
real minimum_horizontal_branch_luminosity(const real mass, const real z);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Core helium burning without envelope (helium star)
real helium_main_sequence_time_for_solar_metalicity(const real mass);
real helium_star_luminosity_for_solar_metalicity(const real mass);
real helium_star_radius_for_solar_metalicity(const real mass_tot);
real helium_main_sequence_luminosity(const real time, const real mass);
real helium_main_sequence_radius(const real time, const real mass, const real mass_tot);
real terminal_helium_main_sequence_luminosity(const real mass);
real helium_giant_luminosity_from_core_mass(
const real m_core, const real mass, const real z);
real helium_giant_radius(const real lum, const real mass,
const real mass_tot, const real z);
real helium_giant_x_mass(const real mass);
real helium_giant_x_luminosity(const real mass);
real helium_giant_B_factor();
real helium_giant_D_factor(const real mass);
real helium_giant_p_parameter();
real helium_giant_q_parameter();
real helium_giant_initial_core_mass(const real mass, const real z = 0);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Small envelope behaviour
void small_envelope_perturbation();
real small_envelope_mu(const real lum, const real mass_tot,
const real m_core);
real perturb_luminosity(const real lum, const real lum_c,
const real mass_tot, const real m_core, const real mu);
real perturb_radius(const real rad, const real rad_c, const real mass_tot,
const real m_core, const real mu);
real s_helper(const real mass_tot, const real mu);
real r_helper(const real rad, const real rad_c, const real mass_tot,
const real mu);
// don't do this:
// real small_envelope_core_luminosity(){return 0;};
// real small_envelope_core_radius(){return 0;};
// real helium_core_radius(){return 0;};
virtual real small_envelope_core_luminosity(){};
virtual real small_envelope_core_radius(){};
virtual real helium_core_radius(){};
//white dwarf
real white_dwarf_radius(real mass, real time);
// for virtual declaration in
// void evolve_core_mass(const real) {}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Shell hydrogen burning with envelope (sub giant)
real hydrogen_rate_constant(const real mass);
real sub_giant_Ah_estimator(const real mass);
real sub_giant_B_factor(const real mass);
real sub_giant_D_factor(const real mass);
real sub_giant_D_factor(const real mass,
const real z);
real sub_giant_p_parameter(const real mass,
const real z);
real sub_giant_q_parameter(const real mass,
const real z);
// real sub_giant_core_mass(const real time,
// const real mass,
// const real z);
real determine_core_mass(const real time,
const real mass,
const real z,
const real A,
const real t_b,
const real l_b);
real determine_age(const real m_core, const real mass,
const real z, const real A,
const real t_b, const real l_b);
real FGB_x_luminosity(const real mass, const real z);
real FGB_x_mass(const real mass, const real z);
real FGB_core_mass_luminosity_relation(const real lum,
const real mass,
const real z);
//real FGB_core_mass_luminosity_relation(const real time,
// const real mass,
// const real z);
real FGB_luminosity_core_mass_relation(const real time,
const real mass,
const real z);
real FGB_luminosity_core_mass_relation(const real m_core,
const real mass);
// real sub_giant_luminosity(const real time,
// const real mass,
// const real z);
// real specific_time_x_factor(const real mass,
// const real z);
real specific_time_boundary(const real mass,
const real A,
const real t_b,
const real l_b,
const real D,
const real p,
const real l_x);
// real specific_time_boundary(const real mass,
// const real z);
real specific_time_limit(const real A,
const real t_min,
const real DB,
const real l_min,
const real pq);
// real specific_upper_time_limit(const real mass,
// const real z,
// real (single_star::*fptr_time)(const real, const real),
// real (single_star::*fptr_luminosity)(const real, const real));
real helium_ignition_time(const real mass,
const real z);
real helium_ignition_time();
real base_giant_branch_core_mass(const real mass,
const real z);
real base_horizontal_branch_radius(const real mass,
const real mass_tot, const real z);
real core_helium_burning_timescale(const real mass,
const real z); //Eq.57
real core_helium_burning_timescale();
real base_AGB_luminosity(const real mass, const real z); // Eq.56
real base_AGB_time(const real mass, const real z);
real base_AGB_time();
real AGB_A_He_estimator(); //Eq.68
real AGB_radius(const real lum, const real mass, const real mass_tot, const real z);
real base_AGB_core_mass(const real mass, const real z); // Eq.66
real base_AGB_relative_mass(const real m_core, const real z); // Eq.66 inverted
real TAGB_time(const real mass, const real mass_tot, const real z);
real dredge_up_core_mass(const real mass, const real z);
real TPAGB_AH_He_estimator();
real maximum_AGB_core_mass(const real mass,
const real z); //Eq.75
real AGB_luminosity(const real CO_core_mass, const real mass,
const real z); //Eq.37
real dredge_up_time(const real mass, const real z);// Eq.70
real dredge_up_luminosity(const real mass, const real z);
// AMUSE
real get_time_offset() {return time_offset;}
void set_time_offset(real t) {time_offset=t;}
//AMUSE
};
// Shorthand for conversion from node pointer to star pointer:
#define N_SS_PTR ((single_star *)n->get_starbase())
// note: automatic conversion from star to dyn scaling
node* mkstar(int, real, stellar_type type=Main_Sequence);
void extract_story_chapter(stellar_type&, real& z,
real& t_cur, real& t_ral,
real&, real&, real&,
real&, real&,
real&, real&, real&,
story&);
void extract_line_text(stellar_type&, real& z, real&, real&, real&,
real&, real&, real&, real&, real&,
real&, real&, story&);
bool merge_elements(single_star* primary, single_star *secondary);
void addstar(node*,
real t_cur=0,
stellar_type type=Main_Sequence,
real z = cnsts.parameters(Zsun),
int id = 1,
bool verbose = false,
real m_rel = 1,
real m_env = 0,
real m_core = 0.0,
real mco_core = 0,
real t_rel = 0);
#endif // _SINGLE_STAR
| 38.887868
| 94
| 0.57731
|
8d749f90072677e325c988bf1eb3f79626c48a34
| 1,463
|
js
|
JavaScript
|
src/database/asc-marca-concesionaria-db.js
|
RadioCooperativa/ms-comun-cooperativa
|
859832f66fe772622bf5f6ecbc35f9c888b8ffdf
|
[
"MIT"
] | null | null | null |
src/database/asc-marca-concesionaria-db.js
|
RadioCooperativa/ms-comun-cooperativa
|
859832f66fe772622bf5f6ecbc35f9c888b8ffdf
|
[
"MIT"
] | 3
|
2020-07-07T19:54:58.000Z
|
2022-01-22T04:52:57.000Z
|
src/database/asc-marca-concesionaria-db.js
|
RadioCooperativa/ms-comun-cooperativa
|
859832f66fe772622bf5f6ecbc35f9c888b8ffdf
|
[
"MIT"
] | null | null | null |
'use strict';
const mysql = require('mysql2/promise');
const configDb = require('../../common/configDb');
const enums = require('../../common/enums');
const pool = mysql.createPool(configDb.db);
async function insertAscMaCo(params){
const { id_marca, id_concesionaria } = params;
const fecha_creacion = {fecha_creacion: new Date()}
let query = 'INSERT INTO T_REGISTROS_MARCA_CONCESIONARIA SET id_marca = ?, id_concesionaria = ?,fecha_creacion = ?, fecha_modificacion = ?, usuario_creacion = ?, usuario_modificacion = ?, vigente = ?';
const result = await pool.query(query,[id_marca, id_concesionaria, fecha_creacion.fecha_creacion, null, null, null, 0]);
if (!result[0]) {
throw new Error('Error al insertar datos y realizar asociación');
}
return result[0];
}
async function deleteAscMaCo(id_marca, id_concesionaria){
const fecha_modificacion = {fecha_modificacion: new Date()}
const eliminado = enums.Eliminado;
let query = 'UPDATE T_REGISTROS_MARCA_CONCESIONARIA SET fecha_modificacion = ?, usuario_modificacion = ?, vigente = ? WHERE ID_MARCA = '+id_marca+' AND ID_CONCESIONARIA = '+id_concesionaria+'';
const result = await pool.query(query,[fecha_modificacion.fecha_modificacion, null, eliminado]);
if (result[0].affectedRows === 0) {
return null;
}
return result[0];
}
module.exports = {
insertAscMaCo: insertAscMaCo,
deleteAscMaCo: deleteAscMaCo
}
| 36.575
| 205
| 0.701299
|
b7152fb50e08e8b3620ec08028a9ca82fa731341
| 1,414
|
cs
|
C#
|
api/database/Program.cs
|
schmared/garden-thyme
|
ca91c0c6429279923ddcfc6bc301f726248e07ee
|
[
"MIT"
] | 1
|
2020-07-22T01:06:27.000Z
|
2020-07-22T01:06:27.000Z
|
api/database/Program.cs
|
schmared/garden-thyme
|
ca91c0c6429279923ddcfc6bc301f726248e07ee
|
[
"MIT"
] | 4
|
2021-03-10T15:01:22.000Z
|
2022-02-27T03:10:01.000Z
|
api/database/Program.cs
|
schmared/garden-thyme
|
ca91c0c6429279923ddcfc6bc301f726248e07ee
|
[
"MIT"
] | 1
|
2020-04-17T00:26:30.000Z
|
2020-04-17T00:26:30.000Z
|
namespace database
{
internal class Program
{
// TODO: Finish Implementing Active Database Migrations (Requires FlientMigrator.Runner package)
private static void Main(string[] args)
{
// using (var scope = CreateServices().CreateScope())
// UpdateDatabase(scope.ServiceProvider);
}
// public static IConfiguration Configuration { get; set; }
// private static IServiceProvider CreateServices()
// {
// Configuration = new ConfigurationBuilder()
// .SetBasePath(Directory.GetCurrentDirectory())
// .AddJsonFile("appsettings.json")
// .Build();
// return new ServiceCollection()
// .AddFluentMigratorCore()
// .ConfigureRunner(rb => rb
// .AddSqlServer()
// .WithGlobalConnectionString(Configuration["{ConnectionStrings.database}"])
// .ScanIn(typeof(M0_EmptyDb).Assembly).For.Migrations())
// .AddLogging(lb => lb.AddFluentMigratorConsole())
// .BuildServiceProvider(false);
// }
// private static void UpdateDatabase(IServiceProvider serviceProvider)
// {
// serviceProvider.GetRequiredService<IMigrationRunner>().MigrateUp();
// }
}
}
| 38.216216
| 105
| 0.553748
|
e725ae33f6d1f3cf0ca151e78da433a317fa3cae
| 110
|
lua
|
Lua
|
test/box/backup_test.lua
|
dmitryikh/tarantool
|
5ca12a403aff06f17840daf966f98da71ba42aa8
|
[
"BSD-2-Clause"
] | 80
|
2019-09-05T21:28:39.000Z
|
2021-06-11T08:58:02.000Z
|
test/box/backup_test.lua
|
dmitryikh/tarantool
|
5ca12a403aff06f17840daf966f98da71ba42aa8
|
[
"BSD-2-Clause"
] | 1
|
2020-03-16T12:03:49.000Z
|
2020-03-16T12:03:49.000Z
|
test/box/backup_test.lua
|
dmitryikh/tarantool
|
5ca12a403aff06f17840daf966f98da71ba42aa8
|
[
"BSD-2-Clause"
] | 5
|
2019-09-06T07:23:40.000Z
|
2020-01-07T12:18:12.000Z
|
#!/usr/bin/env tarantool
box.cfg{listen = os.getenv("LISTEN")}
require('console').listen(os.getenv('ADMIN'))
| 22
| 45
| 0.7
|
af16deaf358c283c62cd961c978b353fcc5a3d71
| 2,305
|
py
|
Python
|
books/views.py
|
pankajlal/prabandh
|
8f313d616f20ff15c852e4e58a34d44983cc9c07
|
[
"Apache-2.0"
] | null | null | null |
books/views.py
|
pankajlal/prabandh
|
8f313d616f20ff15c852e4e58a34d44983cc9c07
|
[
"Apache-2.0"
] | null | null | null |
books/views.py
|
pankajlal/prabandh
|
8f313d616f20ff15c852e4e58a34d44983cc9c07
|
[
"Apache-2.0"
] | 1
|
2019-04-12T16:32:42.000Z
|
2019-04-12T16:32:42.000Z
|
from django.shortcuts import render
# Create your views here.
#{
# "token":"",
# "content":"record",
# "formId":"build_BeMe-Observations_1466792215",
# "formVersion":"",
# "data":[
# {"*meta-instance-id*":"uuid:60754793-2619-4bba-8a33-49e66684a050",
# "*meta-model-version*":null,
# "*meta-ui-version*":null,
# "*meta-submission-date*":"2016-06-25T09:18:02.987Z",
# "*meta-is-complete*":true,
# "*meta-date-marked-as-complete*":"2016-06-25T09:18:02.987Z",
# "instanceID":"uuid:60754793-2619-4bba-8a33-49e66684a050",
# "picture":{
# "filename":"1466834286870.jpg",
# "type":"image/jpeg",
# "url":"https://beme-odk-collect.appspot.com/view/binaryData?blobKey=build_BeMe-Observations_1466792215%5B%40version%3Dnull+and+%40uiVersion%3Dnull%5D%2Fdata%5B%40key%3Duuid%3A60754793-2619-4bba-8a33-49e66684a050%5D%2Fpicture"
# },
# "observations":"Enjoyed coffee",
# "child":"abhimanyu",
# "submitter":"parent",
# "starttime":"2016-06-25T01:36:28.646Z"
# }
# ]
# }
from isbntools import app
from .models import Isbn, Author
from django.core.exceptions import ObjectDoesNotExist
from datetime import date
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
def _make_isbn(isbn_no):
meta_dict = app.meta(isbn_no)
if meta_dict:
if meta_dict.get('Title'):
try:
isbn = Isbn.objects.get(code=isbn_no)
except ObjectDoesNotExist:
isbn = Isbn(code=isbn_no,
title=meta_dict.get('Title'),
publisher=meta_dict.get('Publisher'),
year=date(2001, 1, 1)
)
isbn.save()
for a in meta_dict.get('Authors'):
try:
author = Author.objects.get(name=a)
except ObjectDoesNotExist:
author = Author.objects.create(name=a)
isbn.authors.add(author)
@csrf_exempt
def isbn_post(request):
odk_data = json.loads(request.body.decode('utf-8'))
isbn_details = odk_data.get('data')
for item in isbn_details:
isbn_no = item.get('isbn')
_make_isbn(isbn_no)
return HttpResponse()
| 31.575342
| 234
| 0.604772
|
daacb2f6f44047fdfc34f1ca4b2af754da2f370f
| 9,861
|
php
|
PHP
|
resources/views/system2.blade.php
|
ericting2000/DBMS
|
7a425d128767b43da0198e2833921471389324ea
|
[
"MIT"
] | null | null | null |
resources/views/system2.blade.php
|
ericting2000/DBMS
|
7a425d128767b43da0198e2833921471389324ea
|
[
"MIT"
] | null | null | null |
resources/views/system2.blade.php
|
ericting2000/DBMS
|
7a425d128767b43da0198e2833921471389324ea
|
[
"MIT"
] | null | null | null |
<!DOCTYPE blade.php>
<blade.php lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
<!-- Bootstrap CSS -->
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css"
/>
<title></title>
</head>
<style>
a {
text-decoration: none;
color: black;
}
a:hover {
text-decoration: none;
}
header {
height: 95px;
background: #003865;
filter: drop-shadow(0px 4px 5px rgba(0, 0, 0, 0.25));
}
blade.php,
body,
box,
content {
height: 100%;
width: 100%;
overflow: hidden;
}
.side {
height: auto;
width: 230px;
border-right: 1px solid rgba(0, 0, 0, 0.1);
}
.modal-header {
border-radius: 14px 14px 0 0;
background-color: #003865;
border-bottom: 0 none;
}
.modal-content {
border-radius: 16px;
}
.modal-footer {
border-top: 0 none;
justify-content: center;
}
.logo {
display: flex;
align-items: center;
justify-content: center;
width: 230px;
}
.logo #netflix {
margin: 0;
padding: 25px 0;
}
.sidebar {
display: flex;
align-items: center;
justify-content: center;
width: 230px;
}
.sidebar .menu {
width: 100%;
margin: 0;
padding: 0;
}
.menu li {
list-style: none;
font-size: 18pt;
font-weight: 400;
padding: 10px 0px;
text-align: center;
}
.menu li:hover {
background-color: rgba(108, 159, 200, 0.77);
color: white;
-o-transition: color 0.2s linear;
-webkit-transition: color 0.2s linear;
-moz-transition: color 0.2s linear;
transition: color 0.2s linear;
-o-transition: background-color 0.2s linear;
-webkit-transition: background-color 0.2s linear;
-moz-transition: background-color 0.2s linear;
transition: background-color 0.2s linear;
}
.data {
display: flex;
background: #ffffff;
box-shadow: 0px 0px 11px 7px rgba(0, 0, 0, 0.04);
padding: 50px;
margin-left: 55px;
width: 90%;
}
.row .col-md-12:hover {
background-color: #003865 !important;
color: white;
-o-transition: color 0.2s linear;
-webkit-transition: color 0.2s linear;
-moz-transition: color 0.2s linear;
transition: color 0.2s linear;
-o-transition: background-color 0.2s linear;
-webkit-transition: background-color 0.2s linear;
-moz-transition: background-color 0.2s linear;
transition: background-color 0.2s linear;
}
.row .col-md-12 #p1,
#p2{
width: 50%;
margin: 0;
}
</style>
<script>
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
let getdata = () => {
document.getElementById("nametag").innerHTML = getCookie("name");
}
</script>
<body onload="getdata()">
<header>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<p class="navbar-brand" style="color: white; margin-top: 20px">
顧客管理
</p>
</div>
<div class="dropdown">
<a
class="btn btn-secondary dropdown-toggle"
href="#"
role="button"
id="nametag"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"
style="background-color: #003865; color: white; border: none"
>
登入的人
</a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="./SystemLanding">登出</a>
</div>
</div>
</div>
</nav>
</header>
<box style="display: flex">
<nav class="side">
<div class="logo">
<div id="netflix">
<img src="{{ asset('Logo.png') }}" alt=""/>
</div>
</div>
<div class="sidebar">
<ul class="menu">
<a href="./System1"><li>產品使用者總覽</li></a>
<a href=""><li style="
background-color: rgba(108, 159, 200, 0.77);
color: white;
">報修資訊系統</li></a>
</ul>
</div>
</nav>
<content>
<p style="font-size: 36px; padding: 80px 50px 50px">報修資訊系統</p>
<div class="data" style="display: block">
<div class="row">
<div
class="col-md-6"
style="
background-color: rgba(108, 159, 200, 0.77);
text-align: center;
padding: 5px 0;
"
>
報修公司
</div>
<div
class="col-md-6"
style="
background-color: rgba(108, 159, 200, 0.77);
text-align: center;
padding: 5px 0;
"
>
問題主旨
</div>
</div>
<a href="#detail"
><div class="row">
<div
class="col-md-12"
style="
background-color: rgba(235, 235, 235, 0.63);
text-align: center;
padding: 5px 0;
display: flex;
"
>
<p id="p1">CHT</p>
<p id="p2">股東新增壞了</p>
</div>
</div>
</a>
</div>
</content>
</box>
<!--Modal detail-->
<div
class="modal fade bd-example-modal-lg"
id="detail"
tabindex="-1"
role="dialog"
aria-labelledby="exampleModalCenterTitle"
aria-hidden="true"
>
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5
class="modal-title"
id="exampleModalCenterTitle"
style="color: white; font-weight: 400"
>
資訊細項
</h5>
<button
type="button"
class="close"
data-dismiss="modal"
aria-label="Close"
style="color: white; font-size: 30px"
>
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-7" style="color: rgba(0, 0, 0, 0.5)">報修公司</div>
<div class="col-md-5" style="color: rgba(0, 0, 0, 0.5)">問題主旨</div>
<div
class="col-md-7"
style="font-size: 14pt; padding-bottom: 15px"
>
CHT
</div>
<div class="col-md-5" style="font-size: 14pt; padding-bottom: 15px">
股東新增壞了
</div>
<div class="col-md-7" style="color: rgba(0, 0, 0, 0.5)">問題描述</div>
<div
class="col-md-7"
style="font-size: 14pt; padding-bottom: 15px"
>
股東新增壞了
</div>
</div>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-primary"
style="
background-color: #003865;
border-style: none;
padding: 6px 20px;
"
>
處理完畢
</button>
</div>
</div>
</div>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script
src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"
></script>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
crossorigin="anonymous"
></script>
<script
src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
crossorigin="anonymous"
></script>
<!---date picker-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.js"></script>
<script>
$('.datepicker').datepicker({
format: 'yyyy.mm.dd',
});
</script>
<!-- modal show-->
<script>
$('a[href$="#detail"]').on('click', function () {
$('#detail').modal('show');
});
</script>
</body>
</blade.php>
| 27.391667
| 124
| 0.490518
|
dbf6c269e1d1708586d28ced19b55872d9bf3420
| 384
|
h
|
C
|
Velectric/Velectric/AppClasses/Category/CategoryHome/View/HeaderView.h
|
NameV/Velectric
|
32ee548ec2348761caa7fa21eb3efb5a545cedf5
|
[
"MIT"
] | 1
|
2018-05-05T15:12:13.000Z
|
2018-05-05T15:12:13.000Z
|
Velectric/Velectric/AppClasses/Category/CategoryHome/View/HeaderView.h
|
NameV/Velectric
|
32ee548ec2348761caa7fa21eb3efb5a545cedf5
|
[
"MIT"
] | null | null | null |
Velectric/Velectric/AppClasses/Category/CategoryHome/View/HeaderView.h
|
NameV/Velectric
|
32ee548ec2348761caa7fa21eb3efb5a545cedf5
|
[
"MIT"
] | 2
|
2018-05-05T15:12:16.000Z
|
2019-09-28T14:59:56.000Z
|
//
// HeaderView.h
// Velectric
//
// Created by pengjingli on 16/12/1.
// Copyright © 2016年 LiuXiaoQin. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface HeaderView : UICollectionReusableView
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *label;
@property (weak, nonatomic) IBOutlet UIButton *allBtn;
@end
| 21.333333
| 60
| 0.736979
|
c67e5a6fdcbd223c30896d1b8c1617c7a9b4005d
| 1,541
|
py
|
Python
|
src/0010对称二叉树/index.py
|
zzh2036/OneDayOneLeetcode
|
1198692e68f8f0dbf15555e45969122e1a92840a
|
[
"MIT"
] | null | null | null |
src/0010对称二叉树/index.py
|
zzh2036/OneDayOneLeetcode
|
1198692e68f8f0dbf15555e45969122e1a92840a
|
[
"MIT"
] | null | null | null |
src/0010对称二叉树/index.py
|
zzh2036/OneDayOneLeetcode
|
1198692e68f8f0dbf15555e45969122e1a92840a
|
[
"MIT"
] | null | null | null |
'''
给定一个二叉树,检查它是否是镜像对称的
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
'''
方法1,递归
'''
def isSymmetric1(self, root: TreeNode) -> bool:
if not root:
return True
def recursionFind(l, r):
if not l and not r:
return True
if not l or not r:
return False
if l.val != r.val:
return False
return recursionFind(l.left, r.right) and recursionFind(r.left, l.right)
return recursionFind(root.left, root.right)
'''
方法2,迭代
'''
def isSymmetric2(self, root: TreeNode) -> bool:
if not root:
return True
def check(l, r):
if not l and not r:
return True
if not l or not r:
return False
if l.val != r.val:
return False
return True
deq = deque([(root.left, root.right), ])
while deq:
l, r = deq.popleft()
if not check(l, r):
return False
if l:
deq.append((l.left, r.right))
deq.append((r.left, l.right))
return True
| 20.546667
| 84
| 0.473069
|
af94c4f09016d2ecf0e233b037e48f17413bfb22
| 2,068
|
py
|
Python
|
clr_ext/build.py
|
sho7noka/Python.Passing
|
c418f0c9e730145b390e52437b584af306485169
|
[
"MIT"
] | 1
|
2020-08-09T09:29:19.000Z
|
2020-08-09T09:29:19.000Z
|
clr_ext/build.py
|
sho7noka/Unison
|
c418f0c9e730145b390e52437b584af306485169
|
[
"MIT"
] | null | null | null |
clr_ext/build.py
|
sho7noka/Unison
|
c418f0c9e730145b390e52437b584af306485169
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
import platform
import shutil
import subprocess
from distutils import sysconfig
from setuptools import Extension
from setuptools.command import build_ext
class PythonNetExtension(Extension):
"""
python build system for csc
>>> ext_modules=[PythonNetExtension('package_name', ["test.cs"])],
"""
def __init__(self, name, sources=[], is_lib=True, compiler=None):
"""
Args:
name:
sourcedir:
"""
Extension.__init__(self, name, sources=sources)
self.runtime = sysconfig.get_python_lib() + "Python.Runtime.dll"
self.is_lib = is_lib
self.compiler = compiler
class PythonNetBuild(build_ext.build_ext):
"""
pythonnet 用 setuptoolの拡張
Python.Runtime.dll と python.dll, python.zip
https://docs.python.org/ja/3/distutils/apiref.html
>>> cmdclass={'build_ext': PythonNetBuild},
"""
if platform.platform() == "Windows":
csc = "C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe"
else:
csc = "csc"
def run(self):
try:
_ = subprocess.check_output([self.csc, '/help'])
except OSError:
raise RuntimeError("csc must be installed to build the following extensions: " +
", ".join(e.name for e in self.extensions))
for ext in self.extensions:
self.build_extension(ext)
def build_extension(self, ext):
"""
https://qiita.com/toshirot/items/dcf7809007730d835cfc
Returns:
"""
cmd = [
ext.compiler or self.csc,
"-nologo",
"/t:library" if ext.is_lib else "/t:exe",
"/out:%s.dll" % ext.name if ext.is_lib else "/out:%s.exe" % ext.name,
"/r:%s" % ext.runtime,
ext.sources,
]
subprocess.check_call(cmd, shell=True)
# package
dllib = [".dll", ".a", ".so"]
pythonz = sysconfig.get_python_lib(True, True)
shutil.make_archive(pythonz, "zip", root_dir=pythonz)
| 29.126761
| 92
| 0.585106
|
ddb5037f6c0272d2832afa91af33cf99aa87744b
| 2,553
|
java
|
Java
|
WebMarket12/src/filter/LogFilter.java
|
daehyeonhong/JSP
|
fccf1688dabdca075e093a259cb0fdf5fb0c90bf
|
[
"MIT"
] | 1
|
2020-07-15T05:03:14.000Z
|
2020-07-15T05:03:14.000Z
|
WebMarket12/src/filter/LogFilter.java
|
daehyeonhong/JSP
|
fccf1688dabdca075e093a259cb0fdf5fb0c90bf
|
[
"MIT"
] | null | null | null |
WebMarket12/src/filter/LogFilter.java
|
daehyeonhong/JSP
|
fccf1688dabdca075e093a259cb0fdf5fb0c90bf
|
[
"MIT"
] | null | null | null |
package filter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class LogFilter implements Filter {
/* 로그 기록객체 생성 */
PrintWriter writer;
public void destroy() {
/* 자원해제 처리 */
writer.close();
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
writer.printf("접촉한 클라이언트 IP: %s %n", request.getRemoteAddr());
long start = System.currentTimeMillis();
writer.printf("요청방식: %s %n", ((HttpServletRequest) request).getMethod());
/* ServletRequest -> HttpServletRequest casting */
writer.printf("접근한 URL 경로: %s %n", getURLPath(request));
writer.printf("요청 처리 시작 시각: %s %n", getCurrentTime());
chain.doFilter(request, response);
long end = System.currentTimeMillis();
writer.printf("요청 처리 종료시각: %s %n", getCurrentTime());
writer.printf("요청 처리 소요시간: %s ms%n", (end - start));
writer.printf("─────────────────────%n");
}
private String getCurrentTime() {
/* 날짜 출력 포멧 객체 생성 */
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.S");
/* 달력정보 얻기 */
Calendar calendar = Calendar.getInstance();/* Calendar Singleton객체 얻기 */
/* 달력객체 현재 날짜 시간정보 */
calendar.setTimeInMillis(System.currentTimeMillis());
/* 현재 날짜 정보를 format형식으로 리턴 */
return formatter.format(calendar.getTime());
}
private String getURLPath(ServletRequest request) {
HttpServletRequest req;
String currentPath = "";
String queryString = "";
if (request instanceof HttpServletRequest) {
req = (HttpServletRequest) request;/* casting */
currentPath = req.getRequestURI();
queryString = queryString == null ? "" : "?" + queryString;
}
System.out.println("url: " + currentPath + queryString);
return currentPath + queryString;
}
public void init(FilterConfig fConfig) throws ServletException {
/* 로그기록할 파일정보 얻기 */
String filename = fConfig.getInitParameter("filename");
if (filename == null) {
throw new ServletException("로그파일 이름을 찾을 수 없습니다.");
}
try {
/* 로그기록할 파일객체 생성 */
writer = new PrintWriter(new FileWriter(filename, true), true);
} catch (Exception e) {
throw new ServletException("로그파일을 열 수 없습니다.");
}
}
}
| 31.9125
| 90
| 0.709362
|
b36d9dfedbddc9e37bf3955d56c215e0c0aef5e9
| 10,027
|
py
|
Python
|
pandaclient/openidc_utils.py
|
matthewfeickert/panda-client
|
077bb692a6f42ced0b388c96b8fd64ca032d6df7
|
[
"Apache-2.0"
] | 7
|
2016-01-26T21:37:26.000Z
|
2020-09-10T07:44:54.000Z
|
pandaclient/openidc_utils.py
|
matthewfeickert/panda-client
|
077bb692a6f42ced0b388c96b8fd64ca032d6df7
|
[
"Apache-2.0"
] | 12
|
2017-10-11T09:15:01.000Z
|
2021-11-17T00:23:18.000Z
|
pandaclient/openidc_utils.py
|
matthewfeickert/panda-client
|
077bb692a6f42ced0b388c96b8fd64ca032d6df7
|
[
"Apache-2.0"
] | 9
|
2017-07-20T08:06:36.000Z
|
2021-11-15T04:22:06.000Z
|
import os
import sys
import ssl
import uuid
import json
import time
import glob
import base64
import datetime
try:
from urllib import urlencode
from urllib2 import urlopen, Request, HTTPError
except ImportError:
from urllib.request import urlopen, Request
from urllib.parse import urlencode
from urllib.error import HTTPError
raw_input = input
TOKEN_BASENAME = '.token'
CACHE_PREFIX = '.page_cache_'
class OpenIdConnect_Utils:
# constructor
def __init__(self, auth_config_url, token_dir=None, log_stream=None, verbose=False):
self.auth_config_url = auth_config_url
if token_dir is None:
token_dir = os.environ['PANDA_CONFIG_ROOT']
self.token_dir = os.path.expanduser(token_dir)
if not os.path.exists(token_dir):
os.makedirs(token_dir)
self.log_stream = log_stream
self.verbose = verbose
# get token path
def get_token_path(self):
return os.path.join(self.token_dir, TOKEN_BASENAME)
# get device code
def get_device_code(self, device_auth_endpoint, client_id, audience):
if self.verbose:
self.log_stream.debug('getting device code')
data = {'client_id': client_id,
'scope': "openid profile email offline_access ",#iam",
'audience': audience}
print (data)
rdata = urlencode(data).encode()
req = Request(device_auth_endpoint, rdata)
req.add_header('content-type', 'application/x-www-form-urlencoded')
try:
conn = urlopen(req)
text = conn.read()
if self.verbose:
self.log_stream.debug(text)
return True, json.loads(text)
except HTTPError as e:
return False, 'code={0}. reason={1}. description={2}'.format(e.code, e.reason, e.read())
except Exception as e:
return False, str(e)
# get ID token
def get_id_token(self, token_endpoint, client_id, client_secret, device_code, interval, expires_in):
self.log_stream.info('Ready to get ID token?')
while True:
sys.stdout.write("[y/n] \n")
choice = raw_input().lower()
if choice == 'y':
break
elif choice == 'n':
return False, "aborted"
if self.verbose:
self.log_stream.debug('getting ID token')
startTime = datetime.datetime.utcnow()
data = {'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'urn:ietf:params:oauth:grant-type:device_code',
'device_code': device_code}
rdata = urlencode(data).encode()
req = Request(token_endpoint, rdata)
req.add_header('content-type', 'application/x-www-form-urlencoded')
while datetime.datetime.utcnow() - startTime < datetime.timedelta(seconds=expires_in):
try:
conn = urlopen(req)
text = conn.read().decode()
if self.verbose:
self.log_stream.debug(text)
id_token = json.loads(text)['id_token']
with open(self.get_token_path(), 'w') as f:
f.write(text)
return True, id_token
except HTTPError as e:
text = e.read()
try:
description = json.loads(text)
# pending
if description['error'] == "authorization_pending":
time.sleep(interval + 1)
continue
except Exception:
pass
return False, 'code={0}. reason={1}. description={2}'.format(e.code, e.reason, text)
except Exception as e:
return False, str(e)
# refresh token
def refresh_token(self, token_endpoint, client_id, client_secret, refresh_token_string):
if self.verbose:
self.log_stream.debug('refreshing token')
data = {'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'refresh_token',
'refresh_token': refresh_token_string}
rdata = urlencode(data).encode()
req = Request(token_endpoint, rdata)
req.add_header('content-type', 'application/x-www-form-urlencoded')
try:
conn = urlopen(req)
text = conn.read()
if self.verbose:
self.log_stream.debug(text)
id_token = json.loads(text)['id_token']
with open(self.get_token_path(), 'w') as f:
f.write(text)
return True, id_token
except HTTPError as e:
return False, 'code={0}. reason={1}. description={2}'.format(e.code, e.reason, e.read())
except Exception as e:
return False, str(e)
# fetch page
def fetch_page(self, url):
path = os.path.join(self.token_dir, CACHE_PREFIX + str(uuid.uuid5(uuid.NAMESPACE_URL, str(url))))
if os.path.exists(path) and \
datetime.datetime.now() - datetime.datetime.fromtimestamp(os.path.getmtime(path)) < \
datetime.timedelta(hours=1):
try:
with open(path) as f:
return True, json.load(f)
except Exception as e:
self.log_stream.debug('cached {0} is corrupted: {1}'.format(os.path.basename(url), str(e)))
if self.verbose:
self.log_stream.debug('fetching {0}'.format(url))
try:
context = ssl._create_unverified_context()
conn = urlopen(url, context=context)
text = conn.read().decode()
if self.verbose:
self.log_stream.debug(text)
with open(path, 'w') as f:
f.write(text)
with open(path) as f:
return True, json.load(f)
except HTTPError as e:
return False, 'code={0}. reason={1}. description={2}'.format(e.code, e.reason, e.read())
except Exception as e:
return False, str(e)
# check token expiry
def check_token(self):
token_file = self.get_token_path()
if os.path.exists(token_file):
with open(token_file) as f:
if self.verbose:
self.log_stream.debug('check {0}'.format(token_file))
try:
# decode ID token
data = json.load(f)
enc = data['id_token'].split('.')[1]
enc += '=' * (-len(enc) % 4)
dec = json.loads(base64.urlsafe_b64decode(enc.encode()))
exp_time = datetime.datetime.fromtimestamp(dec['exp'])
delta = exp_time - datetime.datetime.now()
if self.verbose:
self.log_stream.debug('token expiration time : {0}'.\
format(exp_time.strftime("%Y-%m-%d %H:%M:%S")))
# check expiration time
if delta < datetime.timedelta(minutes=10):
# return refresh token
if 'refresh_token' in data:
if self.verbose:
self.log_stream.debug('to refresh token')
return False, data['refresh_token'], dec
else:
# return valid token
if self.verbose:
self.log_stream.debug('valid token is available')
return True, data['id_token'], dec
except Exception as e:
self.log_stream.error('failed to decode cached token with {0}'.format(e))
if self.verbose:
self.log_stream.debug('cached token unavailable')
return False, None, None
# run device authorization flow
def run_device_authorization_flow(self):
# check toke expiry
s, o, dec = self.check_token()
if s:
# still valid
return True, o
refresh_token_string = o
# get auth config
s, o = self.fetch_page(self.auth_config_url)
if not s:
return False, "Failed to get Auth configuration: " + o
auth_config = o
# get endpoint config
s, o = self.fetch_page(auth_config['oidc_config_url'])
if not s:
return False, "Failed to get endpoint configuration: " + o
endpoint_config = o
# refresh token
if refresh_token_string is not None:
s, o = self.refresh_token(endpoint_config['token_endpoint'], auth_config['client_id'],
auth_config['client_secret'], refresh_token_string)
# refreshed
if s:
return True, o
# get device code
s, o = self.get_device_code(endpoint_config['device_authorization_endpoint'], auth_config['client_id'],
auth_config['audience'])
if not s:
return False, 'Failed to get device code: ' + o
# get ID token
self.log_stream.info(("Please go to {0} and sign in. "
"Waiting until authentication is completed").format(o['verification_uri_complete']))
if 'interval' in o:
interval = o['interval']
else:
interval = 5
s, o = self.get_id_token(endpoint_config['token_endpoint'], auth_config['client_id'],
auth_config['client_secret'], o['device_code'], interval, o['expires_in'])
if not s:
return False, "Failed to get ID token: " + o
self.log_stream.info('All set')
return True, o
# cleanup
def cleanup(self):
for patt in [TOKEN_BASENAME, CACHE_PREFIX]:
for f in glob.glob(os.path.join(self.token_dir, patt + '*')):
os.remove(f)
| 40.760163
| 111
| 0.54832
|
bb05a6ae816e64d85120a04930f69cad89cd4c4f
| 4,868
|
cs
|
C#
|
src/ITfoxtec.Identity.Saml2/Util/GenericTypeConverter.cs
|
EugeneZhudro/ITfoxtec.Identity.Saml2
|
036d5bf74379e73ee2477b38ae4322ad52022c90
|
[
"BSD-3-Clause"
] | 156
|
2016-08-04T21:23:06.000Z
|
2022-03-14T13:26:40.000Z
|
src/ITfoxtec.Identity.Saml2/Util/GenericTypeConverter.cs
|
EugeneZhudro/ITfoxtec.Identity.Saml2
|
036d5bf74379e73ee2477b38ae4322ad52022c90
|
[
"BSD-3-Clause"
] | 88
|
2016-07-17T19:09:41.000Z
|
2022-03-23T20:19:21.000Z
|
src/ITfoxtec.Identity.Saml2/Util/GenericTypeConverter.cs
|
EugeneZhudro/ITfoxtec.Identity.Saml2
|
036d5bf74379e73ee2477b38ae4322ad52022c90
|
[
"BSD-3-Clause"
] | 99
|
2016-08-20T19:34:11.000Z
|
2022-03-31T15:26:49.000Z
|
using Schemas = ITfoxtec.Identity.Saml2.Schemas;
using System;
using System.Globalization;
using System.Xml;
using ITfoxtec.Identity.Saml2.Schemas;
using System.Collections.Generic;
#if NETFULL
using System.IdentityModel.Tokens;
#else
using Microsoft.IdentityModel.Tokens.Saml2;
#endif
namespace ITfoxtec.Identity.Saml2.Util
{
internal static class GenericTypeConverter
{
internal static T ConvertValue<T>(string value, XmlNode xmlNode)
{
if (string.IsNullOrWhiteSpace(value))
{
return default;
}
var genericType = typeof(T);
if (genericType == typeof(Uri))
{
return GenericConvertValue<T, Uri>(new Uri(value));
}
else if (genericType == typeof(Saml2Id))
{
return GenericConvertValue<T, Saml2Id>(new Saml2Id(value));
}
else if (genericType == typeof(DateTimeOffset))
{
return GenericConvertValue<T, DateTimeOffset>(DateTimeOffset.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal));
}
else if (genericType == typeof(Saml2NameIdentifier))
{
return GenericConvertValue<T, Saml2NameIdentifier>(new Saml2NameIdentifier(value, ConvertValue<Uri>(xmlNode.Attributes[Schemas.Saml2Constants.Message.Format]?.Value, xmlNode)));
}
else if (genericType == typeof(NameID))
{
return GenericConvertValue<T, NameID>(new NameID { ID = value, Format = xmlNode.Attributes[Schemas.Saml2Constants.Message.Format]?.Value });
}
else if(genericType == typeof(AuthnContextComparisonTypes))
{
if (Enum.TryParse(value, out AuthnContextComparisonTypes authnContextComparisonTypes))
{
return GenericConvertValue<T, AuthnContextComparisonTypes>(authnContextComparisonTypes);
}
else
{
return default;
}
}
else
{
return GenericConvertValue<T, string>(value);
}
}
internal static T ConvertElement<T>(XmlNode xmlNode)
{
if (xmlNode == null)
{
return default;
}
var genericType = typeof(T);
if (genericType == typeof(Subject))
{
return GenericConvertValue<T, Subject>(new Subject { NameID = ConvertValue<NameID>(xmlNode[Schemas.Saml2Constants.Message.NameId, Schemas.Saml2Constants.AssertionNamespace.OriginalString]?.InnerText?.Trim(), xmlNode) });
}
else if (genericType == typeof(NameIdPolicy))
{
return GenericConvertValue<T, NameIdPolicy>(new NameIdPolicy
{
AllowCreate = GenericConvertValueToNullable<bool>(xmlNode.Attributes[Schemas.Saml2Constants.Message.AllowCreate]?.Value),
Format = xmlNode.Attributes[Schemas.Saml2Constants.Message.Format]?.Value,
SPNameQualifier = xmlNode.Attributes[Schemas.Saml2Constants.Message.SpNameQualifier]?.Value
});
}
else if (genericType == typeof(RequestedAuthnContext))
{
return GenericConvertValue<T, RequestedAuthnContext>(new RequestedAuthnContext
{
AuthnContextClassRef = GetAuthnContextClassRef(xmlNode.SelectNodes($"//*[local-name()='{Schemas.Saml2Constants.Message.AuthnContextClassRef}']")),
Comparison = ConvertValue<AuthnContextComparisonTypes>(xmlNode.Attributes[Schemas.Saml2Constants.Message.Comparison]?.Value, xmlNode),
});
}
else
{
throw new NotSupportedException($"Unable to convert element {genericType}.");
}
}
private static IEnumerable<string> GetAuthnContextClassRef(XmlNodeList xmlNodes)
{
foreach (XmlNode xmlNode in xmlNodes)
{
if(!string.IsNullOrWhiteSpace(xmlNode?.InnerText))
{
yield return ConvertValue<string>(xmlNode?.InnerText?.Trim(), xmlNode);
}
}
}
static T GenericConvertValue<T, U>(U value)
{
return (T)Convert.ChangeType(value, typeof(T));
}
static T? GenericConvertValueToNullable<T>(string value) where T : struct
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
else
{
return (T)Convert.ChangeType(value, typeof(T));
}
}
}
}
| 38.634921
| 236
| 0.571487
|
f109e9c747f1d284b9785c31197436d902f20d41
| 215
|
rb
|
Ruby
|
db/migrate/011_alter_pages_add_type.rb
|
djnawara/natto
|
30700263d097502bbf741aa1e959c5291ef8471a
|
[
"MIT"
] | 1
|
2016-05-08T10:30:38.000Z
|
2016-05-08T10:30:38.000Z
|
db/migrate/011_alter_pages_add_type.rb
|
djnawara/natto
|
30700263d097502bbf741aa1e959c5291ef8471a
|
[
"MIT"
] | null | null | null |
db/migrate/011_alter_pages_add_type.rb
|
djnawara/natto
|
30700263d097502bbf741aa1e959c5291ef8471a
|
[
"MIT"
] | null | null | null |
class AlterPagesAddType < ActiveRecord::Migration
def self.up
add_column :pages, :page_type, :string, :null => false, :default => 'Normal'
end
def self.down
remove_column :pages, :page_type
end
end
| 21.5
| 80
| 0.702326
|
a438fb7d7d47d6ee78b50bcba48fa1ce2d593ec1
| 1,969
|
php
|
PHP
|
resources/views/admin/layouts/app.blade.php
|
thehavoc/lcms
|
b04a46a2cd05a3164ac574f0fc778a21c501a831
|
[
"MIT"
] | null | null | null |
resources/views/admin/layouts/app.blade.php
|
thehavoc/lcms
|
b04a46a2cd05a3164ac574f0fc778a21c501a831
|
[
"MIT"
] | null | null | null |
resources/views/admin/layouts/app.blade.php
|
thehavoc/lcms
|
b04a46a2cd05a3164ac574f0fc778a21c501a831
|
[
"MIT"
] | null | null | null |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" id="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name') }}</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Custom CSS -->
<link href="https://blackrockdigital.github.io/startbootstrap-sb-admin-2/dist/css/sb-admin-2.css" rel="stylesheet">
<link href="{{ URL::asset('/assets/admin/css/app.css') }}" rel="stylesheet">
<!-- Custom Fonts -->
<link href="https://blackrockdigital.github.io/startbootstrap-sb-admin-2/vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="admin-app">
@include('admin/partials/side')
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">{{ $title }}</h1>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-body">
@yield('content')
</div>
</div>
</div>
<!-- /.col-lg-12 -->
</div>
<!-- /.row -->
</div>
<alert></alert>
</div>
<script type="text/javascript" src="{{ URL::asset('/assets/admin/js/app.js') }}?v=<?php echo rand(0, 10000); ?>"></script>
</body>
</html>
| 33.948276
| 209
| 0.517522
|
d686bbeff3c3a19b279be5e2eb7b8592c52381b5
| 111
|
cs
|
C#
|
src/Shiny.Push.FirebaseMessaging/AssemblyInfo.cs
|
ScriptBox99/shiny
|
16fc6ce1a39eae733b4bfa8d9d7288b4de015d8e
|
[
"MIT"
] | 1,035
|
2019-03-24T03:48:59.000Z
|
2022-03-31T17:47:32.000Z
|
src/Shiny.Push.FirebaseMessaging/AssemblyInfo.cs
|
ScriptBox99/shiny
|
16fc6ce1a39eae733b4bfa8d9d7288b4de015d8e
|
[
"MIT"
] | 743
|
2019-03-26T22:49:49.000Z
|
2022-03-30T13:55:31.000Z
|
src/Shiny.Push.FirebaseMessaging/AssemblyInfo.cs
|
moljac/shiny
|
935eaecb0f4e8a6583d9e151cabeb9a05052d826
|
[
"MIT"
] | 223
|
2019-03-28T20:31:34.000Z
|
2022-03-30T01:37:46.000Z
|
[assembly: Shiny.Attributes.AutoStartupWithDelegate("Shiny.Push.IPushDelegate", "UseFirebaseMessaging", true)]
| 111
| 111
| 0.828829
|
c6163b61a64ec61d311b713f8fe1d9eb61b4c236
| 11,889
|
asm
|
Assembly
|
plugins/mvtools/src/asm/Interpolation.asm
|
darcyg/vapoursynth-plugins
|
5aaf090d3523cb8c53841949f2da286688ba33bb
|
[
"BSD-2-Clause"
] | null | null | null |
plugins/mvtools/src/asm/Interpolation.asm
|
darcyg/vapoursynth-plugins
|
5aaf090d3523cb8c53841949f2da286688ba33bb
|
[
"BSD-2-Clause"
] | null | null | null |
plugins/mvtools/src/asm/Interpolation.asm
|
darcyg/vapoursynth-plugins
|
5aaf090d3523cb8c53841949f2da286688ba33bb
|
[
"BSD-2-Clause"
] | 1
|
2020-04-06T16:52:59.000Z
|
2020-04-06T16:52:59.000Z
|
%include "include/x86inc.asm"
SECTION_RODATA
word20 times 8 dw 20
SECTION_TEXT
%macro RB2CubicHorizontalInplaceLine_sse2_macro 3 ; weight1, weight2, shift
; prepare constants
pcmpeqw m6, m6 ; = FFFFFFFFFFFFFFFF
psrlw m6, 15
psllw m6, %3 - 1; 4 ; *16 = 16
pcmpeqw m5, m5 ; = FFFFFFFFFFFFFFFF
psrlw m5, 8 ; /256 = 00FF00FF00FF00FF
mov r2d, %1; 05
movd m4, r2d
pshuflw m4, m4, 0
punpcklqdq m4, m4
mov r2d, %2; 10
movd m3, r2d
pshuflw m3, m3, 0
punpcklqdq m3, m3
mov xq, 1 ; very first (left) is skipped
.loopw:
cmp xq, widthq
jge .finish
movdqu m0, [srcpq + xq * 2 - 2]
pand m0, m5; clear odd bytes
movdqu m1, [srcpq + xq * 2 - 1]
pand m1, m5; clear odd bytes
movdqu m2, [srcpq + xq * 2]
pand m2, m5
movdqu m7, [srcpq + xq * 2 + 1]
pand m7, m5
paddw m2, m7
pmullw m2, m3
paddw m0, m2
movdqu m2, [srcpq + xq * 2 + 2]
pand m2, m5; clear odd bytes
paddw m1, m2
pmullw m1, m4
paddw m0, m1
movdqu m1, [srcpq + xq * 2 + 3]
pand m1, m5; clear odd bytes
paddw m0, m1
paddw m0, m6; +16
psrlw m0, %3; /32
packuswb m0, m0 ; words to bytes
movq [srcpq + xq], m0; write 4 bytes
add xq, 8
jmp .loopw
.finish:
RET
%endmacro
INIT_XMM
cglobal RB2CubicHorizontalInplaceLine_sse2, 2, 3, 7, srcp, width, x
RB2CubicHorizontalInplaceLine_sse2_macro 5, 10, 5
INIT_XMM
cglobal RB2QuadraticHorizontalInplaceLine_sse2, 2, 3, 7, srcp, width, x
RB2CubicHorizontalInplaceLine_sse2_macro 9, 22, 6
%macro RB2CubicVerticalLine_sse2_macro 3 ; RB2CubicVerticalLine_SSE(pDst, pSrc, nSrcPitch, nWidthMMX);
; prepare constants
pcmpeqw m6, m6 ; = FFFFFFFFFFFFFFFF
psrlw m6, 15
psllw m6, %3-1; 4 ; *16 = 16
pxor m7, m7 ; =0
mov r4d, %1; 05
movd m4, r4d
pshuflw m4, m4, 0
punpcklqdq m4, m4
mov r4d, %2; 10
movd m3, r4d
pshuflw m3, m3, 0
punpcklqdq m3, m3
sub srcpq, src_strideq ; prepare for valid addresation
sub srcpq, src_strideq
lea src_stride3q, [src_strideq * 3]
lea src_stride5q, [src_strideq * 5]
xor xq, xq
.loopw:
add xq, 8
cmp xq, widthq
jg .finish
movq m0, [srcpq] ; 4 bytes
punpcklbw m0, m7 ; to 4 words
movq m1, [srcpq+src_strideq]
punpcklbw m1, m7
pmullw m1, m4
paddw m0, m1
movq m1, [srcpq+src_strideq*2]
punpcklbw m1, m7
pmullw m1, m3
paddw m0, m1
movq m1, [srcpq+src_stride3q]
punpcklbw m1, m7
pmullw m1, m3
paddw m0, m1
movq m1, [srcpq+src_strideq*4]
punpcklbw m1, m7
pmullw m1, m4
paddw m0, m1
movq m1, [srcpq+src_stride5q]
punpcklbw m1, m7
paddw m0, m1
paddw m0, m6; +16
psrlw m0, %3; /32
packuswb m0, m0 ; words to bytes
movq [dstpq], m0; write 4 bytes
add srcpq, 8
add dstpq, 8
jmp .loopw
.finish:
RET
%endmacro
INIT_XMM
cglobal RB2CubicVerticalLine_sse2, 4, 7, 8, dstp, srcp, src_stride, width, x, src_stride3, src_stride5
RB2CubicVerticalLine_sse2_macro 5, 10, 5
INIT_XMM
cglobal RB2QuadraticVerticalLine_sse2, 4, 7, 8, dstp, srcp, src_stride, width, x, src_stride3, src_stride5
RB2CubicVerticalLine_sse2_macro 5, 10, 5
INIT_XMM
cglobal VerticalBilinear_sse2, 5, 7, 2, dstp, srcp, stride, width, height, x, srcpn
mov srcpnq, srcpq
add srcpnq, strideq
dec heightq
.v_loopy:
xor xq, xq
.v_loopx:
movdqu m0, [srcpq + xq]
movdqu m1, [srcpnq + xq]
pavgb m0, m1
movdqu [dstpq + xq], m0
add xq, 16
cmp xq, widthq
jl .v_loopx
add srcpnq, strideq
add srcpq, strideq
add dstpq, strideq
dec heightq
jnz .v_loopy
xor xq, xq
.v_loopfinal:
movdqu m0, [srcpq + xq]
movdqu [dstpq + xq], m0
add xq, 16
cmp xq, widthq
jl .v_loopfinal
RET
INIT_XMM
cglobal HorizontalBilinear_sse2, 5, 6, 2, x, srcp, stride, width, height, dstp
; extra mov because I need x to contain a byte-sized register and only
; r0 and r1 have it everywhere (Windows, Linux, OS X, 32 bit and 64 bit).
; See DECLARE_REG in x86inc.asm.
mov dstpq, xq
.h_loopy:
xor xq, xq
.h_loopx:
movdqu m0, [srcpq + xq]
movdqu m1, [srcpq + xq + 1]
pavgb m0, m1
movdqu [dstpq + xq], m0
add xq, 16
cmp xq, widthq
jl .h_loopx
mov xb, [srcpq + widthq - 1]
mov [dstpq + widthq - 1], xb
add srcpq, strideq
add dstpq, strideq
dec heightq
jnz .h_loopy
RET
INIT_XMM
cglobal DiagonalBilinear_sse2, 5, 7, 6, x, srcp, stride, width, height, dstp, srcpn
; extra mov because I need x to contain a byte-sized register and only
; r0 and r1 have it everywhere (Windows, Linux, OS X, 32 bit and 64 bit).
; See DECLARE_REG in x86inc.asm.
mov dstpq, xq
pcmpeqw m4, m4
psrlw m4, 15
psllw m4, 1
pxor m5, m5
lea srcpnq, [srcpq + strideq]
.d_loopy:
xor xq, xq
.d_loopx:
movq m0, [srcpq+xq]
movq m1, [srcpq+xq+1]
movq m2, [srcpnq+xq]
movq m3, [srcpnq+xq+1]
punpcklbw m0, m5
punpcklbw m1, m5
punpcklbw m2, m5
punpcklbw m3, m5
paddw m0, m1
paddw m0, m2
paddw m0, m3
paddw m0, m4
psrlw m0, 2
packuswb m0, m5
movq [dstpq+xq], m0
add xq, 8
cmp xq, widthq
jl .d_loopx
; using xmm registers because nothing else is available
movzx xd, byte [srcpq + widthq - 1]
movd m0, xd
movzx xd, byte [srcpnq + widthq - 1]
movd m1, xd
pavgb m0, m1
movd xd, m0
mov [dstpq + widthq - 1], xb
add srcpq, strideq
add dstpq, strideq
add srcpnq, strideq
dec heightq
jnz .d_loopy
xor xq, xq
.d_loop_final :
movq m0, [srcpq+xq]
movq m1, [srcpq+xq+1]
pavgb m0, m1
movq [dstpq+xq], m0
add xq, 8
cmp xq, widthq
jl .d_loop_final
mov xb, [srcpq + widthq - 1]
mov [dstpq + widthq - 1], xb
RET
INIT_XMM
cglobal VerticalWiener_sse2, 5, 7, 8, dstp, srcp, stride, width, height, x, srcpn
mov srcpnq, srcpq
add srcpnq, strideq
sub heightq, 4
xor xq, xq
.vw_loopx0:
movdqu m0, [srcpq + xq]
movdqu m1, [srcpnq + xq]
pavgb m0, m1
movdqu [dstpq + xq], m0
add xq, 16
cmp xq, widthq
jl .vw_loopx0
add srcpq, strideq
add srcpnq, strideq
add dstpq, strideq
dec heightq
xor xq, xq
.vw_loopx1:
movdqu m0, [srcpq + xq]
movdqu m1, [srcpnq + xq]
pavgb m0, m1
movdqu [dstpq + xq], m0
add xq, 16
cmp xq, widthq
jl .vw_loopx1
sub srcpq, strideq ; return it to the original value
add dstpq, strideq
dec heightq
pcmpeqw m6, m6
psrlw m6, 15
psllw m6, 4
pxor m7, m7
.vw_loopy:
xor xq, xq
.vw_loopx:
mov r6, srcpq
movq m0, [srcpq + xq]
add r6, strideq
movq m1, [r6 + xq]
add r6, strideq
movq m2, [r6 + xq]
add r6, strideq
movq m3, [r6 + xq]
add r6, strideq
movq m4, [r6 + xq]
add r6, strideq
movq m5, [r6 + xq]
punpcklbw m0, m7
punpcklbw m1, m7
punpcklbw m2, m7
punpcklbw m3, m7
punpcklbw m4, m7
punpcklbw m5, m7
paddw m2, m3
psllw m2, 2
movdqa m3, m2
psllw m3, 2
paddw m2, m3
paddw m0, m5
paddw m0, m2
paddw m0, m6
paddw m1, m4
movdqa m4, m1
psllw m4, 2
paddw m1, m4
psubusw m0, m1
psrlw m0, 5
packuswb m0, m0
movq [dstpq + xq], m0
add xq, 8
cmp xq, widthq
jl .vw_loopx
add srcpq, strideq
add dstpq, strideq
dec heightq
jnz .vw_loopy
add srcpq, strideq
add srcpq, strideq
mov srcpnq, srcpq
add srcpnq, strideq
xor xq, xq
.vw_loopxh_4:
movdqu m0, [srcpq + xq]
movdqu m1, [srcpnq + xq]
pavgb m0, m1
movdqu [dstpq + xq], m0
add xq, 16
cmp xq, widthq
jl .vw_loopxh_4
add srcpq, strideq
add srcpnq, strideq
add dstpq, strideq
dec heightq
xor xq, xq
.vw_loopxh_3:
movdqu m0, [srcpq + xq]
movdqu m1, [srcpnq + xq]
pavgb m0, m1
movdqu [dstpq + xq], m0
add xq, 16
cmp xq, widthq
jl .vw_loopxh_3
add srcpq, strideq
add srcpnq, strideq
add dstpq, strideq
dec heightq
xor xq, xq
.vw_loopxh_2:
movdqu m0, [srcpq + xq]
movdqu m1, [srcpnq + xq]
pavgb m0, m1
movdqu [dstpq + xq], m0
add xq, 16
cmp xq, widthq
jl .vw_loopxh_2
add srcpq, strideq
add srcpnq, strideq
add dstpq, strideq
dec heightq
xor xq, xq
.vw_loopfinal:
movdqu m0, [srcpq + xq]
movdqu [dstpq + xq], m0
add xq, 16
cmp xq, widthq
jl .vw_loopfinal
RET
INIT_XMM
cglobal HorizontalWiener_sse2, 5, 6, 9, x, srcp, stride, width, height, dstp
; extra mov because I need x to contain a byte-sized register and only
; r0 and r1 have it everywhere (Windows, Linux, OS X, 32 bit and 64 bit).
; See DECLARE_REG in x86inc.asm.
mov dstpq, xq
pcmpeqw m6, m6
psrlw m6, 15
psllw m6, 4
pxor m7, m7
sub widthq, 4
.hw_loopy:
movd m0, [srcpq]
movd m1, [srcpq + 1]
pavgb m0, m1
movd [dstpq], m0
mov xq, 4
.hw_loopx:
movq m0, [srcpq + xq - 2]
movq m1, [srcpq + xq - 1]
punpcklbw m0, m7
punpcklbw m1, m7
movq m2, [srcpq + xq]
movq m3, [srcpq + xq + 1]
punpcklbw m2, m7
punpcklbw m3, m7
movq m4, [srcpq + xq + 2]
movq m5, [srcpq + xq + 3]
punpcklbw m4, m7
punpcklbw m5, m7
paddw m2, m3
pmullw m2, [word20]
paddw m0, m5
paddw m0, m2
paddw m0, m6
paddw m1, m4
movdqa m4, m1
psllw m4, 2
paddw m1, m4
psubusw m0, m1
psrlw m0, 5
packuswb m0, m0
movq [dstpq + xq], m0
add xq, 8
cmp xq, widthq
jl .hw_loopx
movd m0, [srcpq + xq]
movd m1, [srcpq + xq + 1]
pavgb m0, m1
movd [dstpq + xq], m0
mov xb, [srcpq + widthq + 3]
mov [dstpq + widthq + 3], xb
add srcpq, strideq
add dstpq, strideq
dec heightq
jnz .hw_loopy
RET
INIT_XMM
cglobal RB2BilinearFilteredVerticalLine_sse2, 4, 6, 8, dstp, srcp, src_stride, width, x, src_stride3
pcmpeqw m6, m6
psrlw m6, 15
psllw m6, 2
pxor m7, m7
lea src_stride3q, [src_strideq * 3]
sub srcpq, src_strideq
xor xq, xq
.loopw:
add xq, 8
cmp xq, widthq
jg .finish
movq m0, [srcpq]
punpcklbw m0, m7
movq m1, [srcpq + src_strideq]
punpcklbw m1, m7
movq m2, [srcpq + src_strideq * 2]
punpcklbw m2, m7
paddw m1, m2
movdqa m2, m1
psllw m1, 1
paddw m1, m2
paddw m0, m1
movq m1, [srcpq + src_stride3q]
punpcklbw m1, m7
paddw m0, m1
paddw m0, m6
psrlw m0, 3
packuswb m0, m0
movq [dstpq], m0
add srcpq, 8
add dstpq, 8
jmp .loopw
.finish:
RET
INIT_XMM
cglobal RB2BilinearFilteredHorizontalInplaceLine_sse2, 2, 3, 8, srcp, width, x
pcmpeqw m6, m6
psrlw m6, 15
psllw m6, 2
pxor m7, m7
pcmpeqw m5, m5
psrlw m5, 8
mov xq, 1
.loopw:
cmp xq, widthq
jge .finish
movdqu m0, [srcpq + xq * 2 - 1]
pand m0, m5
movdqu m1, [srcpq + xq * 2]
pand m1, m5
movdqu m2, [srcpq + xq * 2 + 1]
pand m2, m5
paddw m1, m2
movdqa m2, m1
psllw m2, 1
paddw m1, m2
paddw m0, m1
movdqu m1, [srcpq + xq * 2 + 2]
pand m1, m5
paddw m0, m1
paddw m0, m6
psrlw m0, 3
packuswb m0, m0
movq [srcpq + xq], m0
add xq, 8
jmp .loopw
.finish:
RET
INIT_XMM
cglobal Average2_sse2, 6, 7, 2, dstp, srcp1, srcp2, stride, width, height, x
.yloop:
xor xq, xq
.xloop:
movdqu m0, [srcp1q + xq]
movdqu m1, [srcp2q + xq]
pavgb m0, m1
movdqu [dstpq + xq], m0
add xq, 16
cmp xq, widthq
jl .xloop
add srcp1q, strideq
add srcp2q, strideq
add dstpq, strideq
dec heightq
jnz .yloop
RET
| 17.691964
| 106
| 0.591976
|
493dc59641a0a0f274685bae420fb2990bafd1fa
| 2,503
|
py
|
Python
|
deepself/models/model_managers/base_model_manager.py
|
Tomoya-K-0504/deepSELF
|
0e5a7d0169b3e9edcb5c8d9802140a84ce5cb69a
|
[
"MIT"
] | 1
|
2021-08-17T09:56:47.000Z
|
2021-08-17T09:56:47.000Z
|
deepself/models/model_managers/base_model_manager.py
|
JIangjiang1108/deepSELF
|
0e5a7d0169b3e9edcb5c8d9802140a84ce5cb69a
|
[
"MIT"
] | null | null | null |
deepself/models/model_managers/base_model_manager.py
|
JIangjiang1108/deepSELF
|
0e5a7d0169b3e9edcb5c8d9802140a84ce5cb69a
|
[
"MIT"
] | 1
|
2021-08-17T09:56:41.000Z
|
2021-08-17T09:56:41.000Z
|
import logging
from abc import ABCMeta, abstractmethod
logger = logging.getLogger(__name__)
import numpy as np
from deepself.models.loss import set_criterion
from dataclasses import dataclass, field
from deepself.models.loss import LossConfig
from typing import List, Any
from omegaconf import MISSING
from deepself.utils.enums import TaskType, ModelType
@dataclass
class ModelConfig: # ML/DL model arguments
model_name: str = ''
model_path: str = '../output/models/sth.pth' # Path to save model
early_stopping: bool = False # Early stopping with validation data
return_prob: bool = False # Returns probability, not predicted labels
loss_config: LossConfig = LossConfig()
checkpoint_path: str = '' # Model weight file to load model
amp: bool = False # Mixed precision training
input_size: List[int] = field(default_factory=lambda: [])
# TODO train_managerと共有したままなのか、継承によって消すのか
class_names: List[str] = field(default_factory=lambda: ['0', '1'])
task_type: TaskType = TaskType.classify
cuda: bool = True # Use cuda to train a model
transfer: bool = False # TODO modify this or remove this feature # Transfer learning from model_path
model_type: ModelType = ModelType.cnn
optim: Any = MISSING
@dataclass
class ExtendedModelConfig(ModelConfig):
mixup_alpha: float = 0.0 # Beta distirbution alpha for mixup
class BaseModelManager(metaclass=ABCMeta):
def __init__(self, class_labels, cfg):
self.class_labels = class_labels
self.cfg = cfg
self.criterion = set_criterion(self.cfg.loss_config, self.cfg.task_type.value, self.cfg.class_names)
self.fitted = False
def anneal_lr(self, learning_anneal):
pass
@abstractmethod
def fit(self, inputs, labels, phase):
pass
def save_model(self):
logger.info(f"Best model is saved to {self.cfg['model_path']}")
self.model.save_model(self.cfg['model_path'])
def load_model(self):
# MLModelは各Modelがfittedを管理しているため、エラーハンドリングの必要がない
try:
self.model.load_model(self.cfg['model_path'])
print('Saved model loaded.')
except FileNotFoundError as e:
print(e)
print(f"trained model file doesn't exist at {self.cfg['model_path']}")
exit(1)
self.fitted = self.model.fitted
@abstractmethod
def predict(self, inputs) -> np.array:
pass
def update_by_epoch(self, phase):
pass
| 30.901235
| 108
| 0.688374
|
2d847806120a91af5758c4a71d0c072199bad347
| 8,571
|
go
|
Go
|
pkg/gds/secret.go
|
frankienicoletti/directory
|
7ac1e8740615bd2e7341917b1389d61d738df0c2
|
[
"MIT"
] | null | null | null |
pkg/gds/secret.go
|
frankienicoletti/directory
|
7ac1e8740615bd2e7341917b1389d61d738df0c2
|
[
"MIT"
] | null | null | null |
pkg/gds/secret.go
|
frankienicoletti/directory
|
7ac1e8740615bd2e7341917b1389d61d738df0c2
|
[
"MIT"
] | null | null | null |
package gds
import (
"context"
"errors"
"fmt"
"math/rand"
"strings"
"time"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
"github.com/rs/zerolog/log"
"github.com/trisacrypto/directory/pkg/gds/config"
secretmanagerpb "google.golang.org/genproto/googleapis/cloud/secretmanager/v1"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var (
chars = []rune("ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz1234567890")
specialChars = []rune("#$%&()*+-<=>?@[]^_{|}~")
ErrSecretNotFound = errors.New("could not add secret version - not found")
ErrFileSizeLimit = errors.New("could not add secret version - file size exceeds limit")
ErrPermissionsDenied = errors.New("could not add secret version - permissions denied at project level")
)
// CreateToken creates a variable length random token that can be used for passwords or API keys.
func CreateToken(length int) string {
random := rand.New(rand.NewSource(time.Now().UnixNano()))
var b strings.Builder
for i := 0; i < length; i++ {
if rand.Float64() <= 0.85 {
b.WriteRune(chars[random.Intn(len(chars))])
} else {
b.WriteRune(specialChars[random.Intn(len(specialChars))])
}
}
return b.String()
}
// SecretManager holds a client to the Google secret manager, and the path to the `parent` project for the secret manager.
type SecretManager struct {
parent string
client *secretmanager.Client
}
// SecretManagerContext maintains a single long-running secret manager that can be used for the duration of the certificate request process
type SecretManagerContext struct {
manager *SecretManager
requestId string
}
// With allows us to engage a single SecretManager across all required calls during the certificate request process
func (sm *SecretManager) With(certRequest string) *SecretManagerContext {
return &SecretManagerContext{
manager: sm,
requestId: certRequest,
}
}
// NewSecretManager creates and returns a new secret manager client and an error if one occurs.
// Note that the `secretmanager` package leverages the GOOGLE_APPLICATION_CREDENTIALS
// environment variable which specifies the json path to the service account
// credentials, meaning that this function is a lightweight method for testing
// that the application can successfully connect to the secret manager API.
// However, this function does not validate the parent path.
func NewSecretManager(config config.SecretsConfig) (sm *SecretManager, err error) {
sm = &SecretManager{
parent: fmt.Sprintf("projects/%s", config.Project),
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if sm.client, err = secretmanager.NewClient(ctx); err != nil {
return nil, fmt.Errorf("could not connect to secret manager: %s", err)
}
return sm, nil
}
// CreateSecret creates a new secret in the Google Cloud Manager top-level directory
// using the `secret` name provided. This function returns an error if any occurs.
// Note: A secret is a logical wrapper around a collection of secret versions.
// To store a secret payload, you must first CreateSecret and then AddSecretVersion.
func (smc *SecretManagerContext) CreateSecret(ctx context.Context, secret string) error {
secretName := fmt.Sprintf("%s-%s", smc.requestId, secret)
// Create an internal context, since a failed API call will result in infinite hang
sctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Build the request.
req := &secretmanagerpb.CreateSecretRequest{
Parent: smc.manager.parent,
SecretId: secretName,
Secret: &secretmanagerpb.Secret{
Replication: &secretmanagerpb.Replication{
Replication: &secretmanagerpb.Replication_Automatic_{
Automatic: &secretmanagerpb.Replication_Automatic{},
},
},
},
}
// Call the API. Note: We don't actually need the result that comes back from the API call
// and not accessing it directly (e.g. logging plaintext, etc) provides added security
_, err := smc.manager.client.CreateSecret(sctx, req)
if err != nil {
// If the API call is malformed, it will hang until the internal context times out
if errors.Is(err, context.DeadlineExceeded) {
return err
}
// If the secret already exists, that means the client already has a password set up
// This is fine because we'll just create a new version with a new password for them
// and CertMan will always look for the most recent secret version.
serr, ok := status.FromError(err)
if ok && serr.Code() == codes.AlreadyExists {
return nil
}
// If the error is something else, something went wrong.
return err
}
return nil
}
// AddSecretVersion adds a new secret version to the given secret and the
// provided payload. Returns an error if one occurs.
// Note: to add a secret version, the secret must first be created using CreateSecret.
func (smc *SecretManagerContext) AddSecretVersion(ctx context.Context, secret string, payload []byte) error {
secretPath := fmt.Sprintf("%s/secrets/%s-%s", smc.manager.parent, smc.requestId, secret)
// Create an internal context, since a failed API call will result in infinite hang
sctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Build the request.
req := &secretmanagerpb.AddSecretVersionRequest{
Parent: secretPath,
Payload: &secretmanagerpb.SecretPayload{
Data: payload,
},
}
// Call the API. Note: We don't actually need the result that comes back from the API call
// and not accessing it directly (e.g. logging plaintext, etc) provides added security
_, err := smc.manager.client.AddSecretVersion(sctx, req)
if err != nil {
// If the API call is malformed, it will hang until the internal context times out
if errors.Is(err, context.DeadlineExceeded) {
return err
}
log.Error().Err(err).Msg("error returned from secret manager")
serr, ok := status.FromError(err)
if ok {
switch serr.Code() {
// If the secret does not exist (e.g. has been deleted or hasn't been created yet)
// we'll get a Not Found error
case codes.NotFound:
return ErrSecretNotFound
// If the secret exceeds 65KiB we'll get a InvalidArgument error
case codes.InvalidArgument:
return ErrFileSizeLimit
// If we give the wrong path to the project, we get a Permission Denied error
case codes.PermissionDenied:
return ErrPermissionsDenied
}
}
// If the error is something else, something went wrong.
return fmt.Errorf("unable to create secret version: %s", err)
}
return nil
}
// GetLatestVersion returns the payload for the latest version of the given secret,
// if one exists, else an error.
func (smc *SecretManagerContext) GetLatestVersion(ctx context.Context, secret string) ([]byte, error) {
versionPath := fmt.Sprintf("%s/secrets/%s-%s/versions/latest", smc.manager.parent, smc.requestId, secret)
// Create an internal context, since a failed API call will result in infinite hang
sctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Build the request.
req := &secretmanagerpb.AccessSecretVersionRequest{
Name: versionPath,
}
// Call the API.
result, err := smc.manager.client.AccessSecretVersion(sctx, req)
if err != nil {
// If the API call is malformed, it will hang until the internal context times out
if errors.Is(err, context.DeadlineExceeded) {
return nil, err
}
// If the error is something else, something went wrong.
return nil, fmt.Errorf("unable to access latest secret version: %s", err)
}
return result.Payload.Data, nil
}
// DeleteSecret deletes the secret with the given the name, and all of its versions.
// Note: this is an irreversible operation. Any service or workload that attempts to
// access a deleted secret receives a Not Found error.
func (smc *SecretManagerContext) DeleteSecret(ctx context.Context, secret string) error {
secretPath := fmt.Sprintf("%s/secrets/%s-%s", smc.manager.parent, smc.requestId, secret)
// Create an internal context, since a failed API call will result in infinite hang
sctx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// Build the request.
req := &secretmanagerpb.DeleteSecretRequest{
Name: secretPath,
}
// Call the API.
err := smc.manager.client.DeleteSecret(sctx, req)
if err != nil {
// If the API call is malformed, it will hang until the internal context times out
if errors.Is(err, context.DeadlineExceeded) {
return err
}
// If the error is something else, something went wrong.
return fmt.Errorf("unable to delete secret; %s", err)
}
return nil
}
| 35.7125
| 139
| 0.735853
|
97d764e82a9f17223ad10c253098a1765bf6a4f9
| 717
|
rb
|
Ruby
|
lib/puppet-lint/plugins/check_strings/quoted_booleans.rb
|
mmerfort/puppet-lint
|
3c379cfe101d0e1705797c0191ab0194c66ef71b
|
[
"MIT"
] | 3
|
2017-10-30T11:50:57.000Z
|
2022-02-08T20:03:58.000Z
|
lib/puppet-lint/plugins/check_strings/quoted_booleans.rb
|
mmerfort/puppet-lint
|
3c379cfe101d0e1705797c0191ab0194c66ef71b
|
[
"MIT"
] | 127
|
2017-11-02T01:24:42.000Z
|
2021-08-02T04:14:23.000Z
|
lib/puppet-lint/plugins/check_strings/quoted_booleans.rb
|
mmerfort/puppet-lint
|
3c379cfe101d0e1705797c0191ab0194c66ef71b
|
[
"MIT"
] | 1
|
2019-03-27T19:43:10.000Z
|
2019-03-27T19:43:10.000Z
|
# Public: Check the manifest tokens for any double or single quoted strings
# containing only a boolean value and record a warning for each instance
# found.
#
# No style guide reference
PuppetLint.new_check(:quoted_booleans) do
STRING_TYPES = Set[:STRING, :SSTRING]
BOOLEANS = Set['true', 'false']
def check
tokens.select { |r|
STRING_TYPES.include?(r.type) && BOOLEANS.include?(r.value)
}.each do |token|
notify(
:warning,
:message => 'quoted boolean value found',
:line => token.line,
:column => token.column,
:token => token
)
end
end
def fix(problem)
problem[:token].type = problem[:token].value.upcase.to_sym
end
end
| 25.607143
| 75
| 0.641562
|
f1e24fe735ab8742ca4739d5fd50c45e00777c2e
| 1,499
|
rb
|
Ruby
|
BetStreak/app/controllers/questions_controller.rb
|
guzamaguza/BetStreak-
|
4b5dc0c83ff35d49884626f4b08094426000e03a
|
[
"MIT"
] | null | null | null |
BetStreak/app/controllers/questions_controller.rb
|
guzamaguza/BetStreak-
|
4b5dc0c83ff35d49884626f4b08094426000e03a
|
[
"MIT"
] | null | null | null |
BetStreak/app/controllers/questions_controller.rb
|
guzamaguza/BetStreak-
|
4b5dc0c83ff35d49884626f4b08094426000e03a
|
[
"MIT"
] | null | null | null |
class QuestionsController < ApplicationController
def start_page
@reg = Reg.find_by(id: params[:reg_id])
render :start_page
end
def show
@question = Question.find_by(id: params[:id])
@reg = Reg.find_by(id: params[:reg_id])
#@question = Question.find_by(id: params[:question])
@game = @reg.game
@questions = @reg.game.questions.all
@players_rem = @game.regs.all.collect{|u| u.w_or_l != "L"}.count #check this later
end
def index
@game = Game.find_by(id: params[:game_id])
#@reg = @game.reg
@questions = @game.questions.all
@players_rem = @game.regs.all.collect{|u| u.w_or_l != "L"}.count #check this later
end
def update
@question = Question.find_by(id: params[:id])
#if submitted on time then update the database, if not then redirect to lost page
if @question.datetime_submitted < @question.datetime_required
if @question.update(question_params)
redirect_to question_path
else
render :show
end
else
@question.result = "l"
@question.game.reg.w_or_l = "l"
render "lostpage"
end
end
def create
@question = Question.find_by(:id => params[:question][:id])
#@question = @reg.game.question.build(question_params)
if @question.present?
#@question.update
redirect_to patch_question_path
else
render :index
end
end
private
def question_params
params.require(:question).permit(:answer, :game_id)
end
end
| 25.40678
| 87
| 0.654436
|
25987e59a2293b2385a96c1d500a2db91a6db124
| 1,463
|
cs
|
C#
|
src/Data/AzureBlobReader.cs
|
hphan9/clockify-nlp-bot
|
3338fa65666082fafd943ab4a7e085dd6c2a77cb
|
[
"MIT"
] | 9
|
2021-08-02T15:59:27.000Z
|
2021-12-31T10:45:04.000Z
|
src/Data/AzureBlobReader.cs
|
hphan9/clockify-nlp-bot
|
3338fa65666082fafd943ab4a7e085dd6c2a77cb
|
[
"MIT"
] | 75
|
2021-07-22T08:40:25.000Z
|
2022-01-26T10:43:11.000Z
|
src/Data/AzureBlobReader.cs
|
hphan9/clockify-nlp-bot
|
3338fa65666082fafd943ab4a7e085dd6c2a77cb
|
[
"MIT"
] | 2
|
2021-10-08T14:54:22.000Z
|
2021-12-26T19:32:29.000Z
|
using System;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Microsoft.WindowsAzure.Storage.Blob;
namespace Bot.Data
{
public class AzureBlobReader : IAzureBlobReader
{
private readonly IConfiguration _configuration;
public AzureBlobReader(IConfiguration configuration)
{
_configuration = configuration;
}
public string[] GetUserKeys()
{
string connectionString = _configuration.GetSection("BlobStorage")["DataConnectionString"];
string containerName = _configuration.GetSection("BlobStorage")["ContainerName"];
var container = CloudBlobContainerFactory.CreateCloudBlobContainer(connectionString, containerName);
// TODO read with listblobsegmentedasync and build a generator.
// Gets List of Blobs
var blobs = container.ListBlobs();
string[] userKeys = blobs.OfType<CloudBlockBlob>()
.Select(b => Uri.UnescapeDataString(b.Name)) // unescape %2f in /
.Where(IsUserState)
.Where(IsNotEmulator)
.ToArray();
return userKeys;
}
private static bool IsUserState(string key)
{
return !key.Contains("conversations");
}
private static bool IsNotEmulator(string key)
{
return !key.Contains("emulator");
}
}
}
| 31.804348
| 112
| 0.61244
|
a33e6e22744f0e6bd4b5caa8e5af64215fde2ff4
| 13,995
|
java
|
Java
|
time/src/main/java/com/zxmn/time/view/WheelView.java
|
xue5455/TimeSelector
|
cbab3f80bc6d3f701cd8cb26e972d715118ccec4
|
[
"MIT"
] | null | null | null |
time/src/main/java/com/zxmn/time/view/WheelView.java
|
xue5455/TimeSelector
|
cbab3f80bc6d3f701cd8cb26e972d715118ccec4
|
[
"MIT"
] | null | null | null |
time/src/main/java/com/zxmn/time/view/WheelView.java
|
xue5455/TimeSelector
|
cbab3f80bc6d3f701cd8cb26e972d715118ccec4
|
[
"MIT"
] | null | null | null |
package com.zxmn.time.view;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.support.v4.content.ContextCompat;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import com.zxmn.time.R;
import com.zxmn.time.adapter.WheelAdapter;
import com.zxmn.time.listeners.OnItemSelectedListener;
import com.zxmn.time.listeners.OnWheelScrollListener;
import com.zxmn.time.utils.Logger;
import java.util.ArrayList;
/**
* Created by XUE on 2016/9/27.
*/
public class WheelView extends View implements OnWheelScrollListener, WheelAdapter.OnDataSetChangedListener {
private WheelAdapter mAdapter;
private int mItemHeight;
private int mTotalHeight;
private float mTextSize;
private float mScaleFactor = 1.3f;
private int mScrollY = 0;
private TextPaint mNormalPaint;
private TextPaint mScaledPaint;
private Paint mLinesPaint;
private Paint mClearPaint;
private Paint mShadowPaint;
private int mNormalColor;
private int mHighLightColor;
private int mUpperEdge;
private int mLowerEdge;
private WheelTouchHelper mTouchHelper;
private OnItemSelectedListener mSelectedListener;
private int mShadowHeight;
private int mLastPosition = 0;
private LinearGradient mBlackToTransparent;
private LinearGradient mTransparentToBlack;
private Bitmap mCacheBitmap;
private Canvas mCacheCanvas;
private Path mPath;
private float[] mVerts;
private Camera mCamera;
public WheelView(Context context) {
this(context, null);
}
public WheelView(Context context, AttributeSet attrs) {
super(context, attrs);
setup();
}
private void setup() {
mTextSize = getContext().getResources().getDimensionPixelSize(R.dimen.wheel_text_size);
//init colors
mHighLightColor = ContextCompat.getColor(getContext(), R.color.wheel_high_light_color);
mNormalColor = ContextCompat.getColor(getContext(), R.color.wheel_normal_color);
//init normal paint;
mNormalPaint = getPaint(mTextSize, mNormalColor);
//init scaled paint
mScaledPaint = getPaint(mTextSize * mScaleFactor, mHighLightColor);
//init lines paint
mLinesPaint = getPaint(getContext().getResources().getDimensionPixelSize(R.dimen.wheel_edge_width), mNormalColor);
//init shadow paint
initShadowPaint();
//init clear paint
initClearPaint();
mTouchHelper = new WheelTouchHelper(this);
mShadowHeight = getResources().getDimensionPixelSize(R.dimen.wheel_shadow_height);
mCacheCanvas = new Canvas();
mCamera = new Camera();
}
private void initShadowPaint() {
mShadowPaint = new Paint();
mShadowPaint.setAntiAlias(true);
mShadowPaint.setStyle(Paint.Style.FILL);
mBlackToTransparent = new LinearGradient(0, 0, 0, 1, Color.parseColor("#30000000"), Color.TRANSPARENT, Shader.TileMode.CLAMP);
mTransparentToBlack = new LinearGradient(0, 0, 0, 1, Color.TRANSPARENT, Color.parseColor("#30000000"), Shader.TileMode.CLAMP);
}
private void initClearPaint() {
mClearPaint = new Paint();
mClearPaint.setColor(Color.TRANSPARENT);
mClearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
}
private Paint getPaint(int strokeWidth, int color) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(color);
paint.setStrokeWidth(strokeWidth);
return paint;
}
private TextPaint getPaint(float textSize, int color) {
TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(textSize);
textPaint.setColor(color);
return textPaint;
}
public void setAdapter(WheelAdapter adapter) {
if (mAdapter != null) {
mAdapter.unregisterDataSetChangedListener(this);
}
mAdapter = adapter;
adapter.registerDataSetChangedListener(this);
mItemHeight = adapter.getItemHeight();
mTotalHeight = adapter.getItemHeight() * adapter.getItemCount();
post(new Runnable() {
@Override
public void run() {
mUpperEdge = getMeasuredHeight() / 2 - mItemHeight / 2;
mLowerEdge = mUpperEdge + mItemHeight;
mScrollY = mTotalHeight - getMeasuredHeight() / 2 + mItemHeight / 2;
initVerts();
invalidate();
}
});
}
public void setTextSize(float textSize) {
mTextSize = textSize;
}
public void setNormalTextColor(int textColor) {
mNormalColor = textColor;
invalidate();
}
public void setHighLightColor(int textColor) {
mHighLightColor = textColor;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mAdapter == null)
return;
//drawContent(canvas);
// drawShadow(canvas);
// drawFilteredText(canvas);
// drawEdges(canvas);
drawCache();
//canvas.drawBitmap(mCacheBitmap, 0, 0, null);
canvas.drawBitmapMesh(mCacheBitmap, 1, mVerts.length / 4 - 1, mVerts, 0, null, 0, null);
// drawFilteredText(canvas);
}
private void drawCache() {
//clear content
mCacheCanvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
//first we draw normal texts
//first we draw normal texts
drawContent(mCacheCanvas);
//draw shadow
// drawShadow(mCacheCanvas);
//then clear center area
// clearCenterArea(canvas);
//draw scaled text
//drawFilteredText(mCacheCanvas);
//draw two lines
// drawEdges(mCacheCanvas);
}
private void drawContent(Canvas canvas) {
canvas.save();
if (mPath == null) {
mPath = new Path();
mPath.addRect(0, 0, getMeasuredWidth(), mUpperEdge, Path.Direction.CW);
mPath.addRect(0, mLowerEdge, getMeasuredWidth(), getMeasuredHeight(), Path.Direction.CW);
}
//canvas.clipPath(mPath);
drawTexts(mNormalPaint, canvas);
canvas.restore();
}
private void drawTexts(Paint paint, Canvas canvas) {
int firstPosition = mScrollY / mItemHeight;
float top = -mScrollY % mItemHeight;
int itemCount = (int) Math.ceil((getMeasuredHeight() - top) / mItemHeight);
float x = getMeasuredWidth() / 2;
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
for (int i = 0; i < itemCount; i++) {
String content = mAdapter.getItem(firstPosition);
int baseline = (int) ((top + mItemHeight + top - fontMetrics.bottom - fontMetrics.top) / 2);
canvas.drawText(content, x - paint.measureText(content) / 2, baseline, paint);
top += mItemHeight;
if (++firstPosition >= mAdapter.getItemCount()) {
firstPosition = 0;
}
}
}
private void drawEdges(Canvas canvas) {
canvas.drawLine(0, mUpperEdge, getMeasuredWidth(), mUpperEdge, mLinesPaint);
canvas.drawLine(0, mLowerEdge, getMeasuredWidth(), mLowerEdge, mLinesPaint);
}
private void drawShadow(Canvas canvas) {
mShadowPaint.setShader(mBlackToTransparent);
canvas.drawRect(0, 0, getMeasuredWidth(), mShadowHeight, mShadowPaint);
mShadowPaint.setShader(mTransparentToBlack);
canvas.drawRect(0, getMeasuredHeight() - mShadowHeight, getMeasuredWidth(), getMeasuredHeight(), mShadowPaint);
}
private void drawFilteredText(Canvas canvas) {
canvas.save();
canvas.clipRect(0, mUpperEdge, getMeasuredWidth(), mLowerEdge);
drawTexts(mScaledPaint, canvas);
canvas.restore();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return mTouchHelper != null &&
mTouchHelper.onTouchEvent(event);
}
@Override
public void onScrolled(int dy) {
mScrollY = amend(mScrollY + dy);
invalidate();
}
private int amend(int y) {
if (y >= mTotalHeight) {
y -= mTotalHeight;
} else if (y < 0) {
y += mTotalHeight;
}
return y;
}
@Override
public void onScrollStateChanged(int newState) {
if (newState == OnWheelScrollListener.STATE_IDLE) {
//scroll to nearest position
int top = amend(mScrollY + mUpperEdge);
int firstPosition = top / mItemHeight;
if (top % mItemHeight < mItemHeight / 2) {
smoothScrollToPosition(firstPosition);
} else {
smoothScrollToPosition(firstPosition + 1);
}
}
}
public void smoothScrollToPosition(int position) {
int destY = amend(position * mItemHeight - mUpperEdge);
int dy = mScrollY - destY;
if (mTotalHeight - mScrollY < mItemHeight && destY == 0) {
dy = mScrollY - mTotalHeight;
}
if (position != mLastPosition && mSelectedListener != null)
mSelectedListener.onItemSelected(position);
mLastPosition = position;
mTouchHelper.smoothScrollBy(dy);
}
public int getCurrentPosition() {
int top = amend(mScrollY + mUpperEdge);
return top / mItemHeight;
}
public void setScaledFactor(float factor) {
mScaleFactor = factor;
invalidate();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(widthSize, heightSize);
mTouchHelper.setViewHeight(getMeasuredHeight());
if (mCacheBitmap == null) {
mCacheBitmap = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(), Bitmap.Config.ARGB_8888);
mCacheCanvas.setBitmap(mCacheBitmap);
}
}
private void initVerts() {
double r = getMeasuredHeight() / 2;
int k = 0;
mVerts = new float[4 * (getMeasuredHeight() + 1)];
float lastY = 0;
ArrayList<Float> topys = new ArrayList<>();
float biggestDelta = 0;
for (int i = 0; i <= getMeasuredHeight(); i++) {
float y = 0;
if (i <= r) {
y = (float) (r - Math.sqrt(r * r - i * i));
if (y - lastY >= biggestDelta)
biggestDelta = y - lastY;
lastY = y;
topys.add(y);
if (y >= r - mItemHeight / 2) {
break;
}
}
}
/*mVerts = new float[80];
double fromHeight = mItemHeight / 2;
double endHeight = 0.5 * mTextSize;
int n = 10;
double k = (getMeasuredHeight() / 2 - 10 * endHeight) / (n * (n + 1) / 2);
Logger.d("k " + k);
int j = 0;
float lastY = 0;
mVerts[j++] = 0;
mVerts[j++] = 0;
mVerts[j++] = getMeasuredWidth();
mVerts[j++] = 0;
for (int i = 0; i < n - 1; i++) {
lastY += (float) (endHeight + k * i);
mVerts[j++] = 0;
mVerts[j++] = lastY;
mVerts[j++] = getMeasuredWidth();
mVerts[j++] = lastY;
Logger.d("y " + (endHeight + k * i));
}
mVerts[j++] = 0;
mVerts[j++] = getMeasuredHeight() / 2;
mVerts[j++] = getMeasuredWidth();
mVerts[j++] = getMeasuredHeight() / 2;
lastY = getMeasuredHeight() / 2;
for (int i = 0; i < n - 1; i++) {
lastY += (float) (fromHeight - k * i);
mVerts[j++] = 0;
mVerts[j++] = lastY;
mVerts[j++] = getMeasuredWidth();
mVerts[j++] = lastY;
Logger.d("y " + (fromHeight - k * i));
}*/
/* float factor = getMeasuredHeight()/5;
float r = getMeasuredWidth();
mVerts = new float[]{
0,0,r,0,
0,0.8f*factor,r,0.8f*factor,
0,mUpperEdge,r,mUpperEdge,
0,mLowerEdge,r,mLowerEdge,
0,4.2f*factor,r,4.2f*factor,
0,5f*factor,r,5f*factor
};*/
}
@Override
public void onDataSetChanged() {
mTotalHeight = mAdapter.getItemHeight() * mAdapter.getItemCount();
invalidate();
}
@Override
public void computeScroll() {
if (mTouchHelper != null)
mTouchHelper.computeScroll();
super.computeScroll();
}
public void scrollToPosition(int position) {
if (position < 0 || mAdapter == null || position >= mAdapter.getItemCount()) {
return;
}
mScrollY = position * mItemHeight + getMeasuredHeight() / 2;
invalidate();
if (position != mLastPosition && mSelectedListener != null)
mSelectedListener.onItemSelected(position);
mLastPosition = position;
}
public void setCurrentPosition(int position) {
if (position < 0 || mAdapter == null || position >= mAdapter.getItemCount()) {
return;
}
//reset scrollY
mScrollY = amend(position * mItemHeight - mUpperEdge);
invalidate();
if (position != mLastPosition && mSelectedListener != null)
mSelectedListener.onItemSelected(position);
mLastPosition = position;
}
}
| 31.378924
| 134
| 0.606288
|
f87e17810a0f6c02692c9f22a69ff899b4086326
| 2,436
|
h
|
C
|
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/O2ODiningFoodNavigationBar.h
|
ceekay1991/AliPayForDebug
|
5795e5db31e5b649d4758469b752585e63e84d94
|
[
"MIT"
] | 5
|
2020-03-29T12:08:37.000Z
|
2021-05-26T05:20:11.000Z
|
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/O2ODiningFoodNavigationBar.h
|
ceekay1991/AliPayForDebug
|
5795e5db31e5b649d4758469b752585e63e84d94
|
[
"MIT"
] | null | null | null |
AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/O2ODiningFoodNavigationBar.h
|
ceekay1991/AliPayForDebug
|
5795e5db31e5b649d4758469b752585e63e84d94
|
[
"MIT"
] | 5
|
2020-04-17T03:24:04.000Z
|
2022-03-30T05:42:17.000Z
|
//
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//
#import <UIKit/UIView.h>
@class CAGradientLayer, NSString, UIButton, UIColor, UIImageView, UILabel;
@interface O2ODiningFoodNavigationBar : UIView
{
_Bool _isFirstAlphaIncreasel;
_Bool _isFirstAlphaReduce;
CDUnknownBlockType _onClickBackAction;
long long _type;
NSString *_searchUrl;
UIView *_mainContainerView;
CAGradientLayer *_bgLayer;
double _insetTop;
UIButton *_searchBtn;
UIButton *_backBtn;
UILabel *_titleLable;
UIImageView *_titleImageView;
UIView *_bottomLineView;
UIColor *_themeColor;
}
@property(retain, nonatomic) UIColor *themeColor; // @synthesize themeColor=_themeColor;
@property(nonatomic) _Bool isFirstAlphaReduce; // @synthesize isFirstAlphaReduce=_isFirstAlphaReduce;
@property(nonatomic) _Bool isFirstAlphaIncreasel; // @synthesize isFirstAlphaIncreasel=_isFirstAlphaIncreasel;
@property(retain, nonatomic) UIView *bottomLineView; // @synthesize bottomLineView=_bottomLineView;
@property(retain, nonatomic) UIImageView *titleImageView; // @synthesize titleImageView=_titleImageView;
@property(retain, nonatomic) UILabel *titleLable; // @synthesize titleLable=_titleLable;
@property(retain, nonatomic) UIButton *backBtn; // @synthesize backBtn=_backBtn;
@property(retain, nonatomic) UIButton *searchBtn; // @synthesize searchBtn=_searchBtn;
@property(nonatomic) double insetTop; // @synthesize insetTop=_insetTop;
@property(retain, nonatomic) CAGradientLayer *bgLayer; // @synthesize bgLayer=_bgLayer;
@property(retain, nonatomic) UIView *mainContainerView; // @synthesize mainContainerView=_mainContainerView;
@property(copy, nonatomic) NSString *searchUrl; // @synthesize searchUrl=_searchUrl;
@property(nonatomic) long long type; // @synthesize type=_type;
@property(copy, nonatomic) CDUnknownBlockType onClickBackAction; // @synthesize onClickBackAction=_onClickBackAction;
- (void).cxx_destruct;
- (void)setTitleImageViewFrameWithImage:(id)arg1;
- (void)onClickBack:(id)arg1;
- (id)searchIconSpm;
- (void)onClickSearchIcon:(id)arg1;
- (void)updateUIWithContentOffSetY:(double)arg1 headerViewHeight:(double)arg2;
- (void)setNavbarStyle:(long long)arg1;
- (void)resetConfig;
- (id)initWithFrame:(struct CGRect)arg1 type:(long long)arg2 insetTop:(double)arg3;
@end
| 44.290909
| 117
| 0.778736
|
a48ce359bbac353037f14ffa8c0daf92f3dc5675
| 498
|
php
|
PHP
|
api/deleteuser-api.php
|
adeleyeayodeji/Simple-REST-API-
|
4263db7f05011d4d4b182cd7ae8b2a212e183224
|
[
"Apache-2.0"
] | 1
|
2020-03-15T13:10:51.000Z
|
2020-03-15T13:10:51.000Z
|
api/deleteuser-api.php
|
adeleyeayodeji/Simple-REST-API-
|
4263db7f05011d4d4b182cd7ae8b2a212e183224
|
[
"Apache-2.0"
] | null | null | null |
api/deleteuser-api.php
|
adeleyeayodeji/Simple-REST-API-
|
4263db7f05011d4d4b182cd7ae8b2a212e183224
|
[
"Apache-2.0"
] | null | null | null |
<?php
include "../include/autoload.php";
//Json response
header("Content-Type: application/json");
//Get user id
if (isset($_GET["id"])) {
$id = $_GET["id"];
//Creating an instance of a class
$loaddata = new UserController();
//Delete user data
$response[] = $loaddata->userDeleteById($id);
echo json_encode($response);
}else{
//if id not found
$error[] = array("message" => "Unique ID is needed");
echo json_encode($error);
}
?>
| 24.9
| 62
| 0.584337
|
79081265030bf7bcad313e6711df92a52320b5ff
| 1,974
|
rb
|
Ruby
|
test/rx/operators/test_average.rb
|
bittrance/rxruby
|
e447980bd199201a6f80b7c9f3890d2cd0c69e48
|
[
"Apache-2.0"
] | 9
|
2017-12-26T04:10:05.000Z
|
2020-06-04T19:07:26.000Z
|
test/rx/operators/test_average.rb
|
bittrance/rxruby
|
e447980bd199201a6f80b7c9f3890d2cd0c69e48
|
[
"Apache-2.0"
] | 53
|
2017-11-14T09:08:39.000Z
|
2020-10-27T10:06:55.000Z
|
test/rx/operators/test_average.rb
|
bittrance/rxruby
|
e447980bd199201a6f80b7c9f3890d2cd0c69e48
|
[
"Apache-2.0"
] | 2
|
2020-10-07T13:05:43.000Z
|
2020-10-27T09:36:16.000Z
|
require 'test_helper'
class TestOperatorAverage < Minitest::Test
include Rx::MarbleTesting
def test_calculates_average_of_emitted_values
source = cold(' -2424|')
expected = msgs('-------(3|)')
source_subs = subs(' ^ !')
actual = scheduler.configure { source.average }
assert_msgs expected, actual
assert_subs source_subs, source
end
def test_maps_with_block
source = cold(' -2424|')
expected = msgs('-------(4|)')
source_subs = subs(' ^ !')
actual = scheduler.configure do
source.average { |n| n + 1 }
end
assert_msgs expected, actual
assert_subs source_subs, source
end
def test_erroring_block
source = cold(' -2424|')
expected = msgs('---#')
source_subs = subs(' ^!')
actual = scheduler.configure do
source.average { |n| raise error }
end
assert_msgs expected, actual
assert_subs source_subs, source
end
def test_propagates_error
source = cold(' -2#')
expected = msgs('----#')
source_subs = subs(' ^ !')
actual = scheduler.configure { source.average }
assert_msgs expected, actual
assert_subs source_subs, source
end
def test_fails_on_non_numerical_values
my_err = ->(err) { err.is_a?(TypeError) && err.message.match(/blah.*numerical/) }
source = cold(' -a', a: 'blah')
expected = msgs('---#', error: my_err)
source_subs = subs(' ^!')
actual = scheduler.configure { source.average }
assert_msgs expected, actual
assert_subs source_subs, source
end
def test_fails_on_empty_sequence
my_err = ->(err) { err.is_a?(RuntimeError) && err.message.include?('no elements') }
source = cold(' -|')
expected = msgs('---#', error: my_err)
source_subs = subs(' ^!')
actual = scheduler.configure { source.average }
assert_msgs expected, actual
assert_subs source_subs, source
end
end
| 24.987342
| 87
| 0.615502
|
b3757dbfeed37e72ecd596a3d9716e0a9bbc3d3e
| 57
|
py
|
Python
|
pyVenv/Lib/site-packages/bpython/_version.py
|
thephilosophicaljijutsumaster/InventoryManagement
|
7c57fcc435976c39b249106642ee848da2eea201
|
[
"MIT"
] | null | null | null |
pyVenv/Lib/site-packages/bpython/_version.py
|
thephilosophicaljijutsumaster/InventoryManagement
|
7c57fcc435976c39b249106642ee848da2eea201
|
[
"MIT"
] | 12
|
2020-07-05T14:30:46.000Z
|
2020-08-06T21:06:00.000Z
|
pyVenv/Lib/site-packages/bpython/_version.py
|
thephilosophicaljijutsumaster/InventoryManagement
|
7c57fcc435976c39b249106642ee848da2eea201
|
[
"MIT"
] | null | null | null |
# Auto-generated file, do not edit!
__version__ = '0.19'
| 19
| 35
| 0.701754
|
a30fb58ec6a1825baf1a5c1d76b4c5f91ffcca55
| 229
|
ts
|
TypeScript
|
sbt-plugin/src/sbt-test/sbt-scala-ts/enumeratum/src/test/resources/Bye.ts
|
chenders/scala-ts
|
68440b1a461cf71b40bacbce673d9e3e5056714f
|
[
"MIT"
] | 82
|
2019-01-26T06:34:05.000Z
|
2022-03-31T23:43:15.000Z
|
sbt-plugin/src/sbt-test/sbt-scala-ts/enumeratum/src/test/resources/Bye.ts
|
chenders/scala-ts
|
68440b1a461cf71b40bacbce673d9e3e5056714f
|
[
"MIT"
] | 181
|
2019-01-24T13:38:32.000Z
|
2022-03-31T17:39:52.000Z
|
sbt-plugin/src/sbt-test/sbt-scala-ts/enumeratum/src/test/resources/Bye.ts
|
chenders/scala-ts
|
68440b1a461cf71b40bacbce673d9e3e5056714f
|
[
"MIT"
] | 14
|
2019-02-27T12:27:22.000Z
|
2021-10-22T02:16:27.000Z
|
// Generated by ScalaTS 0.5.8-SNAPSHOT: https://scala-ts.github.io/scala-ts/
export const ByeInhabitant = 'Bye';
export type Bye = typeof ByeInhabitant;
export function isBye(v: any): v is Bye {
return ByeInhabitant == v;
}
| 22.9
| 76
| 0.716157
|
ff3d869e70cef0652e845beeac9355117d5c3067
| 10,711
|
py
|
Python
|
models.py
|
MartinKist/p2p
|
046c6258f936789aff73b884235b9b202e7e7f7a
|
[
"MIT"
] | 2
|
2021-06-29T11:32:59.000Z
|
2021-06-30T09:11:24.000Z
|
models.py
|
MartinKist/p2p
|
046c6258f936789aff73b884235b9b202e7e7f7a
|
[
"MIT"
] | null | null | null |
models.py
|
MartinKist/p2p
|
046c6258f936789aff73b884235b9b202e7e7f7a
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# (c) 2021 Martin Kistler
from __future__ import annotations
import random
import time
from abc import ABC, abstractmethod
from hashlib import sha256
from typing import Union
BYTEORDER = 'little'
# TODO: write down protocol specifications in respective docstrings
class MessageError(Exception):
def __init__(self, msg_type: bytes, length: int, checksum: bytes, payload: bytes):
self.msg_type = msg_type
self.length = length
self.checksum = checksum
self.payload = payload
# TODO: add description parameter
class VarInt:
def __init__(self, value: Union[int, bytes]):
if isinstance(value, int):
self.value = value
elif isinstance(value, bytes):
if self.get_length(value[0]) != 1:
value = value[1:]
self.value = int.from_bytes(value, BYTEORDER)
@property
def __len__(self) -> int:
"""
Returns the number of bytes this VarInt has, including prefix, if existent.
"""
return len(bytes(self))
@staticmethod
def get_length(first_byte: int) -> int:
"""
Returns the expected length of the VarInt, by examining the first byte.
"""
if first_byte < 253:
return 1
elif first_byte == 253:
return 3
elif first_byte == 254:
return 5
elif first_byte == 255:
return 9
else:
raise ValueError
def __bytes__(self) -> bytes:
if self.value <= int('fc', 16):
return self.value.to_bytes(1, BYTEORDER)
elif self.value <= int('ffff', 16):
return b'\xfd' + self.value.to_bytes(2, BYTEORDER)
elif self.value <= int('ffffffff', 16):
return b'\xfe' + self.value.to_bytes(4, BYTEORDER)
elif self.value <= int('ffffffffffffffff', 16):
return b'\xff' + self.value.to_bytes(8, BYTEORDER)
else:
raise OverflowError
def __int__(self) -> int:
return self.value
class StructABC(ABC):
@abstractmethod
def __bytes__(self) -> bytes:
return NotImplemented
@classmethod
@abstractmethod
def from_bytes(cls, data: bytes):
return NotImplemented
def __eq__(self, other):
return bytes(self) == bytes(other)
def __str__(self):
return str(bytes(self).hex(' '))
class NetworkAddress(StructABC):
def __init__(self, address: Union[bytes, str], port: int, timestamp: int = None):
self.address = address
self.port = port
if timestamp is None:
self.timestamp = int(time.time())
else:
self.timestamp = timestamp
if isinstance(address, bytes):
self.address = ".".join(str(val) for val in self.address)
else:
self.address = self.address.strip()
@property
def addr_bytes(self):
values = self.address.split('.')
return bytes(map(int, values))
def __bytes__(self) -> bytes:
return self.timestamp.to_bytes(4, BYTEORDER) \
+ self.addr_bytes \
+ self.port.to_bytes(2, BYTEORDER)
@classmethod
def from_bytes(cls, data: bytes) -> NetworkAddress:
timestamp = int.from_bytes(data[:4], BYTEORDER)
address = data[4:8]
port = int.from_bytes(data[8:10], BYTEORDER)
return cls(address, port, timestamp)
def __str__(self):
return self.address + ':' + str(self.port)
class Message(StructABC, ABC):
def __init__(self):
self.id = random.randbytes(4) # 4 Byte nonce to identify message
@staticmethod
def calculate_checksum(data: bytes) -> bytes:
return sha256(sha256(data).digest()).digest()[:4]
@property
@abstractmethod
def message_type(self) -> bytes:
return NotImplemented
@property
@abstractmethod
def payload(self) -> bytes:
return NotImplemented
@property
def checksum(self) -> bytes:
return self.calculate_checksum(self.payload)
@property
def length(self) -> int:
return len(self.payload)
def __bytes__(self) -> bytes:
return self.message_type \
+ self.length.to_bytes(4, BYTEORDER) \
+ self.checksum \
+ self.id \
+ self.payload
@classmethod
@abstractmethod
def from_bytes(cls, data: bytes) -> Message:
msg_type = data[:12].rstrip(b'\0')
length = int.from_bytes(data[12:16], BYTEORDER)
checksum = data[16:20]
id = data[20:24]
payload = data[24:24 + length]
if cls.calculate_checksum(payload) == checksum and msg_type in message_types:
new_msg = message_types[msg_type].from_bytes(payload)
new_msg.id = id
return new_msg
else:
raise MessageError(msg_type, length, checksum, payload)
def __str__(self):
return f'Message type: {self.message_type}\n' \
+ f'Payload length: {len(self.payload)}\n' \
+ f'Checksum: {self.checksum}\n' \
+ 'Payload:\n' \
+ str(self.payload)
class HeaderOnly(Message, ABC):
"""
A message containing no payload.
"""
@property
@abstractmethod
def message_type(self) -> bytes:
return NotImplemented
@property
def payload(self) -> bytes:
return b''
@classmethod
def from_bytes(cls, data: bytes):
return cls()
class Version(Message):
"""
A message containing the version of this client and the address on which this client accepts incoming connections,
used in handshake.
"""
def __init__(self, version: int, addr_recv: NetworkAddress, addr_from: NetworkAddress, nonce: bytes, timestamp: int = None):
super().__init__()
self.version = version
self.addr_recv = addr_recv
self.addr_from = addr_from
self.nonce = nonce
if timestamp is None:
self.timestamp = int(time.time())
else:
self.timestamp = timestamp
@property
def message_type(self) -> bytes:
return b'version'.ljust(12, b'\0')
@property
def payload(self) -> bytes:
return self.version.to_bytes(4, BYTEORDER) \
+ self.timestamp.to_bytes(8, BYTEORDER) \
+ bytes(self.addr_recv) \
+ bytes(self.addr_from) \
+ self.nonce
@classmethod
def from_bytes(cls, data: bytes) -> Version:
version = int.from_bytes(data[:4], BYTEORDER)
timestamp = int.from_bytes(data[4:12], BYTEORDER)
addr_recv = NetworkAddress.from_bytes(data[12:22])
addr_from = NetworkAddress.from_bytes(data[22:32])
nonce = data[32:40]
return cls(version, addr_recv, addr_from, nonce, timestamp=timestamp)
class Addr(Message):
"""
A message that contains address information about known network participants.
"""
def __init__(self, addresses: list[NetworkAddress]):
super().__init__()
self.addresses = addresses
@property
def count(self) -> int:
return len(self.addresses)
@property
def message_type(self) -> bytes:
return b'addr'.ljust(12, b'\0')
@property
def payload(self) -> bytes:
return bytes(VarInt(self.count)) \
+ b''.join(bytes(adr) for adr in self.addresses)
@classmethod
def from_bytes(cls, data: bytes) -> Addr:
count_len = VarInt.get_length(data[0])
count = int(VarInt(data[:count_len]))
addresses = [NetworkAddress.from_bytes(data[count_len + x * 10: count_len + x * 10 + 10]) for x in range(count)]
return cls(addresses)
class VerAck(HeaderOnly):
"""
Acknowledgment message sent to a peer to signal that his version is accepted by this client, used in handshake.
"""
@property
def message_type(self) -> bytes:
return b'verack'.ljust(12, b'\0')
class GetAddr(HeaderOnly):
@property
def message_type(self) -> bytes:
return b'getaddr'.ljust(12, b'\0')
class ChatMessage(Message):
def __init__(self, sender: NetworkAddress, chat_message: Union[bytes, str]):
super().__init__()
self.sender = sender
if isinstance(chat_message, bytes):
self.chat_message = chat_message.decode('utf-8')
else:
self.chat_message = chat_message
@property
def message_type(self) -> bytes:
return b'chat'.ljust(12, b'\0')
@property
def payload(self) -> bytes:
return bytes(self.sender) + self.chat_message.encode('utf-8')
@classmethod
def from_bytes(cls, data: bytes) -> ChatMessage:
sender = NetworkAddress.from_bytes(data[:10])
chat_message = data[10:]
return cls(sender, chat_message)
class Ping(Message):
"""
Currently unused, future clients will use these messages to check the health of their peers.
"""
def __init__(self, nonce: bytes = None):
super().__init__()
if nonce is None:
self.nonce = random.randbytes(8)
else:
self.nonce = nonce
@property
def message_type(self) -> bytes:
return b'ping'.ljust(12, b'\0')
@property
def payload(self) -> bytes:
return self.nonce
@classmethod
def from_bytes(cls, data: bytes) -> Ping:
return cls(data)
class Pong(Message):
"""
Currently unused, future clients will use these messages to check the health of their peers.
"""
def __init__(self, nonce: bytes = None):
super().__init__()
if nonce is None:
self.nonce = random.randbytes(8)
else:
self.nonce = nonce
@property
def message_type(self) -> bytes:
return b'pong'.ljust(12, b'\0')
@property
def payload(self) -> bytes:
return self.nonce
@classmethod
def from_bytes(cls, data: bytes) -> Pong:
return cls(data)
class Reject(Message):
"""
Currently unused, future clients will use these messages to signal a peer that something went wrong.
"""
@property
def message_type(self) -> bytes:
return b'reject'.ljust(12, b'\0')
@property
def payload(self) -> bytes:
pass
@classmethod
def from_bytes(cls, data: bytes) -> Reject:
pass
message_types = {b'version': Version,
b'verack': VerAck,
b'ping': Ping,
b'pong': Pong,
b'addr': Addr,
b'getaddr': GetAddr,
b'reject': Reject,
b'chat': ChatMessage}
| 27.185279
| 128
| 0.595369
|
1a5d7ae78fe06729ad8105013b3fcf7c8d4bf1af
| 6,751
|
cs
|
C#
|
src/Sql/Sql/Elastic Jobs/Cmdlet/JobStep/RemoveAzureSqlElasticJobStep.cs
|
mbentancour/azure-powershell
|
142042fb26c23663340dbecd460bcd60866f6aca
|
[
"MIT"
] | 3,336
|
2015-01-03T15:40:07.000Z
|
2022-03-31T09:53:06.000Z
|
src/Sql/Sql/Elastic Jobs/Cmdlet/JobStep/RemoveAzureSqlElasticJobStep.cs
|
mbentancour/azure-powershell
|
142042fb26c23663340dbecd460bcd60866f6aca
|
[
"MIT"
] | 13,768
|
2015-01-03T14:50:54.000Z
|
2022-03-31T22:17:19.000Z
|
src/Sql/Sql/Elastic Jobs/Cmdlet/JobStep/RemoveAzureSqlElasticJobStep.cs
|
mbentancour/azure-powershell
|
142042fb26c23663340dbecd460bcd60866f6aca
|
[
"MIT"
] | 3,968
|
2015-01-02T17:35:24.000Z
|
2022-03-30T13:51:31.000Z
|
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------
using System.Management.Automation;
using Microsoft.Rest.Azure;
using Microsoft.Azure.Commands.Sql.ElasticJobs.Model;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
namespace Microsoft.Azure.Commands.Sql.ElasticJobs.Cmdlet.Job
{
/// <summary>
/// Defines the Remove-AzureRmSqlElasticJobStep Cmdlet
/// </summary>
[Cmdlet(VerbsCommon.Remove, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "SqlElasticJobStep",
SupportsShouldProcess = true,
DefaultParameterSetName = DefaultParameterSet)]
[OutputType(typeof(AzureSqlElasticJobStepModel))]
public class RemoveAzureSqlElasticJobStep : AzureSqlElasticJobStepCmdletBase<AzureSqlElasticJobStepModel>
{
/// <summary>
/// Gets or sets the resource group name
/// </summary>
[Parameter(
Mandatory = true,
ParameterSetName = DefaultParameterSet,
Position = 0,
HelpMessage = "The resource group name")]
[ValidateNotNullOrEmpty]
[ResourceGroupCompleter]
public override string ResourceGroupName { get; set; }
/// <summary>
/// Gets or sets the job step input object
/// </summary>
[Parameter(
Mandatory = true,
ParameterSetName = InputObjectParameterSet,
ValueFromPipeline = true,
Position = 0,
HelpMessage = "The job step input object")]
[ValidateNotNullOrEmpty]
public AzureSqlElasticJobStepModel InputObject { get; set; }
/// <summary>
/// Gets or sets the job step resource id
/// </summary>
[Parameter(
Mandatory = true,
ParameterSetName = ResourceIdParameterSet,
ValueFromPipelineByPropertyName = true,
Position = 0,
HelpMessage = "The job step resource id")]
[ValidateNotNullOrEmpty]
public string ResourceId { get; set; }
/// <summary>
/// Gets or sets the server name
/// </summary>
[Parameter(
Mandatory = true,
ParameterSetName = DefaultParameterSet,
Position = 1,
HelpMessage = "The server name")]
[ValidateNotNullOrEmpty]
public override string ServerName { get; set; }
/// <summary>
/// Gets or sets the server name
/// </summary>
[Parameter(
Mandatory = true,
ParameterSetName = DefaultParameterSet,
Position = 2,
HelpMessage = "The agent name")]
[ValidateNotNullOrEmpty]
public override string AgentName { get; set; }
/// <summary>
/// Gets or sets the job name
/// </summary>
[Parameter(
Mandatory = true,
ParameterSetName = DefaultParameterSet,
Position = 3,
HelpMessage = "The job name")]
[ValidateNotNullOrEmpty]
public override string JobName { get; set; }
/// <summary>
/// Gets or sets the job step name
/// </summary>
[Parameter(
Mandatory = true,
ParameterSetName = DefaultParameterSet,
HelpMessage = "The job step name")]
[Alias("StepName")]
[ValidateNotNullOrEmpty]
public override string Name { get; set; }
/// <summary>
/// Entry point for the cmdlet
/// </summary>
public override void ExecuteCmdlet()
{
InitializeInputObjectProperties(this.InputObject);
InitializeResourceIdProperties(this.ResourceId);
this.Name = this.Name ?? this.StepName;
base.ExecuteCmdlet();
ClearProperties();
}
/// <summary>
/// Gets job to see if job step exists before removing
/// </summary>
/// <returns></returns>
protected override IEnumerable<AzureSqlElasticJobStepModel> GetEntity()
{
try
{
return new List<AzureSqlElasticJobStepModel>
{
ModelAdapter.GetJobStep(this.ResourceGroupName, this.ServerName, this.AgentName, this.JobName, this.Name)
};
}
catch (CloudException ex)
{
if (ex.Response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
// The job doesn't exists
throw new PSArgumentException(
string.Format(Properties.Resources.AzureElasticJobStepNotExists, this.Name, this.JobName),
"JobName");
}
// Unexpected exception encountered
throw;
}
}
/// <summary>
/// Apply user input.
/// </summary>
/// <param name="model">The result of GetEntity</param>
/// <returns>The input model</returns>
protected override IEnumerable<AzureSqlElasticJobStepModel> ApplyUserInputToModel(IEnumerable<AzureSqlElasticJobStepModel> model)
{
return model;
}
/// <summary>
/// Deletes the job step from job.
/// </summary>
/// <param name="entity">The job step to be deleted</param>
/// <returns>The job step that was deleted</returns>
protected override IEnumerable<AzureSqlElasticJobStepModel> PersistChanges(IEnumerable<AzureSqlElasticJobStepModel> entity)
{
var existingEntity = entity.First();
ModelAdapter.RemoveJobStep(existingEntity.ResourceGroupName, existingEntity.ServerName, existingEntity.AgentName, existingEntity.JobName, existingEntity.StepName);
return entity;
}
}
}
| 38.577143
| 176
| 0.570878
|
0bdd747259e6598c7a06ad5f178ba0a2ad7d428b
| 1,512
|
dart
|
Dart
|
test/domain/usecases/email_signup_usecase_test.dart
|
lordvidex/TaskMeter
|
845cc2422b249bf5cdfee0d6531d8d6bbbc2ac42
|
[
"MIT"
] | 2
|
2021-03-06T13:13:16.000Z
|
2021-09-12T19:21:10.000Z
|
test/domain/usecases/email_signup_usecase_test.dart
|
lordvidex/TaskMeter
|
845cc2422b249bf5cdfee0d6531d8d6bbbc2ac42
|
[
"MIT"
] | 1
|
2021-03-30T23:40:59.000Z
|
2021-03-30T23:40:59.000Z
|
test/domain/usecases/email_signup_usecase_test.dart
|
lordvidex/TaskMeter
|
845cc2422b249bf5cdfee0d6531d8d6bbbc2ac42
|
[
"MIT"
] | null | null | null |
import 'package:dartz/dartz.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:task_meter/core/failures.dart';
import 'package:task_meter/domain/usecases/email_signup_usecase.dart';
import 'email_signin_usecase_test.mocks.dart';
void main() {
late AuthenticationRepoMock authRepoMock;
late EmailSignUpUseCase emailSignUp;
setUp(() {
authRepoMock = AuthenticationRepoMock();
emailSignUp = EmailSignUpUseCase(authRepo: authRepoMock);
});
group('Signin Error cases', () {
final tEmail = 'druid9dev@gmail.com';
final tPass = 'well,it\'adruid';
test(
'should return NetworkFailure when user tries to signup without internet access',
() async {
// arrange
when(authRepoMock.signupUserWithEmail(any, any))
.thenAnswer((_) async => Left(NetworkFailure()));
// act
final result = await emailSignUp(tEmail, tPass);
// assert
expect(result, Left(NetworkFailure()));
});
test(
'should return UserExistsFailure when user tries to sign in with unknown credientials',
() async {
// arrange
when(authRepoMock.signupUserWithEmail(any, any))
.thenAnswer((_) async => Left(UserExistsFailure()));
// act
final result = await emailSignUp(tEmail, tPass);
// assert
expect(result, Left(UserExistsFailure()));
});
});
group('SignUp Success cases', () {
//FirebaseUser has no constructors :(
});
}
| 32.170213
| 95
| 0.669312
|
e1c79a2a3ea62a62ea65fc64b00bf08a9b9c2109
| 801
|
cs
|
C#
|
Photon Server/src-server/LoadBalancing/LoadBalancing/Operations/SettingsRequest.cs
|
swDill/PacManProject
|
ba8f8610704f13dfbef504ebb5b62154eede2351
|
[
"MIT"
] | null | null | null |
Photon Server/src-server/LoadBalancing/LoadBalancing/Operations/SettingsRequest.cs
|
swDill/PacManProject
|
ba8f8610704f13dfbef504ebb5b62154eede2351
|
[
"MIT"
] | null | null | null |
Photon Server/src-server/LoadBalancing/LoadBalancing/Operations/SettingsRequest.cs
|
swDill/PacManProject
|
ba8f8610704f13dfbef504ebb5b62154eede2351
|
[
"MIT"
] | null | null | null |
using Photon.SocketServer;
using Photon.SocketServer.Rpc;
namespace Photon.LoadBalancing.Operations
{
public static class SettingsRequestParameters
{
public const byte LobbyStats = 0;
}
public class SettingsRequest : Operation
{
#region .ctr
public SettingsRequest(IRpcProtocol protocol, OperationRequest operationRequest)
: base(protocol, operationRequest)
{
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether the client wants to receive lobby statistics.
/// </summary>
[DataMember(Code = SettingsRequestParameters.LobbyStats, IsOptional = true)]
public bool? ReceiveLobbyStatistics { get; set; }
#endregion
}
}
| 24.272727
| 97
| 0.649189
|
38ac8bf57947ba98a84bde299aa069cd90f855a4
| 710
|
php
|
PHP
|
framework/src/Illuminate/Commands/Templates/Create.php
|
baiseiit/shop
|
6c3f2ea731b48a5ee3c08df8329360ecb067b973
|
[
"MIT"
] | null | null | null |
framework/src/Illuminate/Commands/Templates/Create.php
|
baiseiit/shop
|
6c3f2ea731b48a5ee3c08df8329360ecb067b973
|
[
"MIT"
] | null | null | null |
framework/src/Illuminate/Commands/Templates/Create.php
|
baiseiit/shop
|
6c3f2ea731b48a5ee3c08df8329360ecb067b973
|
[
"MIT"
] | null | null | null |
<?php
namespace Illuminate\Commands\Templates;
use Contracts\Commands\Templatable;
class Create implements Templatable {
public static function controller($name) {
return
"<?php
class $name extends Controller {
//
}";
}
public static function view($name) {
return
"<!DOCTYPE html>
<html>
<head>
<title>$name</title>
</head>
<body>
</body>
</html>";
}
public static function model($name) {
return
"<?php
namespace App\Models;
class $name extends Model {
const TABLE = '" . $name . "';
}";
}
public static function middleware($name) {
return
"<?php
class $name extends Middleware {
public static function handle(\$request, \Closure \$next) {
return \$next(\$request);
}
}";
}
}
| 13.653846
| 60
| 0.669014
|
368b8c28572071b91adc4ba06ea5303d904d2eeb
| 12,173
|
asm
|
Assembly
|
src/test.asm
|
simon-frankau/dirac
|
e300bb2ca7cb60500759245b742aae9db4bd82eb
|
[
"MIT"
] | 3
|
2020-12-17T10:11:42.000Z
|
2020-12-17T10:11:55.000Z
|
src/test.asm
|
simon-frankau/dirac
|
e300bb2ca7cb60500759245b742aae9db4bd82eb
|
[
"MIT"
] | null | null | null |
src/test.asm
|
simon-frankau/dirac
|
e300bb2ca7cb60500759245b742aae9db4bd82eb
|
[
"MIT"
] | null | null | null |
; Basic test program to exercise my simple Z80-based computer.
;
; We flash some LEDs, and then test banking, memory, CTC and SIO.
; There's also support for testing NMIs.
; Banking is at port 0x00.
; CTC is at port 0x10.
; SIO is at port 0x20.
; LED output is at port 0x70.
; Banked memory map:
; 0x00000 - 0x07FFF - ROM (top 4 bits inverted when programming the EEPROM)
; 0x80000 - 0x9FFFF - RAM - Read-only
; 0xC0000 - 0xDFFFF - RAM - Read-write
#target rom
; State for interrupts...
pattern: equ $f000
; Reset vector
#code RESET,0,$4000
jp top
; Counter channel 3 interrupt vector
defs $40 - $
defw fail
defw fail
defw fail
defw isr
; NMI vector
defs $66 - $
jp nmi
; Now the real stuff
; Initial wipe across, no hardware enabled
top: di ; Could have come here without reset, for whatever reason.
ld a,$1
out ($70),a
ld de,$4000
l1: dec de
ld a, d
or e
jp nz, l1
ld a,$2
out ($70),a
ld de,$4000
l2: dec de
ld a, d
or e
jp nz, l2
ld a,$4
out ($70),a
ld de,$4000
l3: dec de
ld a, d
or e
jp nz, l3
ld a,$8
out ($70),a
ld de,$4000
l4: dec de
ld a, d
or e
jp nz, l4
ld a,$10
out ($70),a
ld de,$4000
l5: dec de
ld a, d
or e
jp nz, l5
ld a,$20
out ($70),a
ld de,$4000
l6: dec de
ld a, d
or e
jp nz, l6
ld a,$40
out ($70),a
ld de,$4000
l7: dec de
ld a, d
or e
jp nz, l7
ld a,$80
out ($70),a
; Enable banking
ld bc, $0000
ld a, $00 ; Inverted, selects the default $FF page
out (bc), a
; And do a few more LEDs
ld de,$4000
l8: dec de
ld a, d
or e
jp nz, l8
ld a,$40
out ($70),a
ld de,$4000
l9: dec de
ld a, d
or e
jp nz, l9
ld a,$20
out ($70),a
ld de,$4000
l10: dec de
ld a, d
or e
jp nz, l10
ld a,$10
out ($70),a
ld de,$4000
l11: dec de
ld a, d
or e
jp nz, l11
ld a,$8
out ($70),a
ld de,$4000
l12: dec de
ld a, d
or e
jp nz, l12
ld a,$4
out ($70),a
ld de,$4000
l13: dec de
ld a, d
or e
jp nz, l13
ld a,$2
out ($70),a
ld de,$4000
l14: dec de
ld a, d
or e
jp nz, l14
; Map in some RAM, set SP, and do a pattern with using subroutines
ld bc, $f000
ld a, $c0 ; Inverted, selects a RAM page, RW
out (bc), a
ld sp, $0000
loop: ld a, $03
call disp
ld a, $06
call disp
ld a, $0c
call disp
ld a, $18
call disp
ld a, $30
call disp
ld a, $60
call disp
ld a, $c0
call disp
ld a, $81
call disp
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Right, the basics work: ROM mapped in page 0x0, RAM mapped in page 0xf
;
; Now, check the mapping slots we can:
; For each value, write different values to all available slots,
; then read them back.
; For each number:
ld d, 0
blah0: ld c, 0 ; Lower part of port.
; Write a different number to each slot
ld l, d ; Base value to write
ld b, $e0 ; Last page to write
blah1: out (bc), l ; Write page thing
inc l ; Write next value to next page
ld a, b
sub a, $10 ; Next page
ld b, a
jp nz, blah1 ; Don't write page zero
; Read back numbers and check it's ok
ld l, d ; Thing to compare against
ld b, $e0 ; Last page to write
blah2: in a, (c) ; Read page thing (NB: Really 'in a, (bc)')
cp l
jp nz, fail
inc l ; Read next value from next page
ld a, b
sub a, $10 ; Next page
ld b, a
jp nz, blah2 ; Don't read page zero
dec d
jp nz, blah0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Slots all work. On to a RAM test.
;
; Let's map a single slot, and use it to write over all of RAM, then
; read it all back.
; NB: This corrupts stack. Fortunately, not actually using it...
ld a, 1 ; Display status
out ($70),a
ld l, 23 ; Magic modulo.
; Map physical pages C0-DF into slot 1.
ld h, $c0
ramwouter: ld bc, $1000
out (bc), h
; Loop from $1000 to $2000, scribbling values in as we go.
ld de,$1000
ramwinner: ld a, l
ld (de), a
dec l
jp nz, rwiskip
ld l,23
rwiskip: inc de
ld a, d
sub $20
or e
jp nz, ramwinner
; Written this page, go to next.
inc h
ld a, h
cp a, $e0
jp nz, ramwouter
; Having written, read.
ld a, 3 ; Update status
out ($70),a
ld l, 23
ld h, $c0
ramrouter: ld bc, $1000
out (bc), h
; Loop from $1000 to $2000, reading values as we go.
ld de,$1000
ramrinner: ld a, (de)
cp a, l
jp nz, fail
dec l
jp nz, rriskip
ld l,23
rriskip: inc de
ld a, d
sub $20
or e
jp nz, ramrinner
; Written this page, go to next.
inc h
ld a, h
cp a, $e0
jp nz, ramrouter
; Now, read the read-only mapping, throwing in attempts to write.
ld a, 7 ; Update status
out ($70),a
ld l, 23
; Physical slots 80-9f, this time.
ld h, $80
ramrwouter: ld bc, $1000
out (bc), h
; Loop from $1000 to $2000, trying to write, then reading values as we go.
ld de,$1000
ramrwinner: xor a, a
ld (de), a
ld a, (de)
cp a, l
jp nz, fail
dec l
jp nz, rrwiskip
ld l,23
rrwiskip: inc de
ld a, d
sub $20
or e
jp nz, ramrwinner
; Written this page, go to next.
inc h
ld a, h
cp a, $a0
jp nz, ramrwouter
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Now, a similar test for the ROM
ld a, $f ; Update status
out ($70),a
ld l, 17
; Physical slots 01-07
ld h, $01
romouter: ld bc, $1000
out (bc), h
; Loop from $1000 to $2000, trying to write, then reading values as we go.
ld de,$1000
rominner: xor a, a
ld (de), a
ld a, (de)
cp a, l
jp nz, fail
dec l
jp nz, romiskip
ld l,17
romiskip: inc de
ld a, d
sub $20
or e
jp nz, rominner
; Written this page, go to next.
inc h
ld a, h
cp a, $08
jp nz, romouter
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; CTC test
; Set interrupt vector to 0x40, just after the restarts.
ld a, $40
out ($10), a
; Clock channel 0 at 9600 bps:
; Disable interrupt, timer mode, prescale 16, falling edge
; Auto, time constant, reset, control word
ld a, $07
out ($10), a
ld a, 13 ; 2M / (16 * 9600)
out ($10), a
; Clock channel 1 at 2400 bps:
ld a, $07
out ($11), a
ld a, 52 ; 2M / (16 * 2400)
out ($11), a
; Clock channel 2 at 1 kHz
ld a, $07
out ($12), a
ld a, 125 ; 2M / (16 * 1000)
out ($12), a
; Clock channel 3 at 10 Hz
; Enable interrupt, counter, prescale 16, falling edge
; Auto, time constant, reset, control word
ld a, $c7
out ($13), a
ld a, 100
out ($13), a
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; SIO test
; We will be working with channel A, control port
ld a, $18 ; Channel reset
out ($21), a
ld a, $04 ; WR4
out ($21), a
ld a, $04 ; x1 rate, 1 stop bit, no parity
out ($21), a
ld a, $01 ; WR1
out ($21), a
ld a, $00 ; Disable transmit/receive interrupts
out ($21), a
; WR2 has the interrupt vector - NB channel 2-specific stuff?
ld a, $05 ; WR5
out ($21), a
ld a, $ea ; Enable transmission, RTS, DTR, 8 bits
out ($21), a
ld a, $03 ; WR3
out ($21), a
ld a, $c1 ; Enable receiving, 8 bits
out ($21), a
; What about auto-enable - send on CTS, receive on DC?
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Interrupt initialisation
xor a
ld (pattern), a ; Initialise the counter
ld i, a ; Interrupt vectors in first page.
im 2 ; Vectored interrupt
ei ; Off we go!
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; End and general subroutines
success: ; Upper case/lower case switch
call sio_rd
ld b, $20
xor b
call sio_wr
jp success
fail: ld a, $aa
call disp
jp fail
disp: out ($70),a
ld de,$4000
disp_loop: dec de
ld a, d
or e
jp nz, disp_loop
ret
; Write serial
sio_wr: ld b, a
; Wait until transmit buffer has space
sio_wr_lp: in a, ($21)
and $04
jp z, sio_wr_lp
; Stick the data in the data register
ld a, b
out ($20), a
ret
; Read serial
sio_rd: ; Wait until there's a character to receive
in a, ($21)
and $01
jp z, sio_rd
; Read the data from the data register
in a, ($20)
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; NMI test code
; We try to preserve registers, and display the SP lower contents,
; so that we can see if we're triggering nested NMIs or whatever.
nmi: ex af, af'
exx
; Must be a better way of reading SP, but my z80 asm is poor...
ld hl, 0
add hl, sp
ld a, l
out ($70), a
ld de,$0000
nmi_loop: dec de
ld a, d
or e
jp nz, nmi_loop
exx
ex af, af'
retn
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Counter timer test code
;
isr: push af
ld a, (pattern)
inc a
ld (pattern), a
out ($70), a
pop af
ei ; Must re-enable!
reti
#end
| 23.729045
| 75
| 0.402284
|
1a792107040449f0159e7d8a3c6ba953d30147d6
| 17,531
|
cs
|
C#
|
Source/Test/CompanyCommunicator.Send.Func.Test/Services/NotificationServiceTest.cs
|
microsoft-teams-cc/ccbotv5ce
|
288f9d9b4db8003b1a247f1a4d0a4eb5502cbe7d
|
[
"MIT"
] | null | null | null |
Source/Test/CompanyCommunicator.Send.Func.Test/Services/NotificationServiceTest.cs
|
microsoft-teams-cc/ccbotv5ce
|
288f9d9b4db8003b1a247f1a4d0a4eb5502cbe7d
|
[
"MIT"
] | null | null | null |
Source/Test/CompanyCommunicator.Send.Func.Test/Services/NotificationServiceTest.cs
|
microsoft-teams-cc/ccbotv5ce
|
288f9d9b4db8003b1a247f1a4d0a4eb5502cbe7d
|
[
"MIT"
] | null | null | null |
// <copyright file="NotificationServiceTest.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// </copyright>
namespace Microsoft.Teams.Apps.CompanyCommunicator.Send.Func.Test
{
using System;
using System.Net;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Repositories.NotificationData;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Repositories.ReactionData;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Repositories.SentNotificationData;
using Microsoft.Teams.Apps.CompanyCommunicator.Common.Services.MessageQueues.SendQueue;
using Microsoft.Teams.Apps.CompanyCommunicator.Send.Func.Services;
using Moq;
using Xunit;
/// <summary>
/// NotificationService test class.
/// </summary>
public class NotificationServiceTest
{
private readonly Mock<ISentNotificationDataRepository> sentNotificationDataRepository = new Mock<ISentNotificationDataRepository>();
private readonly Mock<IGlobalSendingNotificationDataRepository> globalSendingNotificationDataRepository = new Mock<IGlobalSendingNotificationDataRepository>();
private readonly SendQueueMessageContent sendQueueMessageContent = new SendQueueMessageContent()
{
RecipientData = new RecipientData()
{
RecipientId = "RecipientId1",
},
NotificationId = "notification1",
};
private readonly int sendRetryDelayNumberOfSeconds = 75;
private readonly string messageId = "messageId";
private readonly string notificationId = "notificationId";
private readonly string recipientId = "RecipientId1";
private readonly int totalNumberOfSendThrottles = 100;
/// <summary>
/// Constructor tests.
/// </summary>
[Fact]
public void NotificationServiceConstructorTest()
{
// Arrange
Action action1 = () => new NotificationService(null /*globalSendingNotificationDataRepository*/, this.sentNotificationDataRepository.Object);
Action action2 = () => new NotificationService(this.globalSendingNotificationDataRepository.Object, null /*sentNotificationDataRepository*/);
Action action3 = () => new NotificationService(this.globalSendingNotificationDataRepository.Object, this.sentNotificationDataRepository.Object);
// Act and Assert.
action1.Should().Throw<ArgumentNullException>("globalSendingNotificationDataRepository is null.");
action2.Should().Throw<ArgumentNullException>("sentNotificationDataRepository is null.");
action3.Should().NotThrow();
}
/// <summary>
/// Test to check send notification is Throttled.
/// </summary>
/// <returns>returns boolean flag representing notification sent.</returns>
[Fact]
public async Task SendNotificationThrottledTest()
{
// Arrange
var notificationService = this.GetNotificationService();
var globalSendingNofificationDataResponse = new GlobalSendingNotificationDataEntity()
{
SendRetryDelayTime = DateTime.UtcNow - TimeSpan.FromSeconds(1),
};
this.globalSendingNotificationDataRepository
.Setup(x => x.GetGlobalSendingNotificationDataEntityAsync())
.ReturnsAsync(globalSendingNofificationDataResponse);
// Act
var serviceResponse = await notificationService.IsSendNotificationThrottled();
// Assert
serviceResponse.Should().BeFalse();
}
/// <summary>
/// Test to check notification is sent when sendRetry delay time is null.
/// </summary>
/// <returns>returns boolean flag representing notification sent.</returns>
[Fact]
public async Task SendNotificationThrottled_SendRetrydelayTime_Test()
{
// Arrange
var notificationService = this.GetNotificationService();
GlobalSendingNotificationDataEntity globalSendingNofificationDataResponse = new GlobalSendingNotificationDataEntity();
this.globalSendingNotificationDataRepository
.Setup(x => x.GetGlobalSendingNotificationDataEntityAsync())
.ReturnsAsync(globalSendingNofificationDataResponse);
// Act
var serviceResponse = await notificationService.IsSendNotificationThrottled();
// Assert
serviceResponse.Should().BeFalse();
}
/// <summary>
/// Test method to handle exception when Recipient id is not set.
/// </summary>
/// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
[Fact]
public async Task NotificationPendingRecipientIdNotFoundTest()
{
// Arrange
var notificationService = this.GetNotificationService();
SendQueueMessageContent sendQueueMessageContent = new SendQueueMessageContent()
{
RecipientData = new RecipientData(),
};
// Act
Func<Task> task = async () => await notificationService.IsPendingNotification(sendQueueMessageContent);
// Assert
await task.Should().ThrowAsync<InvalidOperationException>().WithMessage("Recipient id is not set.");
}
/// <summary>
/// Test to avoid sending duplicate messages.
/// If status code set to initializationStatusCode: this means the notification has not been attempted to be sent to this recipient.
/// </summary>
/// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
[Fact]
public async Task NotificationWithInitializationStatusTest()
{
// Arrange
var notificationService = this.GetNotificationService();
SentNotificationDataEntity notificationData = new SentNotificationDataEntity()
{
StatusCode = SentNotificationDataEntity.InitializationStatusCode,
};
this.sentNotificationDataRepository
.Setup(x => x.GetAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(notificationData);
// Act
var serviceResponse = await notificationService.IsPendingNotification(this.sendQueueMessageContent);
// Assert
serviceResponse.Should().BeTrue();
}
/// <summary>
/// Test to avoid sending duplicate messages.
/// If status code set to FaultedAndRetryingStatusCode: this means the Azure Function previously attempted to send the notification
/// to this recipient but failed and should be retried.
/// </summary>
/// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
[Fact]
public async Task NotificationFaultedAndRetryingStatusTest()
{
// Arrange
var notificationService = this.GetNotificationService();
SentNotificationDataEntity notificationData = new SentNotificationDataEntity()
{
StatusCode = SentNotificationDataEntity.FaultedAndRetryingStatusCode,
};
this.sentNotificationDataRepository
.Setup(x => x.GetAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(notificationData);
// Act
var serviceResponse = await notificationService.IsPendingNotification(this.sendQueueMessageContent);
// Assert
serviceResponse.Should().BeTrue();
}
/// <summary>
/// Test to check is notification is sent.
/// </summary>
/// <returns>returns boolean flag representing notification sent.</returns>
[Fact]
public async Task NotificationSentTest()
{
// Arrange
var notificationService = this.GetNotificationService();
this.sentNotificationDataRepository
.Setup(x => x.GetAsync(It.IsAny<string>(), It.IsAny<string>()))
.Returns(Task.FromResult(default(SentNotificationDataEntity)));
// Act
var serviceResponse = await notificationService.IsPendingNotification(this.sendQueueMessageContent);
// Assert
serviceResponse.Should().BeFalse();
}
/// <summary>
/// Test to set notification sent throttled.
/// </summary>
/// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
[Fact]
public async Task SetSendNotificationThrottledTest()
{
// Arrange
var notificationService = this.GetNotificationService();
this.globalSendingNotificationDataRepository
.Setup(x => x.SetGlobalSendingNotificationDataEntityAsync(It.IsAny<GlobalSendingNotificationDataEntity>()))
.Returns(Task.CompletedTask);
// Act
Func<Task> task = async () => await notificationService.SetSendNotificationThrottled(this.sendRetryDelayNumberOfSeconds);
// Assert
await task.Should().NotThrowAsync<Exception>();
this.globalSendingNotificationDataRepository.Verify(x => x.SetGlobalSendingNotificationDataEntityAsync(It.IsAny<GlobalSendingNotificationDataEntity>()));
}
/// <summary>
/// Test to update sent notification status as FaultedAndRetrying.
/// </summary>
/// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
[Fact]
public async Task UpdateSentNotification_Status_FaultedAndRetrying_Test()
{
// Arrange
var notificationService = this.GetNotificationService();
var notificationData = new SentNotificationDataEntity()
{
StatusCode = SentNotificationDataEntity.FaultedAndRetryingStatusCode,
DeliveryStatus = SentNotificationDataEntity.Retrying,
};
this.sentNotificationDataRepository
.Setup(x => x.GetAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(notificationData);
this.sentNotificationDataRepository
.Setup(x => x.InsertOrMergeAsync(It.IsAny<SentNotificationDataEntity>()))
.Returns(Task.CompletedTask);
// Act
Func<Task> task = async () => await notificationService.UpdateSentNotification(this.notificationId, this.recipientId, this.messageId, this.totalNumberOfSendThrottles, SentNotificationDataEntity.FaultedAndRetryingStatusCode, string.Empty, string.Empty);
// Assert
await task.Should().NotThrowAsync<Exception>();
this.sentNotificationDataRepository.Verify(x => x.InsertOrMergeAsync(It.Is<SentNotificationDataEntity>(x => x.StatusCode == notificationData.StatusCode)));
}
/// <summary>
/// Test to update sent notification status created.
/// </summary>
/// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
[Fact]
public async Task UpdateSentNotification_Status_Created_Test()
{
// Arrange
var notificationService = this.GetNotificationService();
var notificationData = new SentNotificationDataEntity()
{
StatusCode = (int)HttpStatusCode.Created,
DeliveryStatus = SentNotificationDataEntity.Succeeded,
};
this.sentNotificationDataRepository
.Setup(x => x.GetAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(notificationData);
this.sentNotificationDataRepository
.Setup(x => x.InsertOrMergeAsync(It.IsAny<SentNotificationDataEntity>()))
.Returns(Task.CompletedTask);
// Act
Func<Task> task = async () => await notificationService.UpdateSentNotification(this.notificationId, this.recipientId, this.messageId, this.totalNumberOfSendThrottles, (int)HttpStatusCode.Created, string.Empty, string.Empty);
// Assert
await task.Should().NotThrowAsync<Exception>();
this.sentNotificationDataRepository.Verify(x => x.InsertOrMergeAsync(It.Is<SentNotificationDataEntity>(x => x.StatusCode == notificationData.StatusCode)));
}
/// <summary>
/// Test to update sent notification status with too many requests.
/// </summary>
/// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
[Fact]
public async Task UpdateSentNotification_Status_TooManyRequest_Test()
{
// Arrange
var notificationService = this.GetNotificationService();
var notificationData = new SentNotificationDataEntity()
{
StatusCode = (int)HttpStatusCode.TooManyRequests,
DeliveryStatus = SentNotificationDataEntity.Throttled,
};
this.sentNotificationDataRepository
.Setup(x => x.GetAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(notificationData);
this.sentNotificationDataRepository
.Setup(x => x.InsertOrMergeAsync(It.IsAny<SentNotificationDataEntity>()))
.Returns(Task.CompletedTask);
// Act
Func<Task> task = async () => await notificationService.UpdateSentNotification(this.notificationId, this.recipientId, this.messageId, this.totalNumberOfSendThrottles, (int)HttpStatusCode.TooManyRequests, string.Empty, string.Empty);
// Assert
await task.Should().NotThrowAsync<Exception>();
this.sentNotificationDataRepository.Verify(x => x.InsertOrMergeAsync(It.Is<SentNotificationDataEntity>(x => x.StatusCode == notificationData.StatusCode)));
}
/// <summary>
/// Test for update sent notification status as not found.
/// </summary>
/// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
[Fact]
public async Task UpdateSentNotification_Status_NotFound_Test()
{
// Arrange
var notificationService = this.GetNotificationService();
var notificationData = new SentNotificationDataEntity()
{
StatusCode = (int)HttpStatusCode.NotFound,
DeliveryStatus = SentNotificationDataEntity.RecipientNotFound,
};
this.sentNotificationDataRepository
.Setup(x => x.GetAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(notificationData);
this.sentNotificationDataRepository
.Setup(x => x.InsertOrMergeAsync(It.IsAny<SentNotificationDataEntity>()))
.Returns(Task.CompletedTask);
// Act
Func<Task> task = async () => await notificationService.UpdateSentNotification(this.notificationId, this.recipientId, this.messageId, this.totalNumberOfSendThrottles, (int)HttpStatusCode.NotFound, string.Empty, string.Empty);
// Assert
await task.Should().NotThrowAsync<Exception>();
this.sentNotificationDataRepository.Verify(x => x.InsertOrMergeAsync(It.Is<SentNotificationDataEntity>(x => x.StatusCode == notificationData.StatusCode)));
}
/// <summary>
/// Test for update sent notification status as failed.
/// </summary>
/// <returns><see cref="Task"/> representing the asynchronous operation.</returns>
[Fact]
public async Task UpdateSentNotification_Status_Failed_Test()
{
// Arrange
var notificationService = this.GetNotificationService();
var notificationData = new SentNotificationDataEntity()
{
StatusCode = (int)HttpStatusCode.NotFound,
DeliveryStatus = SentNotificationDataEntity.Failed,
};
this.sentNotificationDataRepository
.Setup(x => x.GetAsync(It.IsAny<string>(), It.IsAny<string>()))
.ReturnsAsync(notificationData);
this.sentNotificationDataRepository
.Setup(x => x.InsertOrMergeAsync(It.IsAny<SentNotificationDataEntity>()))
.Returns(Task.CompletedTask);
// Act
Func<Task> task = async () => await notificationService.UpdateSentNotification(this.notificationId, this.recipientId, this.messageId, this.totalNumberOfSendThrottles, 11, string.Empty, string.Empty);
// Assert
await task.Should().NotThrowAsync<Exception>();
this.sentNotificationDataRepository.Verify(x => x.InsertOrMergeAsync(It.Is<SentNotificationDataEntity>(x => x.StatusCode == notificationData.StatusCode)));
}
/// <summary>
/// Initializes a new instance of the <see cref="NotificationService"/> class.
/// </summary>
private NotificationService GetNotificationService()
{
return new NotificationService(this.globalSendingNotificationDataRepository.Object, this.sentNotificationDataRepository.Object);
}
}
}
| 47
| 264
| 0.645599
|
c686999b3c1cf716cd96d0c7de14fa6ef5703102
| 1,247
|
py
|
Python
|
brokenshire/settings/prod.py
|
Brokenshire/brokenshire-django
|
2e1c36286722ee80c33c267c1bab846f042c1784
|
[
"Apache-2.0"
] | null | null | null |
brokenshire/settings/prod.py
|
Brokenshire/brokenshire-django
|
2e1c36286722ee80c33c267c1bab846f042c1784
|
[
"Apache-2.0"
] | null | null | null |
brokenshire/settings/prod.py
|
Brokenshire/brokenshire-django
|
2e1c36286722ee80c33c267c1bab846f042c1784
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2020 Jack Brokenshire
# 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.
# Local imports
from .base import *
# Third-party imports
import django_heroku
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = [
'brokenshire.herokuapp.com',
]
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'd8brjb1q368gku',
}
}
# Heroku: Update database configuration from $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Activate Django-Heroku.
django_heroku.settings(locals())
| 25.44898
| 74
| 0.747394
|
c697329ef0fd923924d8b74377fce9786a9fa84f
| 2,888
|
py
|
Python
|
40transmembrane.py
|
thomasjay3/homework
|
d98d189fbd55f45a12cd28c990abdae47fc1ba8f
|
[
"MIT"
] | null | null | null |
40transmembrane.py
|
thomasjay3/homework
|
d98d189fbd55f45a12cd28c990abdae47fc1ba8f
|
[
"MIT"
] | null | null | null |
40transmembrane.py
|
thomasjay3/homework
|
d98d189fbd55f45a12cd28c990abdae47fc1ba8f
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
import sys
# Write a program that predicts if a protein is trans-membrane
# Trans-membrane proteins have the following properties
# Signal peptide: https://en.wikipedia.org/wiki/Signal_peptide
# Hydrophobic regions(s): https://en.wikipedia.org/wiki/Transmembrane_protein
# No prolines in hydrophobic regions (alpha helix)
# Hydrophobicity is measued via Kyte-Dolittle
# https://en.wikipedia.org/wiki/Hydrophilicity_plot
# For our purposes:
# Signal peptide is 8 aa long, KD > 2.5, first 30 aa
# Hydrophobic region is 11 aa long, KD > 2.0, after 30 aa
# Hints:
# Create a function for KD calculation
# Create a function for amphipathic alpha-helix
protein_list = []
names = []
# Amino Acid One Letter Code Hydropathy Score
# I = 4.5
# V = 4.2
# L = 3.8
# F = 2.8
# C = 2.5
# M = 1.9
# A = 1.8
# G = -0.4
# T = -0.7
# S = -0.8
# W = -0.9
# Y = -1.3
# P = -1.6
# H = -3.2
# E = -3.5
# Q = -3.5
# D = -3.5
# N = -3.5
# K = -3.9
# R = -4.5
# Open protein file and creating a list for proteins and corresponding protein names
assert(len(sys.argv) == 2)
with open(sys.argv[1]) as fp:
seq = ""
for line in fp.readlines():
if line[0] == ">":
protein_list.append(seq)
names.append(line.rstrip())
seq = ""
else:seq += line.rstrip()
# Lining up proteins with their correct names
protein_list = protein_list[1:]
# KD calculation
def kd(protein):
hydrophobicity = 0
length = 0
for aa in protein:
length += 1
if aa == "I": hydrophobicity += 4.5
elif aa == "V": hydrophobicity += 4.2
elif aa == "L": hydrophobicity += 3.8
elif aa == "F": hydrophobicity += 2.8
elif aa == "C": hydrophobicity += 2.5
elif aa == "M": hydrophobicity += 1.9
elif aa == "A": hydrophobicity += 1.8
elif aa == "G": hydrophobicity -= 0.4
elif aa == "T": hydrophobicity -= 0.7
elif aa == "S": hydrophobicity -= 0.8
elif aa == "W": hydrophobicity -= 0.9
elif aa == "Y": hydrophobicity -= 1.3
elif aa == "P": hydrophobicity -= 1.6
elif aa == "H": hydrophobicity -= 3.2
elif aa == "E": hydrophobicity -= 3.5
elif aa == "Q": hydrophobicity -= 3.5
elif aa == "D": hydrophobicity -= 3.5
elif aa == "N": hydrophobicity -= 3.5
elif aa == "K": hydrophobicity -= 3.9
elif aa == "R": hydrophobicity -= 4.5
return hydrophobicity/ length
def fatty_seq(protein, window, threshold):
for i in range(len(protein) - window + 1):
pep = protein[i : i + window]
# print(pep, kd(pep))
if kd(pep) > threshold and 'P' not in pep:
print(pep, kd(pep))
return True
return False
# print(fatty_seq(protein_list[35], 11, 2.5))
total = 0
for protein, name in zip(protein_list, names):
if fatty_seq(protein[:30], 8, 2.5) and fatty_seq(protein[30:], 11, 2.0):
total += 1
print(name[1:13])
print(f'Total:{total}')
"""
python3 40transmembrane.py ../Data/at_prots.fa
AT1G75120.1
AT1G10950.1
AT1G75110.1
AT1G74790.1
AT1G12660.1
AT1G75130.1
"""
| 24.896552
| 84
| 0.642313
|
a44f14e52ee3387fc7efc008afdff3c2327c532f
| 444
|
php
|
PHP
|
application/views/message_error_view.php
|
fadfield/igiter_admin
|
56b02685f4db35079cddbe4da9fb4e876f169012
|
[
"MIT"
] | null | null | null |
application/views/message_error_view.php
|
fadfield/igiter_admin
|
56b02685f4db35079cddbe4da9fb4e876f169012
|
[
"MIT"
] | null | null | null |
application/views/message_error_view.php
|
fadfield/igiter_admin
|
56b02685f4db35079cddbe4da9fb4e876f169012
|
[
"MIT"
] | null | null | null |
<?php $result = $this->session->flashdata('result');?>
<?php if(validation_errors() || (isset($result) && !$result['success']) ):?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="fa fa-warning"></i> Error!</h4>
<?php echo validation_errors(); ?>
<?php echo isset($result['message']) ? $result['message'] : ''; ?>
</div>
<?php endif; ?>
| 49.333333
| 87
| 0.637387
|
b05baf2e414031ea2f5c1a269a99b13d86ec524a
| 170
|
py
|
Python
|
prova02/questao01.py
|
RamonBomfim/lab-de-prog2
|
fdc054cf092cd1a06d34a2bdc0edcb5826f79775
|
[
"MIT"
] | null | null | null |
prova02/questao01.py
|
RamonBomfim/lab-de-prog2
|
fdc054cf092cd1a06d34a2bdc0edcb5826f79775
|
[
"MIT"
] | null | null | null |
prova02/questao01.py
|
RamonBomfim/lab-de-prog2
|
fdc054cf092cd1a06d34a2bdc0edcb5826f79775
|
[
"MIT"
] | null | null | null |
def calcular(a, b):
if (a > b):
total = a * b
elif (a == b):
total = a * (b + 2)
else:
total = a
print(total)
calcular(10, 10)
| 13.076923
| 27
| 0.411765
|
464b6eddd679524fcb602487873b6f6168035ad7
| 7,167
|
php
|
PHP
|
application/models/masterdata/MasterDataTrainingImage_.php
|
gdguradio/admingetfit
|
5f55b717b25531345c71926a9e1c6f4406188bec
|
[
"MIT"
] | null | null | null |
application/models/masterdata/MasterDataTrainingImage_.php
|
gdguradio/admingetfit
|
5f55b717b25531345c71926a9e1c6f4406188bec
|
[
"MIT"
] | null | null | null |
application/models/masterdata/MasterDataTrainingImage_.php
|
gdguradio/admingetfit
|
5f55b717b25531345c71926a9e1c6f4406188bec
|
[
"MIT"
] | null | null | null |
<?php
class MasterDataTrainingImage_ extends CI_Model{
public function loadBranch($id){
$isuserfrommain = $this->selectBranches($id);
if($isuserfrommain == "franchise"){
// $this->db->where('A.SysID',$id);
$this->db->where('A.BranchType',$isuserfrommain);
}
$this->db->where('BranchStatus','yes');
$this->db->where('DeleteStatus','no');
$query = $this->db->select('A.*')
->from('branchdetails as A')
->get();
// print_r($query->result());die();
if($query){
if($query->num_rows() > 0){
return $query->result();
}
}
}
public function selectBranches($id){
// $this->db->where('A.BranchType',"main");
$this->db->where('B.SysID',$id);
$this->db->where('A.BranchStatus','yes');
$this->db->where('A.DeleteStatus','no');
$query = $this->db->select('A.BranchType')
->from('branchdetails as A')
->join('gymmainlogin as B','B.BranchDetailsID = A.SysID','inner')
->get();
if ($query){
return $query->row()->BranchType;
}else{
return FALSE;
}
}
public function loadTrainingImage($id=NULL){
if($id!=NULL){
$this->db->where('A.SysID',$id);
}
$this->db->where('A.DeleteStatus','no');
$this->db->where('A.ImageStatus','yes');
$query = $this->db->select('A.*')
->from('masterdatatrainingimage as A')
->get();
if($query){
if($query->num_rows() > 0){
return $query->result();
}
}
}
public function loadAllTrainingImage($id=NULL){
if($id!=NULL){
$this->db->where('A.SysID',$id);
}
$branchid = $this->session->userdata('branchID');
$this->db->distinct('ImageTitle');
// $this->db->where('A.DeleteStatus','no');
// $this->db->where('A.ImageStatus','yes');
$query = $this->db->select('A.*')
->from('masterdatatrainingimage as A')
->get();
if($query){
if($query->num_rows() > 0){
$result = array();
foreach($query->result() as $x){
array_push($result,array(
'SysID' => $x->SysID,
'ShowToBranch' => $x->ShowToBranch,
'ImageTitle' => $x->ImageTitle,
'ImageDescription' => $x->ImageDescription,
'ImageLink' => $x->ImageLink,
'ImageOrderIndex' => $x->ImageOrderIndex,
'AddedDate' => $x->AddedDate,
'ImageStatus' => $x->ImageStatus,
'BranchName' => $this->getbullenshowto_byid($x->SysID,"BranchName,B.SysID AS BranchID")
));
}
return $result;
}
}
// $this->db->where('A.DeleteStatus','no');
// $this->db->where('A.ImageStatus','yes');
// $query = $this->db->select('A.*')
// ->from('masterdatatrainingimage as A')
// ->get();
// if($query){
// if($query->num_rows() > 0){
// return $query->result();
// }
// }
}
public function getbullenshowto_byid($SysID,$columnname,$branchid= NULL ){
if($SysID != NULL){
$this->db->where('A.masterdatatrainingimageID',$SysID);
}
if($branchid != NULL){
$this->db->where('A.ShowToBranch',$branchid);
}
$this->db->distinct();
$this->db->where('A.ImageStatus',"yes");
$this->db->where('A.DeleteStatus',"no");
$query = $this->db->select($columnname)
->from('masterdatatrainingimageshowto AS A')
->join('branchdetails as B ',' B.SysID = A.ShowToBranch','inner')
->get();
// $this->output->enable_profiler(TRUE);
// die();
if($query){
if($query->num_rows() > 0){
return $query->result();
}
}
}
public function addTrainingImage($data_array,$data_show){
$this->db->trans_start();
$this->db->insert('masterdatatrainingimage',$data_array);
$last_id = $this->db->insert_id();
$tmp = array();
foreach($data_show AS $key=>$val){
$data_show[$key]['masterdatatrainingimageID'] = $last_id;
}
// print_r($mapping);
$this->db->insert_batch('masterdatatrainingimageshowto',$data_show);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){
return FALSE;
}else{
return TRUE;
}
// $query = $this->db->insert('masterdatatrainingimage',$data_array);
// if ($query){
// return TRUE;
// }
}
public function updateTrainingImage($data_array,$data_show,$id){
$this->db->trans_start();
$this->db->where('SysID',$id);
$this->db->update('masterdatatrainingimage',$data_array);
foreach($data_show AS $key=>$val){
$data_show[$key]['masterdatatrainingimageID'] = $id;
}
$this->db->where('masterdatatrainingimageID',$id);
$this->db->delete('masterdatatrainingimageshowto');
$this->db->insert_batch('masterdatatrainingimageshowto',$data_show);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){
return FALSE;
}else{
return TRUE;
}
// $this->db->where('SysID',$id);
// $query = $this->db->update('masterdatatrainingimage',$data_array);
// if ($query){
// return TRUE;
// }
}
public function duplicate_checker($tbl,$column,$value,$id = NULL){
if($id != NULL){
$this->db->where('SysID !=',$id);
}
$this->db->where($column,$value);
$query = $this->db->select($column)
->from($tbl)
->get();
if($query){
if($query->num_rows() > 0){
return TRUE;
}
}
}
public function image_type_checker($menu_type,$id = NULL){
$this->db->where('masterdatatrainingimage',$menu_type);
if($id != NULL){
$this->db->where('SysID !=',$id);
}
$query = $this->db->select('ImageTitle')
->from('masterdatatrainingimage')
->get();
if($query){
if($query->num_rows() > 0){
return TRUE;
//role type exist
}else{
return FALSE;
}
}
}
}
| 35.305419
| 112
| 0.451514
|
9ffb8f4426b6794031a1209af6a1994232cbded3
| 3,283
|
py
|
Python
|
src/301-350/348.py
|
adaggarwal/leetcode1992
|
3cd60646f478d7c90fb5afbdedc7c247f24e76f6
|
[
"MIT"
] | 9
|
2019-11-27T19:30:10.000Z
|
2021-08-07T17:32:17.000Z
|
src/301-350/348.py
|
adityaaggarwal1992/leetcode1992
|
4e0cc19ae89050770a7a6d4ba5b330dc76c8dfdc
|
[
"MIT"
] | 2
|
2020-07-10T01:48:30.000Z
|
2020-07-29T07:16:34.000Z
|
src/301-350/348.py
|
adityaaggarwal1992/leetcode1992
|
4e0cc19ae89050770a7a6d4ba5b330dc76c8dfdc
|
[
"MIT"
] | 5
|
2019-06-14T16:32:07.000Z
|
2020-07-10T01:40:49.000Z
|
'''
348. Design Tic-Tac-Toe
Medium
271
21
Design a Tic-tac-toe game that is played between two players on a n x n grid.
You may assume the following rules:
A move is guaranteed to be valid and is placed on an empty block.
Once a winning condition is reached, no more moves is allowed.
A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.
Example:
Given n = 3, assume that player 1 is "X" and player 2 is "O" in the board.
TicTacToe toe = new TicTacToe(3);
toe.move(0, 0, 1); -> Returns 0 (no one wins)
|X| | |
| | | | // Player 1 makes a move at (0, 0).
| | | |
toe.move(0, 2, 2); -> Returns 0 (no one wins)
|X| |O|
| | | | // Player 2 makes a move at (0, 2).
| | | |
toe.move(2, 2, 1); -> Returns 0 (no one wins)
|X| |O|
| | | | // Player 1 makes a move at (2, 2).
| | |X|
toe.move(1, 1, 2); -> Returns 0 (no one wins)
|X| |O|
| |O| | // Player 2 makes a move at (1, 1).
| | |X|
toe.move(2, 0, 1); -> Returns 0 (no one wins)
|X| |O|
| |O| | // Player 1 makes a move at (2, 0).
|X| |X|
toe.move(1, 0, 2); -> Returns 0 (no one wins)
|X| |O|
|O|O| | // Player 2 makes a move at (1, 0).
|X| |X|
toe.move(2, 1, 1); -> Returns 1 (player 1 wins)
|X| |O|
|O|O| | // Player 1 makes a move at (2, 1).
|X|X|X|
'''
'''
Personally, I didn't get the intuition correct before I saw -> https://leetcode.com/problems/design-tic-tac-toe/discuss/81898/Java-O(1)-solution-easy-to-understand
But then, just to reiterate the meat of that solution:
***
1. We don't store the whole tic-tac-toe board and it's state.
2. Just store the state of pertinent row/col/diagonal/anti-diagonal.
3. By state, what we mean is -> how many times any of the two players have picked that row and column. (Hence the O(1) solution)
4. At any point, as the state becomes the total size 'n'; we have a winner! Congratulations current player :)
***
For solutions to other problems, feel free to visit -> https://github.com/adityaaggarwal1992/leetcode1992
'''
class TicTacToe:
def __init__(self, n):
"""
Initialize your data structure here.
:type n: int
"""
self.row = [0 for x in range(n)]
self.col = [0 for x in range(n)]
self.diag = 0
self.undiag = 0
self.n = n
def move(self, row, col, player):
"""
Player {player} makes a move at ({row}, {col}).
@param row The row of the board.
@param col The column of the board.
@param player The player, can be either 1 or 2.
@return The current winning condition, can be either:
0: No one wins.
1: Player 1 wins.
2: Player 2 wins.
:type row: int
:type col: int
:type player: int
:rtype: int
"""
order = 1 if player == 1 else -1
self.row[row] += order
self.col[col] += order
if row == col:
self.diag += order
if col == self.n-1 -row:
self.undiag += order
if abs(self.row[row]) == self.n or \
abs(self.col[col]) == self.n or \
abs(self.diag) == self.n or \
abs(self.undiag) == self.n:
return player
else:
return 0
| 28.547826
| 163
| 0.572038
|
b03b85560632c7d285f2936c1fc7df527781f42d
| 2,100
|
py
|
Python
|
scripts/scraper.py
|
jhKessler/Tagesschau-Analysis
|
40490b13fa2f3e5cf3bd4b5f4f46b5bf72ab9899
|
[
"MIT"
] | null | null | null |
scripts/scraper.py
|
jhKessler/Tagesschau-Analysis
|
40490b13fa2f3e5cf3bd4b5f4f46b5bf72ab9899
|
[
"MIT"
] | null | null | null |
scripts/scraper.py
|
jhKessler/Tagesschau-Analysis
|
40490b13fa2f3e5cf3bd4b5f4f46b5bf72ab9899
|
[
"MIT"
] | null | null | null |
#
# scraper for getting the data from article descriptions
#
import time
import datetime
import requests
import pandas as pd
from tqdm import tqdm
from bs4 import BeautifulSoup
DATE_FORMAT = "%d/%m/%Y"
ARCHIVE_URL = "https://www.tagesschau.de/multimedia/video/videoarchiv2~_date-"
SECOND_DELAY = 1
# dates
first_description = datetime.date(year=2013, month=4, day=22)
today = datetime.date.today()
current_date = first_description
# list for storing articles
all_articles = []
def update_progress_bar(pbar: tqdm, current_date: datetime.datetime) -> None:
"""Update Progress bar"""
pbar.update(1)
estimated_time = round(((today - current_date).days * (SECOND_DELAY+0.3)) / 60)
pbar.set_description(f"Scraping articles: Date:{current_date.strftime(DATE_FORMAT)}, Articles: {len(all_articles)}, Estimated time left: {round(estimated_time, 2)} min")
# init progressbar
total_days = (today - first_description).days
print(total_days)
progress_bar = tqdm(total=total_days)
update_progress_bar(progress_bar, current_date)
# loop over days
while current_date <= today:
date_string = current_date.strftime("%Y%m%d")
# format url to right form
url_string = f"{ARCHIVE_URL}{date_string}.html"
# request html and scrape it for the datapoints
response = requests.get(url_string).text
soup = BeautifulSoup(response, 'html.parser')
# save articles
article_teasers = list(soup.findAll(class_="teasertext"))
titles = soup.findAll(class_="headline")
dates_and_times = list(soup.findAll(class_="dachzeile"))
for title, date_and_time, article, in zip(titles, dates_and_times, article_teasers):
all_articles.append([current_date.strftime(DATE_FORMAT), article.text, title.text, date_and_time.text])
# go to next day
current_date = current_date + datetime.timedelta(days=1)
# sleep
time.sleep(SECOND_DELAY)
update_progress_bar(progress_bar, current_date)
# format data
article_df = pd.DataFrame(all_articles, columns=["date", "article", "title", "time_text"])
article_df.to_excel("data/raw.xlsx", index=False)
| 32.307692
| 173
| 0.739524
|
af456ffab13a6f1946a2796a28b3e89e83c7a329
| 5,319
|
py
|
Python
|
tests/test_HCA/test_HCA.py
|
Argmaster/optmath
|
389095436bb551c53db710bc3a2d95a3fb8ae0a6
|
[
"MIT"
] | null | null | null |
tests/test_HCA/test_HCA.py
|
Argmaster/optmath
|
389095436bb551c53db710bc3a2d95a3fb8ae0a6
|
[
"MIT"
] | null | null | null |
tests/test_HCA/test_HCA.py
|
Argmaster/optmath
|
389095436bb551c53db710bc3a2d95a3fb8ae0a6
|
[
"MIT"
] | null | null | null |
from dataclasses import dataclass
from io import BytesIO
from pathlib import Path
import matplotlib.pyplot as plt
import numpy
import numpy.typing as npt
import pandas as pd
import pytest
from PIL import Image
from scipy.cluster import hierarchy
from optmath.HCA import (
HCA,
Chebyshev,
Cluster,
CompleteLinkage,
Euclidean,
HCAStep,
Manhattan,
RecordBase,
SingleLinkage,
Ward,
)
from optmath.HCA.record import autoscale
@dataclass(frozen=True)
class Seed(RecordBase):
size: float
quality: float
raw = [
[2, 3],
[3, 8],
[4, 7],
[1, 1],
[0, 0],
]
clusters = Cluster.new(Seed.new(raw))
def compare_ndarrays(first: npt.NDArray, second: npt.NDArray) -> float:
first = first.reshape(-1)
second = second.reshape(-1)
return numpy.count_nonzero(first == second) / len(first)
def dump_dendrogram(z_matrix: npt.NDArray) -> npt.NDArray:
io = BytesIO()
hierarchy.dendrogram(z_matrix, leaf_rotation=90.0, leaf_font_size=8.0)
plt.savefig(io, format="png")
io.seek(0)
image = Image.open(io)
raw = numpy.asarray(image)
return raw
def test_HCA():
algorithm = HCA(clusters, CompleteLinkage(Euclidean()))
algorithm.reduce()
def test_HCA_iteration():
algorithm = HCA(clusters, CompleteLinkage(Euclidean()))
for step in algorithm:
assert isinstance(step, HCAStep)
def test_HCA_result():
algorithm = HCA(clusters, CompleteLinkage(Euclidean()))
assert str(algorithm.result()) == "Cluster(ID=8,s=5,h=8.544)"
def test_HCA_dendrogram_complete_euclidean():
algorithm = HCA(clusters, CompleteLinkage(Euclidean()))
cluster = algorithm.result()
z_custom = cluster.Z()
z_scipy = hierarchy.linkage(raw, method="complete", metric="euclidean")
custom_version = dump_dendrogram(z_custom)
scipy_version = dump_dendrogram(z_scipy)
result = compare_ndarrays(custom_version, scipy_version)
assert result > 0.99
def test_HCA_dendrogram_single_euclidean():
algorithm = HCA(clusters, SingleLinkage(Euclidean()))
cluster = algorithm.result()
z_custom = cluster.Z()
z_scipy = hierarchy.linkage(raw, method="single", metric="euclidean")
custom_version = dump_dendrogram(z_custom)
scipy_version = dump_dendrogram(z_scipy)
result = compare_ndarrays(custom_version, scipy_version)
assert result > 0.99
def test_HCA_dendrogram_single_manhattan():
algorithm = HCA(clusters, SingleLinkage(Manhattan()))
cluster = algorithm.result()
z_custom = cluster.Z()
z_scipy = hierarchy.linkage(raw, method="single", metric="cityblock")
custom_version = dump_dendrogram(z_custom)
scipy_version = dump_dendrogram(z_scipy)
result = compare_ndarrays(custom_version, scipy_version)
assert result > 0.99
def test_HCA_dendrogram_complete_chebyshev():
algorithm = HCA(clusters, SingleLinkage(Chebyshev()))
cluster = algorithm.result()
z_custom = cluster.Z()
z_scipy = hierarchy.linkage(raw, method="single", metric="chebyshev")
custom_version = dump_dendrogram(z_custom)
scipy_version = dump_dendrogram(z_scipy)
result = compare_ndarrays(custom_version, scipy_version)
assert result > 0.99
@pytest.mark.skip(
reason=(
"Known issue with Ward distance selector - "
"mismatch between scipy and this implementation"
)
)
def test_HCA_dendrogram_ward_euclidean():
algorithm = HCA(clusters, Ward(Euclidean()))
cluster = algorithm.result()
z_custom = cluster.Z()
z_scipy = hierarchy.linkage(raw, method="ward", metric="euclidean")
custom_version = dump_dendrogram(z_custom)
scipy_version = dump_dendrogram(z_scipy)
result = compare_ndarrays(custom_version, scipy_version)
assert result > 0.99
@dataclass(frozen=True)
class PumpkinSeed(RecordBase):
Area: float
Perimeter: float
Major_Axis_Length: float
Minor_Axis_Length: float
Solidity: float
Roundness: float
TEST_HCA_DIR = Path(__file__).parent
def test_HCA_complex_pumpkin_data():
raw = pd.read_csv(TEST_HCA_DIR / "data" / "test_seeds.csv").to_numpy()
raw = autoscale(raw)
clusters = Cluster.new(PumpkinSeed.new(raw))
algorithm = HCA(clusters, SingleLinkage(Euclidean()))
cluster = algorithm.result()
z = hierarchy.linkage(raw, method="single", metric="euclidean")
hierarchy.dendrogram(z, leaf_rotation=90.0, leaf_font_size=8.0)
z = cluster.Z()
hierarchy.dendrogram(z, leaf_rotation=90.0, leaf_font_size=8.0)
plt.show()
def test_HCA_complex_pumpkin_data_complete_euclidean():
raw = pd.read_csv(TEST_HCA_DIR / "data" / "test_seeds.csv").to_numpy()
raw = autoscale(raw)
clusters = Cluster.new(PumpkinSeed.new(autoscale(raw)))
algorithm = HCA(clusters, CompleteLinkage(Euclidean()))
cluster = algorithm.result()
z_custom = cluster.Z()
z_scipy = hierarchy.linkage(raw, method="complete", metric="euclidean")
custom_version = dump_dendrogram(z_custom)
scipy_version = dump_dendrogram(z_scipy)
result = compare_ndarrays(custom_version, scipy_version)
assert result > 0.98
| 27.417526
| 76
| 0.686031
|
0d618ed7aaa16835a98af9757abce144cc9414a8
| 1,026
|
h
|
C
|
System/Library/PrivateFrameworks/WorkflowEditor.framework/WFListEditorDeletionConfirmation.h
|
zhangkn/iOS14Header
|
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
|
[
"MIT"
] | 1
|
2020-11-04T15:43:01.000Z
|
2020-11-04T15:43:01.000Z
|
System/Library/PrivateFrameworks/WorkflowEditor.framework/WFListEditorDeletionConfirmation.h
|
zhangkn/iOS14Header
|
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
|
[
"MIT"
] | null | null | null |
System/Library/PrivateFrameworks/WorkflowEditor.framework/WFListEditorDeletionConfirmation.h
|
zhangkn/iOS14Header
|
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
|
[
"MIT"
] | null | null | null |
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 12:27:02 PM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/WorkflowEditor.framework/WorkflowEditor
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@interface WFListEditorDeletionConfirmation : NSObject {
unsigned long long _itemIndex;
/*^block*/id _confirmationHandler;
}
@property (nonatomic,readonly) unsigned long long itemIndex; //@synthesize itemIndex=_itemIndex - In the implementation block
@property (nonatomic,readonly) id confirmationHandler; //@synthesize confirmationHandler=_confirmationHandler - In the implementation block
+(id)confirmationForDeletingItemAtIndex:(unsigned long long)arg1 withHandler:(/*^block*/id)arg2 ;
-(id)confirmationHandler;
-(unsigned long long)itemIndex;
-(id)initWithItemIndex:(unsigned long long)arg1 confirmationHandler:(/*^block*/id)arg2 ;
@end
| 41.04
| 158
| 0.769006
|
54bf1b612082052edb983875c76f013a5b3a5add
| 48
|
rb
|
Ruby
|
matrix/test.rb
|
schweigert/oprp
|
afd6cbba0c72b2573a2b5640208586f74ca24cb8
|
[
"MIT"
] | 2
|
2019-04-11T00:26:43.000Z
|
2019-05-23T13:51:40.000Z
|
pthread_matrix/test.rb
|
schweigert/oprp
|
afd6cbba0c72b2573a2b5640208586f74ca24cb8
|
[
"MIT"
] | null | null | null |
pthread_matrix/test.rb
|
schweigert/oprp
|
afd6cbba0c72b2573a2b5640208586f74ca24cb8
|
[
"MIT"
] | 1
|
2019-03-09T13:38:25.000Z
|
2019-03-09T13:38:25.000Z
|
10.times do
system "./main 10000 10000"
end
| 12
| 31
| 0.666667
|
f038fd30e1f6ee3a5397eed159a820335a902687
| 7,534
|
dart
|
Dart
|
lib/traphouse/entity.dart
|
birdbrainswagtrain/heck
|
93e7a7162027099c16938073697177aec5ed6d5a
|
[
"Unlicense",
"MIT"
] | null | null | null |
lib/traphouse/entity.dart
|
birdbrainswagtrain/heck
|
93e7a7162027099c16938073697177aec5ed6d5a
|
[
"Unlicense",
"MIT"
] | null | null | null |
lib/traphouse/entity.dart
|
birdbrainswagtrain/heck
|
93e7a7162027099c16938073697177aec5ed6d5a
|
[
"Unlicense",
"MIT"
] | null | null | null |
part of traphouse;
abstract class GameEntity extends Bounds {
EntityManager ents;
DisplayObject pixObj;
Vector velocity = new Vector();
Vector control = new Vector();
num controlSpeedCap = 0;
num controlAccelAir = 0;
num controlAccelGround = 0;
bool onGround = false;
num groundDampening = 5;
num gravityMultiplier=1;
bool isSolid = true;
num maxHealth = 0;
num health=0;
num playerDamage=0;
num enemyDamage=0;
num hurtTimer=0;
num deadTimer=0;
bool hurtImmune = false;
bool dead=false;
bool remove=false;
Vector move;
GameEntity(Vector size) : super(size);
bool doDamage(GameEntity other,num dmg) {
if (other.takeDamage(dmg)) {
Vector center = new Vector(center_x,center_y);
Vector other_center = new Vector(other.center_x,other.center_y);
Vector f = center-other_center;
f.setLen(300);
other.velocity+=f;
hitEnemy();
return true;
}
return false;
}
bool takeDamage(num dmg) {
if (maxHealth>0 && health>0 && (!hurtImmune || hurtTimer<=0)) {
health-=dmg;
hurtTimer=1;
if (health<=0) {
onDie();
}
return true;
}
return false;
}
bool castDamage(Bounds b,num dmg) {
bool hit=false;
ents.ent_list.forEach((GameEntity e) {
if ((e!=this) && (this==ents.player?true:e==ents.player)) {
if (b.intersects(e)&&e.takeDamage(dmg)) {
hit=true;
return;
}
}
});
return hit;
}
void onDie() {
dead=true;
deadTimer=2;
isSolid=false;
gravityMultiplier=1.0;
if (pixObj!=null)
pixObj.scale.y=-1.0;
}
void hitEnemy() {}
void think(num dt);
void _iThink(num dt) {
if (!dead)
think(dt);
if (deadTimer>0) {
deadTimer-=dt;
if (deadTimer<=0)
remove=true;
}
Random r = new Random();
if (hurtTimer>0) {
hurtTimer-=dt;
if (pixObj!=null)
pixObj.alpha= r.nextDouble();
} else if (pixObj!=null)
pixObj.alpha= 1.0;
if (!control.isZero()) { //Control
Vector c = control.clone();
c.squareClamp(1);
c *= dt * (onGround?controlAccelGround:controlAccelAir);
if (velocity.x.abs()<controlSpeedCap || velocity.x.sign!=control.x.sign)
velocity.x+=c.x;
if (velocity.y.abs()<controlSpeedCap || velocity.y.sign!=control.y.sign)
velocity.y+=c.y;
} //else { //Dampening
num dampening = dt*(onGround?groundDampening:ents.airDampening);
if (dampening>1)
dampening=1;
velocity*=(1-dampening);
//}
//Gravity
velocity.y += dt*gravityMultiplier*ents.gravity;
move = velocity*dt;
if (isSolid)
ents.doCollisions(this);
else
pos+=move;
if (pixObj!=null) {
pixObj.position ..x=pos.x ..y=pos.y;
}
}
void collideTile(Tile t) {
//kek
}
}
class EntityManager {
Stage stage = new Stage(new Color(0x293D34));
DisplayObjectContainer container = new DisplayObjectContainer();
num gravity=980;
num airDampening = 1;
List<GameEntity> ent_list = [];
GameMap map;
bool edit_mode=false;
GameEntity player;
InteractionData mouseData;
bool mouseDown = false;
bool advanceLevel=false;
int numlives=0;
int cachelives=0;
Sprite lives;
Sprite health;
EntityManager() {
stage.interactive=true;
stage.onMouseMove.listen((InteractionData d) {
mouseData=d;
});
stage.onMouseDown.listen((InteractionData d) {
if (d.originalEvent.which==1)
mouseDown=true;
});
stage.onMouseUp.listen((InteractionData d) {
if (d.originalEvent.which==1)
mouseDown=false;
});
stage.addChild(container);
//hud
Sprite h = new Sprite(new Texture.fromImage("img/hud_health.png"));
h.y=20;
h.x=20;
stage.addChild(h);
health = new Sprite(new Texture.fromImage("img/hud_health1.png"));
health.x=63;
health.pivot.x=63;
h.addChild(health);
lives = new Sprite(new Texture.fromImage("img/hud_lives.png"));
lives.y=40;
lives.x=20;
stage.addChild(lives);
}
void add(GameEntity e) {
e.ents=this;
ent_list.add(e);
if (e.pixObj!=null)
container.addChild(e.pixObj);
}
void think(num dt) {
ent_list.forEach((GameEntity e) {
e._iThink(dt);
if (e.remove&&e.pixObj!=null) {
container.removeChild(e.pixObj);
}
});
ent_list.removeWhere((GameEntity e) => e.remove);
//Hud
health.scale.x=(player.health/player.maxHealth);
if (health.scale.x<0)
health.scale.x=0.0;
if (numlives!=cachelives) {
cachelives=numlives;
if (lives.children.length>0) {
lives.removeChildren();
lives.children.clear();
}
for (int i=0;i<numlives;i++) {
Sprite s = new Sprite(new Texture.fromImage("img/hud_lives1.png"));
s.x=60+i*20;
lives.addChild(s);
}
}
}
void doCollisions(GameEntity e) {
map.doCollisions(e);
if (e.playerDamage>0 && e.intersects(player)) {
e.doDamage(player, e.playerDamage);
} else if (e.enemyDamage>0) {
ent_list.forEach((GameEntity enemy) {
if (enemy==e || enemy==player)
return;
e.doDamage(enemy, e.playerDamage);
});
}
}
//Move this inside of loadmap? Doesnt seem to need to be used anywhere else.
void reset() {
ent_list.clear();
map=null;
var c = new DisplayObjectContainer();
stage.addChild(c);
stage.swapChildren(c, container);
stage.removeChild(container);
container=c;
}
void loadMap(Map mapData) {
reset();
add(player);
Color c = new Color.css(mapData["backgroundcolor"]);
stage.backgroundColor = c;
stage.setBackgroundColor(c);
map= new GameMap(mapData["width"],mapData["height"],mapData["tilewidth"]);
List tileSets = mapData["tilesets"];
tileSets.forEach((Map ts) {
Map tp = ts["tileproperties"];
int offset = ts["firstgid"];
Map index = ts["tiles"];
index.forEach((String s,Map t) {
int i = int.parse(s)+offset;
if (map.tile_types.length<=i)
map.tile_types.length=i+1;
Tile tile = new Tile();
String img = t["image"];
img=img.substring(3);
tile.image = img;
if (tp!=null) {
Map props = tp[s];
if (props!=null) {
String flags = props["flags"];
if (flags!=null) {
flags.split(" ").forEach((String f) {
if (f=="noclip")
tile.solid=false;
});
}
String damage = props["damage"];
if (damage!=null) {
num dmg=num.parse(damage);
if (dmg!=null)
tile.damage=dmg;
}
tile.action = props["action"];
}
}
map.tile_types[i]=tile;
});
});
List layers = mapData["layers"];
layers.forEach((Map l) {
if (l["type"]=="tilelayer") {
map.data = new List.from(l["data"]);
map.refreshSprites();
} else if (l["type"]=="objectgroup") {
List objs = l["objects"];
objs.forEach((Map obj) {
String key = map.tile_types[obj["gid"]].image;
key=key.substring(8,key.length-4);
GameEntity e;
Map props = obj["properties"];
switch (key) {
case "util_player":
e=player;
break;
case "util_bat":
e=new EntBat(props["variant"]);
break;
case "util_g":
e=new EntBigG();
break;
case "util_sinner":
e=new EntSinner(props["extra"]);
break;
case "util_whipper":
e=new EntWhipper();
break;
case "util_hf":
e=new EntHotFoot();
break;
default:
throw "No such object load handler: "+key;
}
e.pos..x=obj["x"]..y=obj["y"];
if (props["float"]!=null)
e.gravityMultiplier=0;
if (key!="util_player")
add(e);
});
}
});
container.addChild(map.dObj);
}
}
| 21.044693
| 77
| 0.610433
|
c6f9195cd8e1c3540f96f82636772bdcc95fd490
| 1,244
|
py
|
Python
|
filtering/Turn_Off_Fitting.py
|
NANOGravDataManagement/bridge
|
a03cf262767b210d1fbb62bb934f87cf411f1885
|
[
"Apache-2.0"
] | null | null | null |
filtering/Turn_Off_Fitting.py
|
NANOGravDataManagement/bridge
|
a03cf262767b210d1fbb62bb934f87cf411f1885
|
[
"Apache-2.0"
] | null | null | null |
filtering/Turn_Off_Fitting.py
|
NANOGravDataManagement/bridge
|
a03cf262767b210d1fbb62bb934f87cf411f1885
|
[
"Apache-2.0"
] | null | null | null |
# Turn_Off_Fitting.py
# A script that takes in a .par file, and an output directory
# as a result, it creates a new .par file with fit option turned OFF
# sample input:
# python Turn_Off_Fitting.py /Users/fkeri/Desktop/B1855+09_NANOGrav_9yv0.par /Users/fkeri/Desktop/
# we can see that it takes in 2 line arguments: [INPUT FILE], [OUTPUT DIRECTORY]
# the output file will have the same name as the input file, with "NoFit_" as a prefix: "NoFit_B1855+09_NANOGrav_9yv0.par"
# it is possible to name the output file differently by putting the file name in [OUTPUT DIRECTORY]: /Users/fkeri/Desktop/filename.par
import sys
import os.path
inputFileName = sys.argv[1]
save_path = sys.argv[2]
if save_path[-4] != '.':
outputFileName = os.path.join( save_path, "NoFit_"+sys.argv[1].split("/")[-1] )
else:
outputFileName = save_path
with open(inputFileName,'r') as readFile:
with open(outputFileName,'w') as writeFile:
for line in readFile:
if("mode" in line.lower() or "nits" in line.lower()):
writeFile.write(line)
else:
temp = line.replace(" 1 "," 0 ")
temp = temp.replace(" 1\n"," 0\n")
writeFile.write(temp)
| 41.466667
| 135
| 0.653537
|
06c8e1cd81b2fa4a5469b3e9aed4b83bf9825968
| 34
|
py
|
Python
|
week_2/import_test.py
|
Precission/pynet
|
427fc2f0437c3e897caf397fa753797cdb17e44f
|
[
"Apache-2.0"
] | 1
|
2018-07-12T16:44:29.000Z
|
2018-07-12T16:44:29.000Z
|
cls2_ex1.py
|
qetennyson/PyNet_Ansible_KBCourse
|
57feaa98873ab824fa7c8c4069f3cd3c18d8dc53
|
[
"Apache-2.0"
] | null | null | null |
cls2_ex1.py
|
qetennyson/PyNet_Ansible_KBCourse
|
57feaa98873ab824fa7c8c4069f3cd3c18d8dc53
|
[
"Apache-2.0"
] | null | null | null |
import my_func
my_func.my_func()
| 8.5
| 17
| 0.794118
|
128cd80fd4d746f779842d5d9ec063927d3f2874
| 230
|
ps1
|
PowerShell
|
Active-Directory/AD-robocopy-example.ps1
|
badgumby/powershell-scripts
|
24cc5f15543c99e915fe61d03574db31e58aac35
|
[
"MIT"
] | null | null | null |
Active-Directory/AD-robocopy-example.ps1
|
badgumby/powershell-scripts
|
24cc5f15543c99e915fe61d03574db31e58aac35
|
[
"MIT"
] | null | null | null |
Active-Directory/AD-robocopy-example.ps1
|
badgumby/powershell-scripts
|
24cc5f15543c99e915fe61d03574db31e58aac35
|
[
"MIT"
] | null | null | null |
$source = "\\server\share"
$dest = "F:\new-share-path"
$date = (Get-Date -format "yyy-MM-dd-HH.mm")
#Do not use /MIR command if using Windows Server DeDupe
robocopy "$source" $dest /MIR /SEC /R:2 /W:2 /LOG:F:\Logs\$date.txt /np
| 32.857143
| 71
| 0.656522
|
b35c59192b369f27f56811705c7cf55171b138aa
| 10,807
|
py
|
Python
|
clients/python/pqstream_pb2.py
|
backwardn/pqstream
|
c9027a0afa15cb7c5412d82eabf12a1dc3f96bd2
|
[
"MIT"
] | 491
|
2017-09-04T05:19:47.000Z
|
2021-12-17T14:47:43.000Z
|
clients/python/pqstream_pb2.py
|
backwardn/pqstream
|
c9027a0afa15cb7c5412d82eabf12a1dc3f96bd2
|
[
"MIT"
] | 72
|
2017-09-04T05:19:52.000Z
|
2021-07-05T22:32:37.000Z
|
clients/python/pqstream_pb2.py
|
backwardn/pqstream
|
c9027a0afa15cb7c5412d82eabf12a1dc3f96bd2
|
[
"MIT"
] | 26
|
2017-09-04T10:50:18.000Z
|
2021-11-09T04:42:37.000Z
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: pqstream.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
from github.com.golang.protobuf.ptypes.struct import struct_pb2 as github_dot_com_dot_golang_dot_protobuf_dot_ptypes_dot_struct_dot_struct__pb2
DESCRIPTOR = _descriptor.FileDescriptor(
name='pqstream.proto',
package='pqs',
syntax='proto3',
serialized_pb=_b('\n\x0epqstream.proto\x12\x03pqs\x1a\x35github.com/golang/protobuf/ptypes/struct/struct.proto\"%\n\rListenRequest\x12\x14\n\x0ctable_regexp\x18\x01 \x01(\t\"\xa6\x01\n\x08RawEvent\x12\x0e\n\x06schema\x18\x01 \x01(\t\x12\r\n\x05table\x18\x02 \x01(\t\x12\x1a\n\x02op\x18\x03 \x01(\x0e\x32\x0e.pqs.Operation\x12\n\n\x02id\x18\x04 \x01(\t\x12(\n\x07payload\x18\x05 \x01(\x0b\x32\x17.google.protobuf.Struct\x12)\n\x08previous\x18\x06 \x01(\x0b\x32\x17.google.protobuf.Struct\"\xa2\x01\n\x05\x45vent\x12\x0e\n\x06schema\x18\x01 \x01(\t\x12\r\n\x05table\x18\x02 \x01(\t\x12\x1a\n\x02op\x18\x03 \x01(\x0e\x32\x0e.pqs.Operation\x12\n\n\x02id\x18\x04 \x01(\t\x12(\n\x07payload\x18\x05 \x01(\x0b\x32\x17.google.protobuf.Struct\x12(\n\x07\x63hanges\x18\x06 \x01(\x0b\x32\x17.google.protobuf.Struct*J\n\tOperation\x12\x0b\n\x07UNKNOWN\x10\x00\x12\n\n\x06INSERT\x10\x01\x12\n\n\x06UPDATE\x10\x02\x12\n\n\x06\x44\x45LETE\x10\x03\x12\x0c\n\x08TRUNCATE\x10\x04\x32\x38\n\x08PQStream\x12,\n\x06Listen\x12\x12.pqs.ListenRequest\x1a\n.pqs.Event\"\x00\x30\x01\x62\x06proto3')
,
dependencies=[github_dot_com_dot_golang_dot_protobuf_dot_ptypes_dot_struct_dot_struct__pb2.DESCRIPTOR,])
_OPERATION = _descriptor.EnumDescriptor(
name='Operation',
full_name='pqs.Operation',
filename=None,
file=DESCRIPTOR,
values=[
_descriptor.EnumValueDescriptor(
name='UNKNOWN', index=0, number=0,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='INSERT', index=1, number=1,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='UPDATE', index=2, number=2,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='DELETE', index=3, number=3,
options=None,
type=None),
_descriptor.EnumValueDescriptor(
name='TRUNCATE', index=4, number=4,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=451,
serialized_end=525,
)
_sym_db.RegisterEnumDescriptor(_OPERATION)
Operation = enum_type_wrapper.EnumTypeWrapper(_OPERATION)
UNKNOWN = 0
INSERT = 1
UPDATE = 2
DELETE = 3
TRUNCATE = 4
_LISTENREQUEST = _descriptor.Descriptor(
name='ListenRequest',
full_name='pqs.ListenRequest',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='table_regexp', full_name='pqs.ListenRequest.table_regexp', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=78,
serialized_end=115,
)
_RAWEVENT = _descriptor.Descriptor(
name='RawEvent',
full_name='pqs.RawEvent',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='schema', full_name='pqs.RawEvent.schema', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='table', full_name='pqs.RawEvent.table', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='op', full_name='pqs.RawEvent.op', index=2,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='id', full_name='pqs.RawEvent.id', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='payload', full_name='pqs.RawEvent.payload', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='previous', full_name='pqs.RawEvent.previous', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=118,
serialized_end=284,
)
_EVENT = _descriptor.Descriptor(
name='Event',
full_name='pqs.Event',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='schema', full_name='pqs.Event.schema', index=0,
number=1, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='table', full_name='pqs.Event.table', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='op', full_name='pqs.Event.op', index=2,
number=3, type=14, cpp_type=8, label=1,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='id', full_name='pqs.Event.id', index=3,
number=4, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=_b("").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='payload', full_name='pqs.Event.payload', index=4,
number=5, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
_descriptor.FieldDescriptor(
name='changes', full_name='pqs.Event.changes', index=5,
number=6, type=11, cpp_type=10, label=1,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None, file=DESCRIPTOR),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
syntax='proto3',
extension_ranges=[],
oneofs=[
],
serialized_start=287,
serialized_end=449,
)
_RAWEVENT.fields_by_name['op'].enum_type = _OPERATION
_RAWEVENT.fields_by_name['payload'].message_type = github_dot_com_dot_golang_dot_protobuf_dot_ptypes_dot_struct_dot_struct__pb2._STRUCT
_RAWEVENT.fields_by_name['previous'].message_type = github_dot_com_dot_golang_dot_protobuf_dot_ptypes_dot_struct_dot_struct__pb2._STRUCT
_EVENT.fields_by_name['op'].enum_type = _OPERATION
_EVENT.fields_by_name['payload'].message_type = github_dot_com_dot_golang_dot_protobuf_dot_ptypes_dot_struct_dot_struct__pb2._STRUCT
_EVENT.fields_by_name['changes'].message_type = github_dot_com_dot_golang_dot_protobuf_dot_ptypes_dot_struct_dot_struct__pb2._STRUCT
DESCRIPTOR.message_types_by_name['ListenRequest'] = _LISTENREQUEST
DESCRIPTOR.message_types_by_name['RawEvent'] = _RAWEVENT
DESCRIPTOR.message_types_by_name['Event'] = _EVENT
DESCRIPTOR.enum_types_by_name['Operation'] = _OPERATION
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
ListenRequest = _reflection.GeneratedProtocolMessageType('ListenRequest', (_message.Message,), dict(
DESCRIPTOR = _LISTENREQUEST,
__module__ = 'pqstream_pb2'
# @@protoc_insertion_point(class_scope:pqs.ListenRequest)
))
_sym_db.RegisterMessage(ListenRequest)
RawEvent = _reflection.GeneratedProtocolMessageType('RawEvent', (_message.Message,), dict(
DESCRIPTOR = _RAWEVENT,
__module__ = 'pqstream_pb2'
# @@protoc_insertion_point(class_scope:pqs.RawEvent)
))
_sym_db.RegisterMessage(RawEvent)
Event = _reflection.GeneratedProtocolMessageType('Event', (_message.Message,), dict(
DESCRIPTOR = _EVENT,
__module__ = 'pqstream_pb2'
# @@protoc_insertion_point(class_scope:pqs.Event)
))
_sym_db.RegisterMessage(Event)
_PQSTREAM = _descriptor.ServiceDescriptor(
name='PQStream',
full_name='pqs.PQStream',
file=DESCRIPTOR,
index=0,
options=None,
serialized_start=527,
serialized_end=583,
methods=[
_descriptor.MethodDescriptor(
name='Listen',
full_name='pqs.PQStream.Listen',
index=0,
containing_service=None,
input_type=_LISTENREQUEST,
output_type=_EVENT,
options=None,
),
])
_sym_db.RegisterServiceDescriptor(_PQSTREAM)
DESCRIPTOR.services_by_name['PQStream'] = _PQSTREAM
# @@protoc_insertion_point(module_scope)
| 37.010274
| 1,073
| 0.737207
|
c97b079ed3292d6fc44baccd47f542f6e9512f9f
| 3,864
|
rs
|
Rust
|
u2fhid-protocol/src/lib.rs
|
chris-ricketts/rust-u2f
|
8641e0ffb94f67a016af18ab36bcaf40230b2c91
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
u2fhid-protocol/src/lib.rs
|
chris-ricketts/rust-u2f
|
8641e0ffb94f67a016af18ab36bcaf40230b2c91
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
u2fhid-protocol/src/lib.rs
|
chris-ricketts/rust-u2f
|
8641e0ffb94f67a016af18ab36bcaf40230b2c91
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate futures;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate slog;
#[macro_use]
extern crate quick_error;
extern crate byteorder;
extern crate itertools;
extern crate slog_stdlog;
extern crate tokio_core;
extern crate u2f_core;
mod definitions;
mod protocol_state_machine;
mod segmenting_sink;
pub use definitions::Packet;
use std::io;
use std::collections::vec_deque::VecDeque;
use futures::{Async, AsyncSink, Future, Poll, Sink, Stream};
use slog::Drain;
use tokio_core::reactor::Handle;
use definitions::*;
use protocol_state_machine::StateMachine;
use segmenting_sink::{Segmenter, SegmentingSink};
use u2f_core::{Service, U2F};
struct PacketSegmenter;
impl Segmenter for PacketSegmenter {
type Item = Response;
type SegmentedItem = Packet;
fn segment(&self, item: Self::Item) -> VecDeque<Self::SegmentedItem> {
item.to_packets()
}
}
pub struct U2FHID<T: Sink + Stream, S> {
logger: slog::Logger,
state_machine: StateMachine<S>,
transport: SegmentingSink<T, PacketSegmenter>,
}
impl<T> U2FHID<T, U2F>
where
T: Sink<SinkItem = Packet, SinkError = io::Error> + Stream<Item = Packet, Error = io::Error>,
{
pub fn bind_service<L: Into<Option<slog::Logger>>>(
handle: &Handle,
transport: T,
service: U2F,
logger: L,
) -> U2FHID<T, U2F> {
let logger = logger
.into()
.unwrap_or(slog::Logger::root(slog_stdlog::StdLog.fuse(), o!()));
let state_machine_logger = logger.new(o!());
U2FHID {
logger: logger,
state_machine: StateMachine::new(service, handle.clone(), state_machine_logger),
transport: SegmentingSink::new(transport, PacketSegmenter),
}
}
}
impl<T, S> Future for U2FHID<T, S>
where
T: Sink<SinkItem = Packet, SinkError = io::Error> + Stream<Item = Packet, Error = io::Error>,
S: Service<
Request = u2f_core::Request,
Response = u2f_core::Response,
Error = io::Error,
Future = Box<Future<Item = u2f_core::Response, Error = io::Error>>,
>,
{
type Item = ();
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
loop {
trace!(self.logger, "Poll U2FHID");
// Always tick the transport first
// TODO self.transport.tick();
try_ready!(self.transport.poll_complete());
if let Some(response) = self.state_machine.step()? {
debug!(self.logger, "Send response"; "channel_id" => &response.channel_id, "message" => &response.message);
assert_send(&mut self.transport, response)?;
continue;
}
match try_ready!(self.transport.poll()) {
Some(packet) => {
trace!(self.logger, "Got packet from transport"; "packet" => &packet);
match self.state_machine.accept_packet(packet)? {
Some(response) => {
debug!(self.logger, "Send response"; "channel_id" => &response.channel_id, "message" => &response.message);
assert_send(&mut self.transport, response)?;
}
None => {}
}
}
None => {
// TODO close
return Ok(Async::Ready(()));
}
};
}
}
}
fn assert_send<S: Sink>(s: &mut S, item: S::SinkItem) -> Result<(), S::SinkError> {
match try!(s.start_send(item)) {
AsyncSink::Ready => Ok(()),
AsyncSink::NotReady(_) => panic!(
"sink reported itself as ready after `poll_ready` but was \
then unable to accept a message"
),
}
}
| 29.272727
| 135
| 0.577899
|
2cb6c94b694687676e30311e354d1d830ba7d363
| 421
|
hpp
|
C++
|
src/pattern-aggregator.hpp
|
Rutvik28/dfc
|
86ce00057c358f91d38826d3c36c95ad0d7b4b74
|
[
"MIT"
] | null | null | null |
src/pattern-aggregator.hpp
|
Rutvik28/dfc
|
86ce00057c358f91d38826d3c36c95ad0d7b4b74
|
[
"MIT"
] | 1
|
2019-09-19T21:31:36.000Z
|
2019-09-23T04:43:25.000Z
|
src/pattern-aggregator.hpp
|
skindstrom/dfc
|
4d7b9c29bc791c0a18a325478eafbeb459b48758
|
[
"MIT"
] | null | null | null |
#ifndef DFC_PATTERN_AGGREGATOR_HPP
#define DFC_PATTERN_AGGREGATOR_HPP
#include <vector>
#include "immutable-pattern.hpp"
namespace dfc {
class PatternAggregator {
private:
std::vector<RawPattern> patterns_;
public:
void add(RawPattern pat);
std::vector<ImmutablePattern> aggregate();
private:
void removeDuplicates();
std::vector<ImmutablePattern> createPatterns() const;
};
} // namespace dfc
#endif
| 17.541667
| 55
| 0.760095
|
2fcb83df8246039030c933b8283469419c30c995
| 1,451
|
py
|
Python
|
models/survey.py
|
SaijaUusi/pts_feedback
|
e3f0d798397fde7e0b60787cd9df8577e84d2b62
|
[
"MIT"
] | null | null | null |
models/survey.py
|
SaijaUusi/pts_feedback
|
e3f0d798397fde7e0b60787cd9df8577e84d2b62
|
[
"MIT"
] | null | null | null |
models/survey.py
|
SaijaUusi/pts_feedback
|
e3f0d798397fde7e0b60787cd9df8577e84d2b62
|
[
"MIT"
] | null | null | null |
import datetime
from app import app, db
from flask import flash, render_template, request, redirect
from wtforms import Form, IntegerField, StringField
class Survey:
__tablename__ = "surveys"
id = int()
description = str()
start_date = datetime.date
end_date = datetime.date
def __init__(self, id_, description_):
self.id = id_
self.description = description_
def __repr__(self):
return "<Question: {}>".format(self.name)
class surveyForm(Form):
id = IntegerField("ID")
description = StringField("Description")
@app.route('/addNewSurvey', methods=['GET', 'POST'])
def addNewSurvey():
form = surveyForm(request.form)
if request.method == 'POST' and form.validate():
new_survey = db.prepare("INSERT INTO survey VALUES ($1, $2)")
with db.xact():
new_survey(form.id.data, form.description.data)
flash("Survey " + str(form.id.data) + " " + \
form.description.data + " saved successfully!")
return redirect('/')
return render_template('new_survey.html', form=form)
@app.route('/printSurveys', methods=['GET', 'POST'])
def printSurveys():
surveys = []
form = surveyForm(request.form)
all_the_surveys = db.prepare("SELECT * FROM survey")
with db.xact():
for survey in all_the_surveys():
surveys.append(survey[1])
return render_template('surveys.html', surveys=surveys)
| 27.903846
| 69
| 0.644383
|
a3654d6f333ab538918bd218efd2d80014e61052
| 318
|
tsx
|
TypeScript
|
App/Components/Organisms/Appbar/styles.tsx
|
Abdulhaseeb026/stripe-terminal-demo-WisePos-E
|
fea8c05ec5a4d9ef32b775b19af0b8211c0a74af
|
[
"MIT"
] | null | null | null |
App/Components/Organisms/Appbar/styles.tsx
|
Abdulhaseeb026/stripe-terminal-demo-WisePos-E
|
fea8c05ec5a4d9ef32b775b19af0b8211c0a74af
|
[
"MIT"
] | null | null | null |
App/Components/Organisms/Appbar/styles.tsx
|
Abdulhaseeb026/stripe-terminal-demo-WisePos-E
|
fea8c05ec5a4d9ef32b775b19af0b8211c0a74af
|
[
"MIT"
] | null | null | null |
import { Dimensions, StyleSheet } from 'react-native'
const { width, height } = Dimensions.get('window')
const useStyles = () =>
StyleSheet.create({
titleStyle: {
position: 'absolute',
left: width * 0.25,
right: width * 0.25,
alignItems: 'center',
},
})
export default useStyles
| 19.875
| 53
| 0.613208
|
6dd65d4e9038d0dac99302c6933bfddaf20f28c5
| 324
|
dart
|
Dart
|
lib/zooper_flutter_logging.dart
|
zooper-lib/zooper_flutter_logging
|
189c7e8635b120cf812818bac9c13f1fd5f6ec17
|
[
"MIT"
] | null | null | null |
lib/zooper_flutter_logging.dart
|
zooper-lib/zooper_flutter_logging
|
189c7e8635b120cf812818bac9c13f1fd5f6ec17
|
[
"MIT"
] | null | null | null |
lib/zooper_flutter_logging.dart
|
zooper-lib/zooper_flutter_logging
|
189c7e8635b120cf812818bac9c13f1fd5f6ec17
|
[
"MIT"
] | null | null | null |
library zooper_flutter_logging;
// Logger
export 'logger/logger.dart';
export 'logger/log_level.dart';
// Writer
export 'writer/console_log_writer.dart';
export 'writer/log_writer.dart';
export 'writer/sentry_log_writer.dart';
// Formatter
export 'formatter/log_formatter.dart';
export 'formatter/pretty_formatter.dart';
| 21.6
| 41
| 0.79321
|
c1fb814f42e075284835149bc05afd7a1b4ba5f5
| 7,242
|
rs
|
Rust
|
testing/jormungandr-integration-tests/src/non_functional/network/big.rs
|
2nd-Layer/jormungandr
|
c20b42757f8621fec341bb3bc9036ca20ab0a3b4
|
[
"Apache-2.0",
"MIT"
] | null | null | null |
testing/jormungandr-integration-tests/src/non_functional/network/big.rs
|
2nd-Layer/jormungandr
|
c20b42757f8621fec341bb3bc9036ca20ab0a3b4
|
[
"Apache-2.0",
"MIT"
] | 24
|
2022-01-04T13:30:47.000Z
|
2022-03-30T13:35:01.000Z
|
testing/jormungandr-integration-tests/src/non_functional/network/big.rs
|
2nd-Layer/jormungandr
|
c20b42757f8621fec341bb3bc9036ca20ab0a3b4
|
[
"Apache-2.0",
"MIT"
] | 1
|
2019-11-21T11:08:05.000Z
|
2019-11-21T11:08:05.000Z
|
use crate::networking::utils;
use chain_impl_mockchain::chaintypes::ConsensusVersion;
use chain_impl_mockchain::milli::Milli;
use chain_impl_mockchain::value::Value;
use function_name::named;
use hersir::builder::NetworkBuilder;
use hersir::builder::Node;
use hersir::builder::SpawnParams;
use hersir::builder::{Blockchain, Topology, WalletTemplate};
use hersir::controller::Controller;
use jormungandr_lib::interfaces::ActiveSlotCoefficient;
use jormungandr_lib::interfaces::SlotDuration;
use jormungandr_testing_utils::testing::jormungandr::{JormungandrProcess, PersistenceMode};
use jormungandr_testing_utils::testing::node::{download_last_n_releases, get_jormungandr_bin};
use jormungandr_testing_utils::testing::sync::MeasurementReportInterval;
use jormungandr_testing_utils::testing::SyncNode;
use jormungandr_testing_utils::testing::SyncWaitParams;
const CORE_NODE: &str = "Core";
const RELAY_NODE: &str = "Relay";
const LEADER_NODE: &str = "Leader";
const LEGACY_NODE: &str = "Legacy";
fn relay_name(i: u32) -> String {
format!("{}_{}", RELAY_NODE, i)
}
fn leader_name(i: u32) -> String {
format!("{}_{}", LEADER_NODE, i)
}
fn legacy_name(i: u32) -> String {
format!("{}_{}", LEGACY_NODE, i)
}
fn wallet_name(i: u32) -> String {
format!("leader_wallet_{}", i)
}
fn prepare_real_scenario(
relay_nodes_count: u32,
nodes_count_per_relay: u32,
legacy_nodes_count_per_relay: u32,
consensus: ConsensusVersion,
) -> Controller {
let mut builder = NetworkBuilder::default();
let mut topology = Topology::default().with_node(Node::new(CORE_NODE));
let mut blockchain = Blockchain::default();
blockchain.set_consensus(consensus);
blockchain.set_slot_duration(SlotDuration::new(1).unwrap());
blockchain.set_consensus_genesis_praos_active_slot_coeff(
ActiveSlotCoefficient::new(Milli::from_millis(700)).unwrap(),
);
for i in 0..relay_nodes_count {
let relay_name = relay_name(i + 1);
topology = topology.with_node(Node::new(&relay_name).with_trusted_peer(CORE_NODE));
blockchain.add_leader(relay_name);
}
let mut leader_counter = 1;
let mut legacy_nodes_counter = 1;
for i in 0..relay_nodes_count {
let relay_name = relay_name(i + 1);
for _ in 0..nodes_count_per_relay {
let leader_name = leader_name(leader_counter);
topology = topology.with_node(Node::new(&leader_name).with_trusted_peer(&relay_name));
blockchain.add_leader(leader_name);
leader_counter += 1;
}
for _ in 0..legacy_nodes_count_per_relay {
let legacy_name = legacy_name(legacy_nodes_counter);
topology = topology.with_node(Node::new(&legacy_name).with_trusted_peer(&relay_name));
blockchain.add_leader(legacy_name);
legacy_nodes_counter += 1;
}
}
builder = builder.topology(topology);
// adds all nodes as leaders
blockchain.add_leader(CORE_NODE);
for i in 1..leader_counter {
let initial_wallet_name = wallet_name(i);
let mut wallet = WalletTemplate::new_account(
initial_wallet_name.to_owned(),
Value(100_000),
blockchain.discrimination(),
);
*wallet.delegate_mut() = Some(leader_name(i).to_owned());
blockchain.add_wallet(wallet);
}
for i in 1..legacy_nodes_counter {
let initial_wallet_name = wallet_name(i);
let mut wallet = WalletTemplate::new_account(
initial_wallet_name.to_owned(),
Value(100_000),
blockchain.discrimination(),
);
*wallet.delegate_mut() = Some(legacy_name(i).to_owned());
blockchain.add_wallet(wallet);
}
builder.blockchain_config(blockchain).build().unwrap()
}
#[test]
#[named]
pub fn real_praos_network() {
let relay_nodes_count = 3;
let leaders_per_relay = 11;
let legacies_per_relay = 0;
real_network(
relay_nodes_count,
leaders_per_relay,
legacies_per_relay,
ConsensusVersion::GenesisPraos,
PersistenceMode::Persistent,
function_name!(),
)
}
#[test]
#[named]
pub fn real_bft_network() {
let relay_nodes_count = 3;
let leaders_per_relay = 11;
let legacies_per_relay = 0;
real_network(
relay_nodes_count,
leaders_per_relay,
legacies_per_relay,
ConsensusVersion::Bft,
PersistenceMode::Persistent,
function_name!(),
)
}
pub fn real_network(
relay_nodes_count: u32,
leaders_per_relay: u32,
legacies_per_relay: u32,
consensus: ConsensusVersion,
persistence_mode: PersistenceMode,
name: &str,
) {
let mut controller = prepare_real_scenario(
relay_nodes_count,
leaders_per_relay,
legacies_per_relay,
consensus,
);
let _core = controller.spawn(SpawnParams::new(CORE_NODE)).unwrap();
let mut relays = vec![];
for i in 0..relay_nodes_count {
relays.push(
controller
.spawn(SpawnParams::new(&relay_name(i + 1)).persistence_mode(persistence_mode))
.unwrap(),
);
}
let mut leaders = vec![];
for i in 0..(relay_nodes_count * leaders_per_relay) {
leaders.push(
controller
.spawn(SpawnParams::new(&leader_name(i + 1)).persistence_mode(persistence_mode))
.unwrap(),
);
}
let releases = download_last_n_releases(1);
let last_release = releases.last().unwrap();
let legacy_app = get_jormungandr_bin(last_release, controller.working_directory());
let version = last_release.version();
let mut legacy_leaders = vec![];
for i in 0..(relay_nodes_count * legacies_per_relay) {
legacy_leaders.push(
controller
.spawn_legacy(
SpawnParams::new(&legacy_name(i + 1))
.persistence_mode(persistence_mode)
.jormungandr(legacy_app.clone()),
&version,
)
.unwrap()
.0,
);
}
let mut sync_nodes: Vec<&dyn SyncNode> =
leaders.iter().map(|node| node as &dyn SyncNode).collect();
sync_nodes.extend(legacy_leaders.iter().map(|node| node as &dyn SyncNode));
utils::measure_how_many_nodes_are_running(&sync_nodes, &format!("{}_bootstrap_score", name));
let leaders_count = leaders.len() as u64;
utils::measure_and_log_sync_time(
&sync_nodes,
SyncWaitParams::large_network(leaders_count).into(),
&format!("{}_sync", name),
MeasurementReportInterval::Long,
)
.unwrap();
let mut wallet = controller.wallet(&wallet_name(1)).unwrap();
let wallet2 = controller.wallet(&wallet_name(2)).unwrap();
let fragment_nodes: Vec<&JormungandrProcess> = leaders.iter().collect();
utils::measure_single_transaction_propagation_speed(
&mut controller,
&mut wallet,
&wallet2,
&fragment_nodes,
SyncWaitParams::large_network(leaders_count).into(),
&format!("{}_single_transaction_propagation", name),
MeasurementReportInterval::Standard,
)
}
| 30.556962
| 98
| 0.653825
|
b1f92b6649399e00a018787f818ec353479a1e05
| 326
|
lua
|
Lua
|
scripts/simulation/elements/Disaster/Plague.lua
|
sjml/dungen
|
f47caf12f3c1db37f5934ff4f556f309dbe4eb91
|
[
"BSD-3-Clause"
] | 4
|
2020-08-04T12:15:49.000Z
|
2021-07-29T01:41:00.000Z
|
scripts/simulation/elements/Disaster/Plague.lua
|
sjml/dungen2
|
f47caf12f3c1db37f5934ff4f556f309dbe4eb91
|
[
"BSD-3-Clause"
] | null | null | null |
scripts/simulation/elements/Disaster/Plague.lua
|
sjml/dungen2
|
f47caf12f3c1db37f5934ff4f556f309dbe4eb91
|
[
"BSD-3-Clause"
] | null | null | null |
caverns = GetRegionsTagged("natural, chamber")
candidates = {}
for _, c in pairs(caverns) do
if c:HasTags("FATE") ~= true and c:HasTags("Plague") ~= true then
table.insert(candidates, c)
end
end
for _, c in pairs(candidates) do
c:AddTag("plague")
c:SetAttributeInt("plague", c:GetAttributeInt("plague") + 1)
end
| 23.285714
| 67
| 0.687117
|
e734b65a79c2a569bc7ffb19760462c9a05abb9b
| 1,809
|
php
|
PHP
|
app/command/Cron.php
|
yangfancn/google_click
|
b339848ca8d800b06d760d38c19737361abfefb5
|
[
"Apache-2.0"
] | 1
|
2020-12-15T08:18:50.000Z
|
2020-12-15T08:18:50.000Z
|
app/command/Cron.php
|
yangfancn/google_click
|
b339848ca8d800b06d760d38c19737361abfefb5
|
[
"Apache-2.0"
] | null | null | null |
app/command/Cron.php
|
yangfancn/google_click
|
b339848ca8d800b06d760d38c19737361abfefb5
|
[
"Apache-2.0"
] | null | null | null |
<?php
declare (strict_types = 1);
namespace app\command;
use app\model\Mask;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Queue;
class Cron extends Command
{
protected function configure()
{
// 指令配置
$this->setName('app\command\cron')
->setDescription('the app\command\cron command');
}
protected function execute(Input $input, Output $output)
{
$start_time = time();
$end_time = strtotime(date('Y-m-d', strtotime('+1 days')));
$min_step = 300; //每个任务最小间隔
//发布每天的队列任务
$masks = Mask::where([['end_time', '>', $start_time]])->select();
foreach ($masks as $mask) {
//[$id, $word, $match, $domain, $inner_page_num, $screenshot] = $data;
$mask->day_has_click = 0;
$mask->save();
$data = [$mask->id, $mask->word, match_host($mask->domain), $mask->domain, $mask->inner_page_num, $mask->screenshot];
$delay_times = [];
for ($i = 0; $i < $mask->day_click_times - $mask->day_has_click; $i++) {
$delay_times[$i] = rand($start_time, $end_time);
}
sort($delay_times);
foreach ($delay_times as $k => &$delay_time) {
if ( $k !== 0 && $delay_time - $delay_times[$k - 1] < $min_step) {
$delay_time += $min_step;
}
//发布任务
Queue::later($delay_time - $start_time, 'Click@click', $data, 'clickQueue');
// Queue::push('Click@click', $data, 'clickQueue');
}
}
// 指令输出
$output->writeln('任务发布完成');
}
}
| 31.189655
| 130
| 0.521282
|
e3ca599c97340e94b7c0a8a801c2fb044495b374
| 921
|
rb
|
Ruby
|
lib/remotipart/middleware.rb
|
whitslar/remotipart
|
6b6b5b1e19da7bd33f1373c4bae050fb47411064
|
[
"MIT"
] | 2
|
2019-02-19T04:14:21.000Z
|
2021-06-12T14:42:14.000Z
|
lib/remotipart/middleware.rb
|
whitslar/remotipart
|
6b6b5b1e19da7bd33f1373c4bae050fb47411064
|
[
"MIT"
] | 2
|
2019-09-10T18:58:32.000Z
|
2020-02-15T20:27:53.000Z
|
lib/remotipart/middleware.rb
|
whitslar/remotipart
|
6b6b5b1e19da7bd33f1373c4bae050fb47411064
|
[
"MIT"
] | 2
|
2021-07-08T17:41:56.000Z
|
2022-03-24T21:20:26.000Z
|
# frozen_string_literal: true
# A middleware to look for our form parameters and
# encourage Rails to respond with the requested format
module Remotipart
class Middleware
def initialize(app)
@app = app
end
def call(env)
# Get request params
begin
params = Rack::Request.new(env).params
rescue TypeError => e
::Rails.logger.warn e.message
::Rails.logger.warn e.backtrace.join("\n")
end
if params
# This was using an iframe transport, and is therefore an XHR
# This is required if we're going to override the http_accept
env['HTTP_X_REQUESTED_WITH'] = 'xmlhttprequest' if params['X-Requested-With'] == 'IFrame'
# Override the accepted format, because it isn't what we really want
env['HTTP_ACCEPT'] = params['X-HTTP-Accept'] if params['X-HTTP-Accept']
end
@app.call(env)
end
end
end
| 25.583333
| 97
| 0.646037
|
05bab7dd8aa43033cc6cb6c7b65c45bd99b34507
| 474
|
py
|
Python
|
chapter01/1.4.4_train.py
|
Myeonghan-Jeong/Deep-learning-from-scratch2
|
9a6df82b4e0eef89926e59a175b7b8f83754ba2f
|
[
"MIT"
] | null | null | null |
chapter01/1.4.4_train.py
|
Myeonghan-Jeong/Deep-learning-from-scratch2
|
9a6df82b4e0eef89926e59a175b7b8f83754ba2f
|
[
"MIT"
] | 1
|
2021-08-23T20:42:43.000Z
|
2021-08-23T20:42:43.000Z
|
chapter01/1.4.4_train.py
|
Myeonghan-Jeong/Deep-learning-from-scratch2
|
9a6df82b4e0eef89926e59a175b7b8f83754ba2f
|
[
"MIT"
] | 2
|
2019-12-29T08:47:08.000Z
|
2020-07-18T15:24:09.000Z
|
from commons.optimizer import SGD
from commons.trainer import Trainer
from datasets import spiral
from two_layer_net import TwoLayerNet
# set hyperparameters
max_epoch = 300
batch_size = 30
hidden_size = 10
learning_rate = 1.0
x, t = spiral.load_data()
model = TwoLayerNet(input_size=2, hidden_size=hidden_size, output_size=3)
optimizer = SGD(lr=learning_rate)
trainer = Trainer(model, optimizer)
trainer.fit(x, t, max_epoch, batch_size, eval_interval=10)
trainer.plot()
| 24.947368
| 73
| 0.797468
|
8508dd319d2b94754dc0837f69eea1c155941ace
| 5,652
|
cs
|
C#
|
base/Windows/csic/base/Debug.cs
|
sphinxlogic/Singularity-RDK-2.0
|
2968c3b920a5383f7360e3e489aa772f964a7c42
|
[
"MIT"
] | null | null | null |
base/Windows/csic/base/Debug.cs
|
sphinxlogic/Singularity-RDK-2.0
|
2968c3b920a5383f7360e3e489aa772f964a7c42
|
[
"MIT"
] | null | null | null |
base/Windows/csic/base/Debug.cs
|
sphinxlogic/Singularity-RDK-2.0
|
2968c3b920a5383f7360e3e489aa772f964a7c42
|
[
"MIT"
] | null | null | null |
using System;
using System.IO;
using System.Text;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices;
using SHDocVw;
public interface IImage {
string Image();
}
public class Debug {
Debug() {}
static public void Assert(bool cond) {
System.Diagnostics.Debug.Assert(cond);
}
static public long Clock {
get { return DateTime.Now.Ticks; }
}
static public void Report(string name, long time) {
if (name.Length > 0)
name += ": ";
Console.Error.WriteLine("[{0}{1:f4}s]", name, time*100.0E-9);
}
static public void Fail(string msg) {
System.Diagnostics.Debug.Fail(msg);
}
static public bool IsSystemObject(object o) {
return o is Symbol && ((Symbol)o).FullName.StartsWith("System")
|| o is SymbolTable && IsSystemObject(((SymbolTable)o).Owner);
}
static public bool IsLeafType(object o) {
if (o == null)
return true;
System.Type t = o.GetType();
return o is string || o is IImage || t.IsValueType || t.IsPrimitive
|| o is ICollection && ((ICollection)o).Count == 0
|| IsSystemObject(o);
}
static string Identity(object o, bool html) {
if (o == null)
return "null";
if (o is IImage)
return ((IImage)o).Image();
else if (o is ICollection && ((ICollection)o).Count == 0)
return String.Format("{0}#{1} (empty)", o.GetType().Name, o.GetHashCode());
else if (IsLeafType(o))
return o.ToString();
else if (html)
return String.Format("<a href=\"#{0}\">{1}</a>", o.GetHashCode(), Identity(o, false));
else
return String.Format("{0}#{1}", o.GetType().Name, o.GetHashCode());
}
static public string Identity(object o) {
return Identity(o, false);
}
const BindingFlags bindingFlags = BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic;
static public string Image(object o) {
System.Type t = o.GetType();
StringBuilder sb = new StringBuilder();
sb.Append(t.Name);
sb.Append('{');
int i = 0;
foreach (FieldInfo f in t.GetFields(bindingFlags)) {
if (i++ > 0)
sb.Append(',');
sb.AppendFormat("{0}={1}", f.Name, Identity(f.GetValue(o)));
}
if (o is IDictionary)
foreach (DictionaryEntry e in (IDictionary)o) {
if (i++ > 0)
sb.Append(',');
sb.AppendFormat("[{0}]={1}", e.Key, e.Value);
}
else if (o is IEnumerable)
foreach (object x in (IEnumerable)o) {
if (i++ > 0)
sb.Append(',');
sb.AppendFormat("{0}", x);
}
sb.Append('}');
return sb.ToString();
}
static void Dump(object o, TextWriter w, Queue q, Hashtable marked, bool html) {
if (IsLeafType(o)) {
w.WriteLine("{0}", Identity(o));
return;
}
if (marked != null) {
if (marked.Contains(o))
return;
marked.Add(o, null);
}
if (html)
w.WriteLine("<dt><a name=\"{1}\">{0}</a>:<dd>", Identity(o), o.GetHashCode());
else
w.WriteLine("{0}:", Identity(o));
System.Type t = o.GetType();
if (t.IsClass)
foreach (FieldInfo f in t.GetFields(bindingFlags)) {
object value = f.GetValue(o);
w.WriteLine(html ? "{0}={1}<br>" : "\t{0}={1}", f.Name, Identity(value, html));
if (q != null && !IsLeafType(value))
q.Enqueue(value);
}
if (o is IDictionary)
foreach (DictionaryEntry e in (IDictionary)o) {
object value = e.Value;
w.WriteLine(html ? "[{0}]={1}<br>" : "\t[{0}]={1}", Identity(e.Key), Identity(value, html));
if (q != null && !IsLeafType(value))
q.Enqueue(value);
}
else if (o is IEnumerable)
foreach (object x in (IEnumerable)o) {
w.WriteLine(html ? "{0}<br>" : "\t{0}", Identity(x, html));
if (q != null && !IsLeafType(x))
q.Enqueue(x);
}
}
static public void Dump(object o, TextWriter w) { Dump(o, w, null, null, false); }
static public void Dump(object o) { Dump(o, Console.Error, null, null, false); }
static public void DumpAll(object o) { DumpAll(o, Console.Error, false); }
class cmp: IComparer {
public int Compare(object x, object y) {
return Object.Equals(x,y) ? 0 : 1;
}
}
static void DumpAll(object o, TextWriter w, bool html) {
Hashtable marked = new Hashtable(null, new cmp());
Queue worklist = new Queue();
worklist.Enqueue(o);
while (worklist.Count > 0)
Dump(worklist.Dequeue(), w, worklist, marked, html);
}
static public void DumpAll(object o, TextWriter w) {
DumpAll(o, w, false);
}
static public void DumpAllHTML(object o, TextWriter w) {
w.WriteLine("<html><body><p><small>{0}</small></p><dl>", DateTime.Now.ToString());
DumpAll(o, w, true);
w.WriteLine("</dl><body><html>");
}
}
public class display {
public static object visit(object ast, TextWriter w, string[] args, MessageWriter msg) {
int nf = 0;
string oname = null;
foreach (string s in args)
if (s.StartsWith("-file=")) {
oname = s.Substring(6);
nf++;
}
if (oname == null) {
oname = Path.GetTempFileName();
File.Delete(oname);
oname = Path.ChangeExtension(oname, ".htm");
}
try {
TextWriter wr = new StreamWriter(oname);
if (oname.EndsWith(".htm") || oname.EndsWith(".html"))
Debug.DumpAllHTML(ast, wr);
else
Debug.DumpAll(ast, wr);
wr.Close();
} catch (Exception e) {
msg.Error("can't write \"{0}\" ({1})", oname, e.ToString());
return ast;
}
if (nf == 0) {
try {
object o = null;
IWebBrowserApp ie = new SHDocVw.InternetExplorer();
ie.Visible = true;
ie.Navigate(oname, ref o, ref o, ref o, ref o);
} catch (Exception e) {
msg.Error("can't launch Internet Explorer ({0})", e.ToString());
}
}
return ast;
}
}
| 30.717391
| 101
| 0.604919
|
15c23a6c9a26e562f47d6073302d0eb7b8986f4b
| 5,853
|
swift
|
Swift
|
PPGetAddressBookSwift/PPGetAddressBookSwift/PPGetAddressBook.swift
|
jkpang/PPGetAddressBookSwift
|
eaa8de8cbdccc0a33216d3bb16c6eebd8bcbc048
|
[
"MIT"
] | 101
|
2016-09-18T03:44:00.000Z
|
2021-12-07T08:17:59.000Z
|
PPGetAddressBookSwift/PPGetAddressBookSwift/PPGetAddressBook.swift
|
jkpang/PPGetAddressBookSwift
|
eaa8de8cbdccc0a33216d3bb16c6eebd8bcbc048
|
[
"MIT"
] | 5
|
2016-10-11T03:19:21.000Z
|
2020-05-25T00:36:39.000Z
|
PPGetAddressBookSwift/PPGetAddressBookSwift/PPGetAddressBook.swift
|
jkpang/PPGetAddressBookSwift
|
eaa8de8cbdccc0a33216d3bb16c6eebd8bcbc048
|
[
"MIT"
] | 18
|
2016-09-18T10:56:35.000Z
|
2020-09-04T11:06:59.000Z
|
//
// PPGetAddressBookSwift.swift
// PPGetAddressBookSwift
//
// Created by AndyPang on 16/9/16.
// Copyright © 2016年 AndyPang. All rights reserved.
//
/*
*********************************************************************************
*
*⭐️⭐️⭐️ 新建 PP-iOS学习交流群: 323408051 欢迎加入!!! ⭐️⭐️⭐️
*
* 如果您在使用 PPGetAddressBookSwift 的过程中出现bug或有更好的建议,还请及时以下列方式联系我,我会及
* 时修复bug,解决问题.
*
* Weibo : jkpang-庞
* Email : jkpang@outlook.com
* QQ 群 : 323408051
* GitHub: https://github.com/jkpang
*
* PS:PPGetAddressBookSwift的Objective-C版本:
* https://github.com/jkpang/PPGetAddressBook
*
* 如果 PPGetAddressBookSwift 好用,希望您能Star支持,你的 ⭐️ 是我持续更新的动力!
*********************************************************************************
*/
import Foundation
import AddressBook
import Contacts
/// 获取原始顺序的所有联系人的闭包
public typealias AddressBookArrayClosure = (_ addressBookArray: [PPPersonModel])->()
/// 获取按A~Z顺序排列的所有联系人的闭包
public typealias AddressBookDictClosure = (_ addressBookDict: [String:[PPPersonModel]], _ nameKeys: [String])->()
public class PPGetAddressBook : NSObject {
/**
请求用户是否授权APP访问通讯录的权限,建议在APPDeletegate.m中的didFinishLaunchingWithOptions方法中调用
*/
public class func requestAddressBookAuthorization() {
PPAddressBookHandle().requestAuthorizationWithSuccessClosure {
PPGetAddressBook.getOrderAddressBook(addressBookInfo: { (addressBookDict, nameKeys) in
}, authorizationFailure: {
})
}
}
override public class func initialize () {
PPGetAddressBook.getOrderAddressBook(addressBookInfo: { (addressBookDict, nameKeys) in
}, authorizationFailure: {
})
}
// MARK: - 获取原始顺序所有联系人
public class func getOriginalAddressBook(addressBookArray success: @escaping AddressBookArrayClosure, authorizationFailure failure: @escaping AuthorizationFailure) {
//开启一个子线程,将耗时操作放到异步串行队列
let queue = DispatchQueue(label: "addressBook.array")
queue.async {
var modelArray = [PPPersonModel]()
PPAddressBookHandle().getAddressBookDataSource(personModel: { (model) in
//将单个联系人模型装进数组
modelArray.append(model)
}, authorizationFailure: {
//将授权失败的信息回调到主线程
DispatchQueue.main.async {
failure()
}
})
// 将联系人数组回调到主线程
DispatchQueue.main.async {
success(modelArray)
}
}
}
// MARK: - 获取按A~Z顺序排列的所有联系人
public class func getOrderAddressBook(addressBookInfo success: @escaping AddressBookDictClosure, authorizationFailure failure: @escaping AuthorizationFailure) {
let queue = DispatchQueue(label:"addressBook.infoDict")
queue.async {
var addressBookDict = [String:[PPPersonModel]]()
PPAddressBookHandle().getAddressBookDataSource(personModel: { (model) in
// 获取到姓名的大写首字母
let firstLetterString = getFirstLetterFromString(aString: model.name)
if addressBookDict[firstLetterString] != nil {
// swift的字典,如果对应的key在字典中没有,则会新增
addressBookDict[firstLetterString]?.append(model)
} else {
var arrGroupNames = [model]
arrGroupNames.append(model)
addressBookDict[firstLetterString] = arrGroupNames
}
}, authorizationFailure: {
//将授权失败的信息回调到主线程
DispatchQueue.main.async {
failure()
}
})
// 将addressBookDict字典中的所有Key值进行排序: A~Z
var nameKeys = Array(addressBookDict.keys).sorted()
// 将 "#" 排列在 A~Z 的后面
if nameKeys.first == "#" {
nameKeys.insert(nameKeys.first!, at: nameKeys.count)
nameKeys.remove(at: 0);
}
// 将排序好的通讯录数据回调到主线程
DispatchQueue.main.async {
success(addressBookDict, nameKeys)
}
}
}
// MARK: - 获取联系人姓名首字母(传入汉字字符串, 返回大写拼音首字母)
private class func getFirstLetterFromString(aString: String) -> (String) {
// 注意,这里一定要转换成可变字符串
let mutableString = NSMutableString.init(string: aString)
// 将中文转换成带声调的拼音
CFStringTransform(mutableString as CFMutableString, nil, kCFStringTransformToLatin, false)
// 去掉声调(用此方法大大提高遍历的速度)
let pinyinString = mutableString.folding(options: String.CompareOptions.diacriticInsensitive, locale: NSLocale.current)
// 将拼音首字母装换成大写
let strPinYin = polyphoneStringHandle(nameString: aString, pinyinString: pinyinString).uppercased()
// 截取大写首字母
let firstString = strPinYin.substring(to: strPinYin.index(strPinYin.startIndex, offsetBy:1))
// 判断姓名首位是否为大写字母
let regexA = "^[A-Z]$"
let predA = NSPredicate.init(format: "SELF MATCHES %@", regexA)
return predA.evaluate(with: firstString) ? firstString : "#"
}
/// 多音字处理
private class func polyphoneStringHandle(nameString:String, pinyinString:String) -> String {
if nameString.hasPrefix("长") {return "chang"}
if nameString.hasPrefix("沈") {return "shen"}
if nameString.hasPrefix("厦") {return "xia"}
if nameString.hasPrefix("地") {return "di"}
if nameString.hasPrefix("重") {return "chong"}
return pinyinString;
}
}
| 34.02907
| 169
| 0.566205
|
daaa199e114bda46373e36e0feae491a14a6ec64
| 1,530
|
php
|
PHP
|
app/Notifications/NewComment.php
|
jazzankan/ankdock-app
|
278665497897cfc1bdc2ad029a0a1b43fa238d87
|
[
"MIT"
] | null | null | null |
app/Notifications/NewComment.php
|
jazzankan/ankdock-app
|
278665497897cfc1bdc2ad029a0a1b43fa238d87
|
[
"MIT"
] | null | null | null |
app/Notifications/NewComment.php
|
jazzankan/ankdock-app
|
278665497897cfc1bdc2ad029a0a1b43fa238d87
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use App\Models\Comment;
class NewComment extends Notification
{
use Queueable;
public $comment;
/**
* Create a new notification instance.
*
* @return void
*/
public function __construct()
{
$this->comment = Comment::latest()->first();
}
/**
* Get the notification's delivery channels.
*
* @param mixed $notifiable
* @return array
*/
public function via($notifiable)
{
return ['mail'];
}
/**
* Get the mail representation of the notification.
*
* @param mixed $notifiable
* @return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$publ = ($this->comment->wishpublic)=='yes' ? "Ja" : "Nej";
return (new MailMessage)
->from('anders@webbsallad.se', 'Ankhemmet')
->subject('Ny kommentar Ankhemmets blogg!')
->line('Det har skapats en ny kommentar')
->line('Önskas publicerad: ' . $publ)
->action('Åtgärda', url('/comments'));
}
/**
* Get the array representation of the notification.
*
* @param mixed $notifiable
* @return array
*/
public function toArray($notifiable)
{
return [
//
];
}
}
| 22.5
| 67
| 0.58366
|
389acdeaee04c4870d3fcc45e2e05927513c82b6
| 2,035
|
php
|
PHP
|
app/Exports/CompaniesExport.php
|
rizkirmdn84/Server_2
|
2e2c6f37c8c16fb11c546576a9154c0ded32b99f
|
[
"MIT"
] | null | null | null |
app/Exports/CompaniesExport.php
|
rizkirmdn84/Server_2
|
2e2c6f37c8c16fb11c546576a9154c0ded32b99f
|
[
"MIT"
] | null | null | null |
app/Exports/CompaniesExport.php
|
rizkirmdn84/Server_2
|
2e2c6f37c8c16fb11c546576a9154c0ded32b99f
|
[
"MIT"
] | null | null | null |
<?php
namespace App\Exports;
use Illuminate\Support\Facades\Http;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\{
FromArray,
ShouldAutoSize,
WithHeadings,
WithStyles,
WithEvents,
WithMapping
};
class CompaniesExport implements ShouldAutoSize, WithHeadings, FromArray, WithStyles, WithEvents, WithMapping
{
private static $response;
public function __construct()
{
self::$response = Http::get('http://127.0.0.1:8000/api/all-company')->json();
date_default_timezone_set('Asia/Jakarta');
}
public function array(): array
{
return self::$response;
}
public function map($response): array
{
return [
$response['no'],
$response['id'],
$response['name'],
$response['email'],
$response['phone'],
$response['address'],
$response['created_at'],
$response['updated_at'],
];
}
public function headings(): array
{
return [
['Export Data User'],
['Jumlah User ', count(self::$response)],
['Di Export Pada ', date("Y-m-d h:i:s")],
[],
['No', 'Id', 'Nama', 'Email', 'Phone', 'Address', 'Created', 'Update'],
];
}
public function styles(Worksheet $sheet)
{
return [
5 => ['font' => ['bold' => true]],
];
}
public function registerEvents(): array
{
$dataCount = count(self::$response) + 5;
return [
AfterSheet::class => function (AfterSheet $event) use ($dataCount) {
$event->sheet
->getDelegate()
->getStyle('A1:H' . $dataCount)
->getAlignment()
->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
},
];
}
}
| 24.817073
| 109
| 0.540049
|
c85deed7666f3bf326598266babb7ed69889ee07
| 44
|
lua
|
Lua
|
lua/parse/char/ascii7/whitespace/vertical.lua
|
taxler/radish
|
2a6787d023efb40d9ba356d23c03e004779d83b8
|
[
"MIT"
] | 1
|
2020-02-02T12:52:02.000Z
|
2020-02-02T12:52:02.000Z
|
lua/parse/char/ascii7/whitespace/vertical.lua
|
taxler/radish
|
2a6787d023efb40d9ba356d23c03e004779d83b8
|
[
"MIT"
] | null | null | null |
lua/parse/char/ascii7/whitespace/vertical.lua
|
taxler/radish
|
2a6787d023efb40d9ba356d23c03e004779d83b8
|
[
"MIT"
] | null | null | null |
local m = require 'lpeg'
return m.S '\r\n'
| 11
| 24
| 0.613636
|
da4d4297e37de96ad6b7d67961cfb9767b98a8a5
| 3,216
|
php
|
PHP
|
Web-PageTemplate/wordpress157/header.php
|
ArmstrongYang/StudyShare
|
6dffcfba6811865589a8e11748ffc7e71a656f50
|
[
"Apache-2.0"
] | 2
|
2017-08-10T13:41:19.000Z
|
2017-11-30T09:00:33.000Z
|
Web-PageTemplate/wordpress157/header.php
|
ArmstrongYang/StudyShare
|
6dffcfba6811865589a8e11748ffc7e71a656f50
|
[
"Apache-2.0"
] | null | null | null |
Web-PageTemplate/wordpress157/header.php
|
ArmstrongYang/StudyShare
|
6dffcfba6811865589a8e11748ffc7e71a656f50
|
[
"Apache-2.0"
] | null | null | null |
<!DOCTYPE html>
<!--[if IE 6]>ie6
<html lang="en-us" class="ie6">
<![endif]--><!--[if IE 7]>
<html lang="en-us" class="ie7">
<![endif]--><!--[if IE 8]>
<html lang="en-us" class="ie8">
<![endif]-->
<head>
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="<?php bloginfo( 'template_url' ); ?>/images/favicon.ico" />
<!--KEY-->
<?php include_once 'inc/key.php'; ?>
<!--调用STYLE样式表-->
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/slimbox2.css" type="text/css" media="screen" />
<link rel="stylesheet" href="<?php bloginfo('template_url'); ?>/css/prettify.css" type="text/css" media="screen" />
<link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" />
</head>
<body><div id="page">
<!-- 顶部 -->
<div id="top">
<div class="wrap">
<!-- 顶部左导航 -->
<?php
$args = array(
"container_id" => "top_left_menu",
"theme_location" => "top_left",
);
wp_nav_menu($args);
?>
<!-- sns -->
<div class="sns">
<?php if(dopt('Rcloud_feed_c')){; ?><a target="_blank" rel="nofollow" class="sns_feed" href="<?php echo dopt('Rcloud_feed'); ?>" title="订阅我吧"></a><?php }; ?>
<?php if(dopt('Rcloud_weibo_c')){; ?><a target="_blank" rel="nofollow" class="sns_weibo" href="<?php echo dopt('Rcloud_weibo'); ?>" title="新浪微博"></a><?php }; ?>
<?php if(dopt('Rcloud_qweibo_c')){; ?><a target="_blank" rel="nofollow" class="sns_qweibo" href="<?php echo dopt('Rcloud_qweibo'); ?>" title="腾讯微博"></a><?php }; ?>
<?php if(dopt('Rcloud_douban_c')){; ?><a target="_blank" rel="nofollow" class="sns_douban" href="<?php echo dopt('Rcloud_douban'); ?>" title="我的豆瓣"></a><?php }; ?>
<?php if(dopt('Rcloud_qq_c')){; ?><a target="_blank" rel="nofollow" class="sns_qq" href="http://wpa.qq.com/msgrd?v=3&uin=<?php echo dopt('Rcloud_qq'); ?>&site=qq&menu=yes" title="联系QQ"></a><?php }; ?>
</div>
<div class="cc"></div>
</div>
</div>
<!-- 头部 -->
<div id="header"><div class="wrap">
<!-- logo -->
<div class="logo">
<a class="logolink" href="<?php bloginfo('url'); ?>" title="<?php bloginfo('name'); ?>"><img src="<?php bloginfo('template_url'); ?>/images/logo.png" alt="<?php bloginfo('name'); ?>" /></a>
<span class="notice"><?php echo dopt('Rcloud_notice'); ?></span>
</div>
<!-- 搜索 -->
<div class="fr">
<?php get_search_form(); ?>
</div>
<div class="cc"></div>
</div></div>
<div id="nav"><div class="wrap">
<!-- 导航左 -->
<?php
$args = array(
"container_id" => "nav_left_menu",
"theme_location" => "nav_left"
);
wp_nav_menu($args);
?>
<!-- 导航右 -->
<?php
$args = array(
"container_id" => "nav_right_menu",
"theme_location" => "nav_right"
);
wp_nav_menu($args);
?>
<div class="cc"></div>
</div></div>
<div id="modienav">
<?php if(is_single()): ?>
<?php the_title(); ?>
<?php ;else: ?>
<div id="modie-list" class="modie-list">首页</div>
<div id="toptobot"></div>
<div id="modie-menu"><ul>
</ul></div>
<?php endif; ?>
</div>
<?php
echo '<div class="wrap">';
the_breadcrumb();
echo '</div>';
?>
| 35.340659
| 203
| 0.584577
|
16953c7cad0a2c584280c30054fe35b1325abf99
| 3,775
|
sql
|
SQL
|
database/ddl/total_monthly_calendar_disbursement.view.sql
|
ONRR/cloud-repo
|
8a4621686030564a37f27d6b9ec74a0ee7ac5a8e
|
[
"CC0-1.0"
] | null | null | null |
database/ddl/total_monthly_calendar_disbursement.view.sql
|
ONRR/cloud-repo
|
8a4621686030564a37f27d6b9ec74a0ee7ac5a8e
|
[
"CC0-1.0"
] | 1
|
2019-11-07T18:10:12.000Z
|
2019-11-07T18:10:12.000Z
|
database/ddl/total_monthly_calendar_disbursement.view.sql
|
ONRR/cloud-repo
|
8a4621686030564a37f27d6b9ec74a0ee7ac5a8e
|
[
"CC0-1.0"
] | null | null | null |
--
-- PostgreSQL database dump
--
-- Dumped from database version 12.9 (Debian 12.9-1.pgdg110+1)
-- Dumped by pg_dump version 13.5 (Ubuntu 13.5-0ubuntu0.21.04.1)
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
--
-- Name: total_monthly_calendar_disbursement; Type: VIEW; Schema: public; Owner: postgres
--
CREATE VIEW public.total_monthly_calendar_disbursement AS
SELECT a.period,
a.year,
a.month,
a.month_long,
a.period_date,
a.land_type,
a.source,
a.sort_order,
a.fund_type,
a.recipient,
a.fund_class,
sum(a.sum) AS sum
FROM ( SELECT period.period,
period.calendar_year AS year,
period.month,
period.month_long,
period.period_date,
location.land_type,
fund.fund_type,
fund.recipient,
CASE
WHEN ((fund.fund_class)::text = ANY (ARRAY[('Native American tribes and individuals'::character varying)::text, ('Land and Water Conservation Fund'::character varying)::text, ('Reclamation Fund'::character varying)::text, ('State and local governments'::character varying)::text, ('U.S. Treasury'::character varying)::text, ('Historic Preservation Fund'::character varying)::text])) THEN fund.fund_class
ELSE 'Other funds'::character varying
END AS fund_class,
(location.land_type)::text AS source,
CASE
WHEN ((location.land_class)::text = 'Native American'::text) THEN 2
WHEN ((location.land_category)::text = 'Not Tied to a Lease'::text) THEN 0
WHEN (((location.land_class)::text = 'Federal'::text) AND ((location.land_category)::text = ''::text)) THEN 1
WHEN (((location.land_class)::text = 'Federal'::text) AND ((location.land_category)::text = 'Onshore'::text)) THEN 4
WHEN (((location.land_class)::text = 'Federal'::text) AND ((location.land_category)::text = 'Offshore'::text)) THEN 3
ELSE 0
END AS sort_order,
sum(disbursement.disbursement) AS sum
FROM ((((public.disbursement
JOIN public.period USING (period_id))
JOIN public.location USING (location_id))
JOIN public.commodity USING (commodity_id))
JOIN public.fund USING (fund_id))
WHERE (((period.period)::text = 'Monthly'::text) AND (period.calendar_year <= ( SELECT max(period_1.calendar_year) AS max
FROM (public.disbursement disbursement_1
JOIN public.period period_1 USING (period_id))
WHERE (period_1.month = 12))) AND (period.calendar_year >= ( SELECT max((period_1.calendar_year - 3)) AS max
FROM (public.disbursement disbursement_1
JOIN public.period period_1 USING (period_id))
WHERE (period_1.month = 12))))
GROUP BY period.period, period.calendar_year, period.month, period.month_long, period.period_date, location.land_category, location.land_class, location.land_type, fund.fund_type, fund.recipient, fund.fund_class) a
GROUP BY a.period, a.year, a.month, a.month_long, a.period_date, a.land_type, a.source, a.sort_order, a.fund_type, a.recipient, a.fund_class
ORDER BY a.period, a.year, a.month, a.sort_order;
ALTER TABLE public.total_monthly_calendar_disbursement OWNER TO postgres;
--
-- PostgreSQL database dump complete
--
| 46.604938
| 423
| 0.645298
|
1644ccaacdca56a6fcb155b7e283c5545aa499b5
| 16,426
|
swift
|
Swift
|
Sources/FileCheck/CheckString.swift
|
mattpolzin/FileCheck
|
d79ccabcf280a26013d92efe30878776472248f1
|
[
"MIT"
] | 1
|
2020-01-22T07:20:27.000Z
|
2020-01-22T07:20:27.000Z
|
Sources/FileCheck/CheckString.swift
|
mattpolzin/FileCheck
|
d79ccabcf280a26013d92efe30878776472248f1
|
[
"MIT"
] | null | null | null |
Sources/FileCheck/CheckString.swift
|
mattpolzin/FileCheck
|
d79ccabcf280a26013d92efe30878776472248f1
|
[
"MIT"
] | null | null | null |
import Foundation
enum CheckType {
case none
case plain
case next
case same
case not
case dag
case label
case badNot
/// MatchEOF - When set, this pattern only matches the end of file. This is
/// used for trailing CHECK-NOTs.
case endOfFile
// Get the count of utf8 bytes of the prefix extension.
var prefixSize : Int {
switch (self) {
case .none:
return 0
case .badNot:
return 0
case .plain:
return ":".utf8.count
case .next:
return "-NEXT:".utf8.count
case .same:
return "-SAME:".utf8.count
case .not:
return "-NOT:".utf8.count
case .dag:
return "-DAG:".utf8.count
case .label:
return "-LABEL:".utf8.count
case .endOfFile:
fatalError("Should not be using endOfFile prefix size")
}
}
}
/// CheckString - This is a check that we found in the input file.
struct CheckString {
/// The pattern to match.
let pattern : Pattern
/// Which prefix name this check matched.
let prefix : String
/// The location in the match file that the check string was specified.
let location : CheckLocation
/// These are all of the strings that are disallowed from occurring between
/// this match string and the previous one (or start of file).
let dagNotStrings : Array<Pattern>
/// Match check string and its "not strings" and/or "dag strings".
func check(_ buffer : String, _ isLabelScanMode : Bool, _ variableTable : [String:String], _ options : FileCheckOptions) -> (NSRange, [String:String])? {
// This condition is true when we are scanning forward to find CHECK-LABEL
// bounds we have not processed variable definitions within the bounded block
// yet so cannot handle any final CHECK-DAG yet this is handled when going
// over the block again (including the last CHECK-LABEL) in normal mode.
let lastPos : Int
let notStrings : [Pattern]
let initialTable : [String:String]
if !isLabelScanMode {
// Match "dag strings" (with mixed "not strings" if any).
guard let (lp, ns, vt) = self.checkDAG(buffer, variableTable, options) else {
return nil
}
lastPos = lp
notStrings = ns
initialTable = vt
} else {
lastPos = 0
notStrings = []
initialTable = variableTable
}
// Match itself from the last position after matching CHECK-DAG.
let matchBuffer = String(buffer[buffer.index(buffer.startIndex, offsetBy: lastPos)...])
guard let (range, mutVariableTable) = self.pattern.match(matchBuffer, initialTable) else {
diagnoseFailedCheck(self.pattern, self.location, self.prefix, variableTable, options, buffer)
return nil
}
let (matchPos, matchLen) = (range.location, range.length)
// Similar to the above, in "label-scan mode" we can't yet handle CHECK-NEXT
// or CHECK-NOT
let finalTable : [String:String]
if !isLabelScanMode {
let startIdx = buffer.index(buffer.startIndex, offsetBy: lastPos)
let skippedRegion = String(buffer[
Range<String.Index>(
uncheckedBounds: (
startIdx,
buffer.index(startIdx, offsetBy: matchPos)
)
)
])
let rest = String(buffer[buffer.index(buffer.startIndex, offsetBy: matchPos)...])
// If this check is a "CHECK-NEXT", verify that the previous match was on
// the previous line (i.e. that there is one newline between them).
if self.checkNext(skippedRegion, rest, options) {
return nil
}
// If this check is a "CHECK-SAME", verify that the previous match was on
// the same line (i.e. that there is no newline between them).
if self.checkSame(skippedRegion, rest, options) {
return nil
}
// If this match had "not strings", verify that they don't exist in the
// skipped region.
let (cond, variableTable) = self.checkNot(skippedRegion, notStrings, mutVariableTable, options)
finalTable = variableTable
if cond {
return nil
}
} else {
finalTable = mutVariableTable
}
return (NSRange(location: lastPos + matchPos, length: matchLen), finalTable)
}
/// Verify there is no newline in the given buffer.
private func checkSame(_ buffer : String, _ rest : String, _ options: FileCheckOptions) -> Bool {
if self.pattern.type != .same {
return false
}
// Count the number of newlines between the previous match and this one.
// assert(Buffer.data() !=
// SM.getMemoryBuffer(SM.FindBufferContainingLoc(
// SMLoc::getFromPointer(Buffer.data())))
// ->getBufferStart() &&
// "CHECK-SAME can't be the first check in a file")
if countNewlines(in: buffer).count != 0 {
diagnose(.error,
at: self.location,
with: self.prefix + "-SAME: is not on the same line as the previous match",
options: options
)
rest.cString(using: .utf8)?.withUnsafeBufferPointer { buf in
let loc = CheckLocation.inBuffer(buf.baseAddress!, buf)
diagnose(.note, at: loc, with: "'next' match was here", options: options)
}
buffer.cString(using: .utf8)?.withUnsafeBufferPointer { buf in
let loc = CheckLocation.inBuffer(buf.baseAddress!, buf)
diagnose(.note, at: loc, with: "previous match ended here", options: options)
}
return true
}
return false
}
/// Verify there is a single line in the given buffer.
private func checkNext(_ buffer : String, _ rest : String, _ options: FileCheckOptions) -> Bool {
if self.pattern.type != .next {
return false
}
// Count the number of newlines between the previous match and this one.
// assert(Buffer.data() !=
// SM.getMemoryBuffer(SM.FindBufferContainingLoc(
// SMLoc::getFromPointer(Buffer.data())))
// ->getBufferStart(), "CHECK-NEXT can't be the first check in a file")
let (numNewLines, firstNewLine) = countNewlines(in: buffer)
if numNewLines == 0 {
diagnose(.error, at: self.location, with: prefix + "-NEXT: is on the same line as previous match", options: options)
rest.cString(using: .utf8)?.withUnsafeBufferPointer { buf in
let loc = CheckLocation.inBuffer(buf.baseAddress!, buf)
diagnose(.note, at: loc, with: "'next' match was here", options: options)
}
buffer.cString(using: .utf8)?.withUnsafeBufferPointer { buf in
let loc = CheckLocation.inBuffer(buf.baseAddress!, buf)
diagnose(.note, at: loc, with: "previous match ended here", options: options)
}
return true
}
if numNewLines != 1 {
diagnose(.error, at: self.location, with: prefix + "-NEXT: is not on the line after the previous match", options: options)
rest.cString(using: .utf8)?.withUnsafeBufferPointer { buf in
let loc = CheckLocation.inBuffer(buf.baseAddress!, buf)
diagnose(.note, at: loc, with: "'next' match was here", options: options)
}
buffer.cString(using: .utf8)?.withUnsafeBufferPointer { buf in
let loc = CheckLocation.inBuffer(buf.baseAddress!, buf)
diagnose(.note, at: loc, with: "previous match ended here", options: options)
if let fnl = firstNewLine {
let noteLoc = CheckLocation.inBuffer(buf.baseAddress!.advanced(by: buffer.distance(from: buffer.startIndex, to: fnl)), buf)
diagnose(.note, at: noteLoc, with: "non-matching line after previous match is here", options: options)
}
}
return true
}
return false
}
/// Verify there's no "not strings" in the given buffer.
private func checkNot(_ buffer : String, _ notStrings : [Pattern], _ variableTable : [String:String], _ options: FileCheckOptions) -> (Bool, [String:String]) {
for pat in notStrings {
assert(pat.type == .not, "Expect CHECK-NOT!")
guard let (range, variableTable) = pat.match(buffer, variableTable) else {
continue
}
buffer.cString(using: .utf8)?.withUnsafeBufferPointer { buf in
let loc = CheckLocation.inBuffer(buf.baseAddress!.advanced(by: range.location), buf)
diagnose(.error, at: loc, with: self.prefix + "-NOT: string occurred!", options: options)
}
diagnose(.note, at: pat.patternLoc, with: self.prefix + "-NOT: pattern specified here", options: options)
return (true, variableTable)
}
return (false, variableTable)
}
/// Match "dag strings" and their mixed "not strings".
private func checkDAG(_ buffer : String, _ variableTable : [String:String], _ options: FileCheckOptions) -> (Int, [Pattern], [String:String])? {
var notStrings = [Pattern]()
if self.dagNotStrings.isEmpty {
return (0, notStrings, variableTable)
}
var lastPos = 0
var startPos = lastPos
var finalTable : [String:String] = variableTable
for pattern in self.dagNotStrings {
assert((pattern.type == .dag || pattern.type == .not), "Invalid CHECK-DAG or CHECK-NOT!")
if pattern.type == .not {
notStrings.append(pattern)
continue
}
assert((pattern.type == .dag), "Expect CHECK-DAG!")
// CHECK-DAG always matches from the start.
let matchBuffer = String(buffer[buffer.index(buffer.startIndex, offsetBy: startPos)...])
// With a group of CHECK-DAGs, a single mismatching means the match on
// that group of CHECK-DAGs fails immediately.
guard let (range, variableTable) = pattern.match(matchBuffer, finalTable) else {
diagnoseFailedCheck(pattern, pattern.patternLoc, self.prefix, finalTable, options, matchBuffer)
return nil
}
finalTable = variableTable
// Re-calc it as the offset relative to the start of the original string.
let matchPos = range.location + startPos
if !notStrings.isEmpty {
if matchPos < lastPos {
// Reordered?
buffer.cString(using: .utf8)?.withUnsafeBufferPointer { buf in
let loc1 = CheckLocation.inBuffer(buf.baseAddress!.advanced(by: matchPos), buf)
diagnose(.error, at: loc1, with: prefix + "-DAG: found a match of CHECK-DAG reordering across a CHECK-NOT", options: options)
let loc2 = CheckLocation.inBuffer(buf.baseAddress!.advanced(by: lastPos), buf)
diagnose(.note, at: loc2, with: prefix + "-DAG: the farthest match of CHECK-DAG is found here", options: options)
}
diagnose(.note, at: notStrings[0].patternLoc, with: prefix + "-NOT: the crossed pattern specified here", options: options)
diagnose(.note, at: pattern.patternLoc, with: prefix + "-DAG: the reordered pattern specified here", options: options)
return nil
}
// All subsequent CHECK-DAGs should be matched from the farthest
// position of all precedent CHECK-DAGs (including this one.)
startPos = lastPos
// If there's CHECK-NOTs between two CHECK-DAGs or from CHECK to
// CHECK-DAG, verify that there's no 'not' strings occurred in that
// region.
let skippedRegion = String(buffer[
Range<String.Index>(
uncheckedBounds: (
buffer.index(buffer.startIndex, offsetBy: lastPos),
buffer.index(buffer.startIndex, offsetBy: matchPos)
)
)
])
let (cond, mutVarTable) = self.checkNot(skippedRegion, notStrings, finalTable, options)
if cond {
return nil
}
finalTable = mutVarTable
// Clear "not strings".
notStrings.removeAll()
}
// Update the last position with CHECK-DAG matches.
lastPos = max(matchPos + range.length, lastPos)
}
return (lastPos, notStrings, finalTable)
}
}
private let whitespaceCharacterSet: Set<Character> = [" ", "\t", "\n", "\r"]
private func diagnoseFailedCheck(
_ pattern: Pattern, _ loc: CheckLocation, _ prefix: String,
_ variableTable: [String : String], _ options: FileCheckOptions,
_ buffer: String
) {
if let rtm = pattern.computeRegexToMatch(variableTable) {
if !pattern.fixedString.isEmpty && !rtm.isEmpty {
diagnose(.error,
at: loc,
with: prefix + ": could not find '\(pattern.fixedString)' (with regex '\(rtm)') in input",
options: options
)
} else if !pattern.fixedString.isEmpty {
diagnose(.error,
at: loc,
with: prefix + ": could not find '\(pattern.fixedString)' in input",
options: options
)
} else {
diagnose(.error,
at: loc,
with: prefix + ": could not find a match for regex '\(rtm)' in input",
options: options
)
}
} else {
diagnose(.error,
at: loc,
with: prefix + ": could not find match for CHECK line",
options: options
)
}
let bufferPrefix = buffer.firstIndex { !whitespaceCharacterSet.contains($0) } ?? buffer.startIndex
diagnose(.note,
at: .string(String(buffer[bufferPrefix...])),
with: "scanning from here",
options: options)
// Note any variables used by the pattern
for (varName, _) in pattern.variableUses {
if varName.first == "@" {
// If we failed with a builtin variable like @LINE, try to report
// what it is bound to.
if let value = pattern.evaluateExpression(varName) {
diagnose(.note,
at: loc,
with: "with expression '\(varName)' equal to '\(value)'",
options: options
)
} else {
// If evaluation fails, we must have an incorrect builtin variable.
diagnose(.note,
at: loc,
with: "uses incorrect expression '\(varName)'",
options: options
)
}
} else {
if let varDef = variableTable[varName] {
diagnose(.note,
at: loc,
with: "with variable '\(varName)' equal to '\(varDef)'",
options: options
)
} else {
diagnose(.note,
at: loc,
with: "uses undefined variable '\(varName)'",
options: options
)
}
}
}
var NumLinesForward = 0
var BestLine : Int? = nil
var BestQuality = 0.0
let exampleString : Substring
if pattern.fixedString.isEmpty {
exampleString = Substring(pattern.regExPattern)
} else {
exampleString = Substring(pattern.fixedString)
}
// Bail with an empty check string.
guard !exampleString.isEmpty else {
return
}
let exampleStringLen = exampleString.count
exampleString.withCString { (exampleBuf) -> Void in
for i in 0..<min(buffer.count, 4096) {
let strIndex = buffer.index(buffer.startIndex, offsetBy: i)
let char = buffer[strIndex]
if char == "\n" {
NumLinesForward += 1
}
// Patterns have leading whitespace stripped, so skip whitespace when
// looking for something which looks like a pattern.
if char == " " || char == "\t" {
continue;
}
let subEndIdx: String.Index
if buffer.count < exampleString.count + i {
subEndIdx = buffer.endIndex
} else {
subEndIdx = buffer.index(buffer.startIndex, offsetBy: exampleString.count + i)
}
let subBuffer = buffer[strIndex..<subEndIdx]
// Compute the "quality" of this match as an arbitrary combination of
// the match distance and the number of lines skipped to get to this
// match.
let bodyBufLen = subBuffer.count
let distance = subBuffer.withCString { (bodyBuf) -> Int in
return editDistance(from: bodyBuf, fromLength: bodyBufLen,
to: exampleBuf, toLength: exampleStringLen)
}
let quality = Double(distance) + (Double(NumLinesForward) / 100.0)
if quality < BestQuality || BestLine == nil {
BestLine = i
BestQuality = quality
}
}
if let Best = BestLine, BestQuality < 50 {
buffer.utf8CString.withUnsafeBufferPointer { buf in
let otherPatternLoc = CheckLocation.inBuffer(
buf.baseAddress!.advanced(by: Best),
UnsafeBufferPointer(start: buf.baseAddress?.advanced(by: Best), count: buf.count - Best)
)
diagnose(.note, at: otherPatternLoc, with: "possible intended match here", options: options)
}
}
}
}
| 36.747204
| 161
| 0.627603
|
9fb29c394a4cbbf9415ef72a5a9910a462602919
| 164
|
sql
|
SQL
|
TSQL_Queries/Statistics/CheckAutoStatsEnabled.sql
|
aadimanchanda/Azure_Synapse_Toolbox
|
50b8b5927cd0271cf648cc222746d6aacb14bde5
|
[
"MIT"
] | 68
|
2020-04-30T02:21:45.000Z
|
2022-03-25T22:02:40.000Z
|
TSQL_Queries/Statistics/CheckAutoStatsEnabled.sql
|
aadimanchanda/Azure_Synapse_Toolbox
|
50b8b5927cd0271cf648cc222746d6aacb14bde5
|
[
"MIT"
] | 2
|
2020-12-15T18:57:58.000Z
|
2021-11-29T22:05:34.000Z
|
TSQL_Queries/Statistics/CheckAutoStatsEnabled.sql
|
aadimanchanda/Azure_Synapse_Toolbox
|
50b8b5927cd0271cf648cc222746d6aacb14bde5
|
[
"MIT"
] | 45
|
2020-04-15T06:18:45.000Z
|
2022-03-22T13:44:11.000Z
|
SELECT name, is_auto_create_stats_on
FROM sys.databases
--To turn on auto create stats:
--ALTER DATABASE <yourdatawarehousename>
--SET AUTO_CREATE_STATISTICS ON
| 27.333333
| 41
| 0.810976
|
e285e17c05cd672f693f8ae835cf2ff6b235196f
| 675
|
js
|
JavaScript
|
lib/util.js
|
rksm/node-watch-interface
|
51aef2061ebf888ef2b8958dd4c653cc5fa9b017
|
[
"MIT"
] | null | null | null |
lib/util.js
|
rksm/node-watch-interface
|
51aef2061ebf888ef2b8958dd4c653cc5fa9b017
|
[
"MIT"
] | null | null | null |
lib/util.js
|
rksm/node-watch-interface
|
51aef2061ebf888ef2b8958dd4c653cc5fa9b017
|
[
"MIT"
] | null | null | null |
var path = require("path");
function log(/*args*/) {
if (log.debug) console.log.apply(console, arguments);
}
log.debug = false;
function uniq(arr) {
return arr.reduce(function(all, ea) {
if (all.indexOf(ea) === -1) all.push(ea);
return all;
}, []);
}
function noLastSlash(name) {
var last = name[name.length-1];
return (last === '/' || last === '\\') ?
name.slice(0,-1) : name;
}
function relativePath(dir, fullPath) {
var rel = path.relative(dir, fullPath);
if (rel === '') rel = '.';
return rel;
}
module.exports.log = log;
module.exports.uniq = uniq;
module.exports.noLastSlash = noLastSlash;
module.exports.relativePath = relativePath;
| 21.09375
| 55
| 0.631111
|
0e851275bcce10cca8f9ac1438fa55985bb9d3df
| 296
|
ps1
|
PowerShell
|
Private/Get-RedfishServiceRoot.ps1
|
rchaganti/RedfishPowerShellTools
|
408019c4e800c59d6ab2538c7c3f68ee71c730f2
|
[
"MIT"
] | null | null | null |
Private/Get-RedfishServiceRoot.ps1
|
rchaganti/RedfishPowerShellTools
|
408019c4e800c59d6ab2538c7c3f68ee71c730f2
|
[
"MIT"
] | null | null | null |
Private/Get-RedfishServiceRoot.ps1
|
rchaganti/RedfishPowerShellTools
|
408019c4e800c59d6ab2538c7c3f68ee71c730f2
|
[
"MIT"
] | null | null | null |
function Get-RedfishServiceRoot
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[String]
$IPAddress
)
$baseURI = "https://${IPAddress}/redfish/v1"
$response = Invoke-RestMethod -UseBasicParsing -Uri $baseURI
return $response
}
| 19.733333
| 64
| 0.597973
|
5aba4603ea79d63cdfdedbda8ab518d386dcc3c0
| 1,664
|
ps1
|
PowerShell
|
tests/Set-DbaExtendedProperty.Tests.ps1
|
petervandivier/dbatools
|
fb6a12d6e1ace31d32c6dd1cae08a5e905c3725f
|
[
"MIT"
] | 1,704
|
2016-09-15T04:39:22.000Z
|
2022-01-12T20:24:14.000Z
|
tests/Set-DbaExtendedProperty.Tests.ps1
|
petervandivier/dbatools
|
fb6a12d6e1ace31d32c6dd1cae08a5e905c3725f
|
[
"MIT"
] | 5,882
|
2016-09-16T03:35:36.000Z
|
2022-01-13T12:12:48.000Z
|
tests/Set-DbaExtendedProperty.Tests.ps1
|
petervandivier/dbatools
|
fb6a12d6e1ace31d32c6dd1cae08a5e905c3725f
|
[
"MIT"
] | 874
|
2016-09-15T12:38:39.000Z
|
2022-01-12T20:46:56.000Z
|
$CommandName = $MyInvocation.MyCommand.Name.Replace(".Tests.ps1", "")
Write-Host -Object "Running $PSCommandPath" -ForegroundColor Cyan
. "$PSScriptRoot\constants.ps1"
Describe "$CommandName Unit Tests" -Tag 'UnitTests' {
Context "Validate parameters" {
[array]$params = ([Management.Automation.CommandMetaData]$ExecutionContext.SessionState.InvokeCommand.GetCommand($CommandName, 'Function')).Parameters.Keys
[object[]]$knownParameters = 'InputObject', 'Value', 'EnableException'
It "Should only contain our specific parameters" {
Compare-Object -ReferenceObject $knownParameters -DifferenceObject $params | Should -BeNullOrEmpty
}
}
}
Describe "$CommandName Integration Tests" -Tag "IntegrationTests" {
BeforeAll {
$random = Get-Random
$instance2 = Connect-DbaInstance -SqlInstance $script:instance2
$null = Get-DbaProcess -SqlInstance $instance2 | Where-Object Program -match dbatools | Stop-DbaProcess -Confirm:$false
$newDbName = "dbatoolsci_newdb_$random"
$db = New-DbaDatabase -SqlInstance $instance2 -Name $newDbName
$db | Add-DbaExtendedProperty -Name "Test_Database_Name" -Value $newDbName
}
AfterAll {
$null = $db | Remove-DbaDatabase -Confirm:$false
}
Context "commands work as expected" {
It "works" {
$ep = Get-DbaExtendedProperty -SqlInstance $instance2 -Name "Test_Database_Name"
$newep = $ep | Set-DbaExtendedProperty -Value "Test_Database_Value"
$newep.Name | Should -Be "Test_Database_Name"
$newep.Value | Should -Be "Test_Database_Value"
}
}
}
| 43.789474
| 163
| 0.682692
|