file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
hard_spheres.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*
import numpy as np
from vpython import sphere, vector, color, rate
from box_utils import build_box, check_wall_hit
def create_balls(N: int=1, r: float=.2) -> list[sphere]:
balls = []
for i in range(N):
ball = sphere(color=color.green, radius=r, make_trail=False, pos=vector.random()*2)
ball.mass = 1.
ball.v = vector.random() * .1
balls.append(ball)
return balls
def main():
side = 4.0
thk = 0.3
s2 = 2 * side - thk
s3 = 2 * side + thk
N = 50
r = 0.2
build_box(side, thk, s2, s3)
balls = create_balls(N)
# Change side according to the thickness of the box and radius of the ball | side = side - thk * 0.5 - r
# Animation loops
dt = 0.05
while True:
rate(200) # Halt computation for 1/200s (it's the frequency of the animation)
for i, ball in enumerate(balls):
ball.pos = ball.pos + ball.v * dt
ball.v = ball.v
check_wall_hit(ball, side)
# Check ball hitting
for ball2 in balls:
if not (ball is ball2):
dpos = ball.pos - ball2.pos
dpos_mag = dpos.mag
if dpos_mag <= r:
# source: https://introcs.cs.princeton.edu/java/assignments/collisions.html
dv = ball.v - ball2.v
J = 2 * dv.dot(dpos)
Jv = J * dpos / (dpos_mag * 2)
ball.v = ball.v + Jv
else:
pass
if __name__ == '__main__':
main() | |
application_gateway_url_path_map.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .sub_resource import SubResource
class ApplicationGatewayUrlPathMap(SubResource):
"""UrlPathMaps give a url path to the backend mapping information for
PathBasedRouting.
:param id: Resource ID.
:type id: str
:param default_backend_address_pool: Default backend address pool resource
of URL path map.
:type default_backend_address_pool:
~azure.mgmt.network.v2017_09_01.models.SubResource
:param default_backend_http_settings: Default backend http settings
resource of URL path map.
:type default_backend_http_settings:
~azure.mgmt.network.v2017_09_01.models.SubResource
:param default_redirect_configuration: Default redirect configuration
resource of URL path map.
:type default_redirect_configuration:
~azure.mgmt.network.v2017_09_01.models.SubResource
:param path_rules: Path rule of URL path map resource.
:type path_rules:
list[~azure.mgmt.network.v2017_09_01.models.ApplicationGatewayPathRule]
:param provisioning_state: Provisioning state of the backend http settings
resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:type provisioning_state: str
:param name: Name of the resource that is unique within a resource group.
This name can be used to access the resource.
:type name: str
:param etag: A unique read-only string that changes whenever the resource
is updated.
:type etag: str
:param type: Type of the resource.
:type type: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'default_backend_address_pool': {'key': 'properties.defaultBackendAddressPool', 'type': 'SubResource'},
'default_backend_http_settings': {'key': 'properties.defaultBackendHttpSettings', 'type': 'SubResource'},
'default_redirect_configuration': {'key': 'properties.defaultRedirectConfiguration', 'type': 'SubResource'},
'path_rules': {'key': 'properties.pathRules', 'type': '[ApplicationGatewayPathRule]'},
'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'etag': {'key': 'etag', 'type': 'str'},
'type': {'key': 'type', 'type': 'str'},
}
def __init__(self, id=None, default_backend_address_pool=None, default_backend_http_settings=None, default_redirect_configuration=None, path_rules=None, provisioning_state=None, name=None, etag=None, type=None):
super(ApplicationGatewayUrlPathMap, self).__init__(id=id)
self.default_backend_address_pool = default_backend_address_pool
self.default_backend_http_settings = default_backend_http_settings
| self.default_redirect_configuration = default_redirect_configuration
self.path_rules = path_rules
self.provisioning_state = provisioning_state
self.name = name
self.etag = etag
self.type = type | |
server_lib_test.py | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# 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.
# ==============================================================================
"""Tests for tf.data service server lib."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.data.experimental.service import server_lib
from tensorflow.python.platform import test
class ServerLibTest(test.TestCase):
def testStartDispatcher(self):
dispatcher = server_lib.DispatchServer(0, start=False)
dispatcher.start()
def testMultipleStartDispatcher(self):
dispatcher = server_lib.DispatchServer(0, start=True)
dispatcher.start()
def testStartWorker(self):
dispatcher = server_lib.DispatchServer(0)
worker = server_lib.WorkerServer(0, dispatcher._address, start=False)
worker.start()
def testMultipleStartWorker(self):
dispatcher = server_lib.DispatchServer(0)
worker = server_lib.WorkerServer(0, dispatcher._address, start=True)
worker.start()
def testStopDispatcher(self):
dispatcher = server_lib.DispatchServer(0)
dispatcher._stop()
dispatcher._stop()
def testStopWorker(self):
dispatcher = server_lib.DispatchServer(0)
worker = server_lib.WorkerServer(0, dispatcher._address)
worker._stop()
worker._stop()
def testStopStartDispatcher(self):
dispatcher = server_lib.DispatchServer(0)
dispatcher._stop()
with self.assertRaisesRegex(
RuntimeError, "Server cannot be started after it has been stopped"):
dispatcher.start()
def testStopStartWorker(self):
|
def testJoinDispatcher(self):
dispatcher = server_lib.DispatchServer(0)
dispatcher._stop()
dispatcher.join()
def testJoinWorker(self):
dispatcher = server_lib.DispatchServer(0)
worker = server_lib.WorkerServer(0, dispatcher._address)
worker._stop()
worker.join()
def testDispatcherNumWorkers(self):
dispatcher = server_lib.DispatchServer(0)
self.assertEqual(0, dispatcher._num_workers())
worker1 = server_lib.WorkerServer(0, dispatcher._address) # pylint: disable=unused-variable
self.assertEqual(1, dispatcher._num_workers())
worker2 = server_lib.WorkerServer(0, dispatcher._address) # pylint: disable=unused-variable
self.assertEqual(2, dispatcher._num_workers())
if __name__ == "__main__":
test.main()
| dispatcher = server_lib.DispatchServer(0)
worker = server_lib.WorkerServer(0, dispatcher._address)
worker._stop()
with self.assertRaisesRegex(
RuntimeError, "Server cannot be started after it has been stopped"):
worker.start() |
aiohttp.py | import sys
import weakref
from sentry_sdk._compat import reraise
from sentry_sdk.hub import Hub
from sentry_sdk.integrations import Integration, DidNotEnable
from sentry_sdk.integrations.logging import ignore_logger
from sentry_sdk.integrations._wsgi_common import (
_filter_headers,
request_body_within_bounds,
)
from sentry_sdk.tracing import Transaction
from sentry_sdk.utils import (
capture_internal_exceptions,
event_from_exception,
transaction_from_function,
HAS_REAL_CONTEXTVARS,
CONTEXTVARS_ERROR_MESSAGE,
AnnotatedValue,
)
try:
import asyncio
from aiohttp import __version__ as AIOHTTP_VERSION
from aiohttp.web import Application, HTTPException, UrlDispatcher
except ImportError:
raise DidNotEnable("AIOHTTP not installed")
from sentry_sdk._types import MYPY
if MYPY:
from aiohttp.web_request import Request
from aiohttp.abc import AbstractMatchInfo
from typing import Any
from typing import Dict
from typing import Optional
from typing import Tuple
from typing import Callable
from typing import Union
from sentry_sdk.utils import ExcInfo
from sentry_sdk._types import EventProcessor
TRANSACTION_STYLE_VALUES = ("handler_name", "method_and_path_pattern")
class AioHttpIntegration(Integration):
identifier = "aiohttp"
def __init__(self, transaction_style="handler_name"):
# type: (str) -> None
if transaction_style not in TRANSACTION_STYLE_VALUES:
raise ValueError(
"Invalid value for transaction_style: %s (must be in %s)"
% (transaction_style, TRANSACTION_STYLE_VALUES)
)
self.transaction_style = transaction_style
@staticmethod
def setup_once():
# type: () -> None
try:
version = tuple(map(int, AIOHTTP_VERSION.split(".")[:2]))
except (TypeError, ValueError):
raise DidNotEnable(
"AIOHTTP version unparseable: {}".format(AIOHTTP_VERSION)
)
if version < (3, 4):
raise DidNotEnable("AIOHTTP 3.4 or newer required.")
if not HAS_REAL_CONTEXTVARS:
# We better have contextvars or we're going to leak state between
# requests.
raise DidNotEnable(
"The aiohttp integration for Sentry requires Python 3.7+ "
" or aiocontextvars package." + CONTEXTVARS_ERROR_MESSAGE
)
ignore_logger("aiohttp.server")
old_handle = Application._handle
async def sentry_app_handle(self, request, *args, **kwargs):
# type: (Any, Request, *Any, **Any) -> Any
hub = Hub.current
if hub.get_integration(AioHttpIntegration) is None:
return await old_handle(self, request, *args, **kwargs)
weak_request = weakref.ref(request)
with Hub(hub) as hub:
# Scope data will not leak between requests because aiohttp
# create a task to wrap each request.
with hub.configure_scope() as scope:
scope.clear_breadcrumbs()
scope.add_event_processor(_make_request_processor(weak_request))
transaction = Transaction.continue_from_headers(
request.headers,
op="http.server",
# If this transaction name makes it to the UI, AIOHTTP's
# URL resolver did not find a route or died trying.
name="generic AIOHTTP request",
)
with hub.start_transaction(
transaction, custom_sampling_context={"aiohttp_request": request}
):
try:
response = await old_handle(self, request)
except HTTPException as e:
transaction.set_http_status(e.status_code)
raise
except asyncio.CancelledError:
transaction.set_status("cancelled")
raise
except Exception:
# This will probably map to a 500 but seems like we
# have no way to tell. Do not set span status.
reraise(*_capture_exception(hub))
transaction.set_http_status(response.status)
return response
Application._handle = sentry_app_handle
old_urldispatcher_resolve = UrlDispatcher.resolve
async def sentry_urldispatcher_resolve(self, request):
# type: (UrlDispatcher, Request) -> AbstractMatchInfo
rv = await old_urldispatcher_resolve(self, request)
hub = Hub.current
integration = hub.get_integration(AioHttpIntegration)
name = None
try:
if integration.transaction_style == "handler_name":
name = transaction_from_function(rv.handler)
elif integration.transaction_style == "method_and_path_pattern":
route_info = rv.get_info()
pattern = route_info.get("path") or route_info.get("formatter")
name = "{} {}".format(request.method, pattern)
except Exception:
pass
if name is not None:
with Hub.current.configure_scope() as scope:
scope.transaction = name
return rv
UrlDispatcher.resolve = sentry_urldispatcher_resolve
def _make_request_processor(weak_request):
# type: (Callable[[], Request]) -> EventProcessor
def aiohttp_processor(
event, # type: Dict[str, Any]
hint, # type: Dict[str, Tuple[type, BaseException, Any]]
):
# type: (...) -> Dict[str, Any]
request = weak_request()
if request is None:
return event
with capture_internal_exceptions():
request_info = event.setdefault("request", {})
request_info["url"] = "%s://%s%s" % (
request.scheme,
request.host,
request.path,
)
request_info["query_string"] = request.query_string
request_info["method"] = request.method
request_info["env"] = {"REMOTE_ADDR": request.remote}
hub = Hub.current
request_info["headers"] = _filter_headers(dict(request.headers))
# Just attach raw data here if it is within bounds, if available.
# Unfortunately there's no way to get structured data from aiohttp
# without awaiting on some coroutine.
request_info["data"] = get_aiohttp_request_data(hub, request)
return event
return aiohttp_processor
def _capture_exception(hub):
# type: (Hub) -> ExcInfo
exc_info = sys.exc_info()
event, hint = event_from_exception(
exc_info,
client_options=hub.client.options, # type: ignore
mechanism={"type": "aiohttp", "handled": False},
)
hub.capture_event(event, hint=hint)
return exc_info
BODY_NOT_READ_MESSAGE = "[Can't show request body due to implementation details.]"
def get_aiohttp_request_data(hub, request):
# type: (Hub, Request) -> Union[Optional[str], AnnotatedValue]
bytes_body = request._read_bytes
if bytes_body is not None:
# we have body to show
if not request_body_within_bounds(hub.client, len(bytes_body)):
return AnnotatedValue(
"",
{"rem": [["!config", "x", 0, len(bytes_body)]], "len": len(bytes_body)},
)
encoding = request.charset or "utf-8"
return bytes_body.decode(encoding, "replace")
| # request has no body
return None | if request.can_read_body:
# body exists but we can't show it
return BODY_NOT_READ_MESSAGE
|
galaxy_to_parquet.py | import json
import os
import sys
from datetime import datetime
import numpy as np
import pandas as pd
from objects.task import Task
from objects.workflow import Workflow
from objects.workload import Workload
pd.set_option('display.max_columns', None)
USAGE = 'Usage: python(3) ./galaxy_to_parquet.py galaxy_folder'
NAME = 'Galaxy'
TARGET_DIR = os.path.join(os.path.dirname(os.getcwd()), 'output_parquet', NAME)
DATETIME_FORMAT = '%Y-%m-%d %H:%M:%S.%f'
EPOCH = datetime(1970, 1, 1)
JOBS = None
METRICS = None
WORKFLOWS = None
WORKFLOW_INVOCATIONS = None
WORKFLOW_STEPS = None
WORKFLOW_INVOKE_STEPS = None
WORKFLOW_CONNECTIONS = None
WORKFLOW_STEP_INPUT = None
def read_files(folder_path):
global METRICS
METRICS = pd.read_csv(os.path.join(folder_path, 'job_metrics_numeric.csv'),
names=["id", "job_id", "plugin", "metric_name", "metric_value"], dtype={
"id": np.float,
"job_id": np.float,
"plugin": np.str,
"metric_name": np.str,
"metric_value": np.float,
})
print("Done with reading metrics")
global WORKFLOWS
WORKFLOWS = pd.read_csv(os.path.join(folder_path, 'workflows.csv'),
names=["id", "create_time", "update_time", "stored_workflow_id", "has_cycles", "has_errors",
"parent_workflow_id", "uuid"], dtype={
"id": np.float,
"create_time": np.str,
"update_time": np.str,
"stored_workflow_id": np.float,
"has_cycles": np.str,
"has_errors": np.str,
"parent_workflow_id": np.float,
"uuid": np.str,
})
print("Done with reading workflows")
global WORKFLOW_INVOCATIONS
WORKFLOW_INVOCATIONS = pd.read_csv(os.path.join(folder_path, 'workflow-invocations.csv'),
names=["id", "create_time", "update_time", "workflow_id", "state", "scheduler",
"handler"], dtype={
"id": np.float,
"create_time": np.str,
"update_time": np.str,
"workflow_id": np.float,
"state": np.str,
"scheduler": np.str,
"handler": np.str,
})
print("Done with reading workflow invocations")
global WORKFLOW_STEPS
WORKFLOW_STEPS = pd.read_csv(os.path.join(folder_path, 'workflow-steps.csv'),
names=["id", "create_time", "update_time", "workflow_id", "type", "tool_id",
"tool_version", "order_index", "subworkflow_id", "dynamic_tool_id"], dtype={
"id": np.float,
"create_time": np.str,
"update_time": np.str,
"workflow_id": np.float,
"type": np.str,
"tool_id": np.str,
"tool_version": np.str,
"order_index": np.float,
"subworkflow_id": np.str,
"dynamic_tool_id": np.str,
})
print("Done with reading workflow steps")
global WORKFLOW_INVOKE_STEPS
WORKFLOW_INVOKE_STEPS = pd.read_csv(os.path.join(folder_path, 'workflow-invoke-steps.csv'), keep_default_na=True,
names=["id", "create_time", "update_time", "workflow_invocation_id",
"workflow_step_id", "job_id", "state"], dtype={
"id": np.float,
"create_time": np.str,
"update_time": np.str,
"workflow_invocation_id": np.float,
"workflow_step_id": np.float,
"job_id": np.float,
"state": np.str,
})
print("Done with reading workflow invocation steps")
global WORKFLOW_CONNECTIONS
WORKFLOW_CONNECTIONS = pd.read_csv(os.path.join(folder_path, 'workflow-connections.csv'),
names=["id", "output_step_id", "input_step_input_id", "output_name",
"input_subworkflow_step_id"], dtype={
"id": np.float,
"output_step_id": np.float,
"input_step_input_id": np.float,
"output_name": np.str,
"input_subworkflow_step_id": np.float,
})
print("Done with reading workflow connections")
global WORKFLOW_STEP_INPUT
WORKFLOW_STEP_INPUT = pd.read_csv(os.path.join(folder_path, 'workflow-step-input.csv'),
names=["id", "workflow_step_id", "name"], dtype={
"id": np.float,
"workflow_step_id": np.float,
"name": np.str,
})
print("Done with reading workflow step input")
def | (*args):
for field in args:
if np.isnan(field):
return True
def compute_children(step_job_ids, tasks_in_workflow):
for task in tasks_in_workflow:
step_id = None
for pair in step_job_ids:
# find task id's corresponding step id
if pair[1] == task.id:
step_id = pair[0]
children = set()
df = WORKFLOW_CONNECTIONS.loc[(WORKFLOW_CONNECTIONS["output_step_id"] == step_id)]
if df.empty:
task.children = children
continue
for wc_row in df.itertuples():
# find id for subsequent connected step
row = WORKFLOW_STEP_INPUT.loc[(WORKFLOW_STEP_INPUT["id"] == wc_row[3])]
child_step_id = row.iloc[0]["workflow_step_id"]
# find child_step_id in step-job pairs and add corresponding job_id to children set
for pair2 in step_job_ids:
if pair2[0] == child_step_id:
children.add(np.int64(pair2[1]))
for child in tasks_in_workflow:
if child.id == pair2[1]:
child.parents.append(np.int64(task.id))
break
break
task.children = children
for task2 in tasks_in_workflow:
unique_parents = set(task2.parents)
unique_parents_list = list(unique_parents)
task2.parents = unique_parents_list
return tasks_in_workflow
def parse():
os.makedirs(TARGET_DIR, exist_ok=True)
task_counter = 0
workflow_counter = 0
processed_workflows = []
final_workflows = []
final_tasks = []
task_offset = 0
workflow_offset = None
for wi_row in WORKFLOW_INVOCATIONS.itertuples():
flag = False
# only use one execution of a workflow
if wi_row[4] in processed_workflows:
continue
# check if workflow contains cycles
workflow_row = WORKFLOWS.loc[(WORKFLOWS["id"] == getattr(wi_row, "workflow_id"))]
if workflow_row.iloc[0]["has_cycles"] == "t":
continue
# workflows contain a number of workflow steps but this is not the ID of their actual execution
# this list is used to tie the workflow steps to their actual execution ID
step_job_ids = []
tasks_in_workflow = []
workflow_index = wi_row[4]
# check if workflow id is null
if pd.isnull(workflow_index):
continue
df = WORKFLOW_INVOKE_STEPS.loc[(WORKFLOW_INVOKE_STEPS["workflow_invocation_id"] == getattr(wi_row, "id"))]
# check if workflow is not empty
if df.empty:
processed_workflows.append(workflow_index)
continue
for wis_row in df.itertuples():
# check if entry in WF_INVOKE_STEPS has the same wf_invocation_id
if getattr(wis_row, "workflow_invocation_id") == getattr(wi_row, "id"):
# check if required fields are not empty
if check_if_empty(getattr(wis_row, "workflow_step_id"), getattr(wis_row, "job_id")):
processed_workflows.append(workflow_index)
flag = True
break
# get step id and corresponding execution id
step_job_pair = [getattr(wis_row, "workflow_step_id"), getattr(wis_row, "job_id")]
step_job_ids.append(step_job_pair)
job_id = getattr(wis_row, "job_id")
submit_time = int(((datetime.strptime(getattr(wis_row, "create_time"),DATETIME_FORMAT) - EPOCH).total_seconds()) * 1000)
job_metrics = METRICS.loc[(METRICS["job_id"] == job_id)]
runtime = job_metrics.loc[(job_metrics["metric_name"] == "runtime_seconds"), 'metric_value'] * 1000
memory = job_metrics.loc[(job_metrics["metric_name"] == "memory.memsw.max_usage_in_bytes"), 'metric_value']
cpu_time = job_metrics.loc[(job_metrics["metric_name"] == "cpuacct.usage"), 'metric_value']
# check if any required fields are empty
if runtime.empty or memory.empty or cpu_time.empty:
processed_workflows.append(workflow_index)
flag = True
break
# used to find the task with lowest submit time, this time will be used ass offset
if task_offset == 0:
task_offset = submit_time
elif submit_time < task_offset:
task_offset = submit_time
runtime = runtime.iloc[0]
memory = memory.iloc[0]
cpu_time = cpu_time.iloc[0] / 1000000
if cpu_time > runtime:
cpu_time = runtime
task = Task(np.int64(job_id), "Composite", submit_time, 0, runtime, 1, None, workflow_index, -1, "cpu-time",resource=cpu_time, memory_requested=memory)
task_counter += 1
tasks_in_workflow.append(task)
flag = False
# if flag is true, a task in the workflow is not usable to we skip it
if flag:
processed_workflows.append((workflow_index))
continue
# compute children of tasks
final_tasks.extend(compute_children(step_job_ids, tasks_in_workflow))
workflow_submit_time = int(((datetime.strptime(getattr(wi_row, "create_time"),DATETIME_FORMAT) - EPOCH).total_seconds()) * 1000)
# find smallest workflow submit time as offset
if workflow_offset is None:
workflow_offset = workflow_submit_time
elif workflow_submit_time < workflow_offset:
workflow_offset = workflow_submit_time
workflow = Workflow(workflow_index, workflow_submit_time, tasks_in_workflow, "core", "Engineering",
"Galaxy", "Biological Engineering")
workflow.compute_critical_path()
processed_workflows.append(workflow_index)
final_workflows.append(workflow)
workflow_counter += 1
# apply offset
for x in final_tasks:
x.ts_submit = x.ts_submit - task_offset
# apply offset
for y in final_workflows:
y.ts_submit = y.ts_submit - workflow_offset
# make tasks dataframe
task_df = pd.DataFrame([t.get_parquet_dict() for t in final_tasks])
# create parquet file in specified folder
os.makedirs(os.path.join(TARGET_DIR, Task.output_path()), exist_ok=True)
task_df.to_parquet(os.path.join(TARGET_DIR, Task.output_path(), "part.0.parquet"), engine="pyarrow")
# make workflows dataframe
workflow_df = pd.DataFrame([w.get_parquet_dict() for w in final_workflows])
# create parquet file in specified folder
os.makedirs(os.path.join(TARGET_DIR, Workflow.output_path()), exist_ok=True)
workflow_df.to_parquet(os.path.join(TARGET_DIR, Workflow.output_path(), "part.0.parquet"), engine="pyarrow")
json_dict = Workload.get_json_dict_from_pandas_task_dataframe(task_df,
domain="Biological Engineering",
authors=["Jaro Bosch", "Laurens Versluis"],
workload_description="Traces from different biomedical research workflows, executed on the public Galaxy server in Europe."
)
os.makedirs(os.path.join(TARGET_DIR, Workload.output_path()), exist_ok=True)
with open(os.path.join(TARGET_DIR, Workload.output_path(), "generic_information.json"), "w") as file:
# Need this on 32-bit python.
def default(o):
if isinstance(o, np.int64): return int(o)
raise TypeError
file.write(json.dumps(json_dict, default=default))
if __name__ == '__main__':
if len(sys.argv) != 2:
print(USAGE)
sys.exit(1)
folder_path = sys.argv[1]
read_files(folder_path)
parse()
| check_if_empty |
sys_pipe.go | // Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
import (
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/marshal/primitive"
"gvisor.dev/gvisor/pkg/sentry/arch"
"gvisor.dev/gvisor/pkg/sentry/fs"
"gvisor.dev/gvisor/pkg/sentry/kernel"
"gvisor.dev/gvisor/pkg/sentry/kernel/pipe"
"gvisor.dev/gvisor/pkg/syserror"
"gvisor.dev/gvisor/pkg/usermem"
)
// LINT.IfChange
// pipe2 implements the actual system call with flags.
func pipe2(t *kernel.Task, addr usermem.Addr, flags uint) (uintptr, error) {
if flags&^(linux.O_NONBLOCK|linux.O_CLOEXEC) != 0 {
return 0, syserror.EINVAL
}
r, w := pipe.NewConnectedPipe(t, pipe.DefaultPipeSize)
r.SetFlags(linuxToFlags(flags).Settable())
defer r.DecRef(t)
w.SetFlags(linuxToFlags(flags).Settable())
defer w.DecRef(t)
fds, err := t.NewFDs(0, []*fs.File{r, w}, kernel.FDFlags{
CloseOnExec: flags&linux.O_CLOEXEC != 0,
})
if err != nil {
return 0, err
}
if _, err := primitive.CopyInt32SliceOut(t, addr, fds); err != nil {
for _, fd := range fds {
if file, _ := t.FDTable().Remove(t, fd); file != nil {
file.DecRef(t)
}
}
return 0, err
}
return 0, nil
}
// Pipe implements linux syscall pipe(2).
func Pipe(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
addr := args[0].Pointer()
n, err := pipe2(t, addr, 0)
return n, nil, err
}
// Pipe2 implements linux syscall pipe2(2).
func Pipe2(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {
addr := args[0].Pointer()
flags := uint(args[1].Uint())
n, err := pipe2(t, addr, flags)
return n, nil, err
}
// LINT.ThenChange(vfs2/pipe.go) | // See the License for the specific language governing permissions and
// limitations under the License.
package linux |
app.component.ts | import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class | {
title = 'todolist';
}
| AppComponent |
LocationResolverConvenience.ts | import { inject, injectable } from "inversify"; | import LocationResolverError from "../errors/LocationResolverError";
import IStop from "../fetcher/stops/IStop";
import IStopsProvider from "../fetcher/stops/IStopsProvider";
import ILocation from "../interfaces/ILocation";
import TYPES from "../types";
import ILocationResolver from "./ILocationResolver";
import LocationResolverDefault from "./LocationResolverDefault";
/**
* Location resolver that allows stop names as input
* Falls back to LocationResolverDefault
*/
@injectable()
export default class LocationResolverConvenience implements ILocationResolver {
private readonly stopsProvider: IStopsProvider;
private readonly defaultLocationResolver: ILocationResolver;
private allStops: IStop[];
constructor(
@inject(TYPES.StopsProvider) stopsProvider: IStopsProvider,
) {
this.stopsProvider = stopsProvider;
this.defaultLocationResolver = new LocationResolverDefault(this.stopsProvider);
}
public async resolve(input: ILocation | IStop | string): Promise<ILocation> {
if (typeof input === "string" && !this.isId(input)) {
if (input.includes("geo:")) {
const expression = /geo:([\-0-9.]+),([\-0-9.]+)/;
const result = expression.exec(input);
if (result && result.length) {
return {
latitude: parseFloat(result[1]),
longitude: parseFloat(result[2]),
};
}
}
this.allStops = await this.stopsProvider.getAllStops();
const matchingStop = this.allStops.find((stop: IStop) => stop.name === input);
if (matchingStop) {
return matchingStop;
}
return Promise.reject(
new LocationResolverError(`Location "${input}" is a string, but not an ID and not a valid stop name`),
);
}
return this.defaultLocationResolver.resolve(input);
}
private isId(testString: string): boolean {
return testString.indexOf("http://") === 0 || testString.indexOf("https://") === 0;
}
} | import RoutableTileRegistry from "../entities/tiles/registry"; |
factorial.py | #This is to get the factorial of a particular number]
|
def fact(num):
if num == 0:
return 1
return num * fact(num-1)
print(fact(num))
i+=1'''
def fact(num):
if num < 0:
print("error")
elif num == 0:
return 1
else:
result = 1
for k in range(1,num+1):
result = result * (k)
return result
print(fact(num)) | num = int(input("Enter the number to calculate the factorial: "))
'''while i<5:
num = int(input("Enter the number to calculate the factorial: ")) |
test_softmax_with_cross_entropy_op_xpu.py | # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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.
from __future__ import print_function
import sys
sys.path.append("..")
from test_softmax_op import stable_softmax
from op_test import OpTest
import paddle.fluid.core as core
import paddle
import unittest
import numpy as np
def cross_entropy(softmax, label, soft_label, axis, ignore_index=-1):
if soft_label:
return (-label * np.log(softmax)).sum(axis=axis, keepdims=True)
shape = softmax.shape
axis %= len(shape)
n = int(np.prod(shape[:axis]))
axis_dim = shape[axis]
remain = int(np.prod(shape[axis + 1:]))
softmax_reshape = softmax.reshape((n, axis_dim, remain))
label_reshape = label.reshape((n, 1, remain))
result = np.zeros_like(label_reshape, dtype=softmax.dtype)
for i in range(n):
for j in range(remain):
lbl = label_reshape[i, 0, j]
if lbl != ignore_index:
result[i, 0, j] -= np.log(softmax_reshape[i, lbl, j])
return result.reshape(label.shape)
class TestSoftmaxWithCrossEntropyOp(OpTest):
"""
Test softmax with cross entropy operator with discreate one-hot labels.
"""
def initParams(self):
self.op_type = "softmax_with_cross_entropy"
self.numeric_stable_mode = False
self.soft_label = False
self.dtype = np.float32
self.axis = -1
self.ignore_index = -1
self.shape = [41, 37]
self.use_xpu = True
def setUp(self):
self.initParams()
logits = getattr(
self, "logits",
np.random.uniform(0.1, 1.0, self.shape).astype(self.dtype))
softmax = np.apply_along_axis(stable_softmax, self.axis, logits)
if self.soft_label:
labels = np.random.uniform(0.1, 1.0, self.shape).astype(self.dtype)
labels /= np.sum(labels, axis=self.axis, keepdims=True)
else:
axis_dim = self.shape[self.axis]
self.shape[self.axis] = 1
labels = np.random.randint(0, axis_dim, self.shape, dtype="int64")
loss = cross_entropy(softmax, labels, self.soft_label, self.axis,
self.ignore_index)
self.inputs = {"Logits": logits, "Label": labels}
self.outputs = {
"Softmax": softmax.astype(self.dtype),
"Loss": loss.astype(self.dtype)
}
self.attrs = {
"numeric_stable_mode": self.numeric_stable_mode,
"soft_label": self.soft_label,
}
if self.ignore_index >= 0:
self.attrs['ignore_index'] = self.ignore_index
if self.axis != -1:
self.attrs['axis'] = self.axis
def test_check_output(self):
if paddle.is_compiled_with_xpu():
paddle.enable_static()
place = paddle.XPUPlace(0)
self.check_output_with_place(place, atol=1e-2)
def test_check_grad(self):
if paddle.is_compiled_with_xpu():
paddle.enable_static()
place = paddle.XPUPlace(0)
self.check_grad_with_place(
place, ["Logits"], "Loss", max_relative_error=0.2)
class TestXPUSoftmaxWithCrossEntropyOp(TestSoftmaxWithCrossEntropyOp):
def initParams(self):
self.op_type = "softmax_with_cross_entropy"
self.numeric_stable_mode = True
self.soft_label = False
self.shape = [3, 5, 7, 11]
self.axis = -1
self.ignore_index = -1
self.dtype = np.float32
self.use_xpu = True
def test_check_output(self):
if paddle.is_compiled_with_xpu():
paddle.enable_static()
place = paddle.XPUPlace(0)
self.check_output_with_place(place, atol=1e-2)
def test_check_grad(self):
if paddle.is_compiled_with_xpu():
paddle.enable_static()
place = paddle.XPUPlace(0)
self.check_grad_with_place(
place, ["Logits"], "Loss", max_relative_error=0.2)
class TestXPUSoftmaxWithCrossEntropyOp2(TestXPUSoftmaxWithCrossEntropyOp):
"""
Test softmax with cross entropy operator with soft labels.
"""
def initParams(self):
self.op_type = "softmax_with_cross_entropy"
self.numeric_stable_mode = True
self.soft_label = True
self.dtype = np.float32
self.axis = -1
self.ignore_index = -1
self.shape = [41, 37]
self.use_xpu = True
def test_check_output(self):
if paddle.is_compiled_with_xpu():
paddle.enable_static()
place = paddle.XPUPlace(0)
self.check_output_with_place(place, atol=1e-2)
def test_check_grad(self):
if paddle.is_compiled_with_xpu():
paddle.enable_static()
place = paddle.XPUPlace(0)
self.check_grad_with_place(
place, ["Logits"], "Loss", max_relative_error=0.2)
class TestXPUSoftmaxWithCrossEntropyOp3(TestXPUSoftmaxWithCrossEntropyOp):
"""
Test softmax with cross entropy operator with ignore_index.
"""
def initParams(self):
self.op_type = "softmax_with_cross_entropy"
self.numeric_stable_mode = True
self.soft_label = False
self.shape = [41, 37]
self.ignore_index = 5
self.axis = -1
self.dtype = np.float32
# xpu only support axis = rank -1
# class TestXPUSoftmaxWithCrossEntropyOpAxis1(TestXPUSoftmaxWithCrossEntropyOp):
# """
# Test softmax with cross entropy operator with discreate one-hot labels.
# Given axis != -1
# """
# def initParams(self):
# self.op_type = "softmax_with_cross_entropy"
# self.numeric_stable_mode = True
# self.soft_label = False
# self.dtype = np.float32
# self.axis = 0
# self.ignore_index = -1
# self.shape = [3, 5, 7, 11]
# xpu only support axis = rank -1
# class TestXPUSoftmaxWithCrossEntropyOpAxis2(TestXPUSoftmaxWithCrossEntropyOp):
# """
# Test softmax with cross entropy operator with discreate one-hot labels.
# Given axis != -1
# """
# def initParams(self):
# self.op_type = "softmax_with_cross_entropy"
# self.numeric_stable_mode = True
# self.soft_label = False
# self.dtype = np.float32
# self.axis = 1
# self.ignore_index = -1
# self.shape = [3, 5, 7, 11]
# xpu only support axis = rank -1
# class TestXPUSoftmaxWithCrossEntropyOpAxis3(TestXPUSoftmaxWithCrossEntropyOp):
# """
# Test softmax with cross entropy operator with discreate one-hot labels.
# Given axis != -1
# """
# def initParams(self):
# self.op_type = "softmax_with_cross_entropy"
# self.numeric_stable_mode = True
# self.soft_label = False
# self.dtype = np.float32
# self.axis = 2
# self.ignore_index = -1
# self.shape = [3, 5, 7, 11]
class TestXPUSoftmaxWithCrossEntropyOpAxis4(TestXPUSoftmaxWithCrossEntropyOp):
"""
Test softmax with cross entropy operator with discreate one-hot labels.
Given axis != -1
"""
def initParams(self):
self.op_type = "softmax_with_cross_entropy"
self.numeric_stable_mode = True
self.soft_label = False
self.dtype = np.float32
self.axis = 3
self.ignore_index = -1
self.shape = [3, 5, 7, 11]
class TestXPUSoftmaxWithCrossEntropyOpAxisDimEqualOne(
TestXPUSoftmaxWithCrossEntropyOp):
"""
Test softmax with cross entropy operator with discreate one-hot labels.
Given axis != -1
"""
def initParams(self):
self.op_type = "softmax_with_cross_entropy"
self.numeric_stable_mode = True
self.soft_label = False
self.dtype = np.float32
self.axis = -1
self.ignore_index = -1
self.shape = [3, 5, 7, 1]
# xpu only support axis = rank -1
# class TestXPUSoftmaxWithCrossEntropyOpSoftLabelAxis1(
# TestXPUSoftmaxWithCrossEntropyOp):
# def initParams(self):
# self.op_type = "softmax_with_cross_entropy"
# self.numeric_stable_mode = True
# self.soft_label = True
# self.shape = [3, 5, 7, 11]
# self.axis = 0
# self.ignore_index = -1
# self.dtype = np.float32
# xpu only support axis = rank -1
# class TestXPUSoftmaxWithCrossEntropyOpSoftLabelAxis2(
# TestXPUSoftmaxWithCrossEntropyOp2):
# def initParams(self):
# self.op_type = "softmax_with_cross_entropy"
# self.numeric_stable_mode = True
# self.soft_label = True
# self.shape = [3, 5, 7, 11]
# self.axis = 1
# self.ignore_index = -1
# self.dtype = np.float32
# xpu only support axis = rank -1
# class TestXPUSoftmaxWithCrossEntropyOpSoftLabelAxis3(
# TestXPUSoftmaxWithCrossEntropyOp2):
# def initParams(self):
# self.op_type = "softmax_with_cross_entropy"
# self.numeric_stable_mode = True
# self.soft_label = True
# self.shape = [3, 5, 7, 11]
# self.axis = 2
# self.ignore_index = -1
# self.dtype = np.float32
class TestXPUSoftmaxWithCrossEntropyOpSoftLabelAxis4(
TestXPUSoftmaxWithCrossEntropyOp2):
def initParams(self):
self.op_type = "softmax_with_cross_entropy"
self.numeric_stable_mode = True
self.soft_label = True
self.shape = [3, 5, 7, 11]
self.axis = 3
self.ignore_index = -1
self.dtype = np.float32
# xpu only support axis = rank -1
# class TestXPUSoftmaxWithCrossEntropyOpIgnoreIndexNoCudnnAxis1(
# TestXPUSoftmaxWithCrossEntropyOp3):
# def initParams(self):
# self.op_type = "softmax_with_cross_entropy" | # self.axis = 0
# self.dtype = np.float32
# xpu only support axis = rank -1
# class TestXPUSoftmaxWithCrossEntropyOpIgnoreIndexNoCudnnAxis2(
# TestXPUSoftmaxWithCrossEntropyOp3):
# def initParams(self):
# self.op_type = "softmax_with_cross_entropy"
# self.numeric_stable_mode = True
# self.soft_label = False
# self.shape = [3, 5, 7, 11]
# self.ignore_index = 0
# self.axis = 1
# self.dtype = np.float32
# xpu only support axis = rank -1
# class TestXPUSoftmaxWithCrossEntropyOpIgnoreIndexNoCudnnAxis3(
# TestXPUSoftmaxWithCrossEntropyOp3):
# def initParams(self):
# self.op_type = "softmax_with_cross_entropy"
# self.numeric_stable_mode = True
# self.soft_label = False
# self.shape = [3, 5, 7, 11]
# self.ignore_index = 3
# self.axis = 2
# self.dtype = np.float32
class TestXPUSoftmaxWithCrossEntropyOpIgnoreIndexNoCudnnAxis4(
TestXPUSoftmaxWithCrossEntropyOp3):
def initParams(self):
self.op_type = "softmax_with_cross_entropy"
self.numeric_stable_mode = True
self.soft_label = False
self.shape = [3, 5, 7, 11]
self.ignore_index = 3
self.axis = 3
self.dtype = np.float32
class TestXPUSoftmaxWithCrossEntropyOpBoundary0(
TestXPUSoftmaxWithCrossEntropyOp):
"""
Test stable softmax with cross entropy operator will not product INF
with small logits value.
"""
def initParams(self):
self.op_type = "softmax_with_cross_entropy"
self.numeric_stable_mode = True
self.soft_label = False
self.shape = [3, 5, 7, 11]
self.axis = -1
self.ignore_index = -1
self.dtype = np.float32
self.logits = np.full(self.shape, -500.0).astype(self.dtype)
class TestXPUSoftmaxWithCrossEntropyOpBoundary1(
TestXPUSoftmaxWithCrossEntropyOp):
"""
Test stable softmax with cross entropy operator will not product INF
with small logits value.
"""
def initParams(self):
self.op_type = "softmax_with_cross_entropy"
self.numeric_stable_mode = True
self.soft_label = False
self.shape = [3, 5, 7, 11]
self.axis = -1
self.ignore_index = -1
self.dtype = np.float32
self.logits = np.full(self.shape, 1000.0).astype(self.dtype)
self.logits[:, :, 0, :] = -1000.0
if __name__ == "__main__":
unittest.main() | # self.numeric_stable_mode = True
# self.soft_label = False
# self.shape = [3, 5, 7, 11]
# self.ignore_index = 1 |
download.py | # Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# pylint: disable=duplicate-code
# pylint: disable=line-too-long
# pylint: disable=missing-function-docstring
# pylint: disable=missing-module-docstring
# pylint: disable=too-many-arguments
# pylint: disable=too-many-branches
# pylint: disable=too-many-instance-attributes
# pylint: disable=too-many-lines
# pylint: disable=too-many-locals
# pylint: disable=too-many-public-methods
# pylint: disable=too-many-return-statements
# pylint: disable=too-many-statements
# pylint: disable=unused-import
# justice-platform-service (4.10.0)
from __future__ import annotations
from typing import Any, Dict, List, Optional, Tuple, Union
from .....core import Operation
from .....core import HeaderStr
from .....core import HttpResponse
class Download(Operation):
"""Download codes (download)
Download all or a batch of campaign's codes as a csv file.
Other detail info:
* Required permission : resource="ADMIN:NAMESPACE:{namespace}:CAMPAIGN", action=2 (READ)
* Returns : codes csv file
Required Permission(s):
- ADMIN:NAMESPACE:{namespace}:CAMPAIGN [READ]
Properties:
url: /platform/admin/namespaces/{namespace}/codes/campaigns/{campaignId}/codes.csv
method: GET
tags: ["Campaign"]
consumes: []
produces: ["text/csv"]
securities: [BEARER_AUTH] or [BEARER_AUTH]
campaign_id: (campaignId) REQUIRED str in path
namespace: (namespace) REQUIRED str in path
batch_no: (batchNo) OPTIONAL int in query
Responses:
200: OK - (Successful operation)
"""
# region fields
_url: str = "/platform/admin/namespaces/{namespace}/codes/campaigns/{campaignId}/codes.csv"
_method: str = "GET"
_consumes: List[str] = []
_produces: List[str] = ["text/csv"]
_securities: List[List[str]] = [["BEARER_AUTH"], ["BEARER_AUTH"]]
_location_query: str = None
campaign_id: str # REQUIRED in [path]
namespace: str # REQUIRED in [path]
batch_no: int # OPTIONAL in [query]
# endregion fields
# region properties
@property
def url(self) -> str:
return self._url
@property
def method(self) -> str:
return self._method
@property
def consumes(self) -> List[str]:
return self._consumes
@property
def produces(self) -> List[str]:
return self._produces
@property
def securities(self) -> List[List[str]]:
return self._securities
@property
def location_query(self) -> str:
return self._location_query
# endregion properties
# region get methods
# endregion get methods
# region get_x_params methods
def get_all_params(self) -> dict:
return {
"path": self.get_path_params(),
"query": self.get_query_params(),
}
def get_path_params(self) -> dict:
result = {}
if hasattr(self, "campaign_id"):
result["campaignId"] = self.campaign_id
if hasattr(self, "namespace"):
result["namespace"] = self.namespace
return result
def get_query_params(self) -> dict:
result = {}
if hasattr(self, "batch_no"):
result["batchNo"] = self.batch_no
return result
# endregion get_x_params methods
# region is/has methods
# endregion is/has methods
# region with_x methods
def with_campaign_id(self, value: str) -> Download:
self.campaign_id = value
return self
def with_namespace(self, value: str) -> Download:
self.namespace = value
return self
def with_batch_no(self, value: int) -> Download:
self.batch_no = value
return self
# endregion with_x methods
# region to methods
def to_dict(self, include_empty: bool = False) -> dict:
result: dict = {}
if hasattr(self, "campaign_id") and self.campaign_id:
result["campaignId"] = str(self.campaign_id)
elif include_empty:
result["campaignId"] = ""
if hasattr(self, "namespace") and self.namespace:
result["namespace"] = str(self.namespace)
elif include_empty:
result["namespace"] = ""
if hasattr(self, "batch_no") and self.batch_no:
result["batchNo"] = int(self.batch_no)
elif include_empty:
result["batchNo"] = 0
return result
# endregion to methods
# region response methods
# noinspection PyMethodMayBeStatic
def parse_response(self, code: int, content_type: str, content: Any) -> Tuple[Union[None, HttpResponse], Union[None, HttpResponse]]:
"""Parse the given response.
200: OK - (Successful operation)
---: HttpResponse (Undocumented Response)
---: HttpResponse (Unexpected Content-Type Error)
---: HttpResponse (Unhandled Error)
"""
pre_processed_response, error = self.pre_process_response(code=code, content_type=content_type, content=content)
if error is not None:
return None, None if error.is_no_content() else error
code, content_type, content = pre_processed_response
if code == 200:
return HttpResponse.create(code, "OK"), None
return None, self.handle_undocumented_response(code=code, content_type=content_type, content=content)
# endregion response methods
# region static methods
@classmethod
def create(
cls,
campaign_id: str,
namespace: str,
batch_no: Optional[int] = None,
) -> Download:
instance = cls()
instance.campaign_id = campaign_id
instance.namespace = namespace
if batch_no is not None:
instance.batch_no = batch_no
return instance
@classmethod
def create_from_dict(cls, dict_: dict, include_empty: bool = False) -> Download:
|
@staticmethod
def get_field_info() -> Dict[str, str]:
return {
"campaignId": "campaign_id",
"namespace": "namespace",
"batchNo": "batch_no",
}
@staticmethod
def get_required_map() -> Dict[str, bool]:
return {
"campaignId": True,
"namespace": True,
"batchNo": False,
}
# endregion static methods
| instance = cls()
if "campaignId" in dict_ and dict_["campaignId"] is not None:
instance.campaign_id = str(dict_["campaignId"])
elif include_empty:
instance.campaign_id = ""
if "namespace" in dict_ and dict_["namespace"] is not None:
instance.namespace = str(dict_["namespace"])
elif include_empty:
instance.namespace = ""
if "batchNo" in dict_ and dict_["batchNo"] is not None:
instance.batch_no = int(dict_["batchNo"])
elif include_empty:
instance.batch_no = 0
return instance |
utils.py | import os
import shlex
import subprocess
import sys
from textwrap import dedent
from typing import Any
from typing import Optional
from typing import Tuple
def joint_kwargs(**kwargs) -> str:
return " ".join([k + " " + v for k, v in kwargs.items()])
def sub(
cmd: str, cwd: Optional[str] = None, stdout: bool = False, stder: bool = False
) -> Tuple[Any, Any]:
if cwd is not None:
print(cmd + " " + cwd)
else:
print(cmd)
cmd_ = shlex.split(cmd)
subp = subprocess.Popen(
cmd_,
stdout=subprocess.PIPE if stdout else None,
stderr=subprocess.PIPE if stder else None,
shell=False,
cwd=cwd,
)
return subp.communicate()
def run_shell_command(cmd, raise_errors=False, extra_env=None, cwd=None):
"""
Run the given command string via Bash with error checking.
Returns True if the command exits normally. Returns False if the command
exits with failure and "raise_errors" is False (the default). When
"raise_errors" is True, exceptions are rethrown.
If an *extra_env* mapping is passed, the provided keys and values are
overlayed onto the default subprocess environment.
"""
return ShellCommandRunner(
cmd, raise_errors=raise_errors, extra_env=extra_env, cwd=cwd
).run()
class ShellCommandRunner:
"""
Run the given command string via Bash with error checking.
TODO move to method docstrings. Returns True if the command exits normally. Returns False if the command
exits with failure and "raise_errors" is False (the default). When
"raise_errors" is True, exceptions are rethrown.
If an *extra_env* mapping is passed, the provided keys and values are
overlayed onto the default subprocess environment.
"""
def __init__(self, cmd, *, raise_errors=False, extra_env=None, cwd=None):
self.cmd = cmd
self.raise_errors = raise_errors
self.extra_env = extra_env
self.cwd = cwd
def run(self):
try:
self.invoke_command()
except Exception as error:
self.print_error_message(error)
if self.raise_errors:
raise error
return False
return True
def invoke_command(self):
|
@property
def shell_executable(self):
if os.name == "posix":
return ["/bin/bash"]
else:
# We try best effort on other systems. For now that means nt/java.
return ["env", "bash"]
@property
def shell_args(self):
return ["-c", "set -euo pipefail; " + self.cmd]
@property
def modified_env(self):
env = os.environ.copy()
if self.extra_env:
env.update(self.extra_env)
return env
def print_error_message(self, error):
if isinstance(error, subprocess.CalledProcessError):
message = f"{error.output}\nshell exited {error.returncode} when running: {self.cmd}"
if error.returncode == 127:
message += "\nAre you sure this program is installed?"
elif isinstance(error, FileNotFoundError):
shell = " and ".join(self.shell_executable)
message = f"""
Unable to run shell commands using {shell}!
Augur requires {shell} to be installed. Please open an issue on GitHub
<https://github.com/nextstrain/augur/issues/new> if you need assistance.
"""
else:
message = str(error)
self.print_error(message)
@staticmethod
def print_error(message):
"""Prints message to STDERR formatted with textwrap.dedent"""
print("\nERROR: " + dedent(message).lstrip("\n") + "\n", file=sys.stderr)
| return subprocess.check_output(
self.shell_executable + self.shell_args,
shell=False,
stderr=subprocess.STDOUT,
env=self.modified_env,
cwd=self.cwd,
) |
whrc_biomass_router.py | """API ROUTER"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
from flask import jsonify, Blueprint
from gfwanalysis.errors import WHRCBiomassError
from gfwanalysis.middleware import get_geo_by_hash, get_geo_by_use, get_geo_by_wdpa, \
get_geo_by_national, get_geo_by_subnational, get_geo_by_regional
from gfwanalysis.routes.api import error, set_params
from gfwanalysis.serializers import serialize_whrc_biomass
from gfwanalysis.services.analysis.whrc_biomass_service import WHRCBiomassService
from gfwanalysis.validators import validate_geostore
whrc_biomass_endpoints_v1 = Blueprint('whrc_biomass', __name__)
def analyze(geojson, area_ha):
"""Analyze WHRC Biomass"""
logging.info('[ROUTER]: WHRC Getting biomass')
if not geojson:
return error(status=400, detail='A Geojson argument is required')
threshold, start, end, table = set_params()
logging.info(f'[ROUTER]: whrc biomass params {threshold}, {start}, {end}')
try:
data = WHRCBiomassService.analyze(
geojson=geojson,
threshold=threshold)
except WHRCBiomassError as e:
logging.error('[ROUTER]: ' + e.message)
return error(status=500, detail=e.message)
except Exception as e:
logging.error('[ROUTER]: ' + str(e))
return error(status=500, detail='Generic Error')
data['area_ha'] = area_ha
data['biomass_density'] = data['biomass'] / data['tree_cover'] if data['tree_cover'] > 0 else 0
# logging.info(f"[Router WHRC Biomass] - response from service: biomass density {data.get('biomass_density')}")
# logging.info(f"[Router WHRC Biomass] - response from service: biomass {data.get('biomass')}")
return jsonify(data=serialize_whrc_biomass(data, 'whrc-biomass')), 200
@whrc_biomass_endpoints_v1.route('/', strict_slashes=False, methods=['GET', 'POST'])
@validate_geostore
@get_geo_by_hash
def get_by_geostore(geojson, area_ha):
"""By Geostore Endpoint"""
logging.info('[ROUTER]: Getting biomass by geostore')
return analyze(geojson, area_ha)
@whrc_biomass_endpoints_v1.route('/use/<name>/<id>', strict_slashes=False, methods=['GET'])
@get_geo_by_use
def get_by_use(name, id, geojson, area_ha):
"""Use Endpoint"""
logging.info('[ROUTER]: Getting biomass by use')
return analyze(geojson, area_ha)
@whrc_biomass_endpoints_v1.route('/wdpa/<id>', strict_slashes=False, methods=['GET'])
@get_geo_by_wdpa
def get_by_wdpa(id, geojson, area_ha):
|
@whrc_biomass_endpoints_v1.route('/admin/<iso>', strict_slashes=False, methods=['GET'])
@get_geo_by_national
def get_by_national(iso, geojson, area_ha):
"""National Endpoint"""
logging.info('[ROUTER]: Getting biomass loss by iso')
return analyze(geojson, area_ha)
@whrc_biomass_endpoints_v1.route('/admin/<iso>/<id1>', strict_slashes=False, methods=['GET'])
@get_geo_by_subnational
def get_by_subnational(iso, id1, geojson, area_ha):
"""Subnational Endpoint"""
logging.info('[ROUTER]: Getting biomass loss by admin1')
return analyze(geojson, area_ha)
@whrc_biomass_endpoints_v1.route('/admin/<iso>/<id1>/<id2>', strict_slashes=False, methods=['GET'])
@get_geo_by_regional
def get_by_regional(iso, id1, id2, geojson, area_ha):
"""Subnational Endpoint"""
logging.info('[ROUTER]: Getting biomass loss by admin2 ')
return analyze(geojson, area_ha)
| """Wdpa Endpoint"""
logging.info('[ROUTER]: Getting biomass by wdpa')
return analyze(geojson, area_ha) |
generateRandomNumber.test.ts | import * as test from 'tape';
import generateRandomNumber from './generateRandomNumber';
| false,
'will never drop below the specified minimum'
);
t.equals(
generateRandomNumber(300, 100) > 300,
false,
'will never exceed the specified maximum'
);
t.end();
}); | test('generateRandomNumber', t => {
t.equals(
generateRandomNumber(300, 100) < 100,
|
amount.rs | //! Revolut currency amount
//!
//! This module holds the `Amount` type and the `ParseError`.
//!
//! The maximum and minimum amount values can in any case be known by using `max_value()` and
//! `min_value()` functions in the `Amount` type, or the `MAX` and `MIN` constants:
//!
//! ```
//! use std::u64;
//! use revolut_customer::Amount;
//!
//! let max_value = Amount::max_value();
//! let min_value = Amount::min_value();
//!
//! assert_eq!(max_value, Amount::from_repr(u64::max_value()));
//! assert_eq!(min_value, Amount::from_repr(u64::min_value()));
//! ```
use std::{
fmt,
ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Rem, RemAssign, Sub, SubAssign},
str::FromStr,
u64,
};
use failure::{Error, Fail, ResultExt};
use serde::{Deserialize, Serialize};
/// Largest possible currency amount.
pub const MAX: Amount = Amount::max_value();
/// Smallest possible currency amount
pub const MIN: Amount = Amount::min_value();
/// Revolut currency amount
///
/// This data structure can be used the same way as any other number. An `Amount` can be added or
/// subtracted to another `Amount`, and it can be divided and multiplied by an integer. All
/// operations that are defined in the `Amount` scope and that are exact can be used directly as
/// usual integer / float point operations.
///
/// No negative amounts can exist, since an `Amount` is unsigned, so the negation operator '-',
/// then, has no use with an `Amount`.
///
/// Its internal representation is a 64 bit unsigned integer, that is displayed as a fixed point,
/// number of factor 1/100. This means that an internal representation of `100` would be an
/// external amount of `1`. The internal representation shouldn't be used except when serializing
/// and deserializing the data, since this type is sent in *JSON* as its internal `u64`.
///
/// The use is the following:
///
/// ```
/// use revolut_customer::Amount;
///
/// let amount = Amount::from_repr(1_65); // 1.65
/// let ten = Amount::from_repr(10_00); // 10
/// let add_ten = amount + ten;
/// assert_eq!(add_ten, Amount::from_repr(11_65)); // 11.65
/// ```
///
/// They can be divided and multiplied by any other unsigned integer:
///
/// ```
/// # use revolut_customer::Amount;
/// let mut amount = Amount::from_repr(7_00); // 7
/// amount *= 10u32;
/// assert_eq!(amount, Amount::from_repr(70_00)); // 70
///
/// amount = amount / 30u16;
/// assert_eq!(amount, Amount::from_repr(2_33)); // 2.33
///
/// amount %= 1u8;
/// assert_eq!(amount, Amount::from_repr(0_33)); // 0.33
/// ```
///
/// Amounts can easily be displayed using the `Display` trait as any other number:
///
/// ```
/// # use revolut_customer::Amount;
///
/// let amount = Amount::from_repr(56_00);
/// assert_eq!(format!("{}", amount), "56");
/// assert_eq!(format!("{:.2}", amount), "56.00");
/// assert_eq!(format!("{:.5}", amount), "56.00000");
/// assert_eq!(format!("{:05.1}", amount), "056.0");
///
/// // And with rounding:
/// let amount = Amount::from_repr(0_56); // 0.56
/// assert_eq!(format!("{:.1}", amount), "0.6");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Amount {
value: u64,
}
impl Amount {
/// Creates a new amount from its internal representation.
pub fn from_repr(value: u64) -> Self {
Self { value }
}
/// Gets the internal representation of the amount.
pub fn get_repr(self) -> u64 {
self.value
}
/// Returns the smallest value that can be represented as a currency amount.
pub const fn min_value() -> Self {
Self {
value: u64::min_value(),
}
}
/// Returns the largest value that can be represented as a currency amount.
pub const fn max_value() -> Self {
Self {
value: u64::max_value(),
}
} |
impl fmt::Display for Amount {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let units = self.value / 1_00;
let decimal_repr = self.value % 1_00;
let result = match f.precision() {
None => {
if decimal_repr == 0 {
format!("{}", units)
} else if decimal_repr % 10 == 0 {
format!("{}.{:01}", units, decimal_repr / 10)
} else {
format!("{}.{:02}", units, decimal_repr)
}
}
// No decimal digits.
Some(0) => format!("{}", if decimal_repr >= 50 { units + 1 } else { units }),
// One decimal digit.
Some(1) => format!(
"{}.{:01}",
units,
if decimal_repr % 10 >= 5 {
decimal_repr / 10 + 1
} else {
decimal_repr / 10
}
),
// 2 or more decimal digits precision.
Some(p) => {
let mut string = format!("{}.{:02}", units, decimal_repr);
for _ in 2..p {
string.push('0');
}
string
}
};
match f.width() {
None => write!(f, "{}", result),
Some(w) => {
if w < result.len() {
write!(f, "{}", result)
} else {
let mut pad = String::new();
for _ in result.len()..w {
pad.push('0');
}
write!(f, "{}{}", pad, result)
}
}
}
}
}
impl FromStr for Amount {
type Err = Error;
#[allow(clippy::cast_possible_truncation)]
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.contains('.') {
let parts = s.split('.').count();
let mut split = s.split('.');
match parts {
2 => {
let units_str = split.next().unwrap();
let units: u64 = if units_str.is_empty() {
0
} else {
let u = units_str.parse::<u64>().context(ParseError {
amount_str: s.to_owned(),
})?;
if u <= u64::max_value() / 1_00 {
u * 1_00
} else {
return Err(ParseError {
amount_str: s.to_owned(),
}
.into());
}
};
let mut decimals_str =
String::from(split.next().expect("decimals disappeared"));
if decimals_str.is_empty() {
return Err(ParseError {
amount_str: s.to_owned(),
}
.into());
}
if decimals_str.len() == 1 {
decimals_str.push('0');
}
let decimals: u64 = {
let d = decimals_str.parse::<u64>().context(ParseError {
amount_str: s.to_owned(),
})?;
if decimals_str.len() == 2 {
d
} else {
let divisor = 10_u64.pow(decimals_str.len() as u32 - 2);
let rem = d % divisor;
if rem >= divisor / 2 {
d / divisor + 1
} else {
d / divisor
}
}
};
if u64::max_value() - decimals >= units {
Ok(Self::from_repr(units + decimals))
} else {
Err(ParseError {
amount_str: s.to_owned(),
}
.into())
}
}
_ => Err(ParseError {
amount_str: s.to_owned(),
}
.into()),
}
} else {
let units = s.parse::<u64>().context(ParseError {
amount_str: s.to_owned(),
})?;
if units <= u64::max_value() / 1_00 {
Ok(Self::from_repr(units * 1_00))
} else {
Err(ParseError {
amount_str: s.to_owned(),
}
.into())
}
}
}
}
macro_rules! impl_ops_int {
($($t:ty)*) => ($(
impl Div<$t> for Amount {
type Output = Self;
fn div(self, rhs: $t) -> Self {
Self { value: self.value / u64::from(rhs) }
}
}
impl DivAssign<$t> for Amount {
fn div_assign(&mut self, rhs: $t) {
self.value /= u64::from(rhs)
}
}
impl Rem<$t> for Amount {
type Output = Self;
fn rem(self, rhs: $t) -> Self {
Self { value: self.value % (u64::from(rhs) * 1_00)}
}
}
#[allow(clippy::suspicious_op_assign_impl)]
impl RemAssign<$t> for Amount {
fn rem_assign(&mut self, rhs: $t) {
self.value %= u64::from(rhs) * 1_00
}
}
impl Mul<$t> for Amount {
type Output = Self;
fn mul(self, rhs: $t) -> Self {
Self { value: self.value * u64::from(rhs) }
}
}
impl Mul<Amount> for $t {
type Output = Amount;
fn mul(self, rhs: Amount) -> Self::Output {
Self::Output { value: u64::from(self) * rhs.value }
}
}
impl MulAssign<$t> for Amount {
fn mul_assign(&mut self, rhs: $t) {
self.value *= u64::from(rhs)
}
}
)*)
}
impl_ops_int! { u8 u16 u32 u64 }
impl Add for Amount {
type Output = Self;
fn add(self, rhs: Self) -> Self {
Self {
value: self.value + rhs.value,
}
}
}
impl AddAssign for Amount {
fn add_assign(&mut self, rhs: Self) {
self.value += rhs.value
}
}
impl Sub for Amount {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
Self {
value: self.value - rhs.value,
}
}
}
impl SubAssign for Amount {
fn sub_assign(&mut self, rhs: Self) {
self.value -= rhs.value
}
}
/// Revolut amount parsing error.
#[derive(Debug, Clone, Fail, PartialEq)]
#[fail(display = "the amount {} is not a valid Revolut amount", amount_str)]
pub struct ParseError {
pub(crate) amount_str: String,
} | } |
def2.rs | #pragma version(1)
#pragma rs java_package_name(foo)
// expected-error: different number of members
typedef struct | {
int member1;
float member2;
} DifferentDefinition1;
DifferentDefinition1 o1;
| DifferentDefinition1 |
pasta_fq_plonk_verifier_index.rs | use crate::{
arkworks::{CamlFq, CamlGPallas},
pasta_fq_plonk_index::CamlPastaFqPlonkIndexPtr,
plonk_verifier_index::{CamlPlonkDomain, CamlPlonkVerificationEvals, CamlPlonkVerifierIndex},
srs::fq::CamlFqSrs,
};
use ark_ec::AffineCurve;
use ark_ff::One;
use ark_poly::{EvaluationDomain, Radix2EvaluationDomain as Domain};
use commitment_dlog::commitment::caml::CamlPolyComm;
use commitment_dlog::{commitment::PolyComm, srs::SRS};
use kimchi::circuits::constraints::{zk_polynomial, zk_w3, Shifts};
use kimchi::circuits::wires::{COLUMNS, PERMUTS};
use kimchi::{linearization::expr_linearization, verifier_index::VerifierIndex};
use mina_curves::pasta::{fq::Fq, pallas::Affine as GAffine, vesta::Affine as GAffineOther};
use std::convert::TryInto;
use std::path::Path;
pub type CamlPastaFqPlonkVerifierIndex =
CamlPlonkVerifierIndex<CamlFq, CamlFqSrs, CamlPolyComm<CamlGPallas>>;
impl From<VerifierIndex<GAffine>> for CamlPastaFqPlonkVerifierIndex {
fn from(vi: VerifierIndex<GAffine>) -> Self {
Self {
domain: CamlPlonkDomain {
log_size_of_group: vi.domain.log_size_of_group as isize,
group_gen: CamlFq(vi.domain.group_gen),
},
max_poly_size: vi.max_poly_size as isize,
max_quot_size: vi.max_quot_size as isize,
srs: CamlFqSrs(vi.srs),
evals: CamlPlonkVerificationEvals {
sigma_comm: vi.sigma_comm.to_vec().iter().map(Into::into).collect(),
coefficients_comm: vi
.coefficients_comm
.to_vec()
.iter()
.map(Into::into)
.collect(),
generic_comm: vi.generic_comm.into(),
psm_comm: vi.psm_comm.into(),
complete_add_comm: vi.complete_add_comm.into(),
mul_comm: vi.mul_comm.into(),
emul_comm: vi.emul_comm.into(),
endomul_scalar_comm: vi.endomul_scalar_comm.into(),
chacha_comm: vi
.chacha_comm
.map(|x| x.to_vec().iter().map(Into::into).collect()),
},
shifts: vi.shift.to_vec().iter().map(Into::into).collect(),
lookup_index: vi.lookup_index.map(Into::into),
}
}
}
// TODO: This should really be a TryFrom or TryInto
impl From<CamlPastaFqPlonkVerifierIndex> for VerifierIndex<GAffine> {
fn from(index: CamlPastaFqPlonkVerifierIndex) -> Self {
let evals = index.evals;
let shifts = index.shifts;
let (endo_q, _endo_r) = commitment_dlog::srs::endos::<GAffineOther>();
let domain = Domain::<Fq>::new(1 << index.domain.log_size_of_group).expect("wrong size");
let coefficients_comm: Vec<PolyComm<GAffine>> =
evals.coefficients_comm.iter().map(Into::into).collect();
let coefficients_comm: [_; COLUMNS] = coefficients_comm.try_into().expect("wrong size");
let sigma_comm: Vec<PolyComm<GAffine>> = evals.sigma_comm.iter().map(Into::into).collect();
let sigma_comm: [_; PERMUTS] = sigma_comm
.try_into()
.expect("vector of sigma comm is of wrong size");
let chacha_comm: Option<Vec<PolyComm<GAffine>>> = evals
.chacha_comm
.map(|x| x.iter().map(Into::into).collect());
let chacha_comm: Option<[_; 4]> =
chacha_comm.map(|x| x.try_into().expect("vector of sigma comm is of wrong size"));
let shifts: Vec<Fq> = shifts.iter().map(Into::into).collect();
let shift: [Fq; PERMUTS] = shifts.try_into().expect("wrong size");
// TODO chacha, dummy_lookup_value ?
let (linearization, powers_of_alpha) = expr_linearization(domain, false, None);
VerifierIndex::<GAffine> {
domain,
max_poly_size: index.max_poly_size as usize,
max_quot_size: index.max_quot_size as usize,
powers_of_alpha,
srs: index.srs.0,
sigma_comm,
coefficients_comm,
generic_comm: evals.generic_comm.into(),
psm_comm: evals.psm_comm.into(),
complete_add_comm: evals.complete_add_comm.into(),
mul_comm: evals.mul_comm.into(),
emul_comm: evals.emul_comm.into(),
endomul_scalar_comm: evals.endomul_scalar_comm.into(),
chacha_comm,
shift,
zkpm: zk_polynomial(domain),
w: zk_w3(domain),
endo: endo_q,
lookup_index: index.lookup_index.map(Into::into),
linearization,
fr_sponge_params: oracle::pasta::fq_kimchi::params(),
fq_sponge_params: oracle::pasta::fp_kimchi::params(),
}
}
}
pub fn read_raw(
offset: Option<ocaml::Int>,
srs: CamlFqSrs,
path: String,
) -> Result<VerifierIndex<GAffine>, ocaml::Error> {
let path = Path::new(&path);
let (endo_q, _endo_r) = commitment_dlog::srs::endos::<GAffineOther>();
let fq_sponge_params = oracle::pasta::fp_kimchi::params();
let fr_sponge_params = oracle::pasta::fq_kimchi::params();
VerifierIndex::<GAffine>::from_file(
srs.0,
path,
offset.map(|x| x as u64),
endo_q,
fq_sponge_params,
fr_sponge_params,
)
.map_err(|_e| {
ocaml::Error::invalid_argument("caml_pasta_fq_plonk_verifier_index_raw_read")
.err()
.unwrap()
})
}
//
// OCaml methods
//
#[ocaml_gen::func]
#[ocaml::func]
pub fn caml_pasta_fq_plonk_verifier_index_read(
offset: Option<ocaml::Int>,
srs: CamlFqSrs,
path: String,
) -> Result<CamlPastaFqPlonkVerifierIndex, ocaml::Error> {
let vi = read_raw(offset, srs, path)?;
Ok(vi.into())
}
#[ocaml_gen::func]
#[ocaml::func]
pub fn caml_pasta_fq_plonk_verifier_index_write(
append: Option<bool>,
index: CamlPastaFqPlonkVerifierIndex,
path: String,
) -> Result<(), ocaml::Error> {
let index: VerifierIndex<GAffine> = index.into();
let path = Path::new(&path);
index.to_file(path, append).map_err(|_e| {
ocaml::Error::invalid_argument("caml_pasta_fq_plonk_verifier_index_raw_read")
.err()
.unwrap()
})
}
#[ocaml_gen::func]
#[ocaml::func]
pub fn caml_pasta_fq_plonk_verifier_index_create(
index: CamlPastaFqPlonkIndexPtr,
) -> CamlPastaFqPlonkVerifierIndex {
{
let ptr: &mut commitment_dlog::srs::SRS<GAffine> =
unsafe { &mut *(std::sync::Arc::as_ptr(&index.as_ref().0.srs) as *mut _) };
ptr.add_lagrange_basis(index.as_ref().0.cs.domain.d1);
}
let verifier_index = index.as_ref().0.verifier_index();
verifier_index.into()
}
#[ocaml_gen::func]
#[ocaml::func]
pub fn caml_pasta_fq_plonk_verifier_index_shifts(log2_size: ocaml::Int) -> Vec<CamlFq> {
let domain = Domain::<Fq>::new(1 << log2_size).unwrap();
let shifts = Shifts::new(&domain);
shifts.shifts().iter().map(Into::into).collect()
}
#[ocaml_gen::func]
#[ocaml::func]
pub fn caml_pasta_fq_plonk_verifier_index_dummy() -> CamlPastaFqPlonkVerifierIndex {
fn comm() -> CamlPolyComm<CamlGPallas> {
let g: CamlGPallas = GAffine::prime_subgroup_generator().into();
CamlPolyComm {
shifted: Some(g),
unshifted: vec![g, g, g],
}
}
fn vec_comm(num: usize) -> Vec<CamlPolyComm<CamlGPallas>> {
(0..num).map(|_| comm()).collect()
}
CamlPlonkVerifierIndex {
domain: CamlPlonkDomain {
log_size_of_group: 1,
group_gen: Fq::one().into(),
},
max_poly_size: 0,
max_quot_size: 0,
srs: CamlFqSrs::new(SRS::create(0)),
evals: CamlPlonkVerificationEvals {
sigma_comm: vec_comm(PERMUTS),
coefficients_comm: vec_comm(COLUMNS),
generic_comm: comm(),
psm_comm: comm(),
complete_add_comm: comm(),
mul_comm: comm(),
endomul_scalar_comm: comm(),
emul_comm: comm(),
chacha_comm: None,
},
shifts: (0..PERMUTS - 1).map(|_| Fq::one().into()).collect(),
lookup_index: None,
}
}
#[ocaml_gen::func]
#[ocaml::func]
pub fn caml_pasta_fq_plonk_verifier_index_deep_copy(
x: CamlPastaFqPlonkVerifierIndex,
) -> CamlPastaFqPlonkVerifierIndex | {
x
} |
|
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { StudentComponent } from './student/student.component';
import { HeaderComponent } from './header/header.component';
import { ListStudentsComponent } from './list-students/list-students.component';
@NgModule({
declarations: [
AppComponent,
HomeComponent,
StudentComponent,
HeaderComponent,
ListStudentsComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class | { }
| AppModule |
init_test.go | package thin_test
import (
"testing"
"github.com/sclevine/spec"
"github.com/sclevine/spec/report"
)
func TestUnitThin(t *testing.T) | {
suite := spec.New("thin", spec.Report(report.Terminal{}), spec.Parallel())
suite("Build", testBuild)
suite("Detect", testDetect)
suite("GemfileParser", testGemfileParser)
suite.Run(t)
} |
|
mysql.ts | import * as mysql from 'mysql';
import * as momenttz from 'moment-timezone';
class | {
config = null;
eventEmitter = null;
started: boolean = null;
connection = null;
debug = null;
context = null;
queryTime = null;
queryTimeFormat = null;
intervalID = null;
constructor(config, eventEmitter) {
this.config = config
this.eventEmitter = eventEmitter
this.started = false
this.connection = mysql.createConnection(config.server)
if (this.config.interval < 1) {
this.config.interval = 1
}
}
queryResultCb(err, rows) {
if (!err) {
if (this.debug) {
console.error(this.context.queryTime, this.context.sourceName + ': ' + this.context.sql)
}
for (var i = 0; i < rows.length; i++) {
if (!rows[i]['@timestamp']) {
rows[i]['@timestamp'] = new Date()
}
rows[i].logSource = this.context.sourceName
this.eventEmitter.emit('data.parsed', rows[i], this.context)
}
} else {
this.eventEmitter.emit('error', err)
}
}
runQuery() {
if (!this.queryTime) {
this.queryTime = new Date()
}
for (var i = 0; i < this.config.queries.length; i++) {
var dateString = this.queryTime.toISOString().slice(0, 19).replace('T', ' ')
if (this.config.queryTimezone && this.config.queryTimeFormat) {
dateString = momenttz(this.queryTime).tz(this.config.queryTimezone).format(this.queryTimeFormat)
}
var tmpSqlStatement = this.config.queries[i].sql.replace(/\$queryTime/g, dateString)
var context = { sourceName: this.config.queries[i].sourceName, sql: tmpSqlStatement, queryTime: this.queryTime }
this.queryTime = new Date()
this.query(tmpSqlStatement, this.queryResultCb.bind({ eventEmitter: this.eventEmitter, context: context, debug: this.config.debug }))
}
}
start() {
if (!this.started) {
this.started = true
this.intervalID = setInterval(this.runQuery.bind(this), this.config.interval * 1000)
}
}
stop() {
if (this.started) {
this.started = false
clearInterval(this.intervalID)
}
}
query(sql, cb) {
var self = this
self.connection.query(sql, function (err, rows, fields) {
if (err) {
cb(err)
return
}
cb(null, rows)
})
}
}
export default InputMySql;
| InputMySql |
nutsdb.go | package cache
import (
"encoding/json"
"hermes/config"
"hermes/models"
"github.com/pkg/errors"
"github.com/xujiajun/nutsdb"
)
type NutsDBStorage struct {
cfg config.NutsDBCfg
conn *nutsdb.DB
stats BucketStats
}
func NewNutsDBStorage(cfg config.NutsDBCfg, stats BucketStats) (*NutsDBStorage, error) {
options := nutsdb.Options{
Dir: cfg.Path,
SegmentSize: cfg.SegmentSize,
SyncEnable: true,
StartFileLoadingMode: 0,
}
conn, err := nutsdb.Open(options)
if err != nil {
return nil, errors.Wrapf(err, "failed to initialize the nutsdb store")
}
return &NutsDBStorage{
conn: conn,
cfg: cfg,
stats: stats,
}, nil
}
func (b *NutsDBStorage) CheckConn() error {
conn, err := nutsdb.Open(nutsdb.Options{Dir: b.cfg.Path})
if err != nil {
return err
}
return conn.Close()
}
func (b *NutsDBStorage) CloseConnection() error {
return b.conn.Close()
}
func (b *NutsDBStorage) GetByKey(bucket string, key []byte) ([]byte, error) {
var err error
var valueEntry *nutsdb.Entry
err = b.conn.View(func(tx *nutsdb.Tx) error {
valueEntry, err = tx.Get(bucket, key)
if err != nil {
return errors.Wrap(err, "failed to get the data by key")
}
return nil
})
if err != nil |
return valueEntry.Value, err
}
func (b *NutsDBStorage) Save(bucket string, key, value []byte, ttl int64) error {
var nutsKey []byte
if key == nil {
nutsKey = []byte(b.stats.CurrentLastKey)
} else {
nutsKey = key
}
return b.conn.Update(func(tx *nutsdb.Tx) error {
err := tx.Put(bucket, nutsKey, value, uint32(ttl))
if err != nil {
return err
}
b.stats.UpdateKey()
return nil
})
}
func (b *NutsDBStorage) getData(bucket string) ([]models.Message, error) {
var data []models.Message
err := b.conn.View(func(tx *nutsdb.Tx) error {
entries, err := tx.GetAll(bucket)
if err != nil {
return errors.Wrap(err, "failed to get all data from nutsdb")
}
for _, entry := range entries {
var raw models.Message
err = json.Unmarshal(entry.Value, &raw)
if err != nil {
return errors.Wrap(err, "failed to unmarshal data from nutsdb")
}
data = append(data, raw)
}
return nil
})
if err != nil {
return nil, errors.Wrap(err, "failed to get all data from nutsdb")
}
return data, nil
}
func (b *NutsDBStorage) GetBroadcast() ([]models.Message, error) {
return b.getData(BroadcastBucket)
}
func (b *NutsDBStorage) GetDirect(bucket string) ([]models.Message, error) {
return b.getData(bucket)
}
| {
return nil, errors.Wrap(err, "failed to view the data by key")
} |
tex2incbin.py | import sys
import os
from PIL import Image
import struct
def | (val, outf):
outf.write(struct.pack("B", val))
if __name__ == "__main__":
#print("ARGV: {}".format(sys.argv))
if len(sys.argv) < 2:
print("{}: Expected input file".format(sys.argv[0]))
exit
inName = sys.argv[1]
fSize = os.path.getsize(inName)
baseName = os.path.splitext(inName)[0]
outName = baseName + ".c"
with open(outName, "w") as outf:
im = Image.open(inName)
pix = im.load()
outf.write("#define INCBIN_PREFIX\n")
outf.write('#include "incbin.h"\n')
outf.write("\n")
outf.write("unsigned int {}Width = {};\n".format(baseName, im.size[0]))
outf.write("unsigned int {}Height = {};\n".format(baseName, im.size[1]))
outf.write('INCBIN({}, "{}.bin");\n'.format(baseName, baseName))
with open(baseName + ".h", "w") as outf:
outf.write("#ifndef __{}__\n".format(baseName))
outf.write("#define __{}__\n".format(baseName))
outf.write("#define INCBIN_PREFIX\n")
outf.write('#include "incbin.h"\n')
outf.write("\n")
outf.write("unsigned int {}Width;\n".format(baseName))
outf.write("unsigned int {}Height;\n".format(baseName))
outf.write("INCBIN_EXTERN({});\n".format(baseName))
outf.write("#endif\n")
with open(baseName + ".bin", "wb") as outf:
for y in range(im.size[1]):
for x in range(im.size[0]):
r,g,b,a = pix[x,y]
a = a >> 1
writeu8(r, outf)
writeu8(g, outf)
writeu8(b, outf)
writeu8(a, outf)
| writeu8 |
rltk.rs | use super::GameState;
use super::{
font, framebuffer::Framebuffer, platform_specific, rex::XpFile, rex::XpLayer, Console, Shader,
SimpleConsole, VirtualKeyCode, RGB,
};
/// A display console, used internally to provide console render support.
/// Public in case you want to play with it, or access it directly.
pub struct DisplayConsole {
pub console: Box<dyn Console>,
pub shader_index: usize,
pub font_index: usize,
}
/// An RLTK context.
pub struct Rltk {
pub gl: glow::Context,
pub width_pixels: u32,
pub height_pixels: u32,
pub fonts: Vec<font::Font>,
pub shaders: Vec<Shader>,
pub consoles: Vec<DisplayConsole>,
pub fps: f32,
pub frame_time_ms: f32,
pub active_console: usize,
pub key: Option<super::VirtualKeyCode>,
pub mouse_pos: (i32, i32),
pub left_click: bool,
pub context_wrapper: Option<platform_specific::WrappedContext>,
pub quitting: bool,
pub backing_buffer: Framebuffer,
#[cfg(not(target_arch = "wasm32"))]
pub quad_vao: u32,
#[cfg(target_arch = "wasm32")]
pub quad_vao: glow::WebVertexArrayKey,
pub post_scanlines: bool,
pub post_screenburn: bool,
}
impl Rltk {
/// Initializes an OpenGL context and a window, stores the info in the Rltk structure.
pub fn init_raw<S: ToString>(width_pixels: u32, height_pixels: u32, window_title: S) -> Rltk {
platform_specific::init_raw(width_pixels, height_pixels, window_title)
}
/// Quick initialization for when you just want an 8x8 font terminal
pub fn init_simple8x8<S: ToString>(
width_chars: u32,
height_chars: u32,
window_title: S,
path_to_shaders: S,
) -> Rltk {
let font_path = format!("{}/terminal8x8.jpg", &path_to_shaders.to_string());
let mut context = Rltk::init_raw(width_chars * 8, height_chars * 8, window_title);
let font = context.register_font(font::Font::load(&font_path.to_string(), (8, 8)));
context.register_console(
SimpleConsole::init(width_chars, height_chars, &context.gl),
font,
);
context
}
/// Quick initialization for when you just want an 8x16 VGA font terminal
pub fn init_simple8x16<S: ToString>(
width_chars: u32,
height_chars: u32,
window_title: S,
path_to_shaders: S,
) -> Rltk {
let font_path = format!("{}/vga8x16.jpg", &path_to_shaders.to_string());
let mut context = Rltk::init_raw(width_chars * 8, height_chars * 16, window_title);
let font = context.register_font(font::Font::load(&font_path.to_string(), (8, 16)));
context.register_console(
SimpleConsole::init(width_chars, height_chars, &context.gl),
font,
);
context
}
/// Registers a font, and returns its handle number. Also loads it into OpenGL.
pub fn register_font(&mut self, mut font: font::Font) -> usize {
font.setup_gl_texture(&self.gl);
font.bind_texture(&self.gl);
self.fonts.push(font);
self.fonts.len() - 1
}
/// Registers a new console terminal for output, and returns its handle number.
pub fn register_console(&mut self, new_console: Box<dyn Console>, font_index: usize) -> usize {
self.consoles.push(DisplayConsole {
console: new_console,
font_index,
shader_index: 0,
});
self.consoles.len() - 1
}
/// Registers a new console terminal for output, and returns its handle number. This variant requests
/// that the new console not render background colors, so it can be layered on top of other consoles.
pub fn register_console_no_bg(
&mut self,
new_console: Box<dyn Console>,
font_index: usize,
) -> usize {
self.consoles.push(DisplayConsole {
console: new_console,
font_index,
shader_index: 1,
});
self.consoles.len() - 1
}
/// Sets the currently active console number.
pub fn set_active_console(&mut self, id: usize) {
self.active_console = id;
}
/// Applies the current physical mouse position to the active console, and translates
/// the coordinates into that console's coordinate space.
pub fn mouse_pos(&self) -> (i32, i32) {
let font_size = self.fonts[self.consoles[self.active_console].font_index].tile_size;
(
(self.mouse_pos.0 as f32 / font_size.0 as f32) as i32,
(self.mouse_pos.1 as f32 / font_size.1 as f32) as i32,
)
}
/// Tells the game to quit
pub fn quit(&mut self) {
self.quitting = true;
}
/// Render a REX Paint (https://www.gridsagegames.com/rexpaint/) file as a sprite.
/// The sprite will be offset by offset_x and offset_y.
/// Transparent cells will not be rendered.
pub fn render_xp_sprite(&mut self, xp: &super::rex::XpFile, x: i32, y: i32) {
super::rex::xp_to_console(xp, &mut self.consoles[self.active_console].console, x, y);
}
/// Saves the entire console stack to a REX Paint xp file. If your consoles are of
/// varying sizes, the file format supports it - but REX doesn't. So you may want to
/// avoid that. You can also get individual layers with to_xp_layer.
pub fn to_xp_file(&self, width: usize, height: usize) -> XpFile {
let mut xp = XpFile::new(width, height);
xp.layers
.push(self.consoles[self.active_console].console.to_xp_layer());
if self.consoles.len() > 1 {
for layer in self.consoles.iter().skip(1) {
xp.layers.push(layer.console.to_xp_layer());
}
}
xp
}
/// Enable scanlines post-processing effect.
pub fn with_post_scanlines(&mut self, with_burn: bool) {
self.post_scanlines = true;
self.post_screenburn = with_burn;
}
}
impl Console for Rltk {
// A couple of ones we'll never use | // Implement pass-through to active console
fn at(&self, x: i32, y: i32) -> usize {
self.consoles[self.active_console].console.at(x, y)
}
fn cls(&mut self) {
self.consoles[self.active_console].console.cls();
}
fn cls_bg(&mut self, background: RGB) {
self.consoles[self.active_console]
.console
.cls_bg(background);
}
fn print(&mut self, x: i32, y: i32, output: &str) {
self.consoles[self.active_console]
.console
.print(x, y, output);
}
fn print_color(&mut self, x: i32, y: i32, fg: RGB, bg: RGB, output: &str) {
self.consoles[self.active_console]
.console
.print_color(x, y, fg, bg, output);
}
fn set(&mut self, x: i32, y: i32, fg: RGB, bg: RGB, glyph: u8) {
self.consoles[self.active_console]
.console
.set(x, y, fg, bg, glyph);
}
fn set_bg(&mut self, x: i32, y: i32, bg: RGB) {
self.consoles[self.active_console].console.set_bg(x, y, bg);
}
fn draw_box(&mut self, x: i32, y: i32, width: i32, height: i32, fg: RGB, bg: RGB) {
self.consoles[self.active_console]
.console
.draw_box(x, y, width, height, fg, bg);
}
fn draw_box_double(&mut self, x: i32, y: i32, width: i32, height: i32, fg: RGB, bg: RGB) {
self.consoles[self.active_console]
.console
.draw_box_double(x, y, width, height, fg, bg);
}
fn draw_bar_horizontal(
&mut self,
x: i32,
y: i32,
width: i32,
n: i32,
max: i32,
fg: RGB,
bg: RGB,
) {
self.consoles[self.active_console]
.console
.draw_bar_horizontal(x, y, width, n, max, fg, bg);
}
fn draw_bar_vertical(
&mut self,
x: i32,
y: i32,
height: i32,
n: i32,
max: i32,
fg: RGB,
bg: RGB,
) {
self.consoles[self.active_console]
.console
.draw_bar_vertical(x, y, height, n, max, fg, bg);
}
fn print_centered(&mut self, y: i32, text: &str) {
self.consoles[self.active_console]
.console
.print_centered(y, text);
}
fn print_color_centered(&mut self, y: i32, fg: RGB, bg: RGB, text: &str) {
self.consoles[self.active_console]
.console
.print_color_centered(y, fg, bg, text);
}
fn to_xp_layer(&self) -> XpLayer {
self.consoles[self.active_console].console.to_xp_layer()
}
fn set_offset(&mut self, x: f32, y: f32) {
self.consoles[self.active_console].console.set_offset(x, y);
}
}
/// Runs the RLTK application, calling into the provided gamestate handler every tick.
pub fn main_loop<GS: GameState>(rltk: Rltk, gamestate: GS) {
platform_specific::main_loop(rltk, gamestate);
}
/// For A-Z menus, translates the keys A through Z into 0..25
pub fn letter_to_option(key: VirtualKeyCode) -> i32 {
match key {
VirtualKeyCode::A => 0,
VirtualKeyCode::B => 1,
VirtualKeyCode::C => 2,
VirtualKeyCode::D => 3,
VirtualKeyCode::E => 4,
VirtualKeyCode::F => 5,
VirtualKeyCode::G => 6,
VirtualKeyCode::H => 7,
VirtualKeyCode::I => 8,
VirtualKeyCode::J => 9,
VirtualKeyCode::K => 10,
VirtualKeyCode::L => 11,
VirtualKeyCode::M => 12,
VirtualKeyCode::N => 13,
VirtualKeyCode::O => 14,
VirtualKeyCode::P => 15,
VirtualKeyCode::Q => 16,
VirtualKeyCode::R => 17,
VirtualKeyCode::S => 18,
VirtualKeyCode::T => 19,
VirtualKeyCode::U => 20,
VirtualKeyCode::V => 21,
VirtualKeyCode::W => 22,
VirtualKeyCode::X => 23,
VirtualKeyCode::Y => 24,
VirtualKeyCode::Z => 25,
_ => -1,
}
} | fn rebuild_if_dirty(&mut self, _gl: &glow::Context) {}
fn gl_draw(&mut self, _font: &font::Font, _shader: &Shader, _gl: &glow::Context) {}
|
init.go | package api
import "log"
// Hub Structure for Managing clients
type Hub struct {
clients map[*Client]bool
broadcast chan []byte
send chan map[string]interface{}
register chan *Client
unregister chan *Client
}
func NewHub() *Hub |
// Run Start websocket server.
func (h *Hub) Run() {
for {
select {
case client := <-h.register:
// log.Println(client.)
str := client.conn.RemoteAddr().String()
log.Println(str)
h.clients[client] = true
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
delete(h.clients, client)
close(client.send)
}
case message := <-h.broadcast:
for client := range h.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
}
func register() {
}
| {
return &Hub{
clients: make(map[*Client]bool),
broadcast: make(chan []byte),
register: make(chan *Client),
unregister: make(chan *Client),
}
} |
passwordprovider.go | //
// Copyright (c) 2021 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
package secretstore
import (
"bytes"
"context"
"fmt"
"os/exec"
"strings"
"syscall"
"github.com/edgexfoundry/go-mod-core-contracts/v2/clients/logger"
)
type PasswordProvider struct {
loggingClient logger.LoggingClient
execRunner ExecRunner
initialized bool
passwordProvider string
passwordProviderArgs []string
resolvedPath string
}
// NewPasswordProvider creates a new PasswordProvider
func NewPasswordProvider(lc logger.LoggingClient, execRunner ExecRunner) *PasswordProvider {
return &PasswordProvider{
loggingClient: lc,
execRunner: execRunner,
}
}
// SetConfiguration parses token provider configuration and resolves paths specified therein
func (p *PasswordProvider) SetConfiguration(passwordProvider string, passwordProviderArgs []string) error {
var err error
p.passwordProvider = passwordProvider
p.passwordProviderArgs = passwordProviderArgs
resolvedPath, err := p.execRunner.LookPath(p.passwordProvider)
if err != nil {
p.loggingClient.Error(fmt.Sprintf("Failed to locate %s on PATH: %s", p.passwordProvider, err.Error()))
return err
}
p.initialized = true
p.resolvedPath = resolvedPath
return nil
}
// Generate retrieves the password from the tool
func (p *PasswordProvider) Generate(ctx context.Context) (string, error) {
var outputBuffer bytes.Buffer
if !p.initialized {
err := fmt.Errorf("PasswordProvider object not initialized; call SetConfiguration() first")
return "", err
}
p.execRunner.SetStdout(&outputBuffer)
p.loggingClient.Info(fmt.Sprintf("Launching password provider %s with arguments %s", p.resolvedPath, strings.Join(p.passwordProviderArgs, " ")))
cmd := p.execRunner.CommandContext(ctx, p.resolvedPath, p.passwordProviderArgs...)
if err := cmd.Start(); err != nil {
// For example, this might occur if a shared library was missing
p.loggingClient.Error(fmt.Sprintf("%s failed to launch: %s", p.resolvedPath, err.Error()))
return "", err
}
err := cmd.Wait()
if exitError, ok := err.(*exec.ExitError); ok |
if err != nil {
p.loggingClient.Error(fmt.Sprintf("%s failed with unexpected error: %s", p.resolvedPath, err.Error()))
return "", err
}
p.loggingClient.Info("password provider exited successfully")
pw := outputBuffer.String()
pw = strings.TrimSuffix(pw, "\n")
return pw, nil
}
| {
waitStatus := exitError.Sys().(syscall.WaitStatus)
p.loggingClient.Error(fmt.Sprintf("%s terminated with non-zero exit code %d", p.resolvedPath, waitStatus.ExitStatus()))
return "", err
} |
main.go | package main
import (
"fmt"
"github.com/yeleo/world/chatroom"
"github.com/yeleo/world/poker"
"github.com/yeleo/world/wordcount"
"strconv"
"time"
)
func main() {
fmt.Println("YeLeo's world!")
fmt.Println("1:WordCount 2:Shuffle 3:PlayCard 4:ChatRoom")
var t int
fmt.Scan(&t)
start := time.Now()
switch t {
case 1:
wordcount.Do("C:/Users/M/Desktop/BigText/", "C:/Users/M/Desktop/BigText/Result-go.txt")
case 2:
deck := poker.NewDeck()
m := make(map[poker.Card][]int)
for i := 0; i < 100000; i++ {
deck.Shuffle()
for index, card := range deck.Cards {
if m[*card] == nil {
m[*card] = make([]int, 54)
}
m[*card][index]++
}
}
for key, value := range m {
if key.Mark == poker.JOKER {
fmt.Print(key.ToString() + "\t->")
} else {
fmt.Print(key.ToString() + "\t\t->")
}
for _, num := range value {
fmt.Print(strconv.Itoa(num) + "\t")
}
fmt.Print("\n")
}
case 3:
table := poker.NewTable()
for {
if len(table.Players) < 4 {
fmt.Printf("请输入玩家%d用户名:", len(table.Players)+1)
var name string
fmt.Scan(&name)
table.AddPlayer(&poker.Player{Name: name})
} else {
break
}
}
table.Deck.Shuffle()
for _, player := range table.Players {
player.Cards = table.Deck.PopCards(13)
}
//table.Banker.Cards = append(table.Banker.Cards, table.Deck.Cards)
for _, player := range table.Players {
player.SortCards()
fmt.Println(player.Name)
}
case 4:
chatroom.Start()
default:
//Pop(13) is random?Yes,though i know,test it
table := poker.NewTable()
result := make(map[*poker.Player][]int, 4)
for {
if len(table.Players) < 4 {
fmt.Printf("请输入玩家%d用户名:", len(table.Players)+1)
var name string
fmt.Scan(&name)
player := &poker.Player{Name: name}
table.AddPlayer(player)
result[player] = make([]int, 15)
} else {
break
}
}
for i := 0; i < 100000; i++ {
table.Deck = poker.NewDeck()
table.Deck.Shuffle()
for player, record := range result {
player.Cards = table.Deck.PopCards(13)
for _, card := range player.Cards {
record[int(card.Value)]++
}
}
}
for player, record := range result {
fmt.Println(player.Name)
fmt.Println(record)
}
}
fmt.Println("TotalTime:" + time.Since(start).String())
} | ||
ffi.rs | #![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(unused)]
use std::mem;
use std::os::raw::{c_char, c_double, c_int, c_longlong, c_uchar, c_void};
use std::ptr;
pub type lua_Integer = c_longlong;
pub type lua_Number = c_double;
pub enum lua_State {}
pub type lua_Alloc = unsafe extern "C" fn(
ud: *mut c_void,
ptr: *mut c_void,
osize: usize,
nsize: usize,
) -> *mut c_void;
pub type lua_KContext = *mut c_void;
pub type lua_KFunction =
unsafe extern "C" fn(state: *mut lua_State, status: c_int, ctx: lua_KContext) -> c_int;
pub type lua_CFunction = unsafe extern "C" fn(state: *mut lua_State) -> c_int;
pub type lua_Hook = unsafe extern "C" fn(state: *mut lua_State, ar: *mut lua_Debug);
#[repr(C)]
pub struct lua_Debug {
pub event: c_int,
pub name: *const c_char,
pub namewhat: *const c_char,
pub what: *const c_char,
pub source: *const c_char,
pub currentline: c_int,
pub linedefined: c_int,
pub lastlinedefined: c_int,
pub nups: c_uchar,
pub nparams: c_uchar,
pub isvararg: c_char,
pub istailcall: c_char,
pub short_src: [c_char; LUA_IDSIZE as usize],
i_ci: *mut c_void,
}
pub const LUA_OK: c_int = 0;
pub const LUA_YIELD: c_int = 1;
pub const LUA_ERRRUN: c_int = 2;
pub const LUA_ERRSYNTAX: c_int = 3;
pub const LUA_ERRMEM: c_int = 4;
pub const LUA_ERRGCMM: c_int = 5;
pub const LUA_ERRERR: c_int = 6;
pub const LUA_NOREF: c_int = -2;
pub const LUA_REFNIL: c_int = -1;
pub const LUA_MULTRET: c_int = -1;
pub const LUAI_MAXSTACK: c_int = 1_000_000;
pub const LUA_REGISTRYINDEX: c_int = -LUAI_MAXSTACK - 1000;
pub const LUA_RIDX_MAINTHREAD: lua_Integer = 1;
pub const LUA_RIDX_GLOBALS: lua_Integer = 2;
pub const LUA_IDSIZE: c_int = 60;
pub const LUA_MINSTACK: c_int = 20;
// Not actually defined in lua.h / luaconf.h
pub const LUA_MAX_UPVALUES: c_int = 255;
pub const LUA_TNONE: c_int = -1;
pub const LUA_TNIL: c_int = 0;
pub const LUA_TBOOLEAN: c_int = 1;
pub const LUA_TLIGHTUSERDATA: c_int = 2;
pub const LUA_TNUMBER: c_int = 3;
pub const LUA_TSTRING: c_int = 4;
pub const LUA_TTABLE: c_int = 5;
pub const LUA_TFUNCTION: c_int = 6;
pub const LUA_TUSERDATA: c_int = 7;
pub const LUA_TTHREAD: c_int = 8;
pub const LUA_GCSTOP: c_int = 0;
pub const LUA_GCRESTART: c_int = 1;
pub const LUA_GCCOLLECT: c_int = 2;
pub const LUA_GCCOUNT: c_int = 3;
pub const LUA_GCCOUNTB: c_int = 4;
pub const LUA_GCSTEP: c_int = 5;
pub const LUA_GCSETPAUSE: c_int = 6;
pub const LUA_GCSETSTEPMUL: c_int = 7;
pub const LUA_GCISRUNNING: c_int = 9;
pub const LUA_MASKCALL: c_int = 1;
pub const LUA_MASKRET: c_int = 2;
pub const LUA_MASKLINE: c_int = 4;
pub const LUA_MASKCOUNT: c_int = 8;
extern "C" {
pub fn lua_newstate(alloc: lua_Alloc, ud: *mut c_void) -> *mut lua_State;
pub fn lua_close(state: *mut lua_State);
pub fn lua_callk(
state: *mut lua_State,
nargs: c_int,
nresults: c_int,
ctx: lua_KContext,
k: Option<lua_KFunction>,
);
pub fn lua_pcallk(
state: *mut lua_State,
nargs: c_int,
nresults: c_int,
msgh: c_int,
ctx: lua_KContext,
k: Option<lua_KFunction>,
) -> c_int;
pub fn lua_resume(state: *mut lua_State, from: *mut lua_State, nargs: c_int) -> c_int;
pub fn lua_status(state: *mut lua_State) -> c_int;
pub fn lua_pushnil(state: *mut lua_State);
pub fn lua_pushvalue(state: *mut lua_State, index: c_int);
pub fn lua_pushboolean(state: *mut lua_State, b: c_int);
pub fn lua_pushinteger(state: *mut lua_State, n: lua_Integer);
pub fn lua_pushnumber(state: *mut lua_State, n: lua_Number);
pub fn lua_pushlstring(state: *mut lua_State, s: *const c_char, len: usize) -> *const c_char;
pub fn lua_pushstring(state: *mut lua_State, s: *const c_char) -> *const c_char;
pub fn lua_pushlightuserdata(state: *mut lua_State, data: *mut c_void);
pub fn lua_pushcclosure(state: *mut lua_State, function: lua_CFunction, n: c_int);
pub fn lua_tointegerx(state: *mut lua_State, index: c_int, isnum: *mut c_int) -> lua_Integer;
pub fn lua_tolstring(state: *mut lua_State, index: c_int, len: *mut usize) -> *const c_char;
pub fn lua_toboolean(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_tonumberx(state: *mut lua_State, index: c_int, isnum: *mut c_int) -> lua_Number;
pub fn lua_touserdata(state: *mut lua_State, index: c_int) -> *mut c_void;
pub fn lua_tothread(state: *mut lua_State, index: c_int) -> *mut lua_State;
pub fn lua_topointer(state: *mut lua_State, index: c_int) -> *const c_void;
pub fn lua_gettop(state: *const lua_State) -> c_int;
pub fn lua_settop(state: *mut lua_State, n: c_int);
pub fn lua_checkstack(state: *mut lua_State, n: c_int) -> c_int;
pub fn lua_rotate(state: *mut lua_State, index: c_int, n: c_int);
pub fn lua_copy(state: *mut lua_State, from: c_int, to: c_int);
pub fn lua_absindex(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_xmove(from: *mut lua_State, to: *mut lua_State, n: c_int);
pub fn lua_isinteger(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_isnumber(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_isstring(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_iscfunction(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_isuserdata(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_type(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_gettable(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_geti(state: *mut lua_State, index: c_int, i: lua_Integer) -> c_int;
pub fn lua_rawget(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_rawgeti(state: *mut lua_State, index: c_int, n: lua_Integer) -> c_int;
pub fn lua_rawseti(state: *mut lua_State, index: c_int, n: lua_Integer);
pub fn lua_getmetatable(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_createtable(state: *mut lua_State, narr: c_int, nrec: c_int);
pub fn lua_newuserdata(state: *mut lua_State, size: usize) -> *mut c_void;
pub fn lua_newthread(state: *mut lua_State) -> *mut lua_State;
pub fn lua_setuservalue(state: *mut lua_State, index: c_int);
pub fn lua_getuservalue(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_getupvalue(state: *mut lua_State, funcindex: c_int, n: c_int) -> *const c_char;
pub fn lua_setupvalue(state: *mut lua_State, funcindex: c_int, n: c_int) -> *const c_char;
pub fn lua_settable(state: *mut lua_State, index: c_int);
pub fn lua_rawset(state: *mut lua_State, index: c_int);
pub fn lua_setmetatable(state: *mut lua_State, index: c_int);
pub fn lua_len(state: *mut lua_State, index: c_int);
pub fn lua_rawlen(state: *mut lua_State, index: c_int) -> usize;
pub fn lua_next(state: *mut lua_State, index: c_int) -> c_int;
pub fn lua_rawequal(state: *mut lua_State, index1: c_int, index2: c_int) -> c_int;
pub fn lua_error(state: *mut lua_State) -> !;
pub fn lua_atpanic(state: *mut lua_State, panic: lua_CFunction) -> lua_CFunction;
pub fn lua_gc(state: *mut lua_State, what: c_int, data: c_int) -> c_int;
pub fn lua_getinfo(state: *mut lua_State, what: *const c_char, ar: *mut lua_Debug) -> c_int;
pub fn lua_sethook(state: *mut lua_State, f: Option<lua_Hook>, mask: c_int, count: c_int);
pub fn luaopen_base(state: *mut lua_State) -> c_int;
pub fn luaopen_coroutine(state: *mut lua_State) -> c_int;
pub fn luaopen_table(state: *mut lua_State) -> c_int;
pub fn luaopen_io(state: *mut lua_State) -> c_int;
pub fn luaopen_os(state: *mut lua_State) -> c_int;
pub fn luaopen_string(state: *mut lua_State) -> c_int;
pub fn luaopen_utf8(state: *mut lua_State) -> c_int;
pub fn luaopen_math(state: *mut lua_State) -> c_int;
pub fn luaopen_debug(state: *mut lua_State) -> c_int;
pub fn luaopen_package(state: *mut lua_State) -> c_int;
pub fn luaL_newstate() -> *mut lua_State;
pub fn luaL_openlibs(state: *mut lua_State);
pub fn luaL_requiref(
state: *mut lua_State,
modname: *const c_char,
openf: lua_CFunction,
glb: c_int,
);
pub fn luaL_loadbufferx(
state: *mut lua_State,
buf: *const c_char,
size: usize,
name: *const c_char,
mode: *const c_char,
) -> c_int;
pub fn luaL_ref(state: *mut lua_State, table: c_int) -> c_int;
pub fn luaL_unref(state: *mut lua_State, table: c_int, lref: c_int);
pub fn luaL_checkstack(state: *mut lua_State, size: c_int, msg: *const c_char);
pub fn luaL_traceback(
push_state: *mut lua_State,
state: *mut lua_State,
msg: *const c_char,
level: c_int,
);
pub fn luaL_len(push_state: *mut lua_State, index: c_int) -> lua_Integer;
pub fn luaL_tolstring(state: *mut lua_State, index: c_int, len: *mut usize) -> *const c_char;
}
// The following are re-implementations of what are macros in the Lua C API
pub unsafe fn lua_getextraspace(state: *mut lua_State) -> *mut c_void {
(state as *mut c_void).offset(-(mem::size_of::<*mut c_void>() as isize))
}
pub unsafe fn lua_pop(state: *mut lua_State, n: c_int) {
lua_settop(state, -n - 1);
}
pub unsafe fn lua_newtable(state: *mut lua_State) {
lua_createtable(state, 0, 0);
}
pub fn lua_upvalueindex(i: c_int) -> c_int {
LUA_REGISTRYINDEX - i
}
pub unsafe fn lua_pushcfunction(state: *mut lua_State, function: lua_CFunction) |
pub unsafe fn lua_tonumber(state: *mut lua_State, index: c_int) -> lua_Number {
lua_tonumberx(state, index, ptr::null_mut())
}
pub unsafe fn lua_tointeger(state: *mut lua_State, index: c_int) -> lua_Integer {
lua_tointegerx(state, index, ptr::null_mut())
}
pub unsafe fn lua_tostring(state: *mut lua_State, index: c_int) -> *const c_char {
lua_tolstring(state, index, ptr::null_mut())
}
pub unsafe fn lua_isfunction(state: *mut lua_State, index: c_int) -> c_int {
if lua_type(state, index) == LUA_TFUNCTION {
1
} else {
0
}
}
pub unsafe fn lua_istable(state: *mut lua_State, index: c_int) -> c_int {
if lua_type(state, index) == LUA_TTABLE {
1
} else {
0
}
}
pub unsafe fn lua_islightuserdata(state: *mut lua_State, index: c_int) -> c_int {
if lua_type(state, index) == LUA_TLIGHTUSERDATA {
1
} else {
0
}
}
pub unsafe fn lua_isnil(state: *mut lua_State, index: c_int) -> c_int {
if lua_type(state, index) == LUA_TNIL {
1
} else {
0
}
}
pub unsafe fn lua_isboolean(state: *mut lua_State, index: c_int) -> c_int {
if lua_type(state, index) == LUA_TBOOLEAN {
1
} else {
0
}
}
pub unsafe fn lua_isthread(state: *mut lua_State, index: c_int) -> c_int {
if lua_type(state, index) == LUA_TTHREAD {
1
} else {
0
}
}
pub unsafe fn lua_isnone(state: *mut lua_State, index: c_int) -> c_int {
if lua_type(state, index) == LUA_TNONE {
1
} else {
0
}
}
pub unsafe fn lua_insert(state: *mut lua_State, index: c_int) {
lua_rotate(state, index, 1);
}
pub unsafe fn lua_remove(state: *mut lua_State, index: c_int) {
lua_rotate(state, index, -1);
lua_pop(state, 1);
}
pub unsafe fn lua_call(state: *mut lua_State, nargs: c_int, nresults: c_int) {
lua_callk(state, nargs, nresults, ptr::null_mut(), None)
}
pub unsafe fn lua_pcall(
state: *mut lua_State,
nargs: c_int,
nresults: c_int,
msgh: c_int,
) -> c_int {
lua_pcallk(state, nargs, nresults, msgh, ptr::null_mut(), None)
}
pub unsafe fn lua_replace(state: *mut lua_State, index: c_int) {
lua_copy(state, -1, index);
lua_pop(state, 1);
}
pub unsafe fn luaL_tostring(state: *mut lua_State, index: c_int) -> *const c_char {
luaL_tolstring(state, index, ptr::null_mut())
}
| {
lua_pushcclosure(state, function, 0);
} |
canvasSVGCreator.tsx | import { Annotation, AnnotationTag, ICoordinates, number2SPId } from "./superpixelCanvas";
const React = require("react");
const { useEffect } = require("react");
const Snap = require("snapsvg-cjs");
const Direction = {
UP: 0,
RIGHT: 1,
DOWN: 2,
LEFT: 3
}
const defaultAnnotation = (id: number) => new Annotation(AnnotationTag.EMPTY, AnnotationTag.EMPTY, id);
interface CanvasSVGCreatorProps {
id: string, canvasWidth: number, canvasHeight: number, segmentationData: any,
defaultColor: string, defaultOpacity: number, defaultLineWidth: number,
onCanvasSVGCreated: (...params: any[]) => void,
}
export const CanvasSVGCreator: React.FC<CanvasSVGCreatorProps> =
({id, canvasWidth, canvasHeight, segmentationData, defaultColor, defaultOpacity, defaultLineWidth, onCanvasSVGCreated}) => {
useEffect( () => {
var s = Snap("#" + id);
if (s && s.selectAll("path").length){
s.clear();
}
// create superpixels
const keys: number[] = [];
if (keys.length === 0) {
for (let k in segmentationData) keys.push(parseInt(k));
}
keys.map(key => {
const annotation = defaultAnnotation(key);
const pixels = segmentationData[String(key)].split(",");
const superpixel = s.path(
getPathFromPoints(
pixels,
canvasWidth,
canvasHeight));
superpixel.attr({ id: number2SPId(key), key, stroke: "white", strokeWidth: defaultLineWidth,
fill: defaultColor,
opacity: defaultOpacity,
tag: annotation.tag,
name: annotation.color,
area: pixels.length });
return superpixel;
});
onCanvasSVGCreated();
});
const getPathFromPoints = (points: any, canvasWidth: number, canvasHeight :number) => {
const gridWidth = canvasWidth + 1;
const gridHeight = canvasHeight + 1;
if(points===undefined || points.length===0)
return undefined;
var currentPoint= convertImg2Grid(parseInt(points[0]), canvasWidth, gridWidth);
const startPoint = currentPoint;
var pathString = "M "+convert2Point(currentPoint, gridWidth).join(" ")+" ";
var traverseDirection = Direction.RIGHT;
var count = 0;
var coordinates = {gridWidth: gridWidth, gridHeight: gridHeight, canvasWidth: canvasWidth, canvasHeight: canvasHeight};
do{
if (traverseDirection === Direction.RIGHT && checkMembership(points, addOffset(currentPoint, [0, -1], gridWidth), coordinates)){
traverseDirection = (traverseDirection + 3 ) % 4;
[ pathString, currentPoint ] = stepForward(currentPoint, traverseDirection, pathString, gridWidth);
} else if (traverseDirection === Direction.RIGHT && checkMembership(points, currentPoint, coordinates)){
[ pathString, currentPoint ] = stepForward(currentPoint, Direction.RIGHT, pathString, gridWidth); | [ pathString, currentPoint ] = stepForward(currentPoint, Direction.DOWN, pathString, gridWidth);
} else if (traverseDirection === Direction.LEFT && checkMembership(points, addOffset(currentPoint, [-1, 0], gridWidth), coordinates)){
traverseDirection = (traverseDirection + 3 ) % 4;
[ pathString, currentPoint ] = stepForward(currentPoint, traverseDirection, pathString, gridWidth);
} else if (traverseDirection === Direction.LEFT && checkMembership(points, addOffset(currentPoint, [-1, -1], gridWidth), coordinates)){
[ pathString, currentPoint ] = stepForward(currentPoint, Direction.LEFT, pathString, gridWidth);
} else if (traverseDirection === Direction.UP && checkMembership(points, addOffset(currentPoint, [-1, -1], gridWidth), coordinates)){
traverseDirection = (traverseDirection + 3 ) % 4;
[ pathString, currentPoint ] = stepForward(currentPoint, traverseDirection, pathString, gridWidth);
} else if (traverseDirection === Direction.UP && checkMembership(points, addOffset(currentPoint, [0, -1], gridWidth), coordinates)){
[ pathString, currentPoint ] = stepForward(currentPoint, Direction.UP, pathString, gridWidth);
} else {
traverseDirection = (traverseDirection + 1 ) % 4;
}
count += 1;
} while(currentPoint !== startPoint && count < 1000);
return pathString + "Z";
}
const addOffset = (point: number, offset: number[], gridWidth: number): number => {
return point + offset[0] + (offset[1] * gridWidth);
}
const convertGrid2Img = (index: number, gridWidth: number, canvasWidth: number): number => {
return index % gridWidth + Math.floor(index / gridWidth) * canvasWidth;
}
const convertImg2Grid = (index: number, canvasWidth: number, gridWidth: number): number => {
return index % canvasWidth + Math.floor(index / canvasWidth) * gridWidth;
}
const convert2Point = (index: number, gridWidth: number): number[] => {
return [ index%gridWidth, Math.floor(index/gridWidth) ];
}
const checkMembership = (points: string[], gridPoint: number, coordinates: ICoordinates): boolean =>{
if(gridPoint < 0 || gridPoint % coordinates.gridWidth >= coordinates.canvasWidth || Math.floor(gridPoint / coordinates.gridWidth) >= coordinates.canvasHeight) // exclude grid edges
return false;
else
return points.includes(String(convertGrid2Img(gridPoint, coordinates.gridWidth, coordinates.canvasWidth)));
}
const moveAlongDirection = (point: number, direction: number, gridWidth: number): number => {
switch (direction){
case Direction.UP:
return addOffset(point, [0, -1], gridWidth);
case Direction.DOWN:
return addOffset(point, [0, 1], gridWidth);
case Direction.LEFT:
return addOffset(point, [-1, 0], gridWidth);
case Direction.RIGHT:
return addOffset(point, [1, 0], gridWidth);
default:
return point;
}
}
const stepForward = (currentPoint: number, direction: number, pathString: string, gridWidth: number): [ string, number ] => {
let newPoint = moveAlongDirection(currentPoint, direction, gridWidth);
let newPathString = pathString + "L "+ convert2Point(newPoint, gridWidth).join(" ")+" ";
return [ newPathString, newPoint ];
}
const viewBoxString = [0, 0, canvasWidth, canvasHeight].join(
" "
);
return <svg onDragStart={() => false} xmlnsXlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" key={id} id={id} colorProfile={AnnotationTag.EMPTY} name={defaultColor} viewBox={viewBoxString}></svg>
} | } else if (traverseDirection === Direction.DOWN && checkMembership(points, currentPoint, coordinates)){
traverseDirection = (traverseDirection + 3 ) % 4;
[ pathString, currentPoint ] = stepForward(currentPoint, traverseDirection, pathString, gridWidth);
} else if (traverseDirection === Direction.DOWN && checkMembership(points, addOffset(currentPoint, [-1, 0], gridWidth), coordinates)){ |
SkyAtmosphere.js | import Cartesian3 from '../Core/Cartesian3.js';
import Cartesian4 from '../Core/Cartesian4.js';
import defaultValue from '../Core/defaultValue.js';
import defined from '../Core/defined.js';
import destroyObject from '../Core/destroyObject.js';
import Ellipsoid from '../Core/Ellipsoid.js';
import EllipsoidGeometry from '../Core/EllipsoidGeometry.js';
import GeometryPipeline from '../Core/GeometryPipeline.js';
import CesiumMath from '../Core/Math.js';
import VertexFormat from '../Core/VertexFormat.js';
import BufferUsage from '../Renderer/BufferUsage.js';
import DrawCommand from '../Renderer/DrawCommand.js';
import RenderState from '../Renderer/RenderState.js';
import ShaderProgram from '../Renderer/ShaderProgram.js';
import ShaderSource from '../Renderer/ShaderSource.js';
import VertexArray from '../Renderer/VertexArray.js';
import SkyAtmosphereFS from '../Shaders/SkyAtmosphereFS.js';
import SkyAtmosphereVS from '../Shaders/SkyAtmosphereVS.js';
import BlendingState from './BlendingState.js';
import CullFace from './CullFace.js';
import SceneMode from './SceneMode.js';
/**
* An atmosphere drawn around the limb of the provided ellipsoid. Based on
* {@link https://developer.nvidia.com/gpugems/GPUGems2/gpugems2_chapter16.html|Accurate Atmospheric Scattering}
* in GPU Gems 2.
* <p>
* This is only supported in 3D. Atmosphere is faded out when morphing to 2D or Columbus view.
* </p>
*
* @alias SkyAtmosphere
* @constructor
*
* @param {Ellipsoid} [ellipsoid=Ellipsoid.WGS84] The ellipsoid that the atmosphere is drawn around.
*
* @example
* scene.skyAtmosphere = new Cesium.SkyAtmosphere();
*
* @demo {@link https://sandcastle.cesium.com/index.html?src=Sky%20Atmosphere.html|Sky atmosphere demo in Sandcastle}
*
* @see Scene.skyAtmosphere
*/
function SkyAtmosphere(ellipsoid) {
ellipsoid = defaultValue(ellipsoid, Ellipsoid.WGS84);
/**
* Determines if the atmosphere is shown.
*
* @type {Boolean}
* @default true
*/
this.show = true;
this._ellipsoid = ellipsoid;
this._command = new DrawCommand({
owner : this
});
this._spSkyFromSpace = undefined;
this._spSkyFromAtmosphere = undefined;
this._spSkyFromSpaceColorCorrect = undefined;
this._spSkyFromAtmosphereColorCorrect = undefined;
/**
* The hue shift to apply to the atmosphere. Defaults to 0.0 (no shift).
* A hue shift of 1.0 indicates a complete rotation of the hues available.
* @type {Number}
* @default 0.0
*/
this.hueShift = 0.0;
/**
* The saturation shift to apply to the atmosphere. Defaults to 0.0 (no shift).
* A saturation shift of -1.0 is monochrome.
* @type {Number}
* @default 0.0
*/
this.saturationShift = 0.0;
/**
* The brightness shift to apply to the atmosphere. Defaults to 0.0 (no shift).
* A brightness shift of -1.0 is complete darkness, which will let space show through.
* @type {Number}
* @default 0.0
*/
this.brightnessShift = 0.0;
this._hueSaturationBrightness = new Cartesian3();
// camera height, outer radius, inner radius, dynamic atmosphere color flag
var cameraAndRadiiAndDynamicAtmosphereColor = new Cartesian4();
// Toggles whether the sun position is used. 0 treats the sun as always directly overhead.
cameraAndRadiiAndDynamicAtmosphereColor.w = 0;
cameraAndRadiiAndDynamicAtmosphereColor.y = Cartesian3.maximumComponent(Cartesian3.multiplyByScalar(ellipsoid.radii, 1.025, new Cartesian3()));
cameraAndRadiiAndDynamicAtmosphereColor.z = ellipsoid.maximumRadius;
this._cameraAndRadiiAndDynamicAtmosphereColor = cameraAndRadiiAndDynamicAtmosphereColor;
var that = this;
this._command.uniformMap = {
u_cameraAndRadiiAndDynamicAtmosphereColor : function() {
return that._cameraAndRadiiAndDynamicAtmosphereColor;
},
u_hsbShift : function() {
that._hueSaturationBrightness.x = that.hueShift;
that._hueSaturationBrightness.y = that.saturationShift;
that._hueSaturationBrightness.z = that.brightnessShift;
return that._hueSaturationBrightness;
}
};
}
Object.defineProperties(SkyAtmosphere.prototype, {
/**
* Gets the ellipsoid the atmosphere is drawn around.
* @memberof SkyAtmosphere.prototype
*
* @type {Ellipsoid}
* @readonly
*/
ellipsoid : {
get : function() {
return this._ellipsoid;
}
}
});
/**
* @private
*/
SkyAtmosphere.prototype.setDynamicAtmosphereColor = function(enableLighting, useSunDirection) {
this._cameraAndRadiiAndDynamicAtmosphereColor.w = enableLighting ? (useSunDirection ? 2.0 : 1.0) : 0.0;
};
/**
* @private
*/
SkyAtmosphere.prototype.update = function(frameState) {
if (!this.show) {
return undefined;
}
var mode = frameState.mode;
if ((mode !== SceneMode.SCENE3D) &&
(mode !== SceneMode.MORPHING)) {
return undefined;
}
// The atmosphere is only rendered during the render pass; it is not pickable, it doesn't cast shadows, etc.
if (!frameState.passes.render) {
return undefined;
}
var command = this._command;
if (!defined(command.vertexArray)) {
var context = frameState.context;
var geometry = EllipsoidGeometry.createGeometry(new EllipsoidGeometry({
radii : Cartesian3.multiplyByScalar(this._ellipsoid.radii, 1.025, new Cartesian3()),
slicePartitions : 256,
stackPartitions : 256,
vertexFormat : VertexFormat.POSITION_ONLY
}));
command.vertexArray = VertexArray.fromGeometry({
context : context,
geometry : geometry,
attributeLocations : GeometryPipeline.createAttributeLocations(geometry),
bufferUsage : BufferUsage.STATIC_DRAW
});
command.renderState = RenderState.fromCache({
cull : {
enabled : true,
face : CullFace.FRONT
},
blending : BlendingState.ALPHA_BLEND,
depthMask : false
});
var vs = new ShaderSource({
defines : ['SKY_FROM_SPACE'],
sources : [SkyAtmosphereVS]
});
this._spSkyFromSpace = ShaderProgram.fromCache({
context : context,
vertexShaderSource : vs,
fragmentShaderSource : SkyAtmosphereFS
});
vs = new ShaderSource({
defines : ['SKY_FROM_ATMOSPHERE'],
sources : [SkyAtmosphereVS]
});
this._spSkyFromAtmosphere = ShaderProgram.fromCache({
context : context,
vertexShaderSource : vs,
fragmentShaderSource : SkyAtmosphereFS
});
}
// Compile the color correcting versions of the shader on demand
var useColorCorrect = colorCorrect(this);
if (useColorCorrect && (!defined(this._spSkyFromSpaceColorCorrect) || !defined(this._spSkyFromAtmosphereColorCorrect))) {
var contextColorCorrect = frameState.context;
var vsColorCorrect = new ShaderSource({
defines : ['SKY_FROM_SPACE'],
sources : [SkyAtmosphereVS]
});
var fsColorCorrect = new ShaderSource({
defines : ['COLOR_CORRECT'],
sources : [SkyAtmosphereFS]
});
this._spSkyFromSpaceColorCorrect = ShaderProgram.fromCache({
context : contextColorCorrect,
vertexShaderSource : vsColorCorrect,
fragmentShaderSource : fsColorCorrect
});
vsColorCorrect = new ShaderSource({
defines : ['SKY_FROM_ATMOSPHERE'],
sources : [SkyAtmosphereVS]
});
this._spSkyFromAtmosphereColorCorrect = ShaderProgram.fromCache({
context : contextColorCorrect,
vertexShaderSource : vsColorCorrect,
fragmentShaderSource : fsColorCorrect
});
}
var cameraPosition = frameState.camera.positionWC;
var cameraHeight = Cartesian3.magnitude(cameraPosition);
this._cameraAndRadiiAndDynamicAtmosphereColor.x = cameraHeight;
if (cameraHeight > this._cameraAndRadiiAndDynamicAtmosphereColor.y) {
// Camera in space
command.shaderProgram = useColorCorrect ? this._spSkyFromSpaceColorCorrect : this._spSkyFromSpace;
} else {
// Camera in atmosphere
command.shaderProgram = useColorCorrect ? this._spSkyFromAtmosphereColorCorrect : this._spSkyFromAtmosphere;
}
return command;
};
function | (skyAtmosphere) {
return !(CesiumMath.equalsEpsilon(skyAtmosphere.hueShift, 0.0, CesiumMath.EPSILON7) &&
CesiumMath.equalsEpsilon(skyAtmosphere.saturationShift, 0.0, CesiumMath.EPSILON7) &&
CesiumMath.equalsEpsilon(skyAtmosphere.brightnessShift, 0.0, CesiumMath.EPSILON7));
}
/**
* Returns true if this object was destroyed; otherwise, false.
* <br /><br />
* If this object was destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
*
* @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
*
* @see SkyAtmosphere#destroy
*/
SkyAtmosphere.prototype.isDestroyed = function() {
return false;
};
/**
* Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
* release of WebGL resources, instead of relying on the garbage collector to destroy this object.
* <br /><br />
* Once an object is destroyed, it should not be used; calling any function other than
* <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
* assign the return value (<code>undefined</code>) to the object as done in the example.
*
* @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
*
*
* @example
* skyAtmosphere = skyAtmosphere && skyAtmosphere.destroy();
*
* @see SkyAtmosphere#isDestroyed
*/
SkyAtmosphere.prototype.destroy = function() {
var command = this._command;
command.vertexArray = command.vertexArray && command.vertexArray.destroy();
this._spSkyFromSpace = this._spSkyFromSpace && this._spSkyFromSpace.destroy();
this._spSkyFromAtmosphere = this._spSkyFromAtmosphere && this._spSkyFromAtmosphere.destroy();
this._spSkyFromSpaceColorCorrect = this._spSkyFromSpaceColorCorrect && this._spSkyFromSpaceColorCorrect.destroy();
this._spSkyFromAtmosphereColorCorrect = this._spSkyFromAtmosphereColorCorrect && this._spSkyFromAtmosphereColorCorrect.destroy();
return destroyObject(this);
};
export default SkyAtmosphere;
| colorCorrect |
containers.py | ##############################################################################
# Copyright (c) 2017 Huawei Technologies Co.,Ltd.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
##############################################################################
from __future__ import absolute_import
import logging
import threading
import time
import uuid
import os
import glob
from six.moves import configparser
from oslo_serialization import jsonutils
from docker import Client
from api import ApiResource
from api.utils import influx
from api.database.v2.handlers import V2ContainerHandler
from api.database.v2.handlers import V2EnvironmentHandler
from yardstick.common import constants as consts
from yardstick.common import utils
from yardstick.common.utils import result_handler
from yardstick.common.utils import get_free_port
from yardstick.common.httpClient import HttpClient
LOG = logging.getLogger(__name__)
LOG.setLevel(logging.DEBUG)
environment_handler = V2EnvironmentHandler()
container_handler = V2ContainerHandler()
class V2Containers(ApiResource):
def post(self):
return self._dispatch_post()
def create_influxdb(self, args):
try:
environment_id = args['environment_id']
except KeyError:
return result_handler(consts.API_ERROR, 'environment_id must be provided')
try:
uuid.UUID(environment_id)
except ValueError:
return result_handler(consts.API_ERROR, 'invalid environment id')
try:
environment = environment_handler.get_by_uuid(environment_id)
except ValueError:
return result_handler(consts.API_ERROR, 'no such environment id')
container_info = environment.container_id
container_info = jsonutils.loads(container_info) if container_info else {}
if container_info.get('influxdb'):
return result_handler(consts.API_ERROR, 'influxdb container already exist')
name = 'influxdb-{}'.format(environment_id[:8])
port = get_free_port(consts.SERVER_IP)
container_id = str(uuid.uuid4())
LOG.info('%s will launch on : %s', name, port)
LOG.info('launch influxdb background')
args = (name, port, container_id)
thread = threading.Thread(target=self._create_influxdb, args=args)
thread.start()
LOG.info('record container in database')
container_init_data = {
'uuid': container_id,
'environment_id': environment_id,
'name': name,
'port': port,
'status': 0
}
container_handler.insert(container_init_data)
LOG.info('update container in environment')
container_info['influxdb'] = container_id
environment_info = {'container_id': jsonutils.dumps(container_info)}
environment_handler.update_attr(environment_id, environment_info)
return result_handler(consts.API_SUCCESS, {'uuid': container_id})
def _check_image_exist(self, client, t):
return any(t in a['RepoTags'][0]
for a in client.images() if a['RepoTags'])
def _create_influxdb(self, name, port, container_id):
client = Client(base_url=consts.DOCKER_URL)
try:
LOG.info('Checking if influxdb image exist')
if not self._check_image_exist(client, '%s:%s' %
(consts.INFLUXDB_IMAGE,
consts.INFLUXDB_TAG)):
LOG.info('Influxdb image not exist, start pulling')
client.pull(consts.INFLUXDB_IMAGE, tag=consts.INFLUXDB_TAG)
LOG.info('Createing influxdb container')
container = self._create_influxdb_container(client, name, port)
LOG.info('Influxdb container is created')
time.sleep(5)
container = client.inspect_container(container['Id'])
ip = container['NetworkSettings']['Networks']['bridge']['IPAddress']
LOG.debug('container ip is: %s', ip)
LOG.info('Changing output to influxdb')
self._change_output_to_influxdb(ip)
LOG.info('Config influxdb')
self._config_influxdb()
container_handler.update_attr(container_id, {'status': 1})
LOG.info('Finished')
except Exception:
container_handler.update_attr(container_id, {'status': 2})
LOG.exception('Creating influxdb failed')
def _create_influxdb_container(self, client, name, port):
ports = [port]
port_bindings = {8086: port}
restart_policy = {"MaximumRetryCount": 0, "Name": "always"}
host_config = client.create_host_config(port_bindings=port_bindings,
restart_policy=restart_policy)
LOG.info('Creating container')
container = client.create_container(image='%s:%s' %
(consts.INFLUXDB_IMAGE,
consts.INFLUXDB_TAG),
ports=ports,
name=name,
detach=True,
tty=True,
host_config=host_config)
LOG.info('Starting container')
client.start(container)
return container
def _config_influxdb(self):
try:
client = influx.get_data_db_client()
client.create_user(consts.INFLUXDB_USER,
consts.INFLUXDB_PASS,
consts.INFLUXDB_DB_NAME)
client.create_database(consts.INFLUXDB_DB_NAME)
LOG.info('Success to config influxDB')
except Exception:
LOG.exception('Config influxdb failed')
def _change_output_to_influxdb(self, ip):
utils.makedirs(consts.CONF_DIR)
parser = configparser.ConfigParser()
LOG.info('Reading output sample configuration')
parser.read(consts.CONF_SAMPLE_FILE)
LOG.info('Set dispatcher to influxdb')
parser.set('DEFAULT', 'dispatcher', 'influxdb')
parser.set('dispatcher_influxdb', 'target',
'http://{}:{}'.format(ip, 8086))
LOG.info('Writing to %s', consts.CONF_FILE)
with open(consts.CONF_FILE, 'w') as f:
parser.write(f)
def create_grafana(self, args):
try:
environment_id = args['environment_id']
except KeyError:
return result_handler(consts.API_ERROR, 'environment_id must be provided')
try:
uuid.UUID(environment_id)
except ValueError:
return result_handler(consts.API_ERROR, 'invalid environment id')
try:
environment = environment_handler.get_by_uuid(environment_id)
except ValueError:
return result_handler(consts.API_ERROR, 'no such environment id')
container_info = environment.container_id
container_info = jsonutils.loads(container_info) if container_info else {}
if not container_info.get('influxdb'):
return result_handler(consts.API_ERROR, 'influxdb not set')
if container_info.get('grafana'):
return result_handler(consts.API_ERROR, 'grafana container already exists')
name = 'grafana-{}'.format(environment_id[:8])
port = get_free_port(consts.SERVER_IP)
container_id = str(uuid.uuid4())
args = (name, port, container_id)
thread = threading.Thread(target=self._create_grafana, args=args)
thread.start()
container_init_data = {
'uuid': container_id,
'environment_id': environment_id,
'name': name,
'port': port,
'status': 0
}
container_handler.insert(container_init_data)
container_info['grafana'] = container_id
environment_info = {'container_id': jsonutils.dumps(container_info)}
environment_handler.update_attr(environment_id, environment_info)
return result_handler(consts.API_SUCCESS, {'uuid': container_id})
def _create_grafana(self, name, port, container_id):
client = Client(base_url=consts.DOCKER_URL)
try:
LOG.info('Checking if grafana image exist')
image = '{}:{}'.format(consts.GRAFANA_IMAGE, consts.GRAFANA_TAG)
if not self._check_image_exist(client, image):
LOG.info('Grafana image not exist, start pulling')
client.pull(consts.GRAFANA_IMAGE, consts.GRAFANA_TAG)
LOG.info('Createing grafana container')
container = self._create_grafana_container(client, name, port)
LOG.info('Grafana container is created')
time.sleep(5)
container = client.inspect_container(container['Id'])
ip = container['NetworkSettings']['Networks']['bridge']['IPAddress']
LOG.debug('container ip is: %s', ip)
LOG.info('Creating data source for grafana')
self._create_data_source(ip)
LOG.info('Creating dashboard for grafana')
self._create_dashboard(ip)
container_handler.update_attr(container_id, {'status': 1})
LOG.info('Finished')
except Exception:
container_handler.update_attr(container_id, {'status': 2})
LOG.exception('Create grafana failed')
def _create_dashboard(self, ip):
url = 'http://admin:admin@{}:{}/api/dashboards/db'.format(ip, 3000)
path = os.path.join(consts.REPOS_DIR, 'dashboard', 'opnfv_yardstick_tc*.json')
for i in sorted(glob.iglob(path)):
with open(i) as f:
data = jsonutils.load(f)
try:
HttpClient().post(url, {'dashboard': data})
except Exception:
LOG.exception('Create dashboard %s failed', i)
raise
def _create_data_source(self, ip):
url = 'http://admin:admin@{}:{}/api/datasources'.format(ip, 3000)
influx_conf = utils.parse_ini_file(consts.CONF_FILE).get('dispatcher_influxdb', {})
data = {
"name": "yardstick",
"type": "influxdb",
"access": "proxy",
"url": influx_conf.get('target', ''),
"password": influx_conf.get('password', ''),
"user": influx_conf.get('username', ''),
"database": "yardstick",
"basicAuth": True,
"basicAuthUser": "admin",
"basicAuthPassword": "admin",
"isDefault": False,
}
try:
HttpClient().post(url, data)
except Exception:
LOG.exception('Create datasources failed')
raise
def _create_grafana_container(self, client, name, port):
ports = [3000]
port_bindings = {3000: port}
restart_policy = {"MaximumRetryCount": 0, "Name": "always"}
host_config = client.create_host_config(port_bindings=port_bindings,
restart_policy=restart_policy)
LOG.info('Creating container')
container = client.create_container(image='%s:%s' %
(consts.GRAFANA_IMAGE,
consts.GRAFANA_TAG),
name=name,
ports=ports,
detach=True,
tty=True,
host_config=host_config)
LOG.info('Starting container')
client.start(container)
return container
class V2Container(ApiResource):
def get(self, container_id):
try:
uuid.UUID(container_id)
except ValueError:
return result_handler(consts.API_ERROR, 'invalid container id')
try:
container = container_handler.get_by_uuid(container_id)
except ValueError: | info = client.inspect_container(name)
data = {
'name': name,
'status': info.get('State', {}).get('Status', 'error'),
'time': info.get('Created'),
'port': container.port
}
return result_handler(consts.API_SUCCESS, {'container': data})
def delete(self, container_id):
try:
uuid.UUID(container_id)
except ValueError:
return result_handler(consts.API_ERROR, 'invalid container id')
try:
container = container_handler.get_by_uuid(container_id)
except ValueError:
return result_handler(consts.API_ERROR, 'no such container id')
environment_id = container.environment_id
client = Client(base_url=consts.DOCKER_URL)
LOG.info('delete container: %s', container.name)
try:
client.remove_container(container.name, force=True)
except Exception:
LOG.exception('delete container failed')
return result_handler(consts.API_ERROR, 'delete container failed')
LOG.info('delete container in database')
container_handler.delete_by_uuid(container_id)
LOG.info('update container in environment')
environment = environment_handler.get_by_uuid(environment_id)
container_info = jsonutils.loads(environment.container_id)
key = next((k for k, v in container_info.items() if v == container_id))
container_info.pop(key)
environment_delete_data = {
'container_id': jsonutils.dumps(container_info)
}
environment_handler.update_attr(environment_id, environment_delete_data)
return result_handler(consts.API_SUCCESS, {'container': container_id}) | return result_handler(consts.API_ERROR, 'no such container id')
name = container.name
client = Client(base_url=consts.DOCKER_URL) |
test_nlp.py | def test_extraction():
from sematch.nlp import Extraction
from sematch.semantic.sparql import EntityFeatures
upm = EntityFeatures().features('http://dbpedia.org/resource/Technical_University_of_Madrid')
extract = Extraction() | cats = extract.category_features(upm['category'])
assert extract.category2words(cats) is not None
def test_rake():
from sematch.nlp import RAKE
from sematch.semantic.sparql import EntityFeatures
upm = EntityFeatures().features('http://dbpedia.org/resource/Technical_University_of_Madrid')
rake = RAKE()
assert rake.extract(upm['abstract']) is not None
def test_TFIDF():
corpus = ['This is the first document.','This is the second second document.','And the third one.','Is this the first document?',]
from sematch.nlp import TFIDF
tfidf = TFIDF(corpus)
assert tfidf.idf('document') is not None
assert tfidf.tfidf('I need a document and second') is not None
def test_Spacy():
from sematch.nlp import SpaCyNLP
sy = SpaCyNLP()
print sy.pos_tag(u'This is the second second document.')
def test_feature_extractor():
from sematch.nlp import FeatureExtractor
from sematch.nlp import EntityFeature
from sematch.nlp import SpaCyNLP
from sematch.utility import FileIO
import itertools
sy = SpaCyNLP()
w_extractor = FeatureExtractor(sy.pos_tag)
features = EntityFeature.load(feature_dict_file='models/query_features.json')
query = FileIO.read_json_file('dataset/ned/query_ned_cleaned.txt')
candidates = list(itertools.chain.from_iterable(map(lambda x: x['candidate'], query)))
set_candidates = list(set(candidates))
for can in set_candidates[:10]:
print w_extractor.entity_word_features([can], features)
def test_entity_feature():
from sematch.utility import FileIO
from sematch.nlp import EntityFeature
query = FileIO.read_json_file('dataset/ned/query_ned_cleaned.txt')
question = FileIO.read_json_file('dataset/ned/question_ned_cleaned.txt')
tweet = FileIO.read_json_file('dataset/ned/tweet_ned_cleaned.txt')
import itertools
candidates = list(itertools.chain.from_iterable(map(lambda x:x['candidate'], question)))
set_candidates = list(set(candidates))
print len(set_candidates)
EntityFeature.candidate_features(set_candidates, export_file='models/question_features.json')
test_feature_extractor() | assert extract.extract_nouns(upm['abstract']) is not None
assert extract.extract_verbs(upm['abstract']) is not None
assert extract.extract_chunks_doc(upm['abstract']) is not None |
gulpfile.js | var SRC = 'app' ,
REQUIREJS = 'build-requirejs' ,
DIST = 'build' ,
CDN = 'cdn' ,
// 如果不是假值,那么这个值会作为 cdn 前缀追加到需要加载的文件里。
// 注意:最后面的斜线 / 一定要加上
CDN_PREFIX = 'https://dn-lmk123.qbox.me/angularjs-requirejs-rjs-md5/' ,
//CDN_PREFIX = 'http://localhost:61111/angularjs-requirejs-rjs-md5/cdn/' ,
//CDN_PREFIX = false ,
paths = {
// 默认情况下所有 js 文件都是由 requireJS 加载的是不需要加前缀的,所以这里要列出不是由 requireJS 加载的 js 文件
jsNotLoadByRequireJS : [ 'bootstrap.js' , 'vendor/require/require.js' ] ,
// 默认情况下所有 css 文件都是要加前缀的,但是由 requireJS 加载的 css 文件不用加
cssLoadByRequireJS : [ /^styles\/.*/ ] ,
js : [
REQUIREJS + '/**/*.js'
] ,
cssFiles : [ REQUIREJS + '/**/*.css' ] ,
htmlFiles : REQUIREJS + '/**/*.html' ,
imageFiles : REQUIREJS + '/**/*.{png,jpg,gif}' ,
copyFiles : [
REQUIREJS + '/**/*' ,
'!' + REQUIREJS + '/**/*.{js,css,html}' ,
'!' + REQUIREJS + '/build.txt' ,
'!' + REQUIREJS + '/vendor/bootstrap/config.json'
]
} ,
fs = require( 'fs' ) ,
gulp = require( 'gulp' ) ,
minifyJS = require( 'gulp-uglify' ) ,
minifyCSS = require( 'gulp-minify-css' ) ,
minifyHTML = require( 'gulp-htmlmin' ) ,
//changed = require( 'gulp-changed' ) ,
concat = require( 'gulp-concat' ) ,
deleteFile = require( 'del' ) ,
revall = new (require( 'gulp-rev-all' ))( {
dontRenameFile : [ /^\/index\.html$/g ] ,
dontSearchFile : [ /^\/vendor\/angular\/.*/g , /^\/vendor\/require\/.*/g ] ,
transformFilename : function ( file , hash ) {
return hash + file.path.slice( file.path.lastIndexOf( '.' ) );
} ,
transformPath : function ( rev , source , file ) {
//if ( rev !== file.revPath ) {
// console.log( 'debugger here' );
//}
if ( CDN_PREFIX ) {
var filePath = file.revPathOriginal.slice( file.base.length ).replace( /\\/g , '/' ) ,
ext = file.revFilenameExtOriginal;
// 不是由 requireJS 加载的 js 文件要加前缀,由 requireJS 加载的 css 文件不要加前缀
if (
('.js' === ext && !matchArray( filePath , paths.jsNotLoadByRequireJS ))
||
('.css' === ext && matchArray( filePath , paths.cssLoadByRequireJS ))
) {
return rev;
}
/**
* 为什么要判断文件是否存在?这是不是多此一举?
*
* 之所以要这么做,是因为如果 css 文件里有引用相对路径的其他资源(比如图片、字体),
* 那么产生的路径是错误的,而这些文件其实不需要加 cdn 前缀,因为只要引用它们的 css 文件加了前
* 缀,那此 css 所引用的相对路径的文件也会从 cdn 上加载
*/
var r;
try {
// 如果文件存在,则加上 cdn
fs.statSync( DIST + '/' + source );
r = CDN_PREFIX + rev;
}
catch ( e ) {
// 否则不加
r = rev;
}
return r;
} else {
return rev;
}
}
} );
gulp.task( 'clean' , clean );
gulp.task( 'requirejs' , [ 'clean' ] , requirejs ); //第一步: 从 SRC 把文件合并至 REQUIREJS 文件夹
// 第二步:下面四个操作是并行的,用于将 REQUIREJS 文件夹下的文件精简至 DIST 文件夹
gulp.task( 'js' , [ 'requirejs' ] , js );
gulp.task( 'css' , [ 'requirejs' ] , css );
gulp.task( 'html' , [ 'requirejs' ] , html );
gulp.task( 'copy' , [ 'requirejs' ] , copy );
// 第三步:将 DIST 文件夹下的文件打上 md5 签名并输出到 CDN 文件夹
gulp.task( 'default' , [ 'js' , 'css' , 'html' , 'copy' ] , md5 );
function clean() {
return deleteFile( [ DIST , REQUIREJS , CDN ] );
}
function js() {
return gulp.src( paths.js )
//.pipe( changed( DIST ) )
.pipe( minifyJS() )
.pipe( gulp.dest( DIST ) );
}
function css() {
return gulp.src( paths.cssFiles )
//.pipe( changed( DIST ) )
.pipe( minifyCSS() )
.pipe( gulp.dest( DIST ) );
}
function html() {
return gulp.src( paths.htmlFiles , { base : REQUIREJS } )
//.pipe( changed( DIST ) )
.pipe( minifyHTML( {
removeComments : true ,
collapseWhitespace : true
} ) )
.pipe( gulp.dest( DIST ) );
}
function copy() {
return gulp.src( paths.copyFiles )
//.pipe( changed( DIST ) )
.pipe( gulp.dest( DIST ) );
}
function md5() {
return gulp.src( DIST + '/**' )
.pipe( revall.revision() )
.pipe( gulp.dest( CDN ) );
//.pipe( revall.manifestFile() )
//.pipe( gulp.dest( CDN ) );
}
function requirejs( done ) {
var r = require( 'requirejs' );
r.optimize( {
| appDir : SRC ,
baseUrl : './' ,
dir : REQUIREJS ,
optimize : 'none' ,
optimizeCss : 'none' ,
removeCombined : true ,
mainConfigFile : SRC + '/bootstrap.js' ,
modules : [
{
name : "bootstrap"
}
] ,
logLevel : 1
} , function () {
done();
} );
}
/**
* 匹配一个数组,数组可能有正则
* @param {String} value - 要匹配的值
* @param {Array} arr - 匹配数组
* @returns {boolean} - 有一个匹配项则返回 true,否则返回 false
*/
function matchArray( value , arr ) {
return arr.some( function ( v ) {
if ( 'string' === typeof v ) {
return v === value;
}
return v.test( value );
} );
}
| |
main.go | package main
import (
"flag"
"fmt"
"io/ioutil"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
"github.com/go-kit/kit/log"
"github.com/hashicorp/hcl"
gitlab "github.com/xanzy/go-gitlab"
"github.com/cosminilie/gitbot"
"github.com/cosminilie/gitbot/plugins"
_ "github.com/cosminilie/gitbot/plugins/droprights"
_ "github.com/cosminilie/gitbot/plugins/lgtm"
)
var (
//Vars that need to be set at build time using :
//go build -ldflags "-X main.majorVersion=1 -X main.minorVersion=0 -X main.gitVersion=c553786277bf05c0aa0320b7c7fc8249c73a27c0
// -X main.buildDate=`date -u +%Y-%m-%d_%H:%M:%S`" -o BackupService
majorVersion = "MajorVersion not set"
minorVersion = "MinorVersion not set"
gitVersion = "GitVersion not set"
buildDate = "BuildDate not set"
)
//Config struct in loading HCL configuration
type Config struct {
Token string `hcl:"token"`
GitURL string `hcl:"git-api-URL"`
DefaultApprovers []string `hcl:"default-approvers"`
Repos []plugins.Repo `hcl:"repo,expand"`
}
func | () {
var (
debugAddr = flag.String("debug.addr", ":9090", "Debug and metrics listen address")
showVersion = flag.Bool("version", false, "Display build version")
configFile = flag.String("config", "/etc/githook.conf", "GitLab Hook config file")
)
flag.Parse()
if *showVersion {
fmt.Printf("Major Version: %s\t Minor Version: %s\nGitVersion: %s\t,BuildDate: %s\n", majorVersion, minorVersion, gitVersion, buildDate)
os.Exit(0)
}
// Logging domain.
var logger log.Logger
{
logger = log.NewLogfmtLogger(os.Stdout)
logger = log.NewContext(logger).With("ts", log.DefaultTimestampUTC)
logger = log.NewContext(logger).With("caller", log.DefaultCaller)
}
logger.Log("msg", "hello")
defer logger.Log("msg", "goodbye")
//global error chan
errc := make(chan error)
// Interrupt handler.
go func() {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
errc <- fmt.Errorf("%s", <-c)
}()
// Business domain.
//create config object
content, err := ioutil.ReadFile(*configFile)
if err != nil {
fmt.Printf("Error loading configuration file %s. Failed with: %s\n", *configFile, err)
os.Exit(1)
}
conf := &Config{}
hclParseTree, err := hcl.ParseBytes(content)
if err != nil {
fmt.Printf("Failed to parse configuration data: %s\n", err)
os.Exit(1)
}
if err := hcl.DecodeObject(&conf, hclParseTree); err != nil {
fmt.Printf("Failed to decode configuration data: %s\n", err)
os.Exit(1)
}
//fmt.Println("Config file is: ", *configFile)
//create gilabclient
var client *gitlab.Client
httpclient := &http.Client{
Timeout: 10 * time.Second,
}
client = gitlab.NewClient(httpclient, conf.Token)
client.SetBaseURL(conf.GitURL)
//create service
var service gitbot.Service
svclogger := log.NewContext(logger).With("service", "basicservice")
service = gitbot.NewBasicService(svclogger, client, conf.Repos, conf.DefaultApprovers)
go func() {
for e := range service.GetErrors() {
errc <- e
}
}()
//business domain
httplogger := log.NewContext(logger).With("transport", "HTTP")
httpserver := &gitbot.Server{
Logger: httplogger,
Service: service,
}
// Debug listener.
go func() {
m := http.NewServeMux()
m.Handle("/debug/pprof/", http.HandlerFunc(pprof.Index))
m.Handle("/debug/pprof/cmdline", http.HandlerFunc(pprof.Cmdline))
m.Handle("/debug/pprof/profile", http.HandlerFunc(pprof.Profile))
m.Handle("/debug/pprof/symbol", http.HandlerFunc(pprof.Symbol))
m.Handle("/debug/pprof/trace", http.HandlerFunc(pprof.Trace))
logger.Log("addr", *debugAddr)
errc <- http.ListenAndServe(*debugAddr, m)
}()
// HTTP transport.
go func() {
logger.Log("addr", ":9091")
m := http.NewServeMux()
m.Handle("/hook", httpserver)
errc <- http.ListenAndServe(":9091", m)
}()
fmt.Println(<-errc)
}
| main |
expected_options.py | # This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.txt for license information
# See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
from __future__ import absolute_import, unicode_literals
import multiprocessing
from build_swift import argparse
from build_swift import defaults
from swift_build_support.swift_build_support import targets
__all__ = [
'HelpOption',
'SetOption',
'SetTrueOption',
'SetFalseOption',
'DisableOption',
'EnableOption',
'ChoicesOption',
'IntOption',
'StrOption',
'PathOption',
'AppendOption',
'UnsupportedOption',
'IgnoreOption',
'EXPECTED_OPTIONS',
'EXPECTED_DEFAULTS',
]
# -----------------------------------------------------------------------------
EXPECTED_DEFAULTS = {
'android': False,
'android_api_level': '21',
'android_deploy_device_path': '/data/local/tmp',
'android_icu_i18n': None,
'android_icu_i18n_include': None,
'android_icu_uc': None,
'android_icu_uc_include': None,
'android_icu_data': None,
'android_ndk': None,
'android_ndk_gcc_version': '4.9',
'android_arch': 'armv7',
'assertions': True,
'benchmark': False,
'benchmark_num_o_iterations': 3,
'benchmark_num_onone_iterations': 3,
'build_android': False,
'build_args': [],
'build_benchmarks': True,
'build_clang_tools_extra': True,
'build_cygwin': True,
'build_external_benchmarks': False,
'build_foundation': False,
'build_cmark': True,
'build_swift': True,
'build_llvm': True,
'build_freebsd': True,
'build_ios': True,
'build_ios_device': False,
'build_ios_simulator': False,
'build_jobs': multiprocessing.cpu_count(),
'build_libdispatch': False,
'build_libicu': False,
'build_linux': True,
'build_llbuild': False,
'build_lldb': False,
'build_libcxx': False,
'build_ninja': False,
'build_osx': True,
'build_playgroundsupport': False,
'build_runtime_with_host_compiler': False,
'build_stdlib_deployment_targets': ['all'],
'build_subdir': None,
'build_swift_dynamic_sdk_overlay': True,
'build_swift_dynamic_stdlib': True,
'build_swift_inspect': False,
'build_swift_static_sdk_overlay': False,
'build_swift_static_stdlib': False,
'build_swift_stdlib_unittest_extra': False,
'build_swiftpm': False,
'build_swift_driver': False,
'build_early_swift_driver': True,
'build_swiftsyntax': False,
'build_libparser_only': False,
'build_skstresstester': False,
'build_swiftformat': False,
'build_swiftevolve': False,
'build_indexstoredb': False,
'test_indexstoredb_sanitize_all': False,
'test_sourcekitlsp_sanitize_all': False,
'build_sourcekitlsp': False,
'install_swiftpm': False,
'install_swiftsyntax': False,
'install_swift_driver': False,
'swiftsyntax_verify_generated_files': False,
'install_playgroundsupport': False,
'install_sourcekitlsp': False,
'install_skstresstester': False,
'install_swiftevolve': False,
'build_toolchainbenchmarks': False,
'build_tvos': True,
'build_tvos_device': False,
'build_tvos_simulator': False,
'build_variant': 'Debug',
'build_watchos': True,
'build_watchos_device': False,
'build_watchos_simulator': False,
'build_xctest': False,
'cmake_c_launcher': None,
'cmake_cxx_launcher': None,
'clang_compiler_version': None,
'clang_profile_instr_use': None,
'clang_user_visible_version': defaults.CLANG_USER_VISIBLE_VERSION,
'clean': False,
'cmake': None,
'cmake_generator': 'Ninja',
'cmark_assertions': True,
'cmark_build_variant': 'Debug',
'compiler_vendor': defaults.COMPILER_VENDOR,
'coverage_db': None,
'cross_compile_hosts': [],
'darwin_deployment_version_ios':
defaults.DARWIN_DEPLOYMENT_VERSION_IOS,
'darwin_deployment_version_osx':
defaults.DARWIN_DEPLOYMENT_VERSION_OSX,
'darwin_deployment_version_tvos':
defaults.DARWIN_DEPLOYMENT_VERSION_TVOS,
'darwin_deployment_version_watchos':
defaults.DARWIN_DEPLOYMENT_VERSION_WATCHOS,
'darwin_symroot_path_filters': [],
'darwin_xcrun_toolchain': None,
'distcc': False,
'sccache': False,
'dry_run': False,
'dsymutil_jobs': defaults.DSYMUTIL_JOBS,
'enable_asan': False,
'enable_experimental_differentiable_programming': True,
'enable_experimental_concurrency': True,
'enable_lsan': False,
'enable_sanitize_coverage': False,
'disable_guaranteed_normal_arguments': False,
'enable_stdlibcore_exclusivity_checking': False,
'enable_tsan': False,
'enable_tsan_runtime': False,
'enable_ubsan': False,
'export_compile_commands': False,
'extra_cmake_options': [],
'extra_swift_args': [],
'force_optimized_typechecker': False,
'foundation_build_variant': 'Debug',
'host_cc': None,
'host_cxx': None,
'host_libtool': None,
'host_lipo': None,
'host_target': targets.StdlibDeploymentTarget.host_target().name,
'host_test': False,
'only_executable_test': False,
'only_non_executable_test': False,
'infer_dependencies': False,
'install_prefix': targets.install_prefix(),
'install_symroot': None,
'install_destdir': None,
'install_all': False,
'ios': False,
'ios_all': False,
'legacy_impl': False,
'libdispatch_build_variant': 'Debug',
'libicu_build_variant': 'Debug',
'lit_args': '-sv',
'llbuild_assertions': True,
'lldb_assertions': True,
'lldb_build_variant': 'Debug',
'lldb_build_with_xcode': '0',
'llvm_assertions': True,
'llvm_build_variant': 'Debug',
'llvm_ninja_targets': [],
'llvm_ninja_targets_for_cross_compile_hosts': [],
'llvm_max_parallel_lto_link_jobs':
defaults.LLVM_MAX_PARALLEL_LTO_LINK_JOBS,
'llvm_targets_to_build': 'X86;ARM;AArch64;PowerPC;SystemZ;Mips',
'tsan_libdispatch_test': False,
'long_test': False,
'lto_type': None,
'maccatalyst': False,
'maccatalyst_ios_tests': False,
'native_clang_tools_path': None,
'native_llvm_tools_path': None,
'native_swift_tools_path': None,
'dump_config': False,
'relocate_xdg_cache_home_under_build_subdir': False,
'show_sdks': False,
'skip_build': False,
'skip_local_build': False,
'stdlib_deployment_targets': None,
'stress_test': False,
'swift_analyze_code_coverage': defaults.SWIFT_ANALYZE_CODE_COVERAGE,
'swift_assertions': True,
'swift_build_variant': 'Debug',
'swift_compiler_version': None,
'swift_disable_dead_stripping': False,
'swift_darwin_module_archs': None,
'swift_darwin_supported_archs': None,
'swift_stdlib_assertions': True,
'swift_stdlib_build_variant': 'Debug',
'swift_tools_max_parallel_lto_link_jobs':
defaults.SWIFT_MAX_PARALLEL_LTO_LINK_JOBS,
'swift_user_visible_version': defaults.SWIFT_USER_VISIBLE_VERSION,
'symbols_package': None,
'clean_llbuild': True,
'clean_swiftpm': True,
'clean_swift_driver': True,
'clean_early_swift_driver': False,
'test': None,
'test_early_swift_driver': None,
'test_android': False,
'test_android_host': False,
'test_cygwin': False,
'test_freebsd': False,
'test_ios': False,
'test_ios_32bit_simulator': False,
'test_watchos_32bit_simulator': True,
'test_ios_host': False,
'test_ios_simulator': False,
'test_linux': False,
'test_optimize_for_size': None,
'test_optimize_none_with_implicit_dynamic': None,
'test_optimized': None,
'test_osx': False,
'test_paths': [],
'test_swift_inspect': True,
'test_tvos': False,
'test_tvos_host': False,
'test_tvos_simulator': False,
'test_watchos': False,
'test_watchos_host': False,
'test_watchos_simulator': False,
'test_playgroundsupport': True,
'test_swiftpm': False,
'test_swift_driver': False,
'test_swiftsyntax': False,
'test_indexstoredb': False,
'test_sourcekitlsp': False,
'test_skstresstester': False,
'test_swiftformat': False,
'test_swiftevolve': False,
'test_toolchainbenchmarks': False,
'tvos': False,
'tvos_all': False,
'validation_test': None,
'verbose_build': False,
'watchos': False,
'watchos_all': False,
'llvm_install_components': defaults.llvm_install_components(),
}
# -----------------------------------------------------------------------------
def _sanitize_option_string(option_string):
if option_string.startswith('--'):
return option_string[2:].replace('-', '_')
if len(option_string) == 2 and option_string[0] == '-':
return option_string[1]
raise ValueError('invalid option_string format: ' + option_string)
class _BaseOption(object):
def __init__(self, option_string, dest=None, default=None):
if dest is None:
dest = _sanitize_option_string(option_string)
if default is None:
default = EXPECTED_DEFAULTS.get(dest, None)
self.option_string = option_string
self.dest = dest
self.default = default
def sanitized_string(self):
return _sanitize_option_string(self.option_string)
class HelpOption(_BaseOption):
"""Option that prints the help message and exits."""
pass
class SetOption(_BaseOption):
"""Option that accepts no arguments, setting the destination to a
hard-coded value or None.
"""
def __init__(self, *args, **kwargs):
self.value = kwargs.pop('value', None)
super(SetOption, self).__init__(*args, **kwargs)
class SetTrueOption(_BaseOption):
"""Option that accepts no arguments, setting the destination value to True
if parsed and defaulting to False otherwise.
"""
pass
class SetFalseOption(_BaseOption):
"""Option that accepts no arguments, setting the destination value to False
if parsed and defaulting to True otherwise.
"""
pass
class EnableOption(_BaseOption):
"""Option that sets the destination to True when parsed and False by default.
Can be toggled True or False with an optional bool argument.
"""
pass
class DisableOption(_BaseOption):
"""Option that sets the destination to False when parsed and True by default.
Can be toggled True or False with an optional bool argument, which is then
negated. Thus if an option is passed the value 'True' it will set the
destination to False and vice versa.
"""
pass
class ChoicesOption(_BaseOption):
"""Option that accepts an argument from a predifined list of choices."""
def __init__(self, *args, **kwargs):
self.choices = kwargs.pop('choices', None)
super(ChoicesOption, self).__init__(*args, **kwargs)
class IntOption(_BaseOption):
"""Option that accepts an int argument."""
pass
class StrOption(_BaseOption):
"""Option that accepts a str argument."""
pass
class PathOption(_BaseOption):
"""Option that accepts a path argument."""
pass
class AppendOption(_BaseOption):
"""Option that can be called more than once to append argument to internal
list.
"""
pass
class UnsupportedOption(_BaseOption):
"""Option that is not supported."""
pass
class IgnoreOption(_BaseOption):
"""Option that should be ignored when generating tests. Instead a test
should be written manually as the behavior cannot or should not be auto-
generated.
"""
pass
class BuildScriptImplOption(_BaseOption):
"""Option that gets forwarded to build-script-impl by migration.py and is
only listed for disambiguation by argparse.
"""
pass
# -----------------------------------------------------------------------------
EXPECTED_OPTIONS = [
# Ignore the help options since they always call sys.exit(0)
HelpOption('-h', dest='help', default=argparse.SUPPRESS),
HelpOption('--help', dest='help', default=argparse.SUPPRESS),
SetOption('--debug', dest='build_variant', value='Debug'),
SetOption('--debug-cmark', dest='cmark_build_variant', value='Debug'),
SetOption('--debug-foundation',
dest='foundation_build_variant', value='Debug'),
SetOption('--debug-libdispatch',
dest='libdispatch_build_variant', value='Debug'),
SetOption('--debug-libicu', dest='libicu_build_variant', value='Debug'),
SetOption('--debug-lldb', dest='lldb_build_variant', value='Debug'),
SetOption('--lldb-build-with-xcode', dest='lldb_build_with_xcode',
value='1'),
SetOption('--lldb-build-with-cmake', dest='lldb_build_with_xcode',
value='0'),
SetOption('--debug-llvm', dest='llvm_build_variant', value='Debug'),
SetOption('--debug-swift', dest='swift_build_variant', value='Debug'),
SetOption('--debug-swift-stdlib',
dest='swift_stdlib_build_variant', value='Debug'),
SetOption('--eclipse',
dest='cmake_generator', value='Eclipse CDT4 - Ninja'),
SetOption('--make', dest='cmake_generator', value='Unix Makefiles'),
SetOption('--release', dest='build_variant', value='Release'),
SetOption('--release-debuginfo',
dest='build_variant', value='RelWithDebInfo'),
SetOption('--min-size-release',
dest='build_variant', value='MinSizeRel'),
SetOption('--xcode', dest='cmake_generator', value='Xcode'),
SetOption('-R', dest='build_variant', value='Release'),
SetOption('-d', dest='build_variant', value='Debug'),
SetOption('-e', dest='cmake_generator', value='Eclipse CDT4 - Ninja'),
SetOption('-m', dest='cmake_generator', value='Unix Makefiles'),
SetOption('-r', dest='build_variant', value='RelWithDebInfo'),
SetOption('-x', dest='cmake_generator', value='Xcode'),
# FIXME: Convert these options to set_true actions
SetOption('--assertions', value=True),
SetOption('--cmark-assertions', value=True),
SetOption('--lldb-assertions', value=True),
SetOption('--llvm-assertions', value=True),
SetOption('--llbuild-assertions', value=True),
SetOption('--swift-assertions', value=True),
SetOption('--swift-stdlib-assertions', value=True),
SetOption('-T', dest='validation_test', value=True),
SetOption('-o', dest='test_optimized', value=True),
SetOption('-s', dest='test_optimize_for_size', value=True),
SetOption('-y',
dest='test_optimize_none_with_implicit_dynamic', value=True),
SetOption('-t', dest='test', value=True),
SetOption('-a', dest='assertions', value=True),
# FIXME: Convert these options to set_false actions
SetOption('--no-assertions', dest='assertions', value=False),
SetOption('-A', dest='assertions', value=False),
SetOption('--no-lldb-assertions', dest='lldb_assertions', value=False),
SetOption('--no-llvm-assertions', dest='llvm_assertions', value=False),
SetOption('--no-llbuild-assertions',
dest='llbuild_assertions', value=False),
SetOption('--no-swift-assertions', dest='swift_assertions', value=False),
SetOption('--no-swift-stdlib-assertions',
dest='swift_stdlib_assertions', value=False),
SetOption('--skip-ios', dest='ios', value=False),
SetOption('--skip-tvos', dest='tvos', value=False),
SetOption('--skip-watchos', dest='watchos', value=False),
SetOption('--skip-test-early-swift-driver',
dest='test_early_swift_driver', value=False),
SetTrueOption('--benchmark'),
SetTrueOption('--clean'),
SetTrueOption('--dry-run'),
SetTrueOption('--dump-config'),
SetTrueOption('--disable-guaranteed-normal-arguments'),
SetTrueOption('--enable-stdlibcore-exclusivity-checking'),
SetTrueOption('--force-optimized-typechecker'),
SetTrueOption('--ios'),
SetTrueOption('--llbuild', dest='build_llbuild'),
SetTrueOption('--lldb', dest='build_lldb'),
SetTrueOption('--libcxx', dest='build_libcxx'),
SetTrueOption('--maccatalyst', dest='maccatalyst'),
SetTrueOption('--maccatalyst-ios-tests', dest='maccatalyst_ios_tests'),
SetTrueOption('--playgroundsupport', dest='build_playgroundsupport'),
SetTrueOption('--install-playgroundsupport',
dest='install_playgroundsupport'),
SetTrueOption('--skip-build'),
SetTrueOption('--swiftpm', dest='build_swiftpm'),
SetTrueOption('--swift-driver', dest='build_swift_driver'),
SetTrueOption('--swiftsyntax', dest='build_swiftsyntax'),
SetTrueOption('--build-libparser-only', dest='build_libparser_only'),
SetTrueOption('--skstresstester', dest='build_skstresstester'),
SetTrueOption('--swiftformat', dest='build_swiftformat'),
SetTrueOption('--swiftevolve', dest='build_swiftevolve'),
SetTrueOption('-B', dest='benchmark'),
SetTrueOption('-S', dest='skip_build'),
SetTrueOption('-b', dest='build_llbuild'),
SetTrueOption('-c', dest='clean'),
SetTrueOption('-i', dest='ios'),
SetTrueOption('-l', dest='build_lldb'),
SetTrueOption('-n', dest='dry_run'),
SetTrueOption('-p', dest='build_swiftpm'),
SetTrueOption('--legacy-impl', dest='legacy_impl'),
SetTrueOption('--infer', dest='infer_dependencies'),
EnableOption('--android'),
EnableOption('--build-external-benchmarks'),
EnableOption('--build-ninja'),
EnableOption('--build-runtime-with-host-compiler'),
EnableOption('--build-swift-dynamic-sdk-overlay'),
EnableOption('--build-swift-dynamic-stdlib'),
EnableOption('--build-swift-static-sdk-overlay'),
EnableOption('--build-swift-static-stdlib'),
EnableOption('--build-swift-stdlib-unittest-extra'),
EnableOption('--distcc'),
EnableOption('--sccache'),
EnableOption('--enable-asan'),
EnableOption('--enable-experimental-differentiable-programming'),
EnableOption('--enable-experimental-concurrency'),
EnableOption('--enable-lsan'),
EnableOption('--enable-sanitize-coverage'),
EnableOption('--enable-tsan'),
EnableOption('--enable-tsan-runtime'),
EnableOption('--enable-ubsan'),
EnableOption('--export-compile-commands'),
EnableOption('--foundation', dest='build_foundation'),
EnableOption('--host-test'),
EnableOption('--only-executable-test'),
EnableOption('--only-non-executable-test'),
EnableOption('--libdispatch', dest='build_libdispatch'),
EnableOption('--libicu', dest='build_libicu'),
EnableOption('--indexstore-db', dest='build_indexstoredb'),
EnableOption('--test-indexstore-db-sanitize-all',
dest='test_indexstoredb_sanitize_all'),
EnableOption('--sourcekit-lsp', dest='build_sourcekitlsp'),
EnableOption('--test-sourcekit-lsp-sanitize-all',
dest='test_sourcekitlsp_sanitize_all'),
EnableOption('--install-swiftsyntax', dest='install_swiftsyntax'),
EnableOption('--swiftsyntax-verify-generated-files',
dest='swiftsyntax_verify_generated_files'),
EnableOption('--install-swiftpm', dest='install_swiftpm'),
EnableOption('--install-swift-driver', dest='install_swift_driver'),
EnableOption('--install-sourcekit-lsp', dest='install_sourcekitlsp'),
EnableOption('--install-skstresstester', dest='install_skstresstester'),
EnableOption('--install-swiftevolve', dest='install_swiftevolve'),
EnableOption('--toolchain-benchmarks', dest='build_toolchainbenchmarks'),
EnableOption('--swift-inspect', dest='build_swift_inspect'),
EnableOption('--tsan-libdispatch-test'),
EnableOption('--long-test'),
EnableOption('--show-sdks'),
EnableOption('--skip-local-build'),
EnableOption('--stress-test'),
EnableOption('--test'),
EnableOption('--test-optimize-for-size'),
EnableOption('--test-optimize-none-with-implicit-dynamic'),
EnableOption('--test-optimized'),
EnableOption('--tvos'),
EnableOption('--validation-test'),
EnableOption('--verbose-build'),
EnableOption('--watchos'),
EnableOption('--xctest', dest='build_xctest'),
EnableOption('--swift-disable-dead-stripping'),
EnableOption('--clean-early-swift-driver', dest='clean_early_swift_driver'),
DisableOption('--skip-build-cmark', dest='build_cmark'),
DisableOption('--skip-build-llvm', dest='build_llvm'),
DisableOption('--skip-build-swift', dest='build_swift'),
DisableOption('--skip-build-android', dest='build_android'),
DisableOption('--skip-build-benchmarks', dest='build_benchmarks'),
DisableOption('--skip-build-cygwin', dest='build_cygwin'),
DisableOption('--skip-build-freebsd', dest='build_freebsd'),
DisableOption('--skip-build-ios', dest='build_ios'),
DisableOption('--skip-build-ios-device', dest='build_ios_device'),
DisableOption('--skip-build-ios-simulator',
dest='build_ios_simulator'),
DisableOption('--skip-build-linux', dest='build_linux'),
DisableOption('--skip-build-osx', dest='build_osx'),
DisableOption('--skip-build-tvos', dest='build_tvos'),
DisableOption('--skip-build-tvos-device', dest='build_tvos_device'),
DisableOption('--skip-build-tvos-simulator',
dest='build_tvos_simulator'),
DisableOption('--skip-build-watchos', dest='build_watchos'),
DisableOption('--skip-build-watchos-device',
dest='build_watchos_device'),
DisableOption('--skip-build-watchos-simulator',
dest='build_watchos_simulator'),
DisableOption('--skip-clean-llbuild', dest='clean_llbuild'),
DisableOption('--skip-early-swift-driver', dest='build_early_swift_driver'),
DisableOption('--skip-clean-swiftpm', dest='clean_swiftpm'),
DisableOption('--skip-clean-swift-driver', dest='clean_swift_driver'),
DisableOption('--skip-test-android', dest='test_android'),
DisableOption('--skip-test-android-host', dest='test_android_host'),
DisableOption('--skip-test-cygwin', dest='test_cygwin'),
DisableOption('--skip-test-freebsd', dest='test_freebsd'),
DisableOption('--skip-test-ios', dest='test_ios'),
DisableOption('--skip-test-ios-32bit-simulator',
dest='test_ios_32bit_simulator'),
DisableOption('--skip-test-watchos-32bit-simulator',
dest='test_watchos_32bit_simulator'),
DisableOption('--skip-test-ios-host', dest='test_ios_host'),
DisableOption('--skip-test-ios-simulator', dest='test_ios_simulator'),
DisableOption('--skip-test-linux', dest='test_linux'),
DisableOption('--skip-test-osx', dest='test_osx'),
DisableOption('--skip-test-tvos', dest='test_tvos'),
DisableOption('--skip-test-tvos-host', dest='test_tvos_host'),
DisableOption('--skip-test-tvos-simulator',
dest='test_tvos_simulator'),
DisableOption('--skip-test-watchos', dest='test_watchos'),
DisableOption('--skip-test-watchos-host', dest='test_watchos_host'),
DisableOption('--skip-test-watchos-simulator',
dest='test_watchos_simulator'),
DisableOption('--skip-test-playgroundsupport',
dest='test_playgroundsupport'),
DisableOption('--skip-test-swiftpm', dest='test_swiftpm'),
DisableOption('--skip-test-swift-driver', dest='test_swift_driver'),
DisableOption('--skip-test-swiftsyntax', dest='test_swiftsyntax'),
DisableOption('--skip-test-indexstore-db', dest='test_indexstoredb'),
DisableOption('--skip-test-sourcekit-lsp', dest='test_sourcekitlsp'),
DisableOption('--skip-test-skstresstester', dest='test_skstresstester'),
DisableOption('--skip-test-swiftformat', dest='test_swiftformat'),
DisableOption('--skip-test-swiftevolve', dest='test_swiftevolve'),
DisableOption('--skip-test-toolchain-benchmarks',
dest='test_toolchainbenchmarks'),
DisableOption('--skip-test-swift-inspect',
dest='test_swift_inspect'),
DisableOption('--skip-build-clang-tools-extra',
dest='build_clang_tools_extra'),
ChoicesOption('--android-ndk-gcc-version',
choices=['4.8', '4.9']),
ChoicesOption('--compiler-vendor',
choices=['none', 'apple']),
ChoicesOption('--swift-analyze-code-coverage',
choices=['false', 'not-merged', 'merged']),
ChoicesOption('--android-arch',
choices=['armv7', 'aarch64']),
StrOption('--android-api-level'),
StrOption('--build-args'),
StrOption('--build-stdlib-deployment-targets'),
StrOption('--darwin-deployment-version-ios'),
StrOption('--darwin-deployment-version-osx'),
StrOption('--darwin-deployment-version-tvos'),
StrOption('--darwin-deployment-version-watchos'),
StrOption('--darwin-xcrun-toolchain'),
StrOption('--host-target'),
StrOption('--lit-args'),
StrOption('--llvm-targets-to-build'),
StrOption('--stdlib-deployment-targets'),
StrOption('--swift-darwin-module-archs'),
StrOption('--swift-darwin-supported-archs'),
PathOption('--android-deploy-device-path'),
PathOption('--android-icu-i18n'),
PathOption('--android-icu-i18n-include'),
PathOption('--android-icu-uc'),
PathOption('--android-icu-uc-include'),
PathOption('--android-icu-data'),
PathOption('--android-ndk'),
PathOption('--build-subdir'),
SetTrueOption('--relocate-xdg-cache-home-under-build-subdir'),
PathOption('--clang-profile-instr-use'),
PathOption('--cmake'),
PathOption('--coverage-db'),
PathOption('--host-cc'),
PathOption('--host-cxx'),
PathOption('--host-libtool'),
PathOption('--host-lipo'),
PathOption('--install-prefix'),
PathOption('--install-symroot'),
PathOption('--install-destdir'),
EnableOption('--install-all'),
PathOption('--native-clang-tools-path'),
PathOption('--native-llvm-tools-path'),
PathOption('--native-swift-tools-path'),
PathOption('--symbols-package'),
PathOption('--cmake-c-launcher'),
PathOption('--cmake-cxx-launcher'),
IntOption('--benchmark-num-o-iterations'),
IntOption('--benchmark-num-onone-iterations'),
IntOption('--jobs', dest='build_jobs'),
IntOption('--llvm-max-parallel-lto-link-jobs'),
IntOption('--swift-tools-max-parallel-lto-link-jobs'),
IntOption('-j', dest='build_jobs'),
IntOption('--dsymutil-jobs', dest='dsymutil_jobs'),
AppendOption('--cross-compile-hosts'),
AppendOption('--extra-cmake-options'),
AppendOption('--extra-swift-args'),
AppendOption('--test-paths'),
AppendOption('--llvm-ninja-targets'),
AppendOption('--llvm-ninja-targets-for-cross-compile-hosts'),
AppendOption('--darwin-symroot-path-filters'),
UnsupportedOption('--build-jobs'),
UnsupportedOption('--common-cmake-options'),
UnsupportedOption('--only-execute'),
UnsupportedOption('--skip-test-optimize-for-size'),
UnsupportedOption('--skip-test-optimize-none-with-implicit-dynamic'),
UnsupportedOption('--skip-test-optimized'),
# Options forwared to build-script-impl
BuildScriptImplOption('--skip-test-swift', dest='impl_skip_test_swift'),
BuildScriptImplOption('--install-swift', dest='impl_install_swift'),
# NOTE: LTO flag is a special case that acts both as an option and has
# valid choices
SetOption('--lto', dest='lto_type'),
ChoicesOption('--lto', dest='lto_type', choices=['thin', 'full']),
# NOTE: We'll need to manually test the behavior of these since they
# validate compiler version strings.
IgnoreOption('--clang-compiler-version'),
IgnoreOption('--clang-user-visible-version'),
IgnoreOption('--swift-compiler-version'),
IgnoreOption('--swift-user-visible-version'),
# TODO: Migrate to unavailable options once new parser is in place
IgnoreOption('-I'),
IgnoreOption('--ios-all'),
IgnoreOption('--tvos-all'),
IgnoreOption('--watchos-all'),
StrOption('--llvm-install-components'),
] | |
ilios-calendar-month-test.js | import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { setupIntl } from 'ember-intl/test-support';
import { render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';
import { component } from 'ilios-common/page-objects/components/ilios-calendar-month';
import { DateTime } from 'luxon';
module('Integration | Component | ilios calendar month', function (hooks) {
setupRenderingTest(hooks);
setupIntl(hooks, 'en-us');
test('month displays with three events', async function (assert) {
const date = DateTime.fromISO('2015-09-30T12:00:00');
this.set('date', date.toISO());
const firstEvent = createUserEventObject();
firstEvent.name = 'Some new thing';
firstEvent.startDate = date.toISO();
firstEvent.endDate = date.plus({ hour: 1 }).toISO();
const secondEvent = createUserEventObject();
secondEvent.name = 'Second new thing';
secondEvent.startDate = date.plus({ hour: 1 }).toISO();
secondEvent.endDate = date.plus({ hour: 3 }).toISO();
const thirdEvent = createUserEventObject();
thirdEvent.name = 'Third new thing';
thirdEvent.startDate = date.plus({ hour: 3 }).toISO();
thirdEvent.endDate = date.plus({ hour: 4 }).toISO();
this.set('events', [firstEvent, secondEvent, thirdEvent]);
await render(hbs`<IliosCalendarMonth
@date={{this.date}}
@calendarEvents={{this.events}} | assert.strictEqual(component.calendar.monthYear, 'September 2015');
assert.strictEqual(component.calendar.events.length, 2);
assert.ok(component.calendar.days[29].hasShowMore);
});
test('month displays with two events', async function (assert) {
const date = new DateTime.fromISO('2015-09-30T12:00:00');
this.set('date', date.toISO());
const firstEvent = createUserEventObject();
firstEvent.name = 'Some new thing';
firstEvent.startDate = date.toISO();
firstEvent.endDate = date.plus({ hour: 1 }).toISO();
const secondEvent = createUserEventObject();
secondEvent.name = 'Second new thing';
secondEvent.startDate = date.plus({ hour: 1 }).toISO();
secondEvent.endDate = date.plus({ hour: 3 }).toISO();
this.set('events', [firstEvent, secondEvent]);
await render(hbs`<IliosCalendarMonth
@date={{this.date}}
@calendarEvents={{this.events}}
@selectEvent={{(noop)}}
/>`);
assert.strictEqual(component.calendar.monthYear, 'September 2015');
assert.strictEqual(component.calendar.events.length, 2);
assert.notOk(component.calendar.days[29].hasShowMore);
});
test('clicking on a day fires the correct event', async function (assert) {
assert.expect(3);
const date = DateTime.fromISO('2015-09-30T12:00:00');
this.set('date', date.toISO());
this.set('changeDate', (newDate) => {
assert.ok(newDate instanceof Date);
assert.ok(newDate.toString().includes('Tue Sep 01'));
});
this.set('changeView', (newView) => {
assert.strictEqual(newView, 'day');
});
await render(hbs`<IliosCalendarMonth
@date={{this.date}}
@changeDate={{this.changeDate}}
@changeView={{this.changeView}}
@calendarEvents={{(array)}}
@areDaysSelectable={{true}}
/>`);
await component.calendar.days[0].selectDay();
});
test('prework', async function (assert) {
const date = DateTime.fromISO('2015-09-30T12:00:00');
const event = createUserEventObject();
const now = DateTime.now();
event.startDate = date.toISO();
event.endDate = date.plus({ hour: 1 }).toISO();
event.prerequisites = [
{
name: 'prework 1',
startDate: now.toISO(),
endDate: now.toISO(),
ilmSession: true,
slug: 'whatever',
postrequisiteSlug: 'something',
postrequisiteName: 'third',
isPublished: true,
isScheduled: false,
isBlanked: false,
},
{
name: 'prework 2',
startDate: now.toISO(),
endDate: now.toISO(),
location: 'room 111',
ilmSession: true,
slug: 'whatever',
postrequisiteSlug: 'something',
postrequisiteName: 'first',
isPublished: true,
isScheduled: false,
isBlanked: false,
},
{
name: 'blanked prework',
startDate: now.toISO(),
endDate: now.toISO(),
location: 'room 111',
ilmSession: true,
slug: 'whatever',
postrequisiteSlug: 'something',
postrequisiteName: 'first',
isPublished: true,
isScheduled: false,
isBlanked: true,
},
{
name: 'scheduled prework',
startDate: now.toISO(),
endDate: now.toISO(),
location: 'room 111',
ilmSession: true,
slug: 'whatever',
postrequisiteSlug: 'something',
postrequisiteName: 'first',
isPublished: true,
isScheduled: true,
isBlanked: false,
},
{
name: 'unpublished prework',
startDate: now.toISO(),
endDate: now.toISO(),
location: 'room 111',
ilmSession: true,
slug: 'whatever',
postrequisiteSlug: 'something',
postrequisiteName: 'first',
isPublished: true,
isScheduled: true,
isBlanked: false,
},
];
this.set('date', date.toISO());
this.set('events', [event]);
await render(hbs`<IliosCalendarMonth
@date={{this.date}}
@calendarEvents={{this.events}}
@selectEvent={{(noop)}}
/>`);
assert.strictEqual(component.prework.events.length, 2);
assert.strictEqual(
component.prework.events[0].text,
`prework 1 Due Before third (${now.toFormat('D')})`
);
assert.strictEqual(
component.prework.events[1].text,
`prework 2 Due Before first (${now.toFormat('D')})`
);
});
test('prework to unpublished/scheduled/blanked events is not visible', async function (assert) {
const date = DateTime.fromISO('2015-09-30T12:00:00');
const now = DateTime.now();
const publishedPrework = {
name: 'published prework',
startDate: now.toISO(),
endDate: now.toISO(),
ilmSession: true,
slug: 'whatever',
postrequisiteSlug: 'something',
postrequisiteName: 'third',
isPublished: true,
isScheduled: false,
isBlanked: false,
};
const unpublishedEvent = createUserEventObject();
unpublishedEvent.isPublished = false;
unpublishedEvent.isScheduled = false;
unpublishedEvent.isBlanked = false;
const scheduledEvent = createUserEventObject();
scheduledEvent.isPublished = true;
scheduledEvent.isScheduled = true;
scheduledEvent.isBlanked = false;
const blankedEvent = createUserEventObject();
blankedEvent.isPublished = true;
blankedEvent.isScheduled = false;
blankedEvent.isBlanked = true;
const events = [unpublishedEvent, scheduledEvent, blankedEvent];
events.forEach((event) => {
event.startDate = date.toISO();
event.endDate = date.plus({ hour: 1 }).toISO();
event.prerequisites = [publishedPrework];
});
this.set('date', date.toISO());
this.set('events', events);
await render(hbs`<IliosCalendarMonth
@date={{this.date}}
@calendarEvents={{this.events}}
@selectEvent={{(noop)}}
/>`);
assert.strictEqual(component.prework.events.length, 0);
});
const createUserEventObject = function () {
return {
user: 1,
name: '',
offering: 1,
startDate: null,
endDate: null,
calendarColor: '#32edfc',
location: 'Rm. 160',
lastModified: new Date(),
isPublished: true,
isScheduled: false,
prerequisites: [],
postrequisites: [],
};
};
test('multiday events', async function (assert) {
const date = DateTime.fromISO('2015-09-20T12:00:00');
const event = createUserEventObject();
event.startDate = date.toISO();
event.endDate = date.plus({ hour: 24 }).toISO();
const event2 = createUserEventObject();
event2.startDate = date.plus({ hour: 48 }).toISO();
event2.endDate = date.plus({ hour: 72 }).toISO();
this.set('date', date.toISO());
this.set('events', [event, event2]);
await render(hbs`<IliosCalendarMonth
@date={{this.date}}
@calendarEvents={{this.events}}
@selectEvent={{(noop)}}
/>`);
assert.strictEqual(component.multiday.events.length, 2);
assert.strictEqual(
component.multiday.events[0].text,
'9/20/15, 12:00 PM – 9/21/15, 12:00 PM Rm. 160'
);
assert.strictEqual(
component.multiday.events[1].text,
'9/22/15, 12:00 PM – 9/23/15, 12:00 PM Rm. 160'
);
});
}); | @selectEvent={{(noop)}}
/>`); |
virtual_network.py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
from ._inputs import *
__all__ = ['VirtualNetwork']
class VirtualNetwork(pulumi.CustomResource):
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
address_space: Optional[pulumi.Input[pulumi.InputType['AddressSpaceArgs']]] = None,
dhcp_options: Optional[pulumi.Input[pulumi.InputType['DhcpOptionsArgs']]] = None,
enable_ddos_protection: Optional[pulumi.Input[bool]] = None,
enable_vm_protection: Optional[pulumi.Input[bool]] = None,
etag: Optional[pulumi.Input[str]] = None,
id: Optional[pulumi.Input[str]] = None,
location: Optional[pulumi.Input[str]] = None,
provisioning_state: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
resource_guid: Optional[pulumi.Input[str]] = None,
subnets: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SubnetArgs']]]]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
virtual_network_name: Optional[pulumi.Input[str]] = None,
virtual_network_peerings: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VirtualNetworkPeeringArgs']]]]] = None,
__props__=None,
__name__=None,
__opts__=None):
"""
Virtual Network resource.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[pulumi.InputType['AddressSpaceArgs']] address_space: The AddressSpace that contains an array of IP address ranges that can be used by subnets.
:param pulumi.Input[pulumi.InputType['DhcpOptionsArgs']] dhcp_options: The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network.
:param pulumi.Input[bool] enable_ddos_protection: Indicates if DDoS protection is enabled for all the protected resources in a Virtual Network.
:param pulumi.Input[bool] enable_vm_protection: Indicates if Vm protection is enabled for all the subnets in a Virtual Network.
:param pulumi.Input[str] etag: Gets a unique read-only string that changes whenever the resource is updated.
:param pulumi.Input[str] id: Resource ID.
:param pulumi.Input[str] location: Resource location.
:param pulumi.Input[str] provisioning_state: The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[str] resource_guid: The resourceGuid property of the Virtual Network resource.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['SubnetArgs']]]] subnets: A list of subnets in a Virtual Network.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: Resource tags.
:param pulumi.Input[str] virtual_network_name: The name of the virtual network.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['VirtualNetworkPeeringArgs']]]] virtual_network_peerings: A list of peerings in a Virtual Network.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = dict()
__props__['address_space'] = address_space
__props__['dhcp_options'] = dhcp_options
__props__['enable_ddos_protection'] = enable_ddos_protection
__props__['enable_vm_protection'] = enable_vm_protection
__props__['etag'] = etag
__props__['id'] = id
__props__['location'] = location
__props__['provisioning_state'] = provisioning_state
if resource_group_name is None:
raise TypeError("Missing required property 'resource_group_name'")
__props__['resource_group_name'] = resource_group_name
__props__['resource_guid'] = resource_guid
__props__['subnets'] = subnets
__props__['tags'] = tags
if virtual_network_name is None:
raise TypeError("Missing required property 'virtual_network_name'")
__props__['virtual_network_name'] = virtual_network_name
__props__['virtual_network_peerings'] = virtual_network_peerings
__props__['name'] = None
__props__['type'] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:network/latest:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20150501preview:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20150615:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20160330:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20160601:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20160901:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20161201:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20170301:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20170601:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20170801:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20170901:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20171001:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20180101:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20180201:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20180401:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20180601:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20180701:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20180801:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20181001:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20181101:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20181201:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20190201:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20190401:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20190601:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20190701:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20190801:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20190901:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20191101:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20191201:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20200301:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20200401:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20200501:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20200601:VirtualNetwork"), pulumi.Alias(type_="azure-nextgen:network/v20200701:VirtualNetwork")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(VirtualNetwork, __self__).__init__(
'azure-nextgen:network/v20171101:VirtualNetwork',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'VirtualNetwork':
"""
Get an existing VirtualNetwork resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = dict()
return VirtualNetwork(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="addressSpace")
def address_space(self) -> pulumi.Output[Optional['outputs.AddressSpaceResponse']]:
"""
The AddressSpace that contains an array of IP address ranges that can be used by subnets.
"""
return pulumi.get(self, "address_space")
@property
@pulumi.getter(name="dhcpOptions")
def dhcp_options(self) -> pulumi.Output[Optional['outputs.DhcpOptionsResponse']]:
"""
The dhcpOptions that contains an array of DNS servers available to VMs deployed in the virtual network.
"""
return pulumi.get(self, "dhcp_options")
@property
@pulumi.getter(name="enableDdosProtection")
def enable_ddos_protection(self) -> pulumi.Output[Optional[bool]]:
"""
Indicates if DDoS protection is enabled for all the protected resources in a Virtual Network.
"""
return pulumi.get(self, "enable_ddos_protection")
@property
@pulumi.getter(name="enableVmProtection")
def enable_vm_protection(self) -> pulumi.Output[Optional[bool]]:
"""
Indicates if Vm protection is enabled for all the subnets in a Virtual Network.
"""
return pulumi.get(self, "enable_vm_protection")
@property
@pulumi.getter
def etag(self) -> pulumi.Output[Optional[str]]:
"""
Gets a unique read-only string that changes whenever the resource is updated.
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter
def location(self) -> pulumi.Output[Optional[str]]:
"""
Resource location.
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> pulumi.Output[Optional[str]]:
"""
The provisioning state of the PublicIP resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="resourceGuid")
def resource_guid(self) -> pulumi.Output[Optional[str]]:
"""
The resourceGuid property of the Virtual Network resource.
"""
return pulumi.get(self, "resource_guid")
@property
@pulumi.getter
def subnets(self) -> pulumi.Output[Optional[Sequence['outputs.SubnetResponse']]]:
|
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
Resource tags.
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
Resource type.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="virtualNetworkPeerings")
def virtual_network_peerings(self) -> pulumi.Output[Optional[Sequence['outputs.VirtualNetworkPeeringResponse']]]:
"""
A list of peerings in a Virtual Network.
"""
return pulumi.get(self, "virtual_network_peerings")
def translate_output_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop
| """
A list of subnets in a Virtual Network.
"""
return pulumi.get(self, "subnets") |
inherent_impls.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This test case tests the incremental compilation hash (ICH) implementation
// for let expressions.
// The general pattern followed here is: Change one thing between rev1 and rev2
// and make sure that the hash has changed, then change nothing between rev2 and
// rev3 and make sure that the hash has not changed.
// must-compile-successfully
// revisions: cfail1 cfail2 cfail3
// compile-flags: -Z query-dep-graph
#![allow(warnings)]
#![feature(rustc_attrs)]
#![crate_type="rlib"]
struct Foo;
// Change Method Name -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
pub fn method_name() { }
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn method_name2() { }
}
// Change Method Body -----------------------------------------------------------
//
// This should affect the method itself, but not the impl.
#[cfg(cfail1)]
impl Foo {
pub fn method_body() { }
}
#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn | () {
println!("Hello, world!");
}
}
// Change Method Privacy -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
pub fn method_privacy() { }
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
fn method_privacy() { }
}
// Change Method Selfness -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
pub fn method_selfness() { }
}
#[cfg(not(cfail1))]
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn method_selfness(&self) { }
}
// Change Method Selfmutness -----------------------------------------------------------
#[cfg(cfail1)]
impl Foo {
pub fn method_selfmutness(&self) { }
}
#[cfg(not(cfail1))]
#[rustc_clean(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_clean(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
impl Foo {
#[rustc_dirty(label="Hir", cfg="cfail2")]
#[rustc_clean(label="Hir", cfg="cfail3")]
#[rustc_metadata_dirty(cfg="cfail2")]
#[rustc_metadata_clean(cfg="cfail3")]
pub fn method_selfmutness(&mut self) { }
}
| method_body |
basic.js | 'use strict'
const log = require('../')
log.debug('Should not be printed')
log.info('Information not shown') | log.warning('You have been warned')
log.error('An error occured')
log.critical('This is the end...')
log.alert('This is also the end...')
log.emergency('This is really the reall end.') | log.notice('Notice me!') |
win.rs | #![cfg(windows)]
use winapi::um::errhandlingapi::GetLastError;
use std::ptr;
pub fn panic_handle(handle: *const winapi::ctypes::c_void, err: &'static str) { | }
}
pub fn panic_code(code: i32, err: &'static str) {
if code == 0 {
winpanic(err);
}
}
fn winpanic(err: &'static str) {
let ec = unsafe { GetLastError() };
println!("error code: {}", ec);
panic!(err);
} | if handle == ptr::null() {
winpanic(err); |
mod.rs | use liquid_error::Error;
use std::borrow::Cow;
pub mod std;
#[cfg(feature = "jekyll-filters")]
pub mod jekyll;
#[cfg(feature = "extra-filters")]
pub mod extra;
pub fn invalid_input<S>(cause: S) -> Error
where
S: Into<Cow<'static, str>>,
{
Error::with_msg("Invalid input").context("cause", cause)
}
| S: Into<Cow<'static, str>>,
{
Error::with_msg("Invalid argument")
.context("argument", argument)
.context("cause", cause)
} | pub fn invalid_argument<S>(argument: S, cause: S) -> Error
where |
controlflow.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use llvm::ValueRef;
use rustc::hir::def::Def;
use middle::lang_items::{PanicFnLangItem, PanicBoundsCheckFnLangItem};
use rustc::ty::subst::Substs;
use base::*;
use basic_block::BasicBlock;
use build::*;
use callee::{Callee, ArgVals};
use cleanup::CleanupMethods;
use cleanup;
use common::*;
use consts;
use debuginfo;
use debuginfo::{DebugLoc, ToDebugLoc};
use expr;
use machine;
use rustc::hir;
use syntax::ast;
use syntax::parse::token::InternedString;
use syntax::parse::token;
pub fn trans_stmt<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
s: &hir::Stmt)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("trans_stmt");
let fcx = cx.fcx;
debug!("trans_stmt({:?})", s);
if cx.unreachable.get() {
return cx;
}
if cx.sess().asm_comments() {
add_span_comment(cx, s.span, &format!("{:?}", s));
}
let mut bcx = cx;
let id = s.node.id();
let cleanup_debug_loc =
debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(), id, s.span, false);
fcx.push_ast_cleanup_scope(cleanup_debug_loc);
match s.node {
hir::StmtExpr(ref e, _) | hir::StmtSemi(ref e, _) => {
bcx = trans_stmt_semi(bcx, &e);
}
hir::StmtDecl(ref d, _) => {
match d.node {
hir::DeclLocal(ref local) => {
bcx = init_local(bcx, &local);
debuginfo::create_local_var_metadata(bcx, &local);
}
// Inner items are visited by `trans_item`/`trans_meth`.
hir::DeclItem(_) => {},
}
}
}
bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, s.node.id());
return bcx;
}
pub fn trans_stmt_semi<'blk, 'tcx>(cx: Block<'blk, 'tcx>, e: &hir::Expr)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("trans_stmt_semi");
if cx.unreachable.get() {
return cx;
}
let ty = expr_ty(cx, e);
if cx.fcx.type_needs_drop(ty) {
expr::trans_to_lvalue(cx, e, "stmt").bcx
} else {
expr::trans_into(cx, e, expr::Ignore)
}
}
pub fn trans_block<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
b: &hir::Block,
mut dest: expr::Dest)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("trans_block");
if bcx.unreachable.get() {
return bcx;
}
let fcx = bcx.fcx;
let mut bcx = bcx;
let cleanup_debug_loc =
debuginfo::get_cleanup_debug_loc_for_ast_node(bcx.ccx(), b.id, b.span, true);
fcx.push_ast_cleanup_scope(cleanup_debug_loc);
for s in &b.stmts {
bcx = trans_stmt(bcx, s);
}
if dest != expr::Ignore {
let block_ty = node_id_type(bcx, b.id);
if b.expr.is_none() || type_is_zero_size(bcx.ccx(), block_ty) {
dest = expr::Ignore;
} else if b.expr.is_some() {
// If the block has an expression, but that expression isn't reachable,
// don't save into the destination given, ignore it.
if let Some(ref cfg) = bcx.fcx.cfg {
if !cfg.node_is_reachable(b.expr.as_ref().unwrap().id) {
dest = expr::Ignore;
}
}
}
}
match b.expr {
Some(ref e) => {
if !bcx.unreachable.get() {
bcx = expr::trans_into(bcx, &e, dest);
}
}
None => {
assert!(dest == expr::Ignore || bcx.unreachable.get());
}
}
bcx = fcx.pop_and_trans_ast_cleanup_scope(bcx, b.id);
return bcx;
}
pub fn trans_if<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
if_id: ast::NodeId,
cond: &hir::Expr,
thn: &hir::Block,
els: Option<&hir::Expr>,
dest: expr::Dest)
-> Block<'blk, 'tcx> |
pub fn trans_while<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
loop_expr: &hir::Expr,
cond: &hir::Expr,
body: &hir::Block)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("trans_while");
if bcx.unreachable.get() {
return bcx;
}
let fcx = bcx.fcx;
// bcx
// |
// cond_bcx_in <--------+
// | |
// cond_bcx_out |
// | | |
// | body_bcx_in |
// cleanup_blk | |
// | body_bcx_out --+
// next_bcx_in
let next_bcx_in = fcx.new_id_block("while_exit", loop_expr.id);
let cond_bcx_in = fcx.new_id_block("while_cond", cond.id);
let body_bcx_in = fcx.new_id_block("while_body", body.id);
fcx.push_loop_cleanup_scope(loop_expr.id, [next_bcx_in, cond_bcx_in]);
Br(bcx, cond_bcx_in.llbb, loop_expr.debug_loc());
// compile the block where we will handle loop cleanups
let cleanup_llbb = fcx.normal_exit_block(loop_expr.id, cleanup::EXIT_BREAK);
// compile the condition
let Result {bcx: cond_bcx_out, val: cond_val} =
expr::trans(cond_bcx_in, cond).to_llbool();
CondBr(cond_bcx_out, cond_val, body_bcx_in.llbb, cleanup_llbb, cond.debug_loc());
// loop body:
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
Br(body_bcx_out, cond_bcx_in.llbb, DebugLoc::None);
fcx.pop_loop_cleanup_scope(loop_expr.id);
return next_bcx_in;
}
pub fn trans_loop<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
loop_expr: &hir::Expr,
body: &hir::Block)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("trans_loop");
if bcx.unreachable.get() {
return bcx;
}
let fcx = bcx.fcx;
// bcx
// |
// body_bcx_in
// |
// body_bcx_out
//
// next_bcx
//
// Links between body_bcx_in and next_bcx are created by
// break statements.
let next_bcx_in = bcx.fcx.new_id_block("loop_exit", loop_expr.id);
let body_bcx_in = bcx.fcx.new_id_block("loop_body", body.id);
fcx.push_loop_cleanup_scope(loop_expr.id, [next_bcx_in, body_bcx_in]);
Br(bcx, body_bcx_in.llbb, loop_expr.debug_loc());
let body_bcx_out = trans_block(body_bcx_in, body, expr::Ignore);
Br(body_bcx_out, body_bcx_in.llbb, DebugLoc::None);
fcx.pop_loop_cleanup_scope(loop_expr.id);
// If there are no predecessors for the next block, we just translated an endless loop and the
// next block is unreachable
if BasicBlock(next_bcx_in.llbb).pred_iter().next().is_none() {
Unreachable(next_bcx_in);
}
return next_bcx_in;
}
pub fn trans_break_cont<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
expr: &hir::Expr,
opt_label: Option<ast::Name>,
exit: usize)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("trans_break_cont");
if bcx.unreachable.get() {
return bcx;
}
let fcx = bcx.fcx;
// Locate loop that we will break to
let loop_id = match opt_label {
None => fcx.top_loop_scope(),
Some(_) => {
match bcx.tcx().def_map.borrow().get(&expr.id).map(|d| d.full_def()) {
Some(Def::Label(loop_id)) => loop_id,
r => {
bug!("{:?} in def-map for label", r)
}
}
}
};
// Generate appropriate cleanup code and branch
let cleanup_llbb = fcx.normal_exit_block(loop_id, exit);
Br(bcx, cleanup_llbb, expr.debug_loc());
Unreachable(bcx); // anything afterwards should be ignored
return bcx;
}
pub fn trans_break<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
expr: &hir::Expr,
label_opt: Option<ast::Name>)
-> Block<'blk, 'tcx> {
return trans_break_cont(bcx, expr, label_opt, cleanup::EXIT_BREAK);
}
pub fn trans_cont<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
expr: &hir::Expr,
label_opt: Option<ast::Name>)
-> Block<'blk, 'tcx> {
return trans_break_cont(bcx, expr, label_opt, cleanup::EXIT_LOOP);
}
pub fn trans_ret<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
return_expr: &hir::Expr,
retval_expr: Option<&hir::Expr>)
-> Block<'blk, 'tcx> {
let _icx = push_ctxt("trans_ret");
if bcx.unreachable.get() {
return bcx;
}
let fcx = bcx.fcx;
let mut bcx = bcx;
if let Some(x) = retval_expr {
let dest = if fcx.llretslotptr.get().is_some() {
expr::SaveIn(fcx.get_ret_slot(bcx, "ret_slot"))
} else {
expr::Ignore
};
bcx = expr::trans_into(bcx, &x, dest);
match dest {
expr::SaveIn(slot) if fcx.needs_ret_allocas => {
Store(bcx, slot, fcx.llretslotptr.get().unwrap());
}
_ => {}
}
}
let cleanup_llbb = fcx.return_exit_block();
Br(bcx, cleanup_llbb, return_expr.debug_loc());
Unreachable(bcx);
return bcx;
}
pub fn trans_fail<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
call_info: NodeIdAndSpan,
fail_str: InternedString)
-> Block<'blk, 'tcx> {
let ccx = bcx.ccx();
let _icx = push_ctxt("trans_fail_value");
if bcx.unreachable.get() {
return bcx;
}
let v_str = C_str_slice(ccx, fail_str);
let loc = bcx.sess().codemap().lookup_char_pos(call_info.span.lo);
let filename = token::intern_and_get_ident(&loc.file.name);
let filename = C_str_slice(ccx, filename);
let line = C_u32(ccx, loc.line as u32);
let expr_file_line_const = C_struct(ccx, &[v_str, filename, line], false);
let align = machine::llalign_of_min(ccx, val_ty(expr_file_line_const));
let expr_file_line = consts::addr_of(ccx, expr_file_line_const, align, "panic_loc");
let args = vec!(expr_file_line);
let did = langcall(bcx, Some(call_info.span), "", PanicFnLangItem);
Callee::def(ccx, did, ccx.tcx().mk_substs(Substs::empty()))
.call(bcx, call_info.debug_loc(), ArgVals(&args), None).bcx
}
pub fn trans_fail_bounds_check<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
call_info: NodeIdAndSpan,
index: ValueRef,
len: ValueRef)
-> Block<'blk, 'tcx> {
let ccx = bcx.ccx();
let _icx = push_ctxt("trans_fail_bounds_check");
if bcx.unreachable.get() {
return bcx;
}
// Extract the file/line from the span
let loc = bcx.sess().codemap().lookup_char_pos(call_info.span.lo);
let filename = token::intern_and_get_ident(&loc.file.name);
// Invoke the lang item
let filename = C_str_slice(ccx, filename);
let line = C_u32(ccx, loc.line as u32);
let file_line_const = C_struct(ccx, &[filename, line], false);
let align = machine::llalign_of_min(ccx, val_ty(file_line_const));
let file_line = consts::addr_of(ccx, file_line_const, align, "panic_bounds_check_loc");
let args = vec!(file_line, index, len);
let did = langcall(bcx, Some(call_info.span), "", PanicBoundsCheckFnLangItem);
Callee::def(ccx, did, ccx.tcx().mk_substs(Substs::empty()))
.call(bcx, call_info.debug_loc(), ArgVals(&args), None).bcx
}
| {
debug!("trans_if(bcx={}, if_id={}, cond={:?}, thn={}, dest={:?})",
bcx.to_str(), if_id, cond, thn.id, dest);
let _icx = push_ctxt("trans_if");
if bcx.unreachable.get() {
return bcx;
}
let mut bcx = bcx;
let cond_val = unpack_result!(bcx, expr::trans(bcx, cond).to_llbool());
// Drop branches that are known to be impossible
if let Some(cv) = const_to_opt_uint(cond_val) {
if cv == 1 {
// if true { .. } [else { .. }]
bcx = trans_block(bcx, &thn, dest);
DebugLoc::None.apply(bcx.fcx);
} else {
if let Some(elexpr) = els {
bcx = expr::trans_into(bcx, &elexpr, dest);
DebugLoc::None.apply(bcx.fcx);
}
}
return bcx;
}
let name = format!("then-block-{}-", thn.id);
let then_bcx_in = bcx.fcx.new_id_block(&name[..], thn.id);
let then_bcx_out = trans_block(then_bcx_in, &thn, dest);
DebugLoc::None.apply(bcx.fcx);
let cond_source_loc = cond.debug_loc();
let next_bcx;
match els {
Some(elexpr) => {
let else_bcx_in = bcx.fcx.new_id_block("else-block", elexpr.id);
let else_bcx_out = expr::trans_into(else_bcx_in, &elexpr, dest);
next_bcx = bcx.fcx.join_blocks(if_id,
&[then_bcx_out, else_bcx_out]);
CondBr(bcx, cond_val, then_bcx_in.llbb, else_bcx_in.llbb, cond_source_loc);
}
None => {
next_bcx = bcx.fcx.new_id_block("next-block", if_id);
Br(then_bcx_out, next_bcx.llbb, DebugLoc::None);
CondBr(bcx, cond_val, then_bcx_in.llbb, next_bcx.llbb, cond_source_loc);
}
}
// Clear the source location because it is still set to whatever has been translated
// right before.
DebugLoc::None.apply(next_bcx.fcx);
next_bcx
} |
elements.rs | use crate::color::*;
use crate::canvas::*; | #[allow(non_snake_case)]
fn onClick(self,canvas:&Canvas)->bool;
#[allow(non_snake_case)]
fn onHover(self,canvas:&Canvas)->bool;
}
#[derive(Copy,Clone)]
pub enum Styles{
Normal,
RoundEdges,
Triangular,
Elliptic,
}
#[derive(Clone,Copy)]
pub struct Button{
color:Color,
x:u16,
y:u16,
width:u16,
height:u16,
border_width:u8,
style:Styles,
text:&'static str,
}
impl PageElement for Button {
fn draw(self,canvas:&mut Canvas){
canvas.textSize(12);
canvas.text(self.x+self.border_width as u16+6,self.y+self.border_width as u16+(self.height/2)+1,self.text);
match self.style{
Styles::Normal=>{
/*canvas.fill(self.color-20);
canvas.rect(self.x,self.y,self.width,self.height);*/
canvas.fill(self.color);
canvas.rect(self.x+self.border_width as u16,self.y+self.border_width as u16,self.width-(self.border_width*2) as u16,self.height-(self.border_width*2) as u16);
},
Styles::RoundEdges=>{
canvas.line(self.x+2,self.y,self.x+self.width-4,self.y);
canvas.bezierCurveVertex((self.x+self.width-4) as i64,self.y as i64,(self.x+self.width-2) as i64,(self.y+2) as i64,(self.x+self.width-4) as i64,self.y as i64,(self.x+self.width-2) as i64,(self.y+2) as i64);
canvas.line(self.x+self.width-2,self.y+2,self.x+self.width-2,self.y+self.height-4);
canvas.bezierCurveVertex((self.x+self.width-2) as i64,(self.y+self.height-4) as i64,(self.x+self.width-4) as i64,(self.y+self.height-2) as i64,(self.x+self.width-2) as i64,(self.y+self.height-4) as i64,(self.x+self.width-4) as i64,(self.y+self.height-2) as i64);
canvas.line(self.x+self.width-4,self.y+self.height-2,self.x+2,self.y+self.height-2);
canvas.bezierCurveVertex((self.x+2) as i64,(self.y+self.height-2) as i64,(self.x) as i64,(self.y+self.height-4) as i64,(self.x+2) as i64,(self.y+self.height-2) as i64,(self.x) as i64,(self.y+self.height-4) as i64);
canvas.line(self.x,self.y+self.height-4,self.x,self.y+2);
canvas.bezierCurveVertex((self.x) as i64,(self.y+2) as i64,(self.x+2) as i64,self.y as i64,(self.x) as i64,(self.y+2) as i64,(self.x+2) as i64,self.y as i64);
},
_=>{},
}
}
#[allow(non_snake_case)]
fn onClick(self,canvas:&Canvas)->bool{
if canvas.mouseClick()==MouseButton::Left && (canvas.mouseX()>self.x && canvas.mouseX()<self.x+self.width) &&(canvas.mouseY()>self.y && canvas.mouseY()<self.y+self.height){
return true;
}
false
}
#[allow(non_snake_case)]
fn onHover(self,canvas:&Canvas)->bool{
if canvas.mouseClick()!=MouseButton::Left && (canvas.mouseX()>self.x && canvas.mouseX()<self.x+self.width) &&(canvas.mouseY()>self.y && canvas.mouseY()<self.y+self.height){
return true;
}
false
}
}
impl Button{
pub fn new(x:u16,y:u16,text:&'static str)->Button{
Button{color:Color::from(190), x,y,width:40,height:20,border_width:2,style:Styles::Normal,text,}
}
pub fn location(&mut self,x:u16,y:u16)->Self{
self.x = x;
self.y = y;
*self
}
pub fn get_location(self)->(u16,u16){
(self.x,self.y)
}
pub fn get_x(self)->u16{
self.x
}
pub fn get_y(self)->u16{
self.y
}
pub fn color(&mut self,color:Color)->Self{
self.color = color;
*self
}
pub fn size(&mut self,width:u16,height:u16)->Self{
self.width = width;
self.height= height;
*self
}
pub fn get_size(self)->(u16,u16){
(self.width,self.height)
}
pub fn get_width(self)->u16{
self.width
}
pub fn get_height(self)->u16{
self.height
}
pub fn width(&mut self,width:u16)->Self{
self.width = width;
*self
}
pub fn height(&mut self,height:u16)->Self{
self.height = height;
*self
}
pub fn border_width(&mut self,width:u8)->Self{
self.border_width = width;
*self
}
pub fn get_border_width(self)->u8{
self.border_width
}
pub fn button_text(&mut self,text:&'static str)->Self{
self.text = text;
*self
}
pub fn get_color(self)->Color{
self.color
}
pub fn style(&mut self,style:Styles)->Self{
self.style = style;
*self
}
} | pub trait PageElement {
fn draw(self,canvas:&mut Canvas); |
nereid.py | #!/usr/bin/env python3
# This file is Copyright (c) 2018-2019 Rohit Singh <[email protected]>
# This file is Copyright (c) 2019 Florent Kermarrec <[email protected]>
# License: BSD
import sys
from migen import *
from litex.build.generic_platform import *
from litex.soc.integration.soc_core import *
from litex.soc.integration.soc_sdram import *
from litex.soc.integration.builder import *
from litex.soc.cores.clock import *
from litex.soc.cores import dna, xadc
from litex.soc.cores.uart import *
from litex.soc.integration.cpu_interface import get_csr_header
from litedram.modules import MT8KTF51264
from litedram.modules import _TechnologyTimings, _SpeedgradeTimings
from litedram.phy import s7ddrphy
from litepcie.phy.s7pciephy import S7PCIEPHY
from litepcie.core import LitePCIeEndpoint, LitePCIeMSI
from litepcie.frontend.dma import LitePCIeDMA
from litepcie.frontend.wishbone import LitePCIeWishboneBridge
from litex_boards.platforms import nereid
# CRG ----------------------------------------------------------------------------------------------
class CRG(Module):
def | (self, platform, sys_clk_freq):
self.clock_domains.cd_sys = ClockDomain()
self.clock_domains.cd_sys4x = ClockDomain(reset_less=True)
self.clock_domains.cd_clk200 = ClockDomain()
clk100 = platform.request("clk100")
self.submodules.pll = pll = S7PLL()
pll.register_clkin(clk100, 100e6)
pll.create_clkout(self.cd_sys, sys_clk_freq)
pll.create_clkout(self.cd_sys4x, 4*sys_clk_freq)
pll.create_clkout(self.cd_clk200, 200e6)
self.comb += pll.reset.eq(platform.request("cpu_reset"))
self.submodules.idelayctrl = S7IDELAYCTRL(self.cd_clk200)
# NereidSoC ----------------------------------------------------------------------------------------
class NereidSoC(SoCSDRAM):
SoCSDRAM.mem_map["csr"] = 0x00000000
SoCSDRAM.mem_map["rom"] = 0x20000000
def __init__(self, platform, with_pcie_uart=True):
sys_clk_freq = int(100e6)
SoCSDRAM.__init__(self, platform, sys_clk_freq,
csr_data_width=32,
integrated_rom_size=0x10000,
integrated_sram_size=0x10000,
integrated_main_ram_size=0x10000, # FIXME: keep this for initial PCIe tests
ident="Nereid LiteX Test SoC", ident_version=True,
with_uart=not with_pcie_uart)
# CRG --------------------------------------------------------------------------------------
self.submodules.crg = CRG(platform, sys_clk_freq)
self.add_csr("crg")
# DNA --------------------------------------------------------------------------------------
self.submodules.dna = dna.DNA()
self.add_csr("dna")
# XADC -------------------------------------------------------------------------------------
self.submodules.xadc = xadc.XADC()
self.add_csr("xadc")
# SDRAM ------------------------------------------------------------------------------------
if not self.integrated_main_ram_size:
self.submodules.ddrphy = s7ddrphy.K7DDRPHY(
platform.request("ddram"),
sys_clk_freq=sys_clk_freq,
iodelay_clk_freq=200e6)
sdram_module = MT8KTF51264(sys_clk_freq, "1:4", speedgrade="800")
self.register_sdram(self.ddrphy,
sdram_module.geom_settings,
sdram_module.timing_settings)
self.add_csr("ddrphy")
# PCIe -------------------------------------------------------------------------------------
# pcie phy
self.submodules.pcie_phy = S7PCIEPHY(platform, platform.request("pcie_x1"), bar0_size=0x20000)
self.pcie_phy.cd_pcie.clk.attr.add("keep")
platform.add_platform_command("create_clock -name pcie_clk -period 8 [get_nets pcie_clk]")
platform.add_false_path_constraints(
self.crg.cd_sys.clk,
self.pcie_phy.cd_pcie.clk)
self.add_csr("pcie_phy")
# pcie endpoint
self.submodules.pcie_endpoint = LitePCIeEndpoint(self.pcie_phy)
# pcie wishbone bridge
self.submodules.pcie_wishbone = LitePCIeWishboneBridge(self.pcie_endpoint,
lambda a: 1, shadow_base=self.shadow_base)
self.add_wb_master(self.pcie_wishbone.wishbone)
# pcie dma
self.submodules.pcie_dma = LitePCIeDMA(self.pcie_phy, self.pcie_endpoint,
with_buffering=True, buffering_depth=1024, with_loopback=True)
self.add_csr("pcie_dma")
# pcie msi
self.submodules.pcie_msi = LitePCIeMSI()
self.add_csr("pcie_msi")
self.comb += self.pcie_msi.source.connect(self.pcie_phy.msi)
self.msis = {
"DMA_WRITER": self.pcie_dma.writer.irq,
"DMA_READER": self.pcie_dma.reader.irq
}
for i, (k, v) in enumerate(sorted(self.msis.items())):
self.comb += self.pcie_msi.irqs[i].eq(v)
self.add_constant(k + "_INTERRUPT", i)
# pcie uart
if with_pcie_uart:
class PCIeUART(Module, AutoCSR):
def __init__(self, uart):
self.rx_valid = CSRStatus()
self.rx_ready = CSR()
self.rx_data = CSRStatus(8)
self.tx_valid = CSR()
self.tx_ready = CSRStatus()
self.tx_data = CSRStorage(8)
# # #
# cpu to pcie
self.comb += [
self.rx_valid.status.eq(uart.sink.valid),
uart.sink.ready.eq(self.rx_ready.re),
self.rx_data.status.eq(uart.sink.data),
]
# pcie to cpu
self.sync += [
If(self.tx_valid.re,
uart.source.valid.eq(1)
).Elif(uart.source.ready,
uart.source.valid.eq(0)
)
]
self.comb += [
self.tx_ready.status.eq(~uart.source.valid),
uart.source.data.eq(self.tx_data.storage)
]
uart_interface = RS232PHYInterface()
self.submodules.uart = UART(uart_interface)
self.add_csr("uart")
self.add_interrupt("uart")
self.submodules.pcie_uart = PCIeUART(uart_interface)
self.add_csr("pcie_uart")
# Leds -------------------------------------------------------------------------------------
# led blinking (sys)
sys_counter = Signal(32)
self.sync.sys += sys_counter.eq(sys_counter + 1)
rgb = platform.request("rgb_led")
self.comb += [
rgb.r.eq(1),
rgb.g.eq(sys_counter[26]),
rgb.b.eq(1),
]
def generate_software_header(self, filename):
csr_header = get_csr_header(self.get_csr_regions(),
self.get_constants(),
with_access_functions=False,
with_shadow_base=False)
tools.write_to_file(filename, csr_header)
# Build --------------------------------------------------------------------------------------------
def main():
platform = nereid.Platform()
soc = NereidSoC(platform)
builder = Builder(soc, output_dir="../build/nereid", csr_csv="../build/nereid/csr.csv",
compile_gateware=not "no-compile" in sys.argv[1:])
vns = builder.build(build_name="nereid")
soc.generate_software_header("../software/kernel/csr.h")
if __name__ == "__main__":
main()
| __init__ |
utils.ts | /**
* @license
* Copyright 2019 Balena Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { ParsedPath, posix } from 'path';
export interface ParsedPathPlus extends ParsedPath {
minusExt: string;
unparsed: string;
}
export function removeExtension(filename: string): string {
const idx = filename.lastIndexOf('.');
if (idx !== -1) {
return filename.substr(0, idx);
}
return filename; | }
/**
* Like path.posix.parse(), with a couple more fields: minusExt and unparsed.
* https://nodejs.org/docs/latest-v8.x/api/path.html#path_path_parse_path
*/
export function parsePosixPath(posixPath: string): ParsedPathPlus {
const { base, dir, ext, name, root } = posix.parse(posixPath);
return {
base,
dir,
ext,
minusExt: dir && dir !== '.' ? `${dir}/${name}` : name,
name,
root,
unparsed: posixPath,
};
} | |
paginator.js | /**
* __PrimeFaces Paginator Widget__
*
* A widget for handling pagination that is usually used by other widget via composition, that is, they create and save
* an instance of this widget during initialization. After you create a new instance of this paginator, you should set
* the `paginate` property to an appropriate callback function.
*
* ```javascript
* const paginator = new PrimeFaces.widget.Paginator(paginatorCfg);
* paginator.paginator = newState => {
* // handle pagination
* };
* ```
*
* @typedef PrimeFaces.widget.Paginator.PaginateCallback A callback method that is invoked when the pagination state
* changes, see {@link PaginatorCfg.paginate}.
* @param {PrimeFaces.widget.Paginator.PaginationState} PrimeFaces.widget.Paginator.PaginateCallback.newState The new
* values for the current page and the rows per page count.
*
* @interface {PrimeFaces.widget.Paginator.PaginationState} PaginatorState Represents a pagination state, that is, a
* range of items that should be displayed.
* @prop {number} PaginatorState.first 0-based index of the first item on the current page.
* @prop {number} PaginatorState.rows The number of rows per page.
* @prop {number} PaginatorState.page The current page, 0-based index.
*
* @prop {JQuery} currentReport DOM element of the status text as configured by the `currentPageTemplate`.
* @prop {JQuery} endLink DOM element of the link to the last page.
* @prop {JQuery} firstLink DOM element of the link back to the first page.
* @prop {JQuery} jtpInput INPUT element for selecting a page to navigate to (`jump to page`)
* @prop {JQuery} jtpSelect SELECT element for selecting a page to navigate to (`jump to page`)
* @prop {JQuery} nextLink DOM element of the link to the next page.
* @prop {JQuery} pagesContainer DOM element of the container with the numbered page links.
* @prop {JQuery} pageLinks DOM elements of each numbered page link.
* @prop {JQuery} prevLink DOM element of the link back to the previous page.
* @prop {JQuery} rppSelect SELECT element for selection the number of pages to display (`rows per page`).
*
* @interface {PrimeFaces.widget.PaginatorCfg} cfg The configuration for the {@link Paginator| Paginator widget}.
* You can access this configuration via {@link PrimeFaces.widget.BaseWidget.cfg|BaseWidget.cfg}. Please note that this
* configuration is usually meant to be read-only and should not be modified.
* @extends {PrimeFaces.widget.BaseWidgetCfg} cfg
*
* @prop {boolean} cfg.alwaysVisible `true` if the paginator should be displayed always, or `false` if it is allowed to
* be hidden under some circumstances that depend on the widget that uses the paginator.
* @prop {string} cfg.ariaPageLabel ARIA LABEL attribute for the page links.
* @prop {string} cfg.currentPageTemplate Template for the paginator text. It may contain placeholders such as
* `{currentPage}` or `{totalPages}`.
* @prop {number} cfg.page The current page, 0-based index.
* @prop {number} cfg.pageCount The number of pages.
* @prop {number} cfg.pageLinks The maximum number of page links to display (when there are many pages).
* @prop {PrimeFaces.widget.Paginator.PaginateCallback} cfg.paginate A callback method that is invoked when the
* pagination state changes, such as when the user selects a different page or changes the current rows per page count.
* This property is usually provided by another widget that makes use of this paginator. You should use this callback to
* perform any actions required to apply the new pagination state.
* @prop {number} cfg.prevRows The number of rows per page for the dropdown.
* @prop {number} cfg.rowCount Total number of rows (records) to be displayed.
* @prop {number} cfg.rows The number of rows per page.
*/
PrimeFaces.widget.Paginator = PrimeFaces.widget.BaseWidget.extend({
/**
* @override
* @inheritdoc
* @param {PrimeFaces.PartialWidgetCfg<TCfg>} cfg
*/
init: function(cfg) {
this._super(cfg);
//elements
this.pagesContainer = this.jq.children('.ui-paginator-pages');
this.pageLinks = this.pagesContainer.children('.ui-paginator-page');
this.rppSelect = this.jq.children('.ui-paginator-rpp-options');
this.jtpSelect = this.jq.children('.ui-paginator-jtp-select');
this.jtpInput = this.jq.children('.ui-paginator-jtp-input');
this.firstLink = this.jq.children('.ui-paginator-first');
this.prevLink = this.jq.children('.ui-paginator-prev');
this.nextLink = this.jq.children('.ui-paginator-next');
this.endLink = this.jq.children('.ui-paginator-last');
this.currentReport = this.jq.children('.ui-paginator-current');
//metadata
this.cfg.rows = this.cfg.rows == 0 ? this.cfg.rowCount : this.cfg.rows;
this.cfg.prevRows = this.cfg.rows;
this.cfg.pageCount = Math.ceil(this.cfg.rowCount / this.cfg.rows)||1;
this.cfg.pageLinks = this.cfg.pageLinks||10;
this.cfg.currentPageTemplate = this.cfg.currentPageTemplate||'({currentPage} of {totalPages})';
//aria message
this.cfg.ariaPageLabel = PrimeFaces.getAriaLabel('paginator.PAGE');
//event bindings
this.bindEvents();
},
/**
* Sets up all event listeners for this widget.
* @private
*/
bindEvents: function(){
var $this = this;
//visuals for first,prev,next,last buttons
this.jq.children('a.ui-state-default').on('mouseover.paginator', function(){
var item = $(this);
if(!item.hasClass('ui-state-disabled')) {
item.addClass('ui-state-hover');
}
})
.on('mouseout.paginator', function() {
$(this).removeClass('ui-state-hover');
})
.on('focus.paginator', function() {
var item = $(this);
if(!item.hasClass('ui-state-disabled')) {
item.addClass('ui-state-focus');
}
})
.on('blur.paginator', function() {
$(this).removeClass('ui-state-focus');
})
.on('keydown.paginator', function(e) {
var key = e.which,
keyCode = $.ui.keyCode;
if((key === keyCode.ENTER)) {
$(this).trigger('click');
e.preventDefault();
}
});
//page links
this.bindPageLinkEvents();
//records per page selection
PrimeFaces.skinSelect(this.rppSelect);
this.rppSelect.on('change', function(e) {
if(!$(this).hasClass("ui-state-disabled")){
$this.setRowsPerPage($(this).val());
}
});
//jump to page dropdown
PrimeFaces.skinSelect(this.jtpSelect);
this.jtpSelect.on('change', function(e) {
if(!$(this).hasClass("ui-state-disabled")){
$this.setPage(parseInt($(this).val()));
}
});
//jump to page input
PrimeFaces.skinInput(this.jtpInput);
this.jtpInput.on('change', function(e) {
if(!$(this).hasClass("ui-state-disabled")){
var page = parseInt($(this).val());
if (isNaN(page) || page > $this.cfg.pageCount || page < 1) {
// restore old value if invalid
$(this).val($this.cfg.page + 1);
}
else {
$this.setPage(page - 1);
}
}
});
//First page link
this.firstLink.on("click", function(e) {
PrimeFaces.clearSelection();
if(!$(this).hasClass("ui-state-disabled")){
$this.setPage(0);
}
e.preventDefault();
});
//Prev page link
this.prevLink.on("click", function(e) {
PrimeFaces.clearSelection();
if(!$(this).hasClass("ui-state-disabled")){
$this.setPage($this.cfg.page - 1);
}
e.preventDefault();
});
//Next page link
this.nextLink.on("click", function(e) {
PrimeFaces.clearSelection();
if(!$(this).hasClass("ui-state-disabled")){
$this.setPage($this.cfg.page + 1);
}
e.preventDefault();
});
//Last page link
this.endLink.on("click", function(e) {
PrimeFaces.clearSelection();
if(!$(this).hasClass("ui-state-disabled")){
$this.setPage($this.cfg.pageCount - 1);
}
e.preventDefault();
});
},
/**
* Sets up the event listeners for page link buttons.
* @private
*/
bindPageLinkEvents: function(){
var $this = this,
pageLinks = this.pagesContainer.children('.ui-paginator-page');
pageLinks.each(function() {
var link = $(this),
pageNumber = parseInt(link.text());
link.attr('aria-label', $this.cfg.ariaPageLabel.replace('{0}', (pageNumber)));
});
pageLinks.on('click.paginator', function(e) {
var link = $(this),
pageNumber = parseInt(link.text());
if(!link.hasClass('ui-state-disabled')&&!link.hasClass('ui-state-active')) {
$this.setPage(pageNumber - 1);
}
e.preventDefault();
})
.on('mouseover.paginator', function() {
var item = $(this);
if(!item.hasClass('ui-state-disabled')&&!item.hasClass('ui-state-active')) {
item.addClass('ui-state-hover');
}
})
.on('mouseout.paginator', function() {
$(this).removeClass('ui-state-hover');
})
.on('focus.paginator', function() {
$(this).addClass('ui-state-focus');
})
.on('blur.paginator', function() {
$(this).removeClass('ui-state-focus');
})
.on('keydown.paginator', function(e) { | $(this).trigger('click');
e.preventDefault();
}
});
},
/**
* Binds swipe events to this paginator to the JQ element passed in.
* @private
* @param {JQuery} owner the owner JQ element of the paginator
* @param {PrimeFaces.PartialWidgetCfg<TCfg>} ownerConfig the owner configuration to check if touch enabled or not
*/
bindSwipeEvents: function(owner, ownerConfig) {
if (!PrimeFaces.env.isTouchable(ownerConfig)) {
return;
}
var $this = this;
owner.swipe({
swipeLeft:function(event) {
$this.prev();
},
swipeRight: function(event) {
$this.next();
},
excludedElements: PrimeFaces.utils.excludedSwipeElements()
});
},
/**
* Removes all event listeners.
* @private
*/
unbindEvents: function() {
var buttons = this.jq.children('a.ui-state-default');
if (buttons.length > 0) {
buttons.off();
}
var pageLinks = this.pagesContainer.children('.ui-paginator-page');
if (pageLinks.length > 0) {
pageLinks.off();
}
},
/**
* Updates the UI so that it reflects the current pagination state.
* @private
*/
updateUI: function() {
//boundaries
if(this.cfg.page === 0) {
this.disableElement(this.firstLink);
this.disableElement(this.prevLink);
}
else {
this.enableElement(this.firstLink);
this.enableElement(this.prevLink);
}
if(this.cfg.page === (this.cfg.pageCount - 1)) {
this.disableElement(this.nextLink);
this.disableElement(this.endLink);
}
else {
this.enableElement(this.nextLink);
this.enableElement(this.endLink);
}
//current page report
var startRecord = (this.cfg.rowCount === 0) ? 0 : (this.cfg.page * this.cfg.rows) + 1,
endRecord = (this.cfg.page * this.cfg.rows) + this.cfg.rows;
if(endRecord > this.cfg.rowCount) {
endRecord = this.cfg.rowCount;
}
var text = this.cfg.currentPageTemplate
.replace("{currentPage}", this.cfg.page + 1)
.replace("{totalPages}", this.cfg.pageCount)
.replace("{totalRecords}", this.cfg.rowCount)
.replace("{startRecord}", startRecord)
.replace("{endRecord}", endRecord);
this.currentReport.text(text);
//rows per page dropdown
if(this.cfg.prevRows !== this.cfg.rows) {
this.rppSelect.filter(':not(.ui-state-focus)').children('option').filter('option[value="' + $.escapeSelector(this.cfg.rows) + '"]').prop('selected', true);
this.cfg.prevRows = this.cfg.rows;
}
//jump to page dropdown
if(this.jtpSelect.length > 0) {
if(this.jtpSelect[0].options.length != this.cfg.pageCount){
var jtpOptions = '';
for(var i = 0; i < this.cfg.pageCount; i++) {
jtpOptions += '<option value="' + i + '">' + (i + 1) + '</option>';
}
this.jtpSelect.html(jtpOptions);
}
this.jtpSelect.children('option[value=' + (this.cfg.page) + ']').prop('selected','selected');
}
//jump to page input
if(this.jtpInput.length > 0) {
this.jtpInput.val(this.cfg.page + 1);
}
//page links
this.updatePageLinks();
},
/**
* Updates the UI of page link button so that they reflect the current pagination state.
* @private
*/
updatePageLinks: function() {
var start, end, delta,
focusedElement = $(document.activeElement),
focusContainer;
if(focusedElement.hasClass('ui-paginator-page')) {
var pagesContainerIndex = this.pagesContainer.index(focusedElement.parent());
if(pagesContainerIndex >= 0) {
focusContainer = this.pagesContainer.eq(pagesContainerIndex);
}
}
//calculate visible page links
this.cfg.pageCount = Math.ceil(this.cfg.rowCount / this.cfg.rows)||1;
var visiblePages = Math.min(this.cfg.pageLinks, this.cfg.pageCount);
//calculate range, keep current in middle if necessary
start = Math.max(0, Math.ceil(this.cfg.page - ((visiblePages) / 2)));
end = Math.min(this.cfg.pageCount - 1, start + visiblePages - 1);
//check when approaching to last page
delta = this.cfg.pageLinks - (end - start + 1);
start = Math.max(0, start - delta);
//update dom
this.pagesContainer.children().remove();
for(var i = start; i <= end; i++) {
var styleClass = 'ui-paginator-page ui-state-default ui-corner-all',
ariaLabel = this.cfg.ariaPageLabel.replace('{0}', (i+1));
if(this.cfg.page == i) {
styleClass += " ui-state-active";
}
this.pagesContainer.append('<a class="' + styleClass + '" aria-label="' + ariaLabel + '" tabindex="0" href="#">' + (i + 1) + '</a>');
}
if(focusContainer) {
focusContainer.children().filter('.ui-state-active').trigger('focus');
}
this.bindPageLinkEvents();
},
/**
* Switches this pagination to the given page.
* @param {number} p 0-based index of the page to switch to.
* @param {boolean} [silent=false] `true` to not invoke any event listeners, `false` otherwise.
*/
setPage: function(p, silent) {
if(p >= 0 && p < this.cfg.pageCount && this.cfg.page != p){
var newState = {
first: this.cfg.rows * p,
rows: this.cfg.rows,
page: p
};
if(silent) {
this.cfg.page = p;
this.updateUI();
}
else {
this.cfg.paginate.call(this, newState);
}
}
},
/**
* Modifies the number of rows that are shown per page.
* @param {number} rpp Number of rows per page to set.
*/
setRowsPerPage: function(rpp) {
if (rpp === '*') {
this.cfg.rows = this.cfg.rowCount;
this.cfg.pageCount = 1;
this.cfg.page = 0;
var newState = {
first: 0,
rows: rpp,
page: this.cfg.page
};
this.cfg.paginate.call(this, newState);
}
else {
var first = this.cfg.rows * this.cfg.page;
this.cfg.rows = parseInt(rpp);
var page = parseInt(first / this.cfg.rows);
this.cfg.pageCount = Math.ceil(this.cfg.rowCount / this.cfg.rows);
this.cfg.page = -1;
this.setPage(page);
}
},
/**
* Modifies the total number of items that are available, and switches to the first page.
* @param {number} value The total number of items to set.
*/
setTotalRecords: function(value) {
this.cfg.rowCount = value;
this.cfg.pageCount = Math.ceil(value / this.cfg.rows)||1;
this.cfg.page = 0;
this.updateUI();
},
/**
* Modifies the total number of items that are available.
* @param {number} value The total number of items to set.
* @private
*/
updateTotalRecords: function(value) {
this.cfg.rowCount = value;
this.cfg.pageCount = Math.ceil(value / this.cfg.rows)||1;
this.updateUI();
},
/**
* Finds the index of the page that is currently displayed.
* @return {number} 0-based index of the current page.
*/
getCurrentPage: function() {
return this.cfg.page;
},
/**
* Finds the index of the item that is shown first on the current page.
* @return {number} 0-based index of the first item on the current page.
*/
getFirst: function() {
return (this.cfg.rows * this.cfg.page);
},
/**
* Finds the current number of rows per page.
* @return {number} The number of rows per page.
*/
getRows: function() {
return this.cfg.rows;
},
/**
* Calculates the required height of the container with the items of the current page.
* @private
* @param {number} margin Additional margin in pixels to consider.
* @return {number} The height of the items container in pixels
*/
getContainerHeight: function(margin) {
var height = 0;
for(var i = 0; i < this.jq.length; i++) {
height += this.jq.eq(i).outerHeight(margin);
}
return height;
},
/**
* Disables one of the items of this pagination.
* @private
* @param {JQuery} element Element to disabled.
*/
disableElement: function(element) {
element.removeClass('ui-state-hover ui-state-focus ui-state-active').addClass('ui-state-disabled').attr('tabindex', -1);
element.removeClass('ui-state-hover ui-state-focus ui-state-active').addClass('ui-state-disabled').attr('tabindex', -1);
},
/**
* Enables one of the items of this pagination.
* @private
* @param {JQuery} element Element to disabled.
*/
enableElement: function(element) {
element.removeClass('ui-state-disabled').attr('tabindex', 0);
},
/**
* Switches to the next page. Does nothing when this pagination is already on the last page.
*/
next: function() {
this.setPage(this.cfg.page + 1);
},
/**
* Switches to the previous page. Does nothing when this pagination is already on the first page.
*/
prev: function() {
this.setPage(this.cfg.page - 1);
}
}); | var key = e.which,
keyCode = $.ui.keyCode;
if((key === keyCode.ENTER)) { |
tdpos.go | //Copyright 2019 Baidu, Inc.
package tdpos
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"math/big"
"os"
"strconv"
"sync"
"time"
log "github.com/xuperchain/log15"
"encoding/hex"
"encoding/json"
"github.com/xuperchain/xuperunion/common"
"github.com/xuperchain/xuperunion/common/config"
cons_base "github.com/xuperchain/xuperunion/consensus/base"
chainedbft "github.com/xuperchain/xuperunion/consensus/common/chainedbft"
bft_config "github.com/xuperchain/xuperunion/consensus/common/chainedbft/config"
"github.com/xuperchain/xuperunion/consensus/tdpos/bft"
"github.com/xuperchain/xuperunion/contract"
crypto_base "github.com/xuperchain/xuperunion/crypto/client/base"
"github.com/xuperchain/xuperunion/global"
"github.com/xuperchain/xuperunion/ledger"
"github.com/xuperchain/xuperunion/p2pv2"
"github.com/xuperchain/xuperunion/pb"
"github.com/xuperchain/xuperunion/utxo"
)
// Init init tdpos
func (tp *TDpos) Init() {
tp.config = tDposConfig{
initProposer: make(map[int64][]*cons_base.CandidateInfo),
}
tp.isProduce = make(map[int64]bool)
tp.candidateBallots = new(sync.Map)
tp.candidateBallotsCache = new(sync.Map)
tp.revokeCache = new(sync.Map)
tp.context = &contract.TxContext{}
tp.mutex = new(sync.RWMutex)
}
// Type return the type of TDpos consensus
func (tp *TDpos) Type() string {
return TYPE
}
// Version return the version of TDpos consensus
func (tp *TDpos) Version() int64 {
return tp.version
}
// Configure is the specific implementation of ConsensusInterface
func (tp *TDpos) Configure(xlog log.Logger, cfg *config.NodeConfig, consCfg map[string]interface{},
extParams map[string]interface{}) error {
if xlog == nil {
xlog = log.New("module", "consensus")
xlog.SetHandler(log.StreamHandler(os.Stderr, log.LogfmtFormat()))
}
address, err := ioutil.ReadFile(cfg.Miner.Keypath + "/address")
if err != nil {
xlog.Warn("load address error", "path", cfg.Miner.Keypath+"/address")
return err
}
tp.log = xlog
tp.address = address
switch extParams["crypto_client"].(type) {
case crypto_base.CryptoClient:
tp.cryptoClient = extParams["crypto_client"].(crypto_base.CryptoClient)
default:
errMsg := "invalid type of crypto_client"
xlog.Warn(errMsg)
return errors.New(errMsg)
}
switch extParams["ledger"].(type) {
case *ledger.Ledger:
tp.ledger = extParams["ledger"].(*ledger.Ledger)
default:
errMsg := "invalid type of ledger"
xlog.Warn(errMsg)
return errors.New(errMsg)
}
switch extParams["utxovm"].(type) {
case *utxo.UtxoVM:
tp.utxoVM = extParams["utxovm"].(*utxo.UtxoVM)
default:
errMsg := "invalid type of utxovm"
xlog.Warn(errMsg)
return errors.New(errMsg)
}
switch extParams["bcname"].(type) {
case string:
tp.bcname = extParams["bcname"].(string)
default:
errMsg := "invalid type of bcname"
xlog.Warn(errMsg)
return errors.New(errMsg)
}
switch extParams["timestamp"].(type) {
case int64:
tp.initTimestamp = extParams["timestamp"].(int64)
default:
errMsg := "invalid type of timestamp"
xlog.Warn(errMsg)
return errors.New(errMsg)
}
if p2psvr, ok := extParams["p2psvr"].(p2pv2.P2PServer); ok {
tp.p2psvr = p2psvr
}
if height, ok := extParams["height"].(int64); ok {
tp.height = height
}
if err = tp.buildConfigs(xlog, nil, consCfg); err != nil {
return err
}
if err = tp.initBFT(cfg); err != nil {
xlog.Warn("init chained-bft failed!", "error", err)
return err
}
if err = tp.initCandidateBallots(); err != nil |
tp.log.Trace("Configure", "TDpos", tp)
return nil
}
func (tp *TDpos) buildConfigs(xlog log.Logger, cfg *config.NodeConfig, consCfg map[string]interface{}) error {
// assemble consensus config
if consCfg["proposer_num"] == nil {
return errors.New("Parse TDpos proposer_num error, can not be null")
}
if consCfg["period"] == nil {
return errors.New("Parse TDpos period error, can not be null")
}
if consCfg["alternate_interval"] == nil {
return errors.New("Parse TDpos alternate_interval error, can not be null")
}
if consCfg["term_interval"] == nil {
return errors.New("Parse TDpos term_interval error, can not be null")
}
if consCfg["vote_unit_price"] == nil {
return errors.New("Parse TDpos vote_unit_price error, can not be null")
}
if consCfg["block_num"] == nil {
return errors.New("Parse TDpos block_num error, can not be null")
}
if consCfg["init_proposer"] == nil {
return errors.New("Parse TDpos init_proposer error, can not be null")
}
if consCfg["version"] == nil {
tp.version = 0
} else {
version, err := strconv.ParseInt(consCfg["version"].(string), 10, 64)
if err != nil {
xlog.Warn("Parse TDpos config version error", "error", err.Error())
return err
}
tp.version = version
}
proposerNum, err := strconv.ParseInt(consCfg["proposer_num"].(string), 10, 64)
if err != nil {
xlog.Warn("Parse TDpos config error", "error", err.Error())
return err
}
tp.config.proposerNum = proposerNum
period, err := strconv.ParseInt(consCfg["period"].(string), 10, 64)
if err != nil {
xlog.Warn("Parse TDpos config period error", "error", err.Error())
return err
}
tp.config.period = period * 1e6
alternateInterval, err := strconv.ParseInt(consCfg["alternate_interval"].(string), 10, 64)
if err != nil {
xlog.Warn("Parse TDpos config alternateInterval error", "error", err.Error())
return err
}
if alternateInterval%period != 0 {
xlog.Warn("Parse TDpos config alternateInterval error", "error", "alternateInterval should be eliminated by period")
return errors.New("alternateInterval should be eliminated by period")
}
tp.config.alternateInterval = alternateInterval * 1e6
termInterval, err := strconv.ParseInt(consCfg["term_interval"].(string), 10, 64)
if err != nil {
xlog.Warn("Parse TDpos config termInterval error", "error", err.Error())
return err
}
if termInterval%period != 0 {
xlog.Warn("Parse TDpos config termInterval error", "error", "termInterval should be eliminated by period")
return errors.New("termInterval should be eliminated by period")
}
tp.config.termInterval = termInterval * 1e6
voteUnitPrice := big.NewInt(0)
if _, ok := voteUnitPrice.SetString(consCfg["vote_unit_price"].(string), 10); !ok {
xlog.Warn("Parse TDpos config vote unit price error")
return errors.New("Parse TDpos config vote unit price error")
}
tp.config.voteUnitPrice = voteUnitPrice
blockNum, err := strconv.ParseInt(consCfg["block_num"].(string), 10, 64)
if err != nil {
xlog.Warn("Parse TDpos block_num period error", "error", err.Error())
return err
}
tp.config.blockNum = blockNum
// read config of need_neturl
needNetURL := false
if needNetURLVal, ok := consCfg["need_neturl"]; ok {
needNetURL = needNetURLVal.(bool)
}
tp.config.needNetURL = needNetURL
initProposer := consCfg["init_proposer"].(map[string]interface{})
xlog.Trace("initProposer", "initProposer", initProposer)
if len(initProposer) != 1 {
xlog.Warn("TDpos init proposer length error", "length", len(initProposer))
return errors.New("TDpos init proposer length error")
}
// first round proposers
if _, ok := initProposer["1"]; !ok {
return errors.New("TDpos init proposer error, Proposer 0 not provided")
}
initProposer1 := initProposer["1"].([]interface{})
if int64(len(initProposer1)) != proposerNum {
return errors.New("TDpos init proposer info error, Proposer 0 should be equal to proposerNum")
}
for _, v := range initProposer1 {
canInfo := &cons_base.CandidateInfo{}
canInfo.Address = v.(string)
tp.config.initProposer[1] = append(tp.config.initProposer[1], canInfo)
}
// if have init_proposer_neturl, this info can be used for core peers connection
if _, ok := consCfg["init_proposer_neturl"]; ok {
proposerNeturls := consCfg["init_proposer_neturl"].(map[string]interface{})
if _, ok := proposerNeturls["1"]; !ok {
return errors.New("TDpos have init_proposer_neturl but don't have term 1")
}
proposerNeturls1 := proposerNeturls["1"].([]interface{})
if int64(len(proposerNeturls1)) != proposerNum {
return errors.New("TDpos init error, Proposer neturl number should be equal to proposerNum")
}
for idx, v := range proposerNeturls1 {
tp.config.initProposer[1][idx].PeerAddr = v.(string)
tp.log.Debug("TDpos proposer info", "index", idx, "proposer", tp.config.initProposer[1][idx])
}
} else {
tp.log.Warn("TDpos have no neturl info for proposers",
"neet_neturl", needNetURL)
if needNetURL {
return errors.New("config error, init_proposer_neturl could not be empty")
}
}
// parse bft related config
tp.config.enableBFT = false
if bftConfData, ok := consCfg["bft_config"].(map[string]interface{}); ok {
bftconf := bft_config.MakeConfig(bftConfData)
// if bft_config is not empty, enable bft
tp.config.enableBFT = true
tp.config.bftConfig = bftconf
}
tp.log.Trace("TDpos after config", "TTDpos.config", tp.config)
return nil
}
func (tp *TDpos) initCandidateBallots() error {
it := tp.utxoVM.ScanWithPrefix([]byte(GenCandidateBallotsPrefix()))
defer it.Release()
for it.Next() {
key := string(it.Key())
address, err := ParseCandidateBallotsKey(key)
tp.log.Trace("initCandidateBallots", "key", key, "address", address)
if err != nil {
tp.log.Warn("initCandidateBallots parseCandidateBallotsKey error", "key", key)
return err
}
ballots, err := strconv.ParseInt(string(it.Value()), 10, 64)
tp.log.Trace("initCandidateBallots", "key", key, "address", address, "ballots", ballots)
if err != nil {
return err
}
tp.candidateBallots.Store(key, ballots)
}
return nil
}
// CompeteMaster is the specific implementation of ConsensusInterface
func (tp *TDpos) CompeteMaster(height int64) (bool, bool) {
sentNewView := false
Again:
t := time.Now()
un := t.UnixNano()
key := un / tp.config.period
sleep := tp.config.period - un%tp.config.period
maxsleeptime := time.Millisecond * 10
if sleep > int64(maxsleeptime) {
sleep = int64(maxsleeptime)
}
v, ok := tp.isProduce[key]
if !ok || v == false {
tp.isProduce[key] = true
} else {
time.Sleep(time.Duration(sleep))
goto Again
}
// 查当前时间的term 和 pos
t2 := time.Now()
un2 := t2.UnixNano()
term, pos, blockPos := tp.minerScheduling(un2)
// 查当前term 和 pos是否是自己
tp.curTerm = term
if blockPos > tp.config.blockNum || pos >= tp.config.proposerNum {
if !sentNewView {
// only run once when term or proposer change
err := tp.notifyNewView(height)
if err != nil {
tp.log.Warn("proposer or term change, bft Newview failed", "error", err)
}
sentNewView = true
}
goto Again
}
// reset proposers when term changed
if pos == 0 && blockPos == 1 {
err := tp.notifyTermChanged(tp.curTerm)
if err != nil {
tp.log.Warn("proposer or term change, bft Update Validators failed", "error", err)
}
}
// if NewView not sent, send NewView message
if !sentNewView {
// if no term or proposer change, run NewView before generate block
err := tp.notifyNewView(height)
if err != nil {
tp.log.Warn("proposer not changed, bft Newview failed", "error", err)
}
sentNewView = true
}
// master check
if tp.isProposer(term, pos, tp.address) {
tp.log.Trace("CompeteMaster now xterm infos", "term", term, "pos", pos, "blockPos", blockPos, "un2", un2,
"master", true)
tp.curBlockNum = blockPos
s := tp.needSync()
return true, s
}
tp.log.Trace("CompeteMaster now xterm infos", "term", term, "pos", pos, "blockPos", blockPos, "un2", un2,
"master", false)
return false, false
}
func (tp *TDpos) needSync() bool {
meta := tp.ledger.GetMeta()
if meta.TrunkHeight == 0 {
return true
}
blockTip, err := tp.ledger.QueryBlock(meta.TipBlockid)
if err != nil {
return true
}
if string(blockTip.Proposer) == string(tp.address) {
return false
}
return true
}
func (tp *TDpos) notifyNewView(height int64) error {
if !tp.config.enableBFT {
// BFT not enabled, continue
return nil
}
// get current proposer
meta := tp.ledger.GetMeta()
proposer, err := tp.getProposer(0, 0)
if err != nil {
return err
}
if meta.TrunkHeight != 0 {
blockTip, err := tp.ledger.QueryBlock(meta.TipBlockid)
if err != nil {
return err
}
proposer = string(blockTip.GetProposer())
}
// get next proposer
// 查当前时间的term 和 pos
t2 := time.Now()
un2 := t2.UnixNano()
term, pos, blockPos := tp.minerScheduling(un2)
nextProposer, err := tp.getNextProposer(term, pos, blockPos)
if err != nil {
return err
}
// old height might out-of-date, use current trunkHeight when NewView
return tp.bftPaceMaker.NextNewView(meta.TrunkHeight+1, nextProposer, proposer)
}
func (tp *TDpos) notifyTermChanged(term int64) error {
if !tp.config.enableBFT {
// BFT not enabled, continue
return nil
}
proposers := tp.getTermProposer(term)
return tp.bftPaceMaker.UpdateValidatorSet(proposers)
}
// CheckMinerMatch is the specific implementation of ConsensusInterface
func (tp *TDpos) CheckMinerMatch(header *pb.Header, in *pb.InternalBlock) (bool, error) {
// 1 验证块信息是否合法
blkid, err := ledger.MakeBlockID(in)
if err != nil {
tp.log.Warn("CheckMinerMatch MakeBlockID error", "logid", header.Logid, "error", err)
return false, nil
}
if !(bytes.Equal(blkid, in.Blockid)) {
tp.log.Warn("CheckMinerMatch equal blockid error", "logid", header.Logid, "redo blockid", global.F(blkid),
"get blockid", global.F(in.Blockid))
return false, nil
}
k, err := tp.cryptoClient.GetEcdsaPublicKeyFromJSON(in.Pubkey)
if err != nil {
tp.log.Warn("CheckMinerMatch get ecdsa from block error", "logid", header.Logid, "error", err)
return false, nil
}
chkResult, _ := tp.cryptoClient.VerifyAddressUsingPublicKey(string(in.Proposer), k)
if chkResult == false {
tp.log.Warn("CheckMinerMatch address is not match publickey", "logid", header.Logid)
return false, nil
}
valid, err := tp.cryptoClient.VerifyECDSA(k, in.Sign, in.Blockid)
if err != nil || !valid {
tp.log.Warn("CheckMinerMatch VerifyECDSA error", "logid", header.Logid, "error", err)
return false, nil
}
if tp.config.enableBFT && !tp.isFirstblock(in.GetHeight()) {
// if BFT enabled and it's not the first proposal
// check whether previous block's QuorumCert is valid
ok, err := tp.bftPaceMaker.GetChainedBFT().IsQuorumCertValidate(in.GetJustify())
if err != nil || !ok {
tp.log.Warn("CheckMinerMatch bft IsQuorumCertValidate failed", "logid", header.Logid, "error", err)
return false, nil
}
}
// 2 验证轮数信息
preBlock, err := tp.ledger.QueryBlock(in.PreHash)
if err != nil {
tp.log.Warn("CheckMinerMatch failed, get preblock error")
return false, nil
}
tp.log.Trace("CheckMinerMatch", "preBlock.CurTerm", preBlock.CurTerm, "in.CurTerm", in.CurTerm, " in.Proposer",
string(in.Proposer), "blockid", fmt.Sprintf("%x", in.Blockid))
term, pos, _ := tp.minerScheduling(in.Timestamp)
if tp.isProposer(term, pos, in.Proposer) {
// curTermProposerProduceNumCache is not thread safe, lock before use it.
tp.mutex.Lock()
defer tp.mutex.Unlock()
// 当不是第一轮时需要和前面的
if in.CurTerm != 1 {
// 减少矿工50%概率恶意地输入时间
if preBlock.CurTerm > term {
tp.log.Warn("CheckMinerMatch failed, preBlock.CurTerm is bigger than this!")
return false, nil
}
// 当系统切轮时初始化 curTermProposerProduceNum
if preBlock.CurTerm < term || (tp.curTerm == term && tp.curTermProposerProduceNumCache == nil) {
tp.curTermProposerProduceNumCache = make(map[int64]map[string]map[string]bool)
tp.curTermProposerProduceNumCache[in.CurTerm] = make(map[string]map[string]bool)
}
}
// 判断某个矿工是否恶意出块
if tp.curTermProposerProduceNumCache != nil && tp.curTermProposerProduceNumCache[in.CurTerm] != nil {
if _, ok := tp.curTermProposerProduceNumCache[in.CurTerm][string(in.Proposer)]; !ok {
tp.curTermProposerProduceNumCache[in.CurTerm][string(in.Proposer)] = make(map[string]bool)
tp.curTermProposerProduceNumCache[in.CurTerm][string(in.Proposer)][hex.EncodeToString(in.Blockid)] = true
} else {
if !tp.curTermProposerProduceNumCache[in.CurTerm][string(in.Proposer)][hex.EncodeToString(in.Blockid)] {
tp.curTermProposerProduceNumCache[in.CurTerm][string(in.Proposer)][hex.EncodeToString(in.Blockid)] = true
}
}
if int64(len(tp.curTermProposerProduceNumCache[in.CurTerm][string(in.Proposer)])) > tp.config.blockNum+1 {
tp.log.Warn("CheckMinerMatch failed, proposer produce more than config blockNum!", "blockNum", len(tp.curTermProposerProduceNumCache[in.CurTerm][string(in.Proposer)]))
return false, ErrProposeBlockMoreThanConfig
}
}
} else {
tp.log.Warn("CheckMinerMatch failed, revieved block shouldn't proposed!")
return false, nil
}
return true, nil
}
// ProcessBeforeMiner is the specific implementation of ConsensusInterface
func (tp *TDpos) ProcessBeforeMiner(timestamp int64) (map[string]interface{}, bool) {
res := make(map[string]interface{})
term, pos, blockPos := tp.minerScheduling(timestamp)
if term != tp.curTerm || blockPos > tp.config.blockNum || pos >= tp.config.proposerNum {
return res, false
}
if !tp.isProposer(term, pos, tp.address) {
tp.log.Warn("ProcessBeforeMiner prepare too long, omit!")
return nil, false
}
// check bft status
if tp.config.enableBFT {
// TODO: what if IsLastViewConfirmed failed in competemaster, but succeed in ProcessBeforeMiner?
if !tp.isFirstblock(tp.ledger.GetMeta().GetTrunkHeight() + 1) {
if ok, _ := tp.bftPaceMaker.IsLastViewConfirmed(); !ok {
tp.log.Warn("ProcessBeforeMiner last block not confirmed, walk to previous block")
lastBlockid := tp.ledger.GetMeta().GetTipBlockid()
lastBlock, err := tp.ledger.QueryBlock(lastBlockid)
if err != nil {
tp.log.Warn("ProcessBeforeMiner tip block query failed", "error", err)
return nil, false
}
err = tp.utxoVM.Walk(lastBlock.GetPreHash())
if err != nil {
tp.log.Warn("ProcessBeforeMiner utxo walk failed", "error", err)
return nil, false
}
err = tp.ledger.Truncate(tp.utxoVM.GetLatestBlockid())
if err != nil {
tp.log.Warn("ProcessBeforeMiner ledger truncate failed", "error", err)
return nil, false
}
}
}
qc, err := tp.bftPaceMaker.CurrentQCHigh([]byte(""))
if err != nil {
return nil, false
}
res["quorum_cert"] = qc
}
res["type"] = TYPE
//res["curTerm"] = tp.curTerm
//res["curBlockNum"] = tp.curBlockNum
res["curTerm"] = term
res["curBlockNum"] = blockPos
tp.log.Trace("ProcessBeforeMiner", "res", res)
return res, true
}
// ProcessConfirmBlock is the specific implementation of ConsensusInterface
func (tp *TDpos) ProcessConfirmBlock(block *pb.InternalBlock) error {
// send bft NewProposal if bft enable and it's the miner
if tp.config.enableBFT && bytes.Compare(block.GetProposer(), tp.address) == 0 {
blockData := &pb.Block{
Bcname: tp.bcname,
Blockid: block.Blockid,
Block: block,
}
err := tp.bftPaceMaker.NextNewProposal(block.Blockid, blockData)
if err != nil {
tp.log.Warn("ProcessConfirmBlock: bft next proposal failed", "error", err)
return err
}
}
return nil
}
// InitCurrent is the specific implementation of ConsensusInterface
func (tp *TDpos) InitCurrent(block *pb.InternalBlock) error {
return nil
}
// Run is the specific implementation of interface contract
func (tp *TDpos) Run(desc *contract.TxDesc) error {
switch desc.Method {
// 进行投票
case voteMethod:
return tp.runVote(desc, tp.context.Block)
case revokeVoteMethod:
return tp.runRevokeVote(desc, tp.context.Block)
case nominateCandidateMethod:
return tp.runNominateCandidate(desc, tp.context.Block)
case revokeCandidateMethod:
return tp.runRevokeCandidate(desc, tp.context.Block)
case checkvValidaterMethod:
return tp.runCheckValidater(desc, tp.context.Block)
default:
tp.log.Warn("method not definated", "module", desc.Method, "method", desc.Method)
return nil
}
}
// Rollback is the specific implementation of interface contract
func (tp *TDpos) Rollback(desc *contract.TxDesc) error {
switch desc.Method {
// 回滚投票
case voteMethod:
return tp.rollbackVote(desc, tp.context.Block)
case revokeVoteMethod:
return tp.rollbackRevokeVote(desc, tp.context.Block)
case nominateCandidateMethod:
return tp.rollbackNominateCandidate(desc, tp.context.Block)
case revokeCandidateMethod:
return tp.rollbackRevokeCandidate(desc, tp.context.Block)
case checkvValidaterMethod:
return tp.rollbackCheckValidater(desc, tp.context.Block)
default:
tp.log.Warn("method not definated", "module", desc.Method, "method", desc.Method)
return nil
}
}
// Finalize is the specific implementation of interface contract
func (tp *TDpos) Finalize(blockid []byte) error {
tp.candidateBallotsCache.Range(func(k, v interface{}) bool {
key := k.(string)
value := v.(*candidateBallotsCacheValue)
if value.isDel {
tp.context.UtxoBatch.Delete([]byte(key))
tp.candidateBallots.Delete(key)
} else {
tp.context.UtxoBatch.Put([]byte(key), []byte(strconv.FormatInt(value.ballots, 10)))
tp.candidateBallots.Store(key, value.ballots)
}
return true
})
return nil
}
// SetContext is the specific implementation of interface contract
func (tp *TDpos) SetContext(context *contract.TxContext) error {
tp.context = context
tp.candidateBallotsCache = &sync.Map{}
tp.revokeCache = &sync.Map{}
return nil
}
// Stop is the specific implementation of interface contract
func (tp *TDpos) Stop() {
if tp.config.enableBFT && tp.bftPaceMaker != nil {
tp.bftPaceMaker.Stop()
}
}
// ReadOutput is the specific implementation of interface contract
func (tp *TDpos) ReadOutput(desc *contract.TxDesc) (contract.ContractOutputInterface, error) {
return nil, nil
}
// GetVerifiableAutogenTx is the specific implementation of interface VAT
func (tp *TDpos) GetVerifiableAutogenTx(blockHeight int64, maxCount int, timestamp int64) ([]*pb.Transaction, error) {
term, _, _ := tp.minerScheduling(timestamp)
key := GenTermCheckKey(tp.version, term+1)
val, err := tp.utxoVM.GetFromTable(nil, []byte(key))
txs := []*pb.Transaction{}
if val == nil && common.NormalizedKVError(err) == common.ErrKVNotFound {
desc := &contract.TxDesc{
Module: "tdpos",
Method: checkvValidaterMethod,
Args: make(map[string]interface{}),
}
desc.Args["version"] = strconv.FormatInt(tp.version, 10)
desc.Args["term"] = strconv.FormatInt(term+1, 10)
descJSON, err := json.Marshal(desc)
if err != nil {
return nil, err
}
tx, err := tp.utxoVM.GenerateEmptyTx(descJSON)
txs = append(txs, tx)
return txs, nil
}
return nil, nil
}
// GetVATWhiteList the specific implementation of interface VAT
func (tp *TDpos) GetVATWhiteList() map[string]bool {
whiteList := map[string]bool{
checkvValidaterMethod: true,
}
return whiteList
}
// GetCoreMiners get the information of core miners
func (tp *TDpos) GetCoreMiners() []*cons_base.MinerInfo {
res := []*cons_base.MinerInfo{}
timestamp := time.Now().UnixNano()
term, _, _ := tp.minerScheduling(timestamp)
proposers := tp.getTermProposer(term)
for _, proposer := range proposers {
minerInfo := &cons_base.MinerInfo{
Address: proposer.Address,
PeerInfo: proposer.PeerAddr,
}
res = append(res, minerInfo)
}
return res
}
// GetStatus get the current status of consensus
func (tp *TDpos) GetStatus() *cons_base.ConsensusStatus {
timestamp := time.Now().UnixNano()
term, pos, blockPos := tp.minerScheduling(timestamp)
proposers := tp.getTermProposer(term)
status := &cons_base.ConsensusStatus{
Term: term,
BlockNum: blockPos,
}
if int(pos) < 0 || int(pos) >= len(proposers) {
tp.log.Warn("current pos illegal", "pos", pos)
} else {
status.Proposer = proposers[int(pos)].Address
}
return status
}
func (tp *TDpos) initBFT(cfg *config.NodeConfig) error {
// BFT not enabled
if !tp.config.enableBFT {
return nil
}
// read keys
pkpath := cfg.Miner.Keypath + "/public.key"
pkJSON, err := ioutil.ReadFile(pkpath)
if err != nil {
tp.log.Warn("load private key error", "path", pkpath)
return err
}
skpath := cfg.Miner.Keypath + "/private.key"
skJSON, err := ioutil.ReadFile(skpath)
if err != nil {
tp.log.Warn("load private key error", "path", skpath)
return err
}
sk, err := tp.cryptoClient.GetEcdsaPrivateKeyFromJSON(skJSON)
if err != nil {
tp.log.Warn("parse private key failed", "privateKey", skJSON)
return err
}
// initialize bft
bridge := bft.NewCbftBridge(tp.bcname, tp.ledger, tp.log, tp)
qcNeeded := 3
qc := make([]*pb.QuorumCert, qcNeeded)
meta := tp.ledger.GetMeta()
if meta.TrunkHeight != 0 {
blockid := meta.TipBlockid
for qcNeeded > 0 {
qcNeeded--
block, err := tp.ledger.QueryBlock(blockid)
if err != nil {
tp.log.Warn("initBFT: get block failed", "error", err)
return err
}
qc[qcNeeded] = block.GetJustify()
blockid = block.GetPreHash()
}
}
cbft, err := chainedbft.NewChainedBft(
tp.log,
tp.config.bftConfig,
tp.bcname,
string(tp.address),
string(pkJSON),
sk,
tp.config.initProposer[1],
bridge,
tp.cryptoClient,
tp.p2psvr,
qc[2], qc[1], qc[0])
if err != nil {
tp.log.Warn("initBFT: create ChainedBft failed", "error", err)
return err
}
paceMaker, err := bft.NewDPoSPaceMaker(tp.bcname, tp.height, meta.TrunkHeight,
string(tp.address), cbft, tp.log, tp, tp.ledger)
if err != nil {
if err != nil {
tp.log.Warn("initBFT: create DPoSPaceMaker failed", "error", err)
return err
}
}
tp.bftPaceMaker = paceMaker
bridge.SetPaceMaker(paceMaker)
return tp.bftPaceMaker.Start()
}
func (tp *TDpos) isFirstblock(targetHeight int64) bool {
consStartHeight := tp.height
if consStartHeight == 0 {
consStartHeight++
}
tp.log.Debug("isFirstblock check", "consStartHeight", consStartHeight,
"targetHeight", targetHeight)
return consStartHeight == targetHeight
}
| {
return err
} |
bundle.ts | import assert from "node:assert";
import * as fs from "node:fs";
import * as path from "node:path";
import * as esbuild from "esbuild";
import makeModuleCollector from "./module-collection";
import type { Config } from "./config";
import type { Entry } from "./entry";
import type { CfModule, CfScriptFormat } from "./worker";
type BundleResult = {
modules: CfModule[];
resolvedEntryPointPath: string;
bundleType: "esm" | "commonjs";
stop: (() => void) | undefined;
};
/**
* Generate a bundle for the worker identified by the arguments passed in.
*/
export async function bundleWorker(
entry: Entry,
destination: string,
options: {
serveAssetsFromWorker: boolean;
jsxFactory: string | undefined;
jsxFragment: string | undefined;
format: CfScriptFormat;
rules: Config["rules"];
watch?: esbuild.WatchMode;
}
): Promise<BundleResult> {
const {
serveAssetsFromWorker,
jsxFactory,
jsxFragment,
format,
rules,
watch,
} = options;
const moduleCollector = makeModuleCollector({ format, rules });
const result = await esbuild.build({
...getEntryPoint(entry.file, serveAssetsFromWorker),
bundle: true,
absWorkingDir: entry.directory,
outdir: destination,
external: ["__STATIC_CONTENT_MANIFEST"],
format: "esm",
sourcemap: true,
metafile: true,
conditions: ["worker", "browser"],
loader: {
".js": "jsx",
".mjs": "jsx",
".cjs": "jsx",
},
plugins: [moduleCollector.plugin],
...(jsxFactory && { jsxFactory }),
...(jsxFragment && { jsxFragment }),
watch,
});
const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
([_path, output]) => output.entryPoint !== undefined
);
assert(
entryPointOutputs.length > 0,
`Cannot find entry-point "${entry.file}" in generated bundle.` +
listEntryPoints(entryPointOutputs)
);
assert(
entryPointOutputs.length < 2,
"More than one entry-point found for generated bundle." +
listEntryPoints(entryPointOutputs)
);
const entryPointExports = entryPointOutputs[0][1].exports;
const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
return {
modules: moduleCollector.modules,
resolvedEntryPointPath: path.resolve(
entry.directory,
entryPointOutputs[0][0]
),
bundleType,
stop: result.stop,
};
}
type EntryPoint =
| { stdin: esbuild.StdinOptions; nodePaths: string[] }
| { entryPoints: string[] };
/**
* Create an object that describes the entry point for esbuild.
*
* If we are using the experimental asset handling, then the entry point is
* actually a shim worker that will either return an asset from a KV store,
* or delegate to the actual worker.
*/
function | (
entryFile: string,
serveAssetsFromWorker: boolean
): EntryPoint {
if (serveAssetsFromWorker) {
return {
stdin: {
contents: fs
.readFileSync(
path.join(__dirname, "../templates/static-asset-facade.js"),
"utf8"
)
.replace("__ENTRY_POINT__", entryFile),
sourcefile: "static-asset-facade.js",
resolveDir: path.dirname(entryFile),
},
nodePaths: [path.join(__dirname, "../vendor")],
};
} else {
return { entryPoints: [entryFile] };
}
}
/**
* Generate a string that describes the entry-points that were identified by esbuild.
*/
function listEntryPoints(
outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
): string {
return outputs.map(([_input, output]) => output.entryPoint).join("\n");
}
type ValueOf<T> = T[keyof T];
| getEntryPoint |
conv.rs | use wasm_bindgen::prelude::wasm_bindgen;
use crate::{layers::padding::handle_padding, DTypes, Tensor};
use super::extract_data;
macro_rules! conv {
(
$arr: expr, $weight: expr, $bias: expr, $len: expr,
$in_shape: expr, $weight_shape: expr, $out_shape: expr,
$stride_y: expr, $stride_x: expr
) => {{
let kernel_channel_size = $weight_shape[2] * $weight_shape[3];
let kernel_size = $weight_shape[1] * kernel_channel_size;
let in_row_stride = $in_shape[3] - $weight_shape[3];
let in_channel_stride = $in_shape[2] * $in_shape[3] - $weight_shape[2] * $in_shape[3];
let mut out_idx = 0;
let mut out_data = vec![0.; $len];
for c in 0..$out_shape[1] {
for y in 0..$out_shape[2] {
for x in 0..$out_shape[3] {
let start_y = y * $stride_y;
let start_x = x * $stride_x;
let mut sum = 0.;
let mut weight_offset = c * kernel_size;
let mut in_offset = start_y * $in_shape[3] + start_x;
for _ in 0..$weight_shape[1] {
for _ in 0..$weight_shape[2] {
for _ in 0..$weight_shape[3] {
sum += $weight[weight_offset] * $arr[in_offset];
in_offset += 1;
weight_offset += 1;
}
in_offset += in_row_stride;
}
in_offset += in_channel_stride;
}
out_data[out_idx] = sum + $bias[c];
out_idx += 1;
}
}
}
out_data
}};
}
#[wasm_bindgen(js_name = handleConv)]
pub fn handle_conv(
kernel_height: usize,
kernel_width: usize,
pad_top: usize,
pad_left: usize,
pad_bottom: usize,
pad_right: usize,
stride_y: usize,
stride_x: usize,
input: &Tensor,
weight: &Tensor,
bias: Option<Tensor>,
) -> Tensor {
let padding = if pad_top != 0 || pad_left != 0 || pad_bottom != 0 || pad_right != 0 {
handle_padding(input, pad_top, pad_left, pad_bottom, pad_right)
} else {
input.clone()
};
let mut output = Tensor::new_empty();
let in_shape = padding.get_shape();
let weight_shape = weight.get_shape();
let out_shape = vec![
in_shape[0],
weight_shape[0],
(in_shape[2] - kernel_height) / stride_y + 1,
(in_shape[3] - kernel_width) / stride_x + 1,
];
output.set_shape(out_shape.clone());
let out_data = match &padding.get_data() {
DTypes::F32(arr) => {
let len = output.get_length();
let weight = extract_data!(weight, DTypes::F32);
let bias = bias.map_or(vec![0.; len], |tensor| {
extract_data!(tensor, DTypes::F32).to_vec()
});
DTypes::F32(conv!(
arr,
weight,
bias,
len,
in_shape,
weight_shape,
out_shape,
stride_y,
stride_x
))
}
DTypes::F64(arr) => {
let len = output.get_length();
let weight = extract_data!(weight, DTypes::F64);
let bias = bias.map_or(vec![0.; len], |tensor| {
extract_data!(tensor, DTypes::F64).to_vec()
});
DTypes::F64(conv!(
arr,
weight, | len,
in_shape,
weight_shape,
out_shape,
stride_y,
stride_x
))
}
_ => {
panic!("Convolutional does not support these data type!!")
}
};
output.set_data(out_data);
output
} | bias, |
recovery.rs | use crate::lookup_value;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;
/// A recovery entry.
///
/// It provides all the necessary detail regarding the recovery from a given disease.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct | {
/// Targeted Disease or agent
#[serde(rename = "tg")]
pub targeted_disease: Cow<'static, str>,
/// ISO 8601 complete date of first positive NAA test result
#[serde(rename = "fr")]
pub result_date: Cow<'static, str>,
/// Country of Test
#[serde(rename = "co")]
pub country: Cow<'static, str>,
/// Certificate Issuer
#[serde(rename = "is")]
pub issuer: String,
/// ISO 8601 complete date: Certificate Valid From
#[serde(rename = "df")]
pub valid_from: String,
/// ISO 8601 complete date: Certificate Valid Until
#[serde(rename = "du")]
pub valid_until: String,
/// Unique Certificate Identifier, UVCI
#[serde(rename = "ci")]
pub id: String,
}
impl Recovery {
/// Updates all the ids in the recovery entry with their descriptive counterparts using
/// the official valueset.
pub fn expand_values(&mut self) {
self.targeted_disease = lookup_value(&self.targeted_disease);
self.country = lookup_value(&self.country);
}
}
| Recovery |
instant.rs | use std::ops::{Add, AddAssign, Sub, SubAssign};
use std::time::Duration;
use crate::*;
thread_local! {
static PERFORMANCE_NOW: JSObjectFromString = JSObjectFromString::new("function now() { return performance.now() }; now");
}
pub fn now() -> f64 {
let result = PERFORMANCE_NOW.with(|f| f.call(&JSObject::NULL)).unwrap();
result.get_value_f64()
}
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Hash)]
pub struct Instant(Duration);
impl Ord for Instant {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.partial_cmp(other)
.expect("an instant should never be NaN or Inf.")
}
}
impl Eq for Instant {}
impl Instant {
#[inline]
pub fn now() -> Self {
Instant(duration_from_f64(now()))
}
#[inline]
pub fn duration_since(&self, earlier: Instant) -> Duration {
assert!(
earlier.0 <= self.0,
"`earlier` cannot be later than `self`."
);
self.0 - earlier.0
}
#[inline]
pub fn elapsed(&self) -> Duration {
Self::now().duration_since(*self)
}
#[inline]
pub fn checked_add(&self, duration: Duration) -> Option<Instant> {
self.0.checked_add(duration).map(Instant)
}
#[inline]
pub fn checked_sub(&self, duration: Duration) -> Option<Instant> {
self.0.checked_sub(duration).map(Instant)
}
}
impl Add<Duration> for Instant {
type Output = Self;
#[inline]
fn add(self, rhs: Duration) -> Self {
Instant(self.0 + rhs)
}
}
impl AddAssign<Duration> for Instant {
#[inline]
fn | (&mut self, rhs: Duration) {
self.0 += rhs
}
}
impl Sub<Duration> for Instant {
type Output = Self;
#[inline]
fn sub(self, rhs: Duration) -> Self {
Instant(self.0 - rhs)
}
}
impl Sub<Instant> for Instant {
type Output = Duration;
#[inline]
fn sub(self, rhs: Instant) -> Duration {
self.duration_since(rhs)
}
}
impl SubAssign<Duration> for Instant {
#[inline]
fn sub_assign(&mut self, rhs: Duration) {
self.0 -= rhs
}
}
fn duration_from_f64(millis: f64) -> Duration {
Duration::from_millis(millis.trunc() as u64)
+ Duration::from_nanos((millis.fract() * 1.0e6) as u64)
}
| add_assign |
elm_deps_upgrade.py | #! /usr/bin/env python
from __future__ import print_function
import sys
import json
import requests
import struct
import argparse
def load_all_packages(elm_version, url=None):
if url is None:
url = "http://package.elm-lang.org/all-packages?elm-package-version="
payload = requests.get("{url}{elm_version}".format(
url=url,
elm_version=elm_version
))
return { item['name'] : item for item in payload.json() }
def load_versions(package_name, url=None):
if url is None:
url = "http://package.elm-lang.org/versions?name="
payload = requests.get("{url}{package_name}".format(
url=url,
package_name=package_name
))
return payload.content
def load_local_packages(elm_package):
with open(elm_package) as f:
return json.load(f)['dependencies']
def top_range(field):
only_end = field[field.index('v'):]
if '=' in only_end:
return only_end.split('=')[-1].strip()
if '<' in only_end:
number = only_end.split('<')[-1].strip()
if patch(number) == 0:
if minor(number) == 0:
return '{maj}.{min}.{pat}'.format(
maj = major(number) - 1,
min = 9999999,
pat = 0 )
return '{maj}.{min}.{pat}'.format(
maj = major(number) - 1,
min = minor(number) - 1,
pat = 0 )
return '{maj}.{min}.{pat}'.format(
maj = major(number) - 1,
min = minor(number) - 1,
pat = patch(number) - 1 )
def major(version):
return int(version.split('.')[0])
def minor(version):
return int(version.split('.')[1])
def patch(version):
return int(version.split('.')[2])
def get_major_upgrades(top, versions):
major_top = major(top)
return [ version for version in versions if major(version) > major_top ]
def get_minor_upgrades(top, versions):
major_top = major(top)
minor_top = minor(top)
return [ version for version in versions if minor(version) > minor_top and major(version) == major_top ]
def get_patch_upgrades(top, versions):
major_top = major(top)
minor_top = minor(top)
patch_top = patch(top)
return [ version for version in versions
if major(version) == major_top and minor_top == minor(version) and patch_top > patch(version) ]
def find_newer_versions(local_deps, remote_deps):
upgrade_suggestions = {}
for (dep, version) in local_deps.items():
if dep not in remote_deps:
continue
current_version = top_range(version)
patches = get_patch_upgrades(current_version, remote_deps[dep]['versions'])
minors = get_minor_upgrades(current_version, remote_deps[dep]['versions'])
majors = get_major_upgrades(current_version, remote_deps[dep]['versions'])
upgrade_suggestions[dep] = {
'patches': patches,
'minors': minors,
'majors': majors
}
return upgrade_suggestions
def newest_version(suggestions):
if suggestions['majors']:
return suggestions['majors'][-1]
elif suggestions['minors']:
return suggestions['majors'][-1]
else:
return suggestions['patches'][-1]
def print_newer_versions(local_deps, remote_deps):
upgrade_suggestions = []
| for (dep, suggestions) in find_newer_versions(local_deps, remote_deps).items():
patches = suggestions['patches']
minors = suggestions['minors']
majors = suggestions['majors']
if len(patches) > 0:
upgrade_suggestions.append(
'Patches available for {dep}: [{patches}]'.format(dep=dep, patches=', '.join(patches))
)
if len(minors) > 0:
upgrade_suggestions.append(
'Minors available for {dep}: [{minors}]'.format(dep=dep, minors=', '.join(minors))
)
if len(majors) > 0:
upgrade_suggestions.append(
'Majors available for {dep}: [{majors}]'.format(dep=dep, majors=', '.join(majors))
)
if not upgrade_suggestions:
print('No upgrades available')
else:
print('\n'.join(upgrade_suggestions))
def main():
parser = argparse.ArgumentParser(description='Check deps file for possible upgrades')
parser.add_argument('--elm-version', help='specify your current elm version', default='0.18')
parser.add_argument('local')
args = parser.parse_args()
local = load_local_packages(args.local)
remote = load_all_packages(args.elm_version)
print_newer_versions(local, remote)
if __name__ == '__main__':
main() | |
1200_minimum_absolute_difference.py | class | (object):
def minimumAbsDifference(self, arr):
"""
:type arr: List[int]
:rtype: List[List[int]]
"""
if len(arr) < 2:
return []
sa = sorted(arr)
min_diff = sa[1] - sa[0]
res = [[sa[0], sa[1]]]
for i in range(1, len(sa) - 1):
v = sa[i + 1] - sa[i]
if v < min_diff:
res = [[sa[i], sa[i + 1]]]
min_diff = v
continue
if v == min_diff:
res.append([sa[i], sa[i + 1]])
return res
def test_minimum_abs_difference():
s = Solution()
assert [[1, 2], [2, 3], [3, 4]] == s.minimumAbsDifference([4, 2, 1, 3])
assert [[1, 3]] == s.minimumAbsDifference([1, 3, 6, 10, 15])
assert [[-14, -10], [19, 23], [23, 27]
] == s.minimumAbsDifference([3, 8, -10, 23, 19, -4, -14, 27])
| Solution |
test_human.py | from os import linesep
from unittest import TestCase
from unittest.mock import patch
from axelrod import Action, Cooperator, Player
from axelrod.strategies.human import ActionValidator, Human
from prompt_toolkit.validation import ValidationError
from .test_player import TestPlayer
C, D = Action.C, Action.D
class TestDocument(object):
"""
A class to mimic a prompt-toolkit document having just the text attribute.
"""
def __init__(self, text):
self.text = text
class TestActionValidator(TestCase):
def test_validator(self):
test_documents = [TestDocument(x) for x in ["C", "c", "D", "d"]]
for test_document in test_documents:
ActionValidator().validate(test_document)
test_document = TestDocument("E")
self.assertRaises(ValidationError, ActionValidator().validate, test_document)
class TestHumanClass(TestPlayer):
name = "Human: human, C, D"
player = Human
expected_classifier = {
"memory_depth": float("inf"),
"stochastic": True,
"makes_use_of": set(["length", "game"]),
"long_run_time": True,
"inspects_source": True,
"manipulates_source": False,
"manipulates_state": False,
}
def test_init(self):
human = Human(name="test human", c_symbol="X", d_symbol="Y")
self.assertEqual(human.human_name, "test human")
self.assertEqual(human.symbols, {C: "X", D: "Y"})
def test_history_toolbar(self):
human = Human()
expected_content = ""
actual_content = human._history_toolbar(None)[0][1]
self.assertEqual(actual_content, expected_content)
human.history = [C]
human.opponent_history = [C]
expected_content = "History (human, opponent): [('C', 'C')]"
actual_content = human._history_toolbar(None)[0][1]
self.assertIn(actual_content, expected_content)
def test_status_messages(self):
human = Human()
expected_messages = {
"toolbar": None,
"print": "{}Starting new match".format(linesep),
}
actual_messages = human._status_messages()
self.assertEqual(actual_messages, expected_messages)
human.history = [C]
human.opponent_history = [C]
expected_print_message = "{}Turn 1: human played C, opponent played C".format(
linesep
)
actual_messages = human._status_messages()
self.assertEqual(actual_messages["print"], expected_print_message)
self.assertIsNotNone(actual_messages["toolbar"])
def test_get_human_input_c(self):
|
def test_get_human_input_C(self):
with patch("axelrod.human.prompt", return_value="C") as prompt_:
actions = [(C, C)] * 5
self.versus_test(Cooperator(), expected_actions=actions)
self.assertEqual(
prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",)
)
def test_get_human_input_d(self):
with patch("axelrod.human.prompt", return_value="d") as prompt_:
actions = [(D, C)] * 5
self.versus_test(Cooperator(), expected_actions=actions)
self.assertEqual(
prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",)
)
def test_get_human_input_D(self):
with patch("axelrod.human.prompt", return_value="D") as prompt_:
actions = [(D, C)] * 5
self.versus_test(Cooperator(), expected_actions=actions)
self.assertEqual(
prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",)
)
def test_strategy(self):
human = Human()
expected_action = C
actual_action = human.strategy(Player(), lambda: C)
self.assertEqual(actual_action, expected_action)
def test_reset_history_and_attributes(self):
"""Overwrite the reset method for this strategy."""
pass
def test_repr(self):
human = Human()
self.assertEqual(human.__repr__(), "Human: human")
human = Human(name="John Nash")
self.assertEqual(human.__repr__(), "Human: John Nash")
human = Human(name="John Nash", c_symbol="1", d_symbol="2")
self.assertEqual(human.__repr__(), "Human: John Nash")
| with patch("axelrod.human.prompt", return_value="c") as prompt_:
actions = [(C, C)] * 5
self.versus_test(Cooperator(), expected_actions=actions)
self.assertEqual(
prompt_.call_args[0], ("Turn 5 action [C or D] for human: ",)
) |
tasks.py | from typing import Optional
from celery import app
from celery.utils.log import get_task_logger
from gnosis.eth import EthereumClientProvider
from gnosis.eth.ethereum_client import EthereumNetwork
from safe_transaction_service.history.utils import close_gevent_db_connection
from .models import Token
logger = get_task_logger(__name__)
@app.shared_task()
def | () -> Optional[int]:
ethereum_client = EthereumClientProvider()
ethereum_network = ethereum_client.get_network()
if ethereum_network == EthereumNetwork.MAINNET:
try:
number = Token.pool_tokens.fix_all_pool_tokens()
if number:
logger.info('%d pool token names were fixed', number)
return number
finally:
close_gevent_db_connection()
| fix_pool_tokens_task |
dataFetcher.py | #!/usr/bin/env python
# coding: utf-8
# # Loading data
import pandas as pd
import plotly.express as px
from tqdm import tqdm
import functools
import numpy as np
from difflib import SequenceMatcher
from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
from datetime import datetime, timedelta
import pprint
import requests
import os
import getpass
import json
from queue import Queue
from threading import Thread
from time import time
import logging
import os
#cashing in case of multiple calls.
@functools.lru_cache(maxsize=128)
def get_tiles(municipalityId: int) -> pd.DataFrame:
"""Fetches tile information for a municipality id.
Args:
municipalityId: id of the municipality as defined in by the federal office of statistics,
https://www.bfs.admin.ch/bfs/fr/home/bases-statistiques/repertoire-officiel-communes-suisse.assetdetail.11467406.html
Return:
A dataframe containing the following columns:
[tileId, ll_lon, ll_lat, urL-lon, ur_lat]
tileID: corresponds to a unique ID as defined in the Swisscom FAQ page.
ll_lon: longitude coordinate of the lower left corner of the tile.
ll_lat: latitude coordinate of the lower left corner of the tile.
ur_lon: longitude coordinate of the upper right corner of the tile.
ur_lat: latitude coordinate of the upper right corner of the tile.
If municipalityId is invalid will print an error message and return an empty DataFrame
"""
api_request = (
BASE_URL
+ f'/grids/municipalities/{municipalityId}'
)
data = oauth.get(api_request, headers=headers).json()
if(data.get('status') == None):
tileID = [t['tileId'] for t in data['tiles']]
ll_lon = [t['ll']['x'] for t in data['tiles']]
ll_lat= [t['ll']['y'] for t in data['tiles']]
ur_lon = [t['ur']['x'] for t in data['tiles']]
ur_lat = [t['ur']['y'] for t in data['tiles']]
else:
print(f'get_tiles: failed with status code {data.get("status")}. {data.get("message")}')
return pd.DataFrame(data={'tileID': [], 'll_lat': [], 'll_lon': [], 'ur_lat': [], 'ur_lon': []})
return pd.DataFrame(data={'tileID': tileID, 'll_lat': ll_lat, 'll_lon': ll_lon, 'ur_lat': ur_lat, 'ur_lon': ur_lon})
def get_municipalityID(name: str) -> np.array(int):
"""Converts a municipality name to ID
Args:
name of municipality.
Returns:
An array containing all the municipality ID's corresponding to the name.
If the name invalid will return an empty array.
"""
return commune.loc[commune.GDENAME == name].GDENR.to_numpy()
def visualize_coordinates(df: pd.DataFrame, latitude: str, longitude: str) -> None :
"""Visualizes coordinates in dataframe on map
Retrieves columns with name latitude and logitude and visualizes it on a map.
Args:
df: A dataframe containing the coordinates.
latitude: String key of the column in the dataframe containing the latitude.
longitude: String key of the column in the dataframe containing the longitude.
"""
fig = px.scatter_mapbox(df, lat=latitude, lon=longitude,
color_continuous_scale=px.colors.cyclical.IceFire, size_max=15, zoom=10,
mapbox_style="carto-positron")
fig.show()
def get_all_tiles_switzerland() -> pd.DataFrame:
"""Fetches the tile information for all the tiles in Switzerland.
Returns:
A Dataframe containg the tile information for every tile in switzerland.
The format of the DataFrame is the same as the return of get_tiles()
"""
tiles = get_tiles(commune.GDENR.unique()[0])
for c in tqdm(commune.GDENR.unique().tolist()):
tiles = tiles.append(get_tiles(c))
return tiles
def get_daily_demographics(tiles, day=datetime(year=2020, month=1, day=27, hour=0, minute=0) ):
"""Fetches daily demographics
Fetches the daily demographics, age distribution, of the tiles.
Args:
tiles: Array of tile id's, what will be used to querry demographic data.
day: date of the data to be fetched.
Returns:
A dataframe containing as a key the tileID and as columns ageDistribution and the maleProportion
+----------+-----------------------+---------------------+
| | ageDistribution | maleProportion |
+----------+-----------------------+---------------------+
| 44554639 | NaN | 0.49828359484672546 |
+----------+-----------------------+---------------------+
| 44271906 | [0.21413850784301758, | 0.493218 |
| | 0.27691012620925903, | |
| | 0.37422287464141846, | |
| | 0.13472850620746613] | |
+----------+-----------------------+---------------------+
In the example above tile 44554639 does not have any age distribution data.
The data is k-anonymized. Therefor is some tiles are missing data it
means that the data is not available. To find out more about demographics visit the Heatmap FAQ.
"""
dates = [(day + timedelta(hours=delta)) for delta in range(24)]
date2score = dict()
for tiles_subset in [tiles[i:i + MAX_NB_TILES_REQUEST] for i in range(0, len(tiles), MAX_NB_TILES_REQUEST)]:
api_request = (
BASE_URL
+ f'/heatmaps/dwell-demographics/daily/{day.isoformat().split("T")[0]}'
+ "?tiles="
+ "&tiles=".join(map(str, tiles_subset))
)
data = oauth.get(api_request, headers=headers).json()
for t in data.get("tiles", []):
if date2score.get(t['tileId']) == None:
date2score[t['tileId']] = dict()
date2score[t['tileId']] = {"ageDistribution": t.get("ageDistribution"),"maleProportion": t.get("maleProportion")}
return pd.DataFrame.from_dict(date2score).transpose()
def get_hourly_demographics_dataframe(tiles, day=datetime(year=2020, month=1, day=27, hour=0, minute=0)):
"""Fetches hourly demographics of age categories for 24 hours
Fetches the hourly demographics, age distribution, of the tiles.
Age categories are the following 0 - 19, 20 - 39, 40 - 64, >64
Args:
tiles: Array of tile id's, what will be used to querry demographic data.
day: date of the data to be fetched.
Returns:
DataFrame containing the demographics. The name
of the collumns are:
[age_cat, age_distribution, male_proportion]
+----------+---------------------+---------+------------------+-----------------+
| | | age_cat | age_distribution | male_proportion |
+----------+---------------------+---------+------------------+-----------------+
| tileID | time | | | |
+----------+---------------------+---------+------------------+-----------------+
| 44394309 | 2020-01-27T00:00:00 | NaN | NaN | 0.474876 |
+----------+---------------------+---------+------------------+-----------------+
| | 2020-01-27T01:00:00 | NaN | NaN | 0.483166 |
+----------+---------------------+---------+------------------+-----------------+
| | ... | | | |
+----------+---------------------+---------+------------------+-----------------+
| 44290729 | 2020-01-27T06:00:00 | 0.0 | 0.192352 | 0.497038 |
+----------+---------------------+---------+------------------+-----------------+
| | 2020-01-27T06:00:00 | 1.0 | 0.269984 | 0.497038 |
+----------+---------------------+---------+------------------+-----------------+
| | 2020-01-27T06:00:00 | 2.0 | 0.363481 | 0.497038 |
+----------+---------------------+---------+------------------+-----------------+
| | 2020-01-27T06:00:00 | 3.0 | 0.174183 | 0.497038 |
+----------+---------------------+---------+------------------+-----------------+
The data is k-anonymized. Therefor is some tiles are not present in the output dataframe it
means that the data is not available. To find out more about demographics visit the Heatmap FAQ.
"""
def get_hourly_demographics(tiles, day=datetime(year=2020, month=1, day=27, hour=0, minute=0) ):
"""Fetches hourly male proportion and age categories for 24 hours
Args:
tiles: Array of tile id's, what will be used to querry demographic data.
day: date of the data to be fetched.
Returns:
Returns a dictionary with as a key the tileID, and as a value an object that is as follows:
{tileID: {dateTime:{ "ageDistribution": [0-19, 20-39, 40-64, 64+], "maleProportion": value},
{dateTime2: ...}}}
26994514: {'2020-01-27T00:00:00': {'ageDistribution': [0.1925136297941208,
0.2758632302284241,
0.362215131521225,
0.16940800845623016],
'maleProportion': 0.4727686941623688},
'2020-01-27T01:00:00': {'ageDistribution': None,
'maleProportion': 0.4896690547466278},
'2020-01-27T02:00:00': {'ageDistribution': None,
'maleProportion': 0.48882684111595154},
The data is k-anonymized. Therefor is some values are None it means that no data was available
To find out more about demographics visit the Heatmap FAQ.
"""
dates = [(day + timedelta(hours=delta)) for delta in range(24)]
date2score = dict()
for dt in tqdm(dates, desc="get_hourly_demographics: hours", leave=True):
for tiles_subset in [tiles[i:i + 100] for i in range(0, len(tiles), 100)]:
api_request = (
BASE_URL
+ f'/heatmaps/dwell-demographics/hourly/{dt.isoformat()}'
+ "?tiles="
+ "&tiles=".join(map(str, tiles_subset))
)
data = oauth.get(api_request, headers=headers).json()
for t in data.get("tiles", []):
if date2score.get(t['tileId']) == None:
date2score[t['tileId']] = dict()
date2score.get(t['tileId'])[dt.isoformat()] = {"ageDistribution": t.get("ageDistribution"),"maleProportion": t.get("maleProportion")}
return date2score
data = get_hourly_demographics(tiles, day)
tile_id = []
time_data = []
age_distribution = []
age_cat = []
male_proportion = []
for i in data:
for time in data[i]:
if data[i][time].get("ageDistribution") != None:
|
else:
tile_id.append(i)
time_data.append(time)
age_distribution.append(None)
male_proportion.append(data[i][time].get("maleProportion"))
age_cat.append(None)
return pd.DataFrame(data={'tileID': tile_id, "age_cat": age_cat, 'age_distribution':age_distribution, "male_proportion": male_proportion, 'time': time_data}).set_index(['tileID', 'time'])
def get_daily_density(tiles: np.array(int), day=datetime(year=2020, month=1, day=27)) -> pd.DataFrame:
"""Fetches the daily density of tiles.
Fetches the daily density of the tiles and creates a dataframe of the fetched data.
Args:
tiles: Array of tile id's that daily density data needs to be fetched.
day: Day to fetch the density data for.
Returns:
DataFrame containg the tileId and the score. The name of the collumns are:
[score]
The identifier of the row is bassed on the tileID
+----------+-------+
| | score |
+----------+-------+
| tileID | |
+----------+-------+
| 44394309 | 1351 |
+----------+-------+
| 44394315 | 1103 |
+----------+-------+
| 44460297 | 875 |
+----------+-------+
| 44488589 | 1387 |
+----------+-------+
| 44498028 | 678 |
+----------+-------+
Tile with k-anonymized dwell density score. If tile not present Swisscom is
unable to provide a value due to k-anonymization. To find out more on density
scores read the Heatmap FAQ.
"""
tileID = []
score = []
for tiles_subset in [tiles[i:i + MAX_NB_TILES_REQUEST] for i in range(0, len(tiles), MAX_NB_TILES_REQUEST)]:
api_request = (
BASE_URL
+ f'/heatmaps/dwell-density/daily/{day.isoformat().split("T")[0]}'
+ "?tiles="
+ "&tiles=".join(map(str, tiles_subset))
)
data = oauth.get(api_request, headers=headers).json()
if data.get("tiles") != None:
for t in data["tiles"]:
tileID.append(t['tileId'])
score.append(t["score"])
return pd.DataFrame(data={'tileID': tileID, 'score':score}).set_index("tileID")
def get_hourly_density_dataframe(tiles, day=datetime(year=2020, month=1, day=27, hour=0, minute=0)):
"""Fetches the hourly density of tiles for 24 hours.
Fetches the hourly density of the tiles and creates a dataframe of the fetched data.
Args:
tiles: Array of tile id's that daily density data needs to be fetched.
day: Day to fetch the density data for.
Returns:
DataFrame containg the tileId and the score. The name of the collumns are:
[score]
The identifier of the row is bassed on the [tileID, time]
+----------+---------------------+-------+
| | | score |
+----------+---------------------+-------+
| tileID | time | |
+----------+---------------------+-------+
| 44394309 | 2020-01-27T00:00:00 | 52 |
| +---------------------+-------+
| | 2020-01-27T01:00:00 | 68 |
| +---------------------+-------+
| | 2020-01-27T02:00:00 | 69 |
| +---------------------+-------+
| | 2020-01-27T03:00:00 | 69 |
| +---------------------+-------+
| | 2020-01-27T04:00:00 | 69 |
+----------+---------------------+-------+
Tile with k-anonymized dwell density score. If tile not present Swisscom is
unable to provide a value due to k-anonymization. To find out more on density
scores read the Heatmap FAQ.
"""
def get_hourly_density(tiles, day=datetime(year=2020, month=1, day=27, hour=0, minute=0)):
dates = [(day + timedelta(hours=delta)) for delta in range(24)]
date2score = dict()
print("getHourlyDensity")
for dt in tqdm(dates, desc="get_hourly_density: hours", leave=True):
for tiles_subset in [tiles[i:i + 100] for i in range(0, len(tiles), 100)]:
api_request = (
BASE_URL
+ f'/heatmaps/dwell-density/hourly/{dt.isoformat()}'
+ "?tiles="
+ "&tiles=".join(map(str, tiles_subset))
)
for t in oauth.get(api_request, headers=headers).json().get("tiles",[]):
if date2score.get(t['tileId']) == None:
date2score[t['tileId']] = dict()
date2score.get(t['tileId'])[dt.isoformat()] = t['score']
return date2score
tiles_data = []
time_data = []
score = []
data = get_hourly_density(tiles, day)
for t in data:
for time in data[t]:
time_data.append(time)
tiles_data.append(t)
score.append(data[t][time])
return pd.DataFrame(data={'tileID': tiles_data, 'score':score, 'time': time_data}).set_index(['tileID', 'time'])
def fetch_data_city(city: str) -> None:
"""Fetches the data for a city if the data is not yet cashed on the computer.
"""
compression = ".xz"
folder = os.path.join(".","data")
def file_path(file_name: str) -> str:
return os.path.join(folder, file_name)
if not(os.path.exists(folder)):
os.mkdir(folder)
tiles_path = file_path(f'{city}Tiles.pkl{compression}')
hourly_dem_path = file_path(f'{city}HourlyDemographics.pkl{compression}')
hourly_density_path = file_path(f'{city}HourlyDensity.pkl{compression}')
daily_density_path = file_path(f'{city}DensityDaily.pkl{compression}')
daily_demographics_path = file_path(f'{city}DemographicsDaily.pkl{compression}')
if not(os.path.isfile(tiles_path)):
tiles = get_tiles(get_municipalityID(city)[0])
tiles.to_pickle(tiles_path)
else:
tiles = pd.read_pickle(tiles_path)
if not(os.path.isfile(hourly_dem_path)):
hourly_dem = get_hourly_demographics_dataframe(tiles['tileID'].to_numpy())
hourly_dem.to_pickle(hourly_dem_path)
if not(os.path.isfile(hourly_density_path)):
hourly_dens = get_hourly_density_dataframe(tiles['tileID'].to_numpy())
hourly_dens.to_pickle(hourly_density_path)
if not(os.path.isfile(daily_density_path)):
get_daily_density(tiles['tileID'].to_numpy()).to_pickle(daily_density_path)
if not(os.path.isfile(daily_demographics_path)):
get_daily_demographics(tiles['tileID'].to_numpy()).to_pickle(daily_demographics_path)
def clean_cities_list(cities: [str]) -> [str]:
"""Cleans the list of cities by removing all the cities that are not found in the
official list of cities provided by the Federal Statisitics Office.
Args:
List of cities to check and clean.
Return:
List containing a subset of the input list such that all elements are valid.
"""
invalid_cities = []
#validation that the cities names are valid
for c in cities:
if len(commune.loc[commune.GDENAME == c].GDENR.to_numpy()) == 0:
city = []
sim_value = []
for f in commune.GDENAME:
r = SequenceMatcher(None, c, f).ratio()
if r > 0.5:
city.append(f)
sim_value.append(r)
d = pd.DataFrame(data={"city": city, "value": sim_value})
potential_cities = d.sort_values("value", ascending=False).head(5).city.to_numpy()
print(f"City nammed: {c} cannot be found in official records. Did you mean: {potential_cities} ? {c} will be ignored.")
invalid_cities.append(c)
return [c for c in cities if not(c in invalid_cities)]
# Multithread fetch implementation
class DownloadWorker(Thread):
def __init__(self, queue):
Thread.__init__(self)
self.queue = queue
def run(self):
while True:
# Get the work from the queue and expand the tuple
city = self.queue.get()
if city == -1:
self.queue.put(-1)
break
try:
fetch_data_city(city)
finally:
self.queue.task_done()
def download_commune_excel() -> None:
'''
Downloads the excel spreadsheet from the Swiss Federal Statistical Office that maps the town name to unique ID
'''
print('Beginning commune file download with requests')
folder = os.path.join(".","data")
if not(os.path.exists(folder)):
os.mkdir(folder)
url = 'https://www.bfs.admin.ch/bfsstatic/dam/assets/11467406/master'
r = requests.get(url)
with open(os.path.join(".", "data", 'commune.xlsx'), 'wb') as f:
f.write(r.content)
print("End of commune file download")
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
BASE_URL = "https://api.swisscom.com/layer/heatmaps/demo"
TOKEN_URL = "https://consent.swisscom.com/o/oauth2/token"
MAX_NB_TILES_REQUEST = 100
headers = {"scs-version": "2"}
client_id = "" # customer key in the Swisscom digital market place
client_secret = "" # customer secret in the Swisscom digital market place
if client_id == "":
client_id = os.environ.get("CLIENT_ID", "")
if client_id == "":
client_id = input("Enter MIP Client ID: ")
os.environ["CLIENT_ID"] = client_id
if client_secret == "":
client_secret = os.environ.get("CLIENT_SECRET", "")
if client_secret == "":
client_secret = getpass.getpass('Enter MIP client secret:')
os.environ["CLIENT_SECRET"] = client_secret
# Fetch an access token
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
oauth.fetch_token(token_url=TOKEN_URL, client_id=client_id,
client_secret=client_secret)
def main():
ts = time()
if not(os.path.exists(os.path.join(".", "data", 'commune.xlsx'))):
download_commune_excel()
global commune
commune = pd.read_excel(os.path.join(".", "data", 'commune.xlsx'), sheet_name='GDE')
cities = ["Saas-Fee", "Arosa", "Bulle", "Laax","Belp" ,"Saanen","Adelboden", "Andermatt", "Davos", "Bulle", "Bern", "Genève", "Lausanne", "Zürich", "Neuchâtel", "Sion", "St. Gallen", "Appenzell", "Solothurn", "Zug", "Fribourg", "Luzern", "Ecublens (VD)", "Kloten", "Le Grand-Saconnex", "Nyon", "Zermatt", "Lugano"]
cities = clean_cities_list(cities)
queue = Queue()
for x in range(2):
worker = DownloadWorker(queue)
worker.deamen = True
worker.start()
for c in cities:
logger.info('Queueing {}'.format(c))
queue.put(c)
queue.join()
queue.put(-1)
logger.info('Took %s', time() - ts)
list_of_cities_path = os.path.join(".", "data","CityList.json")
cityList=[]
if os.path.isfile(list_of_cities_path):
with open(list_of_cities_path, "r") as filehandle:
cityList = json.load(filehandle)
with open(list_of_cities_path, "w") as filehandle:
for city in cities:
if not(city in cityList):
cityList.append(city)
json.dump(cityList, filehandle)
if __name__ == "__main__":
main()
# Other functions not currently used
def get_daily_demographics_male(tiles: np.array(int), day=datetime(year=2020, month=1, day=27)) -> pd.DataFrame:
"""Fetches Daily demographics.
Fetches the daily male proportion of the tiles and creates a dataframe of the fetched data.
Args:
tiles: Array of tile id's, what will be used to querry demographic data.
day: date of the data to be fetched.
Returns:
DataFrame containing the tileId and the proportion of male. The name of the collumns are:
[tileID, maleProportion]
The data is k-anonymized. Therefor is some tiles are not present in the output dataframe it
means that the data is not available. To find out more about demographics visit the Heatmap FAQ.
"""
tileID = []
maleProportion = []
for tiles_subset in [tiles[i:i + MAX_NB_TILES_REQUEST] for i in range(0, len(tiles), MAX_NB_TILES_REQUEST)]:
api_request = (
BASE_URL
+ f'/heatmaps/dwell-demographics/daily/{day.isoformat().split("T")[0]}'
+ "?tiles="
+ "&tiles=".join(map(str, tiles_subset))
)
data = oauth.get(api_request, headers=headers).json()
if data.get("tiles") != None:
for t in data["tiles"]:
if t.get("maleProportion") != None:
tileID.append(t['tileId'])
maleProportion.append(t["maleProportion"])
return pd.DataFrame(data={'tileID': tileID, 'maleProportion':maleProportion})
def get_daily_demographics_age(tiles: np.array(int), day=datetime(year=2020, month=1, day=27)) -> pd.DataFrame:
"""Fetches daily demographics of age categories
Fetches the daily demographics, age distribution, of the tiles and creates a dataframe of the fetched data.
Args:
tiles: Array of tile id's, what will be used to querry demographic data.
day: date of the data to be fetched.
Returns:
DataFrame containing the tileId and a array of values corresponding to the age distribution. The name
of the collumns are:
[tileID, ageDistribution]
The data is k-anonymized. Therefor is some tiles are not present in the output dataframe it
means that the data is not available. To find out more about demographics visit the Heatmap FAQ.
"""
tileID = []
ageDistribution = []
for tiles_subset in [tiles[i:i + MAX_NB_TILES_REQUEST] for i in range(0, len(tiles), MAX_NB_TILES_REQUEST)]:
api_request = (
BASE_URL
+ f'/heatmaps/dwell-demographics/daily/{day.isoformat().split("T")[0]}'
+ "?tiles="
+ "&tiles=".join(map(str, tiles_subset))
)
data = oauth.get(api_request, headers=headers).json()
for t in data.get("tiles", []):
if t.get("ageDistribution") != None:
tileID.append(t['tileId'])
ageDistribution.append(t["ageDistribution"])
return pd.DataFrame(data={'tileID': tileID, 'ageDistribution':ageDistribution})
| for (idx,a) in enumerate(data[i][time].get("ageDistribution", [])):
age_cat.append(idx)
age_distribution.append(a)
tile_id.append(i)
time_data.append(time)
male_proportion.append(data[i][time].get("maleProportion")) |
tree_bench.rs | extern crate test;
use io_context::Context;
use crate::storage::mkvs::tree::*;
use self::test::Bencher;
const INSERT_ITEMS: usize = 10000;
fn gen_pairs() -> (Vec<Vec<u8>>, Vec<Vec<u8>>) {
let mut keys: Vec<Vec<u8>> = Vec::new();
let mut vals: Vec<Vec<u8>> = Vec::new();
for i in 0..INSERT_ITEMS {
keys.push(format!("key{}", i).into_bytes());
vals.push(format!("val{}", i).into_bytes());
}
(keys, vals)
}
fn gen_tree() -> (Tree, Vec<Vec<u8>>) {
let mut tree = Tree::builder()
.with_root_type(RootType::State)
.build(Box::new(NoopReadSyncer));
let (keys, vals) = gen_pairs();
for i in 0..keys.len() {
tree.insert(Context::background(), keys[i].as_ref(), vals[i].as_ref())
.expect("insert");
}
(tree, keys)
}
#[bench]
fn bench_nonexistent_get(b: &mut Bencher) {
let (tree, _) = gen_tree();
b.iter(|| {
tree.get(Context::background(), b"foo").expect("get");
});
}
#[bench]
fn bench_existing_scan(b: &mut Bencher) {
let (tree, keys) = gen_tree();
let keys_capture = &keys.clone();
b.iter(|| {
for k in keys_capture {
tree.get(Context::background(), k.as_ref()).expect("get");
}
});
}
#[bench]
fn bench_single_inserts(b: &mut Bencher) {
let (keys, vals) = gen_pairs();
let mut tree = Tree::builder()
.with_root_type(RootType::State)
.build(Box::new(NoopReadSyncer));
let mut i = 0;
b.iter(|| {
tree.insert(
Context::background(),
keys[i % keys.len()].as_ref(),
vals[i % vals.len()].as_ref(),
)
.expect("insert");
i += 1;
});
}
#[bench]
fn bench_insert(b: &mut Bencher) {
let (keys, vals) = gen_pairs();
b.iter(|| {
let mut tree = Tree::builder()
.with_root_type(RootType::State) | for i in 0..keys.len() {
tree.insert(Context::background(), keys[i].as_ref(), vals[i].as_ref())
.expect("insert");
}
tree.commit(Context::background(), Default::default(), 0)
.expect("commit");
});
}
fn bench_insert_batch(b: &mut Bencher, num_values: usize, commit: bool) {
b.iter(|| {
let mut tree = Tree::builder()
.with_root_type(RootType::State)
.build(Box::new(NoopReadSyncer));
for i in 0..num_values {
let key = format!("key {}", i);
let value = format!("value {}", i);
tree.insert(Context::background(), key.as_bytes(), value.as_bytes())
.expect("insert");
}
if commit {
tree.commit(Context::background(), Default::default(), 0)
.expect("commit");
}
});
}
#[bench]
fn bench_insert_commit_batch_1(b: &mut Bencher) {
bench_insert_batch(b, 1, true)
}
#[bench]
fn bench_insert_commit_batch_10(b: &mut Bencher) {
bench_insert_batch(b, 10, true)
}
#[bench]
fn bench_insert_commit_batch_100(b: &mut Bencher) {
bench_insert_batch(b, 100, true)
}
#[bench]
fn bench_insert_commit_batch_1000(b: &mut Bencher) {
bench_insert_batch(b, 1000, true)
}
#[bench]
fn bench_insert_no_commit_batch_1(b: &mut Bencher) {
bench_insert_batch(b, 1, false)
}
#[bench]
fn bench_insert_no_commit_batch_10(b: &mut Bencher) {
bench_insert_batch(b, 10, false)
}
#[bench]
fn bench_insert_no_commit_batch_100(b: &mut Bencher) {
bench_insert_batch(b, 100, false)
}
#[bench]
fn bench_insert_no_commit_batch_1000(b: &mut Bencher) {
bench_insert_batch(b, 1000, false)
} | .build(Box::new(NoopReadSyncer));
|
wordle_results.py | from typing import Any
from tortoise import fields
from tortoise.models import Model
from crimsobot.models import DiscordUser
from crimsobot.models.user import User
class WordleResults(Model):
uuid = fields.UUIDField(pk=True)
name = fields.TextField(default='wordle result')
user = fields.ForeignKeyField('models.User', related_name='wordle_results', index=True)
guesses = fields.IntField() # guesses to solve word (0 for quit)
word = fields.TextField() # word guessed
created_at = fields.DatetimeField(null=True, auto_now_add=True)
@classmethod
async def create_result(cls, discord_user: DiscordUser, guesses: int, word: str) -> None:
user = await User.get_by_discord_user(discord_user)
result = WordleResults(user=user, guesses=guesses, word=word)
await result.save()
@classmethod
async def fetch_all_by_user(cls, discord_user: DiscordUser) -> Any:
user = await User.get_by_discord_user(discord_user)
stat = await WordleResults.filter(user=user)
return stat
class Meta:
| table = 'wordle_results' |
|
server.rs | // Copyright 2018 Google LLC
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT.
use clap::Parser;
use futures::{future, prelude::*};
use rand::{
distributions::{Distribution, Uniform},
thread_rng,
};
use service::{init_tracing, World};
use std::{
net::{IpAddr, Ipv6Addr, SocketAddr},
time::Duration,
};
use tarpc::{
context,
server::{self, incoming::Incoming, Channel},
tokio_serde::formats::Json,
};
use tokio::time;
#[derive(Parser)]
struct Flags {
/// Sets the port number to listen on.
#[clap(long)]
port: u16,
}
// This is the type that implements the generated World trait. It is the business logic
// and is used to start the server.
#[derive(Clone)]
struct HelloServer(SocketAddr);
#[tarpc::server]
impl World for HelloServer {
async fn | (self, _: context::Context, name: String) -> String {
let sleep_time =
Duration::from_millis(Uniform::new_inclusive(1, 10).sample(&mut thread_rng()));
time::sleep(sleep_time).await;
format!("Hello, {}! You are connected from {}", name, self.0)
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let flags = Flags::parse();
init_tracing("Tarpc Example Server")?;
let server_addr = (IpAddr::V6(Ipv6Addr::LOCALHOST), flags.port);
// JSON transport is provided by the json_transport tarpc module. It makes it easy
// to start up a serde-powered json serialization strategy over TCP.
let mut listener = tarpc::serde_transport::tcp::listen(&server_addr, Json::default).await?;
listener.config_mut().max_frame_length(usize::MAX);
listener
// Ignore accept errors.
.filter_map(|r| future::ready(r.ok()))
.map(server::BaseChannel::with_defaults)
// Limit channels to 1 per IP.
.max_channels_per_key(1, |t| t.transport().peer_addr().unwrap().ip())
// serve is generated by the service attribute. It takes as input any type implementing
// the generated World trait.
.map(|channel| {
let server = HelloServer(channel.transport().peer_addr().unwrap());
channel.execute(server.serve())
})
// Max 10 channels.
.buffer_unordered(10)
.for_each(|_| async {})
.await;
Ok(())
}
| hello |
YoutubeVideo.py | from _socket import timeout
from urllib.error import URLError
from pytube import YouTube
from pytube.exceptions import RegexMatchError
from old_code.Stream import Stream
import time
import tools as tools
class YoutubeVideo(object):
# todo (2): subtitles
conn_errors = 0
def __init__(self, url, score=0, preferred_container='mp4', min_resolution=360,
max_resolution=1080, force_preferred_container=False):
########################################
self.url = None
self.source = None
self.delete = None
self.complete = None
self.is_play_trailer = None
self.title = None
self.thumbnail_url = None
self.channel = None
self.tags = list()
self.view_count = None
self.rating = None
self.adjusted_rating = None
self.resolution = None
self.quality_score = None
self.length = None
self.resolution_ratio = None
self.streams = list()
self.best_video_stream = None
self.best_audio_stream = None
self.best_combined_stream = None
########################################
self.url = url
self.delete = False
self.is_play_trailer = False
self.complete = True
tries = 0
while True:
try:
self.source = YouTube(url)
except KeyError as e:
if e.args[0] == 'url':
self.delete = True
self.is_play_trailer = True
# todo (1): add youtube-dl info grabber/downloader
# stuff I need: title, length, keywords?
return
elif e.args[0] == 'url_encoded_fmt_stream_map':
if tries > 4:
print('Failed to load youtube data, retrying. Reason: ' + str(e))
self.delete = True
return
print('Failed to load youtube data, retrying. Reason: ' + str(e))
time.sleep(2)
tries += 1
else:
raise
except RegexMatchError as e:
print('Pytube failed to load video info. Reason: ' + url + ': ' + str(e))
self.delete = True
return
except timeout as e:
if tries > 4:
print('Pytube failed to load video info. Reason: ' + str(e))
self.complete = False
if Stream.conn_errors > 2:
raise
else:
Stream.conn_errors += 1
return
print('Pytube failed to load video info. Reason: ' + str(e) + ', retrying...')
tries += 1
time.sleep(1)
except URLError as e:
if tries > 2:
print('Pytube failed to load video info. Reason: ' + str(e))
self.complete = False
if YoutubeVideo.conn_errors > 2:
raise
else:
YoutubeVideo.conn_errors += 1
return
print('Pytube failed to load video info. Reason: ' + str(e) + ', retrying...')
time.sleep(1)
tries += 1
else:
YoutubeVideo.conn_errors = 0
break
self.score = score
self.title = self.source.title
self.title = tools.get_clean_string(self.title)
self.rating = float(self.source.player_config_args['avg_rating'])
self.view_count = int(self.source.player_config_args['view_count'])
self.channel = self.source.player_config_args['author']
self.length = self.source.player_config_args['length_seconds']
self.thumbnail_url = self.source.thumbnail_url
try:
self.thumbnail_url = self.source.thumbnail_url
except KeyError:
self.thumbnail_url = None
try:
self.tags = self.source.player_config_args['keywords'].split(',')
except KeyError:
self.tags = ''
if self.view_count < 100:
self.view_count = 100
self.adjusted_rating = self.rating * (1 - 1 / ((self.view_count / 60) ** 0.5))
self.load_streams(min_resolution, max_resolution)
self.update_quality_score(preferred_container)
self.update_best_audio_stream(preferred_container, force_preferred_container)
self.update_best_video_stream(preferred_container, force_preferred_container)
self.update_best_combined_stream(preferred_container, force_preferred_container)
if self.is_play_trailer:
self.update_youtube_dl_info()
def update_youtube_dl_info(self):
pass
|
for stream in self.streams:
if stream.type != 'video':
continue
quality_score = 0
pixel_bitrate = stream.bitrate_per_pixel
if stream.resolution == 1080:
pixel_bitrate /= 1
quality_score = 120
elif stream.resolution == 720:
pixel_bitrate /= 1.22
quality_score = 108
elif stream.resolution == 480:
pixel_bitrate /= 1.52
quality_score = 65
elif stream.resolution == 360:
pixel_bitrate /= 1.39
quality_score = 40
elif stream.resolution == 240:
pixel_bitrate /= 2.15
quality_score = 20
elif stream.resolution == 144:
pixel_bitrate /= 2.65
quality_score = 10
if preferred_container.lower() == stream.container:
quality_score *= 1.2
quality_score *= pixel_bitrate
if stream.resolution > max_res:
self.quality_score = quality_score
max_res = stream.resolution
self.resolution_ratio = stream.size[0] / stream.size[1]
elif stream.resolution == max_res:
if quality_score > self.quality_score:
self.quality_score = quality_score
def load_streams(self, min_resolution=360, max_resolution=1080):
self.streams = list()
self.complete = True
for source_stream in self.source.streams.fmt_streams:
stream = Stream(source_stream, int(self.length))
if stream.complete:
if stream.resolution is not None:
if stream.resolution > max_resolution or stream.resolution < min_resolution:
continue
self.streams.append(stream)
elif stream.retry:
self.complete = False
if Stream.conn_errors != 0:
self.complete = False
def update_best_video_stream(self, preferred_container='mp4', force_preferred_container=False):
highest_resolution = 0
best_stream = None
highest_pref_resolution = 0
best_pref_stream = None
for stream in self.streams:
if 'video' != stream.type:
continue
if stream.resolution > highest_resolution:
highest_resolution = stream.resolution
best_stream = stream
if stream.container.lower() == preferred_container.lower():
if stream.resolution > highest_pref_resolution:
highest_pref_resolution = stream.resolution
best_pref_stream = stream
if highest_resolution == highest_pref_resolution or force_preferred_container:
ret = best_pref_stream
else:
ret = best_stream
self.best_video_stream = ret
def update_best_audio_stream(self, preferred_container='mp4', force_preferred_container=False):
highest_bitrate = 0
best_stream = None
highest_pref_bitrate = 0
best_pref_stream = None
for stream in self.streams:
if 'audio' != stream.type:
continue
if stream.bitrate > highest_bitrate:
highest_bitrate = stream.bitrate
best_stream = stream
if stream.container.lower() == preferred_container.lower():
if stream.bitrate > highest_pref_bitrate:
highest_pref_bitrate = stream.bitrate
best_pref_stream = stream
if highest_bitrate <= highest_pref_bitrate * 1.35 or force_preferred_container:
ret = best_pref_stream
else:
ret = best_stream
self.best_audio_stream = ret
def update_best_combined_stream(self, preferred_container='mp4', force_preferred_container=False):
highest_resolution = 0
for stream in self.streams:
if 'combined' != stream.type:
continue
if stream.resolution > highest_resolution:
highest_resolution = stream.resolution
max_score = 0
selected_stream = None
for stream in self.streams:
if 'combined' != stream.type:
continue
score = 0
resolution = stream.resolution
if force_preferred_container:
if stream.container != preferred_container:
continue
if resolution == highest_resolution:
score += 10 ** 1
if stream.container == preferred_container:
score += 10 ** 0
if score > max_score:
max_score = score
selected_stream = stream
self.best_combined_stream = selected_stream | def update_quality_score(self, preferred_container='mp4'):
self.quality_score = 0
max_res = 0 |
server_utils.go | /*
Copyright © 2021 VMware
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bufio"
"fmt"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"github.com/Masterminds/semver/v3"
corev1 "github.com/kubeapps/kubeapps/cmd/kubeapps-apis/gen/core/packages/v1alpha1"
kappctrlv1alpha1 "github.com/vmware-tanzu/carvel-kapp-controller/pkg/apis/kappctrl/v1alpha1"
datapackagingv1alpha1 "github.com/vmware-tanzu/carvel-kapp-controller/pkg/apiserver/apis/datapackaging/v1alpha1"
"gopkg.in/yaml.v3"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
structuralschema "k8s.io/apiextensions-apiserver/pkg/apiserver/schema"
"k8s.io/apimachinery/pkg/runtime"
)
type pkgSemver struct {
pkg *datapackagingv1alpha1.Package
version *semver.Version
}
// pkgVersionsMap recturns a map of packages keyed by the packagemetadataName.
//
// A Package CR in carvel is really a particular version of a package, so we need
// to sort them by the package metadata name, since this is what they share in common.
// The packages are then sorted by version.
func getPkgVersionsMap(packages []*datapackagingv1alpha1.Package) (map[string][]pkgSemver, error) {
pkgVersionsMap := map[string][]pkgSemver{}
for _, pkg := range packages {
semverVersion, err := semver.NewVersion(pkg.Spec.Version)
if err != nil {
return nil, fmt.Errorf("required field spec.version was not semver compatible on kapp-controller Package: %v\n%v", err, pkg)
}
pkgVersionsMap[pkg.Spec.RefName] = append(pkgVersionsMap[pkg.Spec.RefName], pkgSemver{pkg, semverVersion})
}
for _, pkgVersions := range pkgVersionsMap {
sort.Slice(pkgVersions, func(i, j int) bool {
return pkgVersions[i].version.GreaterThan(pkgVersions[j].version)
})
}
return pkgVersionsMap, nil
}
// statusReasonForKappStatus returns the reason for a given status
func statusReasonForKappStatus(status kappctrlv1alpha1.AppConditionType) corev1.InstalledPackageStatus_StatusReason {
switch status {
case kappctrlv1alpha1.ReconcileSucceeded:
return corev1.InstalledPackageStatus_STATUS_REASON_INSTALLED
case "ValuesSchemaCheckFailed", kappctrlv1alpha1.ReconcileFailed:
return corev1.InstalledPackageStatus_STATUS_REASON_FAILED
case kappctrlv1alpha1.Reconciling:
return corev1.InstalledPackageStatus_STATUS_REASON_PENDING
}
// Fall back to unknown/unspecified.
return corev1.InstalledPackageStatus_STATUS_REASON_UNSPECIFIED
}
// userReasonForKappStatus returns the reason for a given status
func userReasonForKappStatus(status kappctrlv1alpha1.AppConditionType) string {
switch status {
case kappctrlv1alpha1.ReconcileSucceeded:
return "Reconcile succeeded"
case "ValuesSchemaCheckFailed", kappctrlv1alpha1.ReconcileFailed:
return "Reconcile failed"
case kappctrlv1alpha1.Reconciling:
return "Reconciling"
}
// Fall back to unknown/unspecified.
return "Unknown"
}
// pageOffsetFromPageToken converts a page token to an integer offset representing the page of results.
//
// TODO(mnelson): When aggregating results from different plugins, we'll
// need to update the actual query in GetPaginatedChartListWithFilters to
// use a row offset rather than a page offset (as not all rows may be consumed
// for a specific plugin when combining).
func pageOffsetFromPageToken(pageToken string) (int, error) {
if pageToken == "" {
return 0, nil
}
offset, err := strconv.ParseUint(pageToken, 10, 0)
if err != nil {
return 0, err
}
return int(offset), nil
}
// extracts the value for a key from a JSON-formatted string
// body - the JSON-response as a string. Usually retrieved via the request body
// key - the key for which the value should be extracted
// returns - the value for the given key
// https://stackoverflow.com/questions/17452722/how-to-get-the-key-value-from-a-json-string-in-go/37332972
func extractValue(body string, key string) string {
keystr := "\"" + key + "\":[^,;\\]}]*"
r, _ := regexp.Compile(keystr)
match := r.FindString(body)
keyValMatch := strings.Split(match, ":")
value := ""
if len(keyValMatch) > 1 {
value = strings.ReplaceAll(keyValMatch[1], "\"", "")
}
return value
}
// defaultValuesFromSchema returns a yaml string with default values generated from an OpenAPI v3 Schema
func defaultValuesFromSchema(schema []byte, isCommentedOut bool) (string, error) {
if len(schema) == 0 {
return "", nil
}
// Deserialize the schema passed into the function
jsonSchemaProps := &apiextensions.JSONSchemaProps{}
if err := yaml.Unmarshal(schema, jsonSchemaProps); err != nil {
return "", err
}
structural, err := structuralschema.NewStructural(jsonSchemaProps)
if err != nil {
return "", err
}
// Generate the default values
unstructuredDefaultValues := make(map[string]interface{})
defaultValues(unstructuredDefaultValues, structural)
yamlDefaultValues, err := yaml.Marshal(unstructuredDefaultValues)
if err != nil {
return "", err
}
strYamlDefaultValues := string(yamlDefaultValues)
// If isCommentedOut, add a yaml comment character '#' to the beginning of each line
if isCommentedOut {
var sb strings.Builder
scanner := bufio.NewScanner(strings.NewReader(strYamlDefaultValues))
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
sb.WriteString("# ")
sb.WriteString(fmt.Sprintln(scanner.Text()))
}
strYamlDefaultValues = sb.String()
}
return strYamlDefaultValues, nil
}
// Default does defaulting of x depending on default values in s.
// Based upon https://github.com/kubernetes/apiextensions-apiserver/blob/release-1.21/pkg/apiserver/schema/defaulting/algorithm.go
// Plus modifications from https://github.com/vmware-tanzu/tanzu-framework/pull/1422
// In short, it differs from upstream in that:
// -- 1. Prevent deep copy of int as it panics
// -- 2. For type object scan the first level properties for any defaults to create an empty map to populate
// -- 3. If the property does not have a default, add one based on the type ("", false, etc)
func defaultValues(x interface{}, s *structuralschema.Structural) {
if s == nil {
return
}
switch x := x.(type) {
case map[string]interface{}:
for k, prop := range s.Properties { //nolint
// if Default for object is nil, scan first level of properties for any defaults to create an empty default
if prop.Default.Object == nil {
createDefault := false
if prop.Properties != nil {
for _, v := range prop.Properties { //nolint
if v.Default.Object != nil {
createDefault = true
break
}
}
}
if createDefault {
prop.Default.Object = make(map[string]interface{})
// If not generating an empty object, fall back to the data type's defaults
} else {
switch prop.Type {
case "string":
prop.Default.Object = ""
case "number":
prop.Default.Object = 0
case "integer":
prop.Default.Object = 0
case "boolean":
prop.Default.Object = false
case "array":
prop.Default.Object = []interface{}{}
case "object":
prop.Default.Object = make(map[string]interface{})
}
}
}
if _, found := x[k]; !found || isNonNullableNull(x[k], &prop) {
if isKindInt(prop.Default.Object) {
x[k] = prop.Default.Object
} else {
x[k] = runtime.DeepCopyJSONValue(prop.Default.Object)
}
}
}
for k := range x {
if prop, found := s.Properties[k]; found {
defaultValues(x[k], &prop)
} else if s.AdditionalProperties != nil { | }
case []interface{}:
for i := range x {
if isNonNullableNull(x[i], s.Items) {
if isKindInt(s.Items.Default.Object) {
x[i] = s.Items.Default.Object
} else {
x[i] = runtime.DeepCopyJSONValue(s.Items.Default.Object)
}
}
defaultValues(x[i], s.Items)
}
default:
// scalars, do nothing
}
}
// isNonNullalbeNull returns true if the item is nil AND it's nullable
func isNonNullableNull(x interface{}, s *structuralschema.Structural) bool {
return x == nil && s != nil && !s.Generic.Nullable
}
// isKindInt returns true if the item is an int
func isKindInt(src interface{}) bool {
return src != nil && reflect.TypeOf(src).Kind() == reflect.Int
}
|
if isNonNullableNull(x[k], s.AdditionalProperties.Structural) {
if isKindInt(s.AdditionalProperties.Structural.Default.Object) {
x[k] = s.AdditionalProperties.Structural.Default.Object
} else {
x[k] = runtime.DeepCopyJSONValue(s.AdditionalProperties.Structural.Default.Object)
}
}
defaultValues(x[k], s.AdditionalProperties.Structural)
}
|
resize.ts | import sharp from 'sharp'
import fs from 'fs-extra'
import { thumbnails } from './storage'
import path from 'path'
export type Size = 'medium' | 'small' | 'square' | const getDimensions = (size: Size) =>
({
small: { width: 100, height: 100 },
medium: { width: Math.floor((400 * 35) / 45), height: 400 },
square: { width: 400, height: 400 },
}[size] || { width: 0, height: 0 })
export default async function resize(
imagePath: string,
uuid: string,
size?: Size
) {
const { width, height } = getDimensions(size || 'medium')
if (width === 0 && height === 0) {
return imagePath
}
const thumbnailPath = `${thumbnails}/${uuid}/${path
.basename(imagePath)
.replace(/(\.[\w\d_-]+)$/i, `-${width || 'auto'}x${height || 'auto'}$1`)}`
if (!(await fs.pathExists(thumbnailPath))) {
await fs.ensureFile(thumbnailPath)
await sharp(imagePath).resize(width, height).toFile(thumbnailPath)
}
return thumbnailPath
} | |
debug.rs | use anyhow::{bail, ensure, Error};
use object::endian::{BigEndian, Endian, Endianness, LittleEndian};
use object::{RelocationEncoding, RelocationKind};
use std::collections::HashMap;
pub fn create_gdbjit_image(
mut bytes: Vec<u8>,
code_region: (*const u8, usize),
defined_funcs_offset: usize,
funcs: &[*const u8],
) -> Result<Vec<u8>, Error> {
let e = ensure_supported_elf_format(&bytes)?;
// patch relocs
relocate_dwarf_sections(&bytes, defined_funcs_offset, funcs)?;
// elf is still missing details...
match e {
Endianness::Little => {
convert_object_elf_to_loadable_file::<LittleEndian>(&mut bytes, code_region)
}
Endianness::Big => {
convert_object_elf_to_loadable_file::<BigEndian>(&mut bytes, code_region)
}
}
// let mut file = ::std::fs::File::create(::std::path::Path::new("test.o")).expect("file");
// ::std::io::Write::write_all(&mut file, &bytes).expect("write");
Ok(bytes)
}
fn relocate_dwarf_sections(
bytes: &[u8],
defined_funcs_offset: usize,
funcs: &[*const u8],
) -> Result<(), Error> {
use object::read::{File, Object, ObjectSection, ObjectSymbol, RelocationTarget};
let obj = File::parse(bytes)?;
let mut func_symbols = HashMap::new();
for sym in obj.symbols() {
match (sym.name(), sym.section_index()) {
(Ok(name), Some(_section_index)) if name.starts_with("_wasm_function_") => {
let index = name["_wasm_function_".len()..].parse::<usize>()?;
let data = funcs[index - defined_funcs_offset];
func_symbols.insert(sym.index(), data);
}
_ => (),
}
}
for section in obj.sections() {
for (off, r) in section.relocations() {
if r.kind() != RelocationKind::Absolute
|| r.encoding() != RelocationEncoding::Generic
|| r.size() != 64
{
continue;
}
let data = match r.target() {
RelocationTarget::Symbol(ref index) => func_symbols.get(index),
_ => None,
};
let data: *const u8 = match data {
Some(data) => *data,
None => {
continue;
}
};
let target = (data as u64).wrapping_add(r.addend() as u64);
let entry_ptr = section.data_range(off, 8).unwrap().unwrap().as_ptr();
unsafe {
std::ptr::write(entry_ptr as *mut u64, target);
}
}
}
Ok(())
}
fn ensure_supported_elf_format(bytes: &[u8]) -> Result<Endianness, Error> {
use object::elf::*;
use object::read::elf::*;
use std::mem::size_of;
let kind = match object::FileKind::parse(bytes) {
Ok(file) => file,
Err(err) => {
bail!("Failed to parse file: {}", err);
}
};
let header = match kind {
object::FileKind::Elf64 => match object::elf::FileHeader64::<Endianness>::parse(bytes) {
Ok(header) => header,
Err(err) => {
bail!("Unsupported ELF file: {}", err);
}
},
_ => {
bail!("only 64-bit ELF files currently supported")
}
};
let e = header.endian().unwrap();
match header.e_machine.get(e) {
EM_AARCH64 => (),
EM_X86_64 => (),
EM_S390 => (),
machine => {
bail!("Unsupported ELF target machine: {:x}", machine);
}
}
ensure!(
header.e_phoff.get(e) == 0 && header.e_phnum.get(e) == 0,
"program header table is empty"
);
let e_shentsize = header.e_shentsize.get(e);
let req_shentsize = match e {
Endianness::Little => size_of::<SectionHeader64<LittleEndian>>(),
Endianness::Big => size_of::<SectionHeader64<BigEndian>>(),
};
ensure!(e_shentsize as usize == req_shentsize, "size of sh");
Ok(e)
}
fn convert_object_elf_to_loadable_file<E: Endian>(
bytes: &mut Vec<u8>,
code_region: (*const u8, usize),
) {
use object::elf::*;
use std::ffi::CStr;
use std::mem::size_of;
use std::os::raw::c_char;
let e = E::default();
let header: &FileHeader64<E> = unsafe { &*(bytes.as_mut_ptr() as *const FileHeader64<_>) }; | let e_shentsize = header.e_shentsize.get(e);
let e_shoff = header.e_shoff.get(e);
let e_shnum = header.e_shnum.get(e);
let mut shstrtab_off = 0;
for i in 0..e_shnum {
let off = e_shoff as isize + i as isize * e_shentsize as isize;
let section: &SectionHeader64<E> =
unsafe { &*(bytes.as_ptr().offset(off) as *const SectionHeader64<_>) };
if section.sh_type.get(e) != SHT_STRTAB {
continue;
}
shstrtab_off = section.sh_offset.get(e);
}
let mut segment: Option<_> = None;
for i in 0..e_shnum {
let off = e_shoff as isize + i as isize * e_shentsize as isize;
let section: &mut SectionHeader64<E> =
unsafe { &mut *(bytes.as_mut_ptr().offset(off) as *mut SectionHeader64<_>) };
if section.sh_type.get(e) != SHT_PROGBITS {
continue;
}
// It is a SHT_PROGBITS, but we need to check sh_name to ensure it is our function
let sh_name_off = section.sh_name.get(e);
let sh_name = unsafe {
CStr::from_ptr(
bytes
.as_ptr()
.offset((shstrtab_off + sh_name_off as u64) as isize)
as *const c_char,
)
.to_str()
.expect("name")
};
if sh_name != ".text" {
continue;
}
assert!(segment.is_none());
// Patch vaddr, and save file location and its size.
section.sh_addr.set(e, code_region.0 as u64);
let sh_offset = section.sh_offset.get(e);
let sh_size = section.sh_size.get(e);
segment = Some((sh_offset, sh_size));
}
// LLDB wants segment with virtual address set, placing them at the end of ELF.
let ph_off = bytes.len();
let e_phentsize = size_of::<ProgramHeader64<E>>();
let e_phnum = 1;
bytes.resize(ph_off + e_phentsize * e_phnum, 0);
if let Some((sh_offset, sh_size)) = segment {
let (v_offset, size) = code_region;
let program: &mut ProgramHeader64<E> =
unsafe { &mut *(bytes.as_ptr().add(ph_off) as *mut ProgramHeader64<_>) };
program.p_type.set(e, PT_LOAD);
program.p_offset.set(e, sh_offset);
program.p_vaddr.set(e, v_offset as u64);
program.p_paddr.set(e, v_offset as u64);
program.p_filesz.set(e, sh_size);
program.p_memsz.set(e, size as u64);
} else {
unreachable!();
}
// It is somewhat loadable ELF file at this moment.
let header: &mut FileHeader64<E> =
unsafe { &mut *(bytes.as_mut_ptr() as *mut FileHeader64<_>) };
header.e_type.set(e, ET_DYN);
header.e_phoff.set(e, ph_off as u64);
header.e_phentsize.set(e, e_phentsize as u16);
header.e_phnum.set(e, e_phnum as u16);
} | |
statistics.go | package main
import (
"encoding/json"
"fmt"
"math"
"os"
"text/tabwriter"
"time"
metrics "github.com/rcrowley/go-metrics"
tmrpc "github.com/torusresearch/tendermint/rpc/client"
"github.com/torusresearch/tendermint/types"
)
type statistics struct {
TxsThroughput metrics.Histogram `json:"txs_per_sec"`
BlocksThroughput metrics.Histogram `json:"blocks_per_sec"`
}
// calculateStatistics calculates the tx / second, and blocks / second based
// off of the number the transactions and number of blocks that occurred from
// the start block, and the end time.
func calculateStatistics(
client tmrpc.Client,
minHeight int64,
timeStart time.Time,
duration int,
) (*statistics, error) {
timeEnd := timeStart.Add(time.Duration(duration) * time.Second)
stats := &statistics{
BlocksThroughput: metrics.NewHistogram(metrics.NewUniformSample(1000)),
TxsThroughput: metrics.NewHistogram(metrics.NewUniformSample(1000)),
}
var (
numBlocksPerSec = make(map[int64]int64)
numTxsPerSec = make(map[int64]int64)
)
// because during some seconds blocks won't be created...
for i := int64(0); i < int64(duration); i++ {
numBlocksPerSec[i] = 0
numTxsPerSec[i] = 0
}
blockMetas, err := getBlockMetas(client, minHeight, timeStart, timeEnd)
if err != nil {
return nil, err
}
// iterates from max height to min height
for _, blockMeta := range blockMetas {
// check if block was created after timeStart
if blockMeta.Header.Time.Before(timeStart) {
break
}
// check if block was created before timeEnd
if blockMeta.Header.Time.After(timeEnd) {
continue
}
sec := secondsSinceTimeStart(timeStart, blockMeta.Header.Time)
// increase number of blocks for that second
numBlocksPerSec[sec]++
// increase number of txs for that second
numTxsPerSec[sec] += blockMeta.Header.NumTxs
logger.Debug(fmt.Sprintf("%d txs at block height %d", blockMeta.Header.NumTxs, blockMeta.Header.Height))
}
for i := int64(0); i < int64(duration); i++ {
stats.BlocksThroughput.Update(numBlocksPerSec[i])
stats.TxsThroughput.Update(numTxsPerSec[i])
}
return stats, nil
}
func getBlockMetas(client tmrpc.Client, minHeight int64, timeStart, timeEnd time.Time) ([]*types.BlockMeta, error) |
func secondsSinceTimeStart(timeStart, timePassed time.Time) int64 {
return int64(math.Round(timePassed.Sub(timeStart).Seconds()))
}
func printStatistics(stats *statistics, outputFormat string) {
if outputFormat == "json" {
result, err := json.Marshal(struct {
TxsThroughput float64 `json:"txs_per_sec_avg"`
BlocksThroughput float64 `json:"blocks_per_sec_avg"`
}{stats.TxsThroughput.Mean(), stats.BlocksThroughput.Mean()})
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(string(result))
} else {
w := tabwriter.NewWriter(os.Stdout, 0, 0, 5, ' ', 0)
fmt.Fprintln(w, "Stats\tAvg\tStdDev\tMax\tTotal\t")
fmt.Fprintln(
w,
fmt.Sprintf(
"Txs/sec\t%.0f\t%.0f\t%d\t%d\t",
stats.TxsThroughput.Mean(),
stats.TxsThroughput.StdDev(),
stats.TxsThroughput.Max(),
stats.TxsThroughput.Sum(),
),
)
fmt.Fprintln(
w,
fmt.Sprintf("Blocks/sec\t%.3f\t%.3f\t%d\t%d\t",
stats.BlocksThroughput.Mean(),
stats.BlocksThroughput.StdDev(),
stats.BlocksThroughput.Max(),
stats.BlocksThroughput.Sum(),
),
)
w.Flush()
}
}
| {
// get blocks between minHeight and last height
// This returns max(minHeight,(last_height - 20)) to last_height
info, err := client.BlockchainInfo(minHeight, 0)
if err != nil {
return nil, err
}
var (
blockMetas = info.BlockMetas
lastHeight = info.LastHeight
diff = lastHeight - minHeight
offset = len(blockMetas)
)
for offset < int(diff) {
// get blocks between minHeight and last height
info, err := client.BlockchainInfo(minHeight, lastHeight-int64(offset))
if err != nil {
return nil, err
}
blockMetas = append(blockMetas, info.BlockMetas...)
offset = len(blockMetas)
}
return blockMetas, nil
} |
test_default_modules.py | # -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
from __future__ import absolute_import
from collections import namedtuple
import errno
import dnf
from mock import call, Mock, patch, PropertyMock
import pytest
from module_build_service.common.config import conf
from module_build_service.common.errors import UnprocessableEntity
from module_build_service.common.models import ModuleBuild
from module_build_service.common.utils import import_mmd, load_mmd, mmd_to_str
from module_build_service.scheduler import default_modules
from module_build_service.scheduler.db_session import db_session
from tests import clean_database, make_module_in_db, read_staged_data
@patch("module_build_service.scheduler.default_modules.handle_collisions_with_base_module_rpms")
@patch("module_build_service.scheduler.default_modules._get_default_modules")
def test_add_default_modules(mock_get_dm, mock_hc):
"""
Test that default modules present in the database are added, and the others are ignored.
"""
clean_database()
mmd = load_mmd(read_staged_data("formatted_testmodule.yaml"))
xmd_brs = mmd.get_xmd()["mbs"]["buildrequires"]
assert set(xmd_brs.keys()) == {"platform"}
platform = ModuleBuild.get_build_from_nsvc(
db_session,
"platform",
xmd_brs["platform"]["stream"],
xmd_brs["platform"]["version"],
xmd_brs["platform"]["context"],
)
assert platform
platform_mmd = platform.mmd()
platform_xmd = mmd.get_xmd()
platform_xmd["mbs"]["use_default_modules"] = True
platform_mmd.set_xmd(platform_xmd)
platform.modulemd = mmd_to_str(platform_mmd)
dependencies = [
{"requires": {"platform": ["f28"]},
"buildrequires": {"platform": ["f28"]}}]
make_module_in_db("python:3:12345:1", base_module=platform, dependencies=dependencies)
make_module_in_db("nodejs:11:2345:2", base_module=platform, dependencies=dependencies)
db_session.commit()
mock_get_dm.return_value = {
"nodejs": "11",
"python": "3",
"ruby": "2.6",
}
defaults_added = default_modules.add_default_modules(mmd)
# Make sure that the default modules were added. ruby:2.6 will be ignored since it's not in
# the database
assert set(mmd.get_xmd()["mbs"]["buildrequires"].keys()) == {"nodejs", "platform", "python"}
mock_get_dm.assert_called_once_with(
"f28",
"https://pagure.io/releng/fedora-module-defaults.git",
)
assert "ursine_rpms" not in mmd.get_xmd()["mbs"]
assert defaults_added is True
@patch("module_build_service.scheduler.default_modules._get_default_modules")
def test_add_default_modules_not_linked(mock_get_dm):
"""
Test that no default modules are added when they aren't linked from the base module.
"""
clean_database()
mmd = load_mmd(read_staged_data("formatted_testmodule.yaml"))
assert set(mmd.get_xmd()["mbs"]["buildrequires"].keys()) == {"platform"}
default_modules.add_default_modules(mmd)
assert set(mmd.get_xmd()["mbs"]["buildrequires"].keys()) == {"platform"}
mock_get_dm.assert_not_called()
def test_add_default_modules_platform_not_available():
|
@patch("module_build_service.scheduler.default_modules._get_default_modules")
def test_add_default_modules_compatible_platforms(mock_get_dm):
"""
Test that default modules built against compatible base module streams are added.
"""
clean_database(add_platform_module=False)
# Create compatible base modules.
mmd = load_mmd(read_staged_data("platform"))
for stream in ["f27", "f28"]:
mmd = mmd.copy("platform", stream)
# Set the virtual stream to "fedora" to make these base modules compatible.
xmd = mmd.get_xmd()
xmd["mbs"]["virtual_streams"] = ["fedora"]
xmd["mbs"]["use_default_modules"] = True
mmd.set_xmd(xmd)
import_mmd(db_session, mmd)
mmd = load_mmd(read_staged_data("formatted_testmodule.yaml"))
xmd_brs = mmd.get_xmd()["mbs"]["buildrequires"]
assert set(xmd_brs.keys()) == {"platform"}
platform_f27 = ModuleBuild.get_build_from_nsvc(
db_session, "platform", "f27", "3", "00000000")
assert platform_f27
# Create python default module which requires platform:f27 and therefore cannot be used
# as default module for platform:f28.
dependencies = [
{"requires": {"platform": ["f27"]},
"buildrequires": {"platform": ["f27"]}}]
make_module_in_db("python:3:12345:1", base_module=platform_f27, dependencies=dependencies)
# Create nodejs default module which requries any platform stream and therefore can be used
# as default module for platform:f28.
dependencies[0]["requires"]["platform"] = []
make_module_in_db("nodejs:11:2345:2", base_module=platform_f27, dependencies=dependencies)
db_session.commit()
mock_get_dm.return_value = {
"nodejs": "11",
"python": "3",
"ruby": "2.6",
}
defaults_added = default_modules.add_default_modules(mmd)
# Make sure that the default modules were added. ruby:2.6 will be ignored since it's not in
# the database
assert set(mmd.get_xmd()["mbs"]["buildrequires"].keys()) == {"nodejs", "platform"}
mock_get_dm.assert_called_once_with(
"f28",
"https://pagure.io/releng/fedora-module-defaults.git",
)
assert defaults_added is True
@patch("module_build_service.scheduler.default_modules._get_default_modules")
def test_add_default_modules_request_failed(mock_get_dm):
"""
Test that an exception is raised when the call to _get_default_modules failed.
"""
clean_database()
make_module_in_db("python:3:12345:1")
make_module_in_db("nodejs:11:2345:2")
mmd = load_mmd(read_staged_data("formatted_testmodule.yaml"))
xmd_brs = mmd.get_xmd()["mbs"]["buildrequires"]
assert set(xmd_brs.keys()) == {"platform"}
platform = ModuleBuild.get_build_from_nsvc(
db_session,
"platform",
xmd_brs["platform"]["stream"],
xmd_brs["platform"]["version"],
xmd_brs["platform"]["context"],
)
assert platform
platform_mmd = platform.mmd()
platform_xmd = mmd.get_xmd()
platform_xmd["mbs"]["use_default_modules"] = True
platform_mmd.set_xmd(platform_xmd)
platform.modulemd = mmd_to_str(platform_mmd)
db_session.commit()
expected_error = "some error"
mock_get_dm.side_effect = ValueError(expected_error)
with pytest.raises(ValueError, match=expected_error):
default_modules.add_default_modules(mmd)
@pytest.mark.parametrize("is_rawhide", (True, False))
@patch("shutil.rmtree")
@patch("tempfile.mkdtemp")
@patch("module_build_service.scheduler.default_modules.Modulemd.ModuleIndex.new")
@patch("module_build_service.scheduler.default_modules.scm.SCM")
@patch("module_build_service.scheduler.default_modules._get_rawhide_version")
def test_get_default_modules(
mock_get_rawhide, mock_scm, mock_mmd_new, mock_mkdtemp, mock_rmtree, is_rawhide,
):
"""
Test that _get_default_modules returns the default modules.
"""
mock_scm.return_value.sourcedir = "/some/path"
if is_rawhide:
mock_scm.return_value.checkout_ref.side_effect = [
UnprocessableEntity("invalid branch"),
None,
]
mock_get_rawhide.return_value = "f32"
expected = {"nodejs": "11"}
mock_mmd_new.return_value.get_default_streams.return_value = expected
rv = default_modules._get_default_modules("f32", conf.default_modules_scm_url)
assert rv == expected
if is_rawhide:
mock_scm.return_value.checkout_ref.assert_has_calls(
[call("f32"), call(conf.rawhide_branch)]
)
else:
mock_scm.return_value.checkout_ref.assert_called_once_with("f32")
@pytest.mark.parametrize("uses_rawhide", (True, False))
@patch("shutil.rmtree")
@patch("tempfile.mkdtemp")
@patch(
"module_build_service.scheduler.default_modules.conf.uses_rawhide",
new_callable=PropertyMock,
)
@patch("module_build_service.scheduler.default_modules.Modulemd.ModuleIndex.new")
@patch("module_build_service.scheduler.default_modules.scm.SCM")
@patch("module_build_service.scheduler.default_modules._get_rawhide_version")
def test_get_default_modules_invalid_branch(
mock_get_rawhide, mock_scm, mock_mmd_new, mock_uses_rawhide, mock_mkdtemp, mock_rmtree,
uses_rawhide,
):
"""
Test that _get_default_modules raises an exception with an invalid branch.
"""
mock_uses_rawhide.return_value = uses_rawhide
mock_scm.return_value.sourcedir = "/some/path"
mock_scm.return_value.checkout_ref.side_effect = [
UnprocessableEntity("invalid branch"),
UnprocessableEntity("invalid branch"),
]
if uses_rawhide:
mock_get_rawhide.return_value = "f32"
else:
mock_get_rawhide.return_value = "something_else"
with pytest.raises(RuntimeError, match="Failed to retrieve the default modules"):
default_modules._get_default_modules("f32", conf.default_modules_scm_url)
mock_mmd_new.assert_not_called()
if uses_rawhide:
mock_scm.return_value.checkout_ref.assert_has_calls(
[call("f32"), call(conf.rawhide_branch)],
)
else:
mock_scm.return_value.checkout_ref.assert_called_once_with("f32")
@patch("module_build_service.scheduler.default_modules.get_session")
def test_get_rawhide_version(mock_get_session):
"""
Test that _get_rawhide_version will return rawhide Fedora version.
"""
mock_get_session.return_value.getBuildTarget.return_value = {
"build_tag_name": "f32-build",
}
assert default_modules._get_rawhide_version() == "f32"
@patch("module_build_service.scheduler.default_modules.get_session")
@patch("module_build_service.scheduler.default_modules._get_rpms_from_tags")
def test_handle_collisions_with_base_module_rpms(mock_grft, mock_get_session):
"""
Test that handle_collisions_with_base_module_rpms will add conflicts for NEVRAs in the
modulemd.
"""
mmd = load_mmd(read_staged_data("formatted_testmodule.yaml"))
xmd = mmd.get_xmd()
xmd["mbs"]["buildrequires"]["platform"]["koji_tag"] = "module-el-build"
xmd["mbs"]["buildrequires"]["python"] = {"koji_tag": "module-python27"}
xmd["mbs"]["buildrequires"]["bash"] = {"koji_tag": "module-bash"}
mmd.set_xmd(xmd)
bm_rpms = {
"bash-completion-1:2.7-5.el8.noarch",
"bash-0:4.4.19-7.el8.aarch64",
"python2-tools-0:2.7.16-11.el8.aarch64",
"python2-tools-0:2.7.16-11.el8.x86_64",
"python3-ldap-0:3.1.0-4.el8.aarch64",
"python3-ldap-0:3.1.0-4.el8.x86_64",
}
non_bm_rpms = {
"bash-0:4.4.20-1.el8.aarch64",
"python2-tools-0:2.7.18-1.module+el8.1.0+3568+bbd875cb.aarch64",
"python2-tools-0:2.7.18-1.module+el8.1.0+3568+bbd875cb.x86_64",
}
mock_grft.side_effect = [bm_rpms, non_bm_rpms]
default_modules.handle_collisions_with_base_module_rpms(mmd, ["aarch64", "x86_64"])
mock_get_session.assert_called_once()
xmd_mbs = mmd.get_xmd()["mbs"]
assert set(xmd_mbs["ursine_rpms"]) == {
"bash-0:4.4.19-7.el8.aarch64",
"python2-tools-0:2.7.16-11.el8.aarch64",
"python2-tools-0:2.7.16-11.el8.x86_64",
}
assert mock_grft.call_count == 2
# We can't check the calls directly because the second argument is a set converted to a list,
# so the order can't be determined ahead of time.
first_call = mock_grft.mock_calls[0][1]
assert first_call[0] == mock_get_session.return_value
assert first_call[1] == ["module-el-build"]
assert first_call[2] == ["aarch64", "x86_64"]
second_call = mock_grft.mock_calls[1][1]
assert second_call[0] == mock_get_session.return_value
assert set(second_call[1]) == {"module-bash", "module-python27"}
assert second_call[2] == ["aarch64", "x86_64"]
@patch("module_build_service.scheduler.default_modules.koji_retrying_multicall_map")
@patch("module_build_service.scheduler.default_modules._get_rpms_in_external_repo")
def test_get_rpms_from_tags(mock_grier, mock_multicall_map):
"""
Test the function queries Koji for the tags' and the tags' external repos' for RPMs.
"""
mock_session = Mock()
bash_tagged = [
[
{
"arch": "aarch64",
"epoch": 0,
"name": "bash",
"version": "4.4.20",
"release": "1.module+el8.1.0+123+bbd875cb",
},
{
"arch": "x86_64",
"epoch": 0,
"name": "bash",
"version": "4.4.20",
"release": "1.module+el8.1.0+123+bbd875cb",
}
],
None,
]
python_tagged = [
[
{
"arch": "aarch64",
"epoch": 0,
"name": "python2-tools",
"version": "2.7.18",
"release": "1.module+el8.1.0+3568+bbd875cb",
},
{
"arch": "x86_64",
"epoch": 0,
"name": "python2-tools",
"version": "2.7.18",
"release": "1.module+el8.1.0+3568+bbd875cb",
}
],
None,
]
bash_repos = []
external_repo_url = "http://domain.local/repo/latest/$arch/"
python_repos = [{
"external_repo_id": "12",
"tag_name": "module-python27",
"url": external_repo_url,
}]
mock_multicall_map.side_effect = [
[bash_tagged, python_tagged],
[bash_repos, python_repos],
]
mock_grier.return_value = {
"python2-test-0:2.7.16-11.module+el8.1.0+3568+bbd875cb.aarch64",
"python2-test-0:2.7.16-11.module+el8.1.0+3568+bbd875cb.x86_64",
}
tags = ["module-bash", "module-python27"]
arches = ["aarch64", "x86_64"]
rv = default_modules._get_rpms_from_tags(mock_session, tags, arches)
expected = {
"bash-0:4.4.20-1.module+el8.1.0+123+bbd875cb.aarch64",
"bash-0:4.4.20-1.module+el8.1.0+123+bbd875cb.x86_64",
"python2-tools-0:2.7.18-1.module+el8.1.0+3568+bbd875cb.aarch64",
"python2-tools-0:2.7.18-1.module+el8.1.0+3568+bbd875cb.x86_64",
"python2-test-0:2.7.16-11.module+el8.1.0+3568+bbd875cb.aarch64",
"python2-test-0:2.7.16-11.module+el8.1.0+3568+bbd875cb.x86_64",
}
assert rv == expected
assert mock_multicall_map.call_count == 2
mock_grier.assert_called_once_with(external_repo_url, arches, "module-python27-12")
@patch("module_build_service.scheduler.default_modules.koji_retrying_multicall_map")
def test_get_rpms_from_tags_error_listTaggedRPMS(mock_multicall_map):
"""
Test that an exception is raised if the listTaggedRPMS Koji query fails.
"""
mock_session = Mock()
mock_multicall_map.return_value = None
tags = ["module-bash", "module-python27"]
arches = ["aarch64", "x86_64"]
expected = (
"Getting the tagged RPMs of the following Koji tags failed: module-bash, module-python27"
)
with pytest.raises(RuntimeError, match=expected):
default_modules._get_rpms_from_tags(mock_session, tags, arches)
@patch("module_build_service.scheduler.default_modules.koji_retrying_multicall_map")
def test_get_rpms_from_tags_error_getExternalRepoList(mock_multicall_map):
"""
Test that an exception is raised if the getExternalRepoList Koji query fails.
"""
mock_session = Mock()
mock_multicall_map.side_effect = [[[[], []]], None]
tags = ["module-bash", "module-python27"]
arches = ["aarch64", "x86_64"]
expected = (
"Getting the external repos of the following Koji tags failed: module-bash, module-python27"
)
with pytest.raises(RuntimeError, match=expected):
default_modules._get_rpms_from_tags(mock_session, tags, arches)
@patch("dnf.Base")
@patch("os.makedirs")
def test_get_rpms_in_external_repo(mock_makedirs, mock_dnf_base):
"""
Test that DNF can query the external repos for the available packages.
"""
RPM = namedtuple("RPM", ["arch", "epoch", "name", "release", "version"])
mock_dnf_base.return_value.sack.query.return_value.available.return_value = [
RPM("aarch64", 0, "python", "1.el8", "2.7"),
RPM("aarch64", 0, "python", "1.el8", "3.7"),
RPM("x86_64", 0, "python", "1.el8", "2.7"),
RPM("x86_64", 0, "python", "1.el8", "3.7"),
RPM("i686", 0, "python", "1.el8", "2.7"),
RPM("i686", 0, "python", "1.el8", "3.7"),
]
external_repo_url = "http://domain.local/repo/latest/$arch/"
arches = ["aarch64", "x86_64", "i686"]
cache_dir_name = "module-el-build-12"
rv = default_modules._get_rpms_in_external_repo(external_repo_url, arches, cache_dir_name)
expected = {
"python-0:2.7-1.el8.aarch64",
"python-0:3.7-1.el8.aarch64",
"python-0:2.7-1.el8.x86_64",
"python-0:3.7-1.el8.x86_64",
"python-0:2.7-1.el8.i686",
"python-0:3.7-1.el8.i686",
}
assert rv == expected
# Test that i686 is mapped to i386 using the koji.canonArch().
mock_dnf_base.return_value.repos.add_new_repo.assert_called_with(
"repo_i386",
mock_dnf_base.return_value.conf,
baseurl=["http://domain.local/repo/latest/i386/"],
minrate=conf.dnf_minrate,
)
def test_get_rpms_in_external_repo_invalid_repo_url():
"""
Test that an exception is raised when an invalid repo URL is passed in.
"""
external_repo_url = "http://domain.local/repo/latest/"
arches = ["aarch64", "x86_64"]
cache_dir_name = "module-el-build-12"
expected = (
r"The external repo http://domain.local/repo/latest/ does not contain the \$arch variable"
)
with pytest.raises(ValueError, match=expected):
default_modules._get_rpms_in_external_repo(external_repo_url, arches, cache_dir_name)
@patch("dnf.Base")
@patch("os.makedirs")
def test_get_rpms_in_external_repo_failed_to_load(mock_makedirs, mock_dnf_base):
"""
Test that an exception is raised when an external repo can't be loaded.
"""
class FakeRepo(dict):
@staticmethod
def add_new_repo(*args, **kwargs):
pass
mock_dnf_base.return_value.update_cache.side_effect = dnf.exceptions.RepoError("Failed")
external_repo_url = "http://domain.local/repo/latest/$arch/"
arches = ["aarch64", "x86_64"]
cache_dir_name = "module-el-build-12"
expected = "Failed to load the external repos"
with pytest.raises(RuntimeError, match=expected):
default_modules._get_rpms_in_external_repo(external_repo_url, arches, cache_dir_name)
@patch("os.makedirs")
def test_get_rpms_in_external_repo_failed_to_create_cache(mock_makedirs):
"""
Test that an exception is raised when the cache can't be created.
"""
exc = OSError()
exc.errno = errno.EACCES
mock_makedirs.side_effect = exc
external_repo_url = "http://domain.local/repo/latest/$arch/"
arches = ["aarch64", "x86_64"]
cache_dir_name = "module-el-build-12"
expected = "The MBS cache is not writeable."
with pytest.raises(RuntimeError, match=expected):
default_modules._get_rpms_in_external_repo(external_repo_url, arches, cache_dir_name)
| """
Test that an exception is raised when the platform module that is buildrequired is missing.
This error should never occur in practice.
"""
clean_database(False, False)
mmd = load_mmd(read_staged_data("formatted_testmodule.yaml"))
expected_error = "Failed to retrieve the module platform:f28:3:00000000 from the database"
with pytest.raises(RuntimeError, match=expected_error):
default_modules.add_default_modules(mmd) |
enum_count.rs | use strum::{EnumCount, EnumIter, IntoEnumIterator};
#[derive(Debug, EnumCount, EnumIter)]
enum Week {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
#[test]
fn simple_test() {
assert_eq!(7, Week::COUNT);
assert_eq!(Week::iter().count(), Week::COUNT);
}
#[test]
fn crate_module_path_test() {
pub mod nested {
pub mod module {
pub use strum;
}
}
#[derive(Debug, EnumCount, EnumIter)]
#[strum(crate = "nested::module::strum")]
enum Week {
Sunday,
Monday,
Tuesday, | Wednesday,
Thursday,
Friday,
Saturday,
}
assert_eq!(7, Week::COUNT);
assert_eq!(Week::iter().count(), Week::COUNT);
} | |
index.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import re
import web
import sys
sys.path.append("/home/www/ShortURL/shorturl")
from libs.qrcode import QRCode, ErrorCorrectLevel
import settings
import models
debug = web.config.debug = settings.DEBUG
render = web.template.render(settings.TEMPLATE_DIR,
base=settings.BASE_TEMPLATE)
app = web.application(settings.URLS, globals())
db = models.DB(settings.DATABASES)
class Index(object):
"""首页"""
def GET(self):
return render.index()
class Shorten(object):
"""网址缩短结果页"""
def __init__(self):
self.db = db
def add_scheme(self, url):
"""给 URL 添加 scheme(qq.com -> http://qq.com)"""
# 支持的 URL scheme
# 常规 URL scheme
scheme2 = re.compile(r'(?i)^[a-z][a-z0-9+.\-]*://')
# 特殊 URL scheme
scheme3 = ('git@', 'mailto:', 'javascript:', 'about:', 'opera:',
'afp:', 'aim:', 'apt:', 'attachment:', 'bitcoin:',
'callto:', 'cid:', 'data:', 'dav:', 'dns:', 'fax:', 'feed:',
'gg:', 'go:', 'gtalk:', 'h323:', 'iax:', 'im:', 'itms:',
'jar:', 'magnet:', 'maps:', 'message:', 'mid:', 'msnim:',
'mvn:', 'news:', 'palm:', 'paparazzi:', 'platform:',
'pres:', 'proxy:', 'psyc:', 'query:', 'session:', 'sip:',
'sips:', 'skype:', 'sms:', 'spotify:', 'steam:', 'tel:',
'things:', 'urn:', 'uuid:', 'view-source:', 'ws:', 'xfire:',
'xmpp:', 'ymsgr:', 'doi:',
)
url_lower = url.lower()
# 如果不包含规定的 URL scheme,则给网址添加 http:// 前缀
scheme = scheme2.match(url_lower)
if not scheme:
for scheme in scheme3:
url_splits = url_lower.split(scheme)
if len(url_splits) > 1:
break
else:
url = 'http://' + url
return url
def qrcode_table(self, data, type_number=4, error_correct_level='H'):
"""生成 QR Code html 表格,可以通过 css 控制黑白块的显示"""
if error_correct_level == 'L':
error_correct_level = ErrorCorrectLevel.L
elif error_correct_level == 'M':
error_correct_level = ErrorCorrectLevel.M
elif error_correct_level == 'Q':
error_correct_level = ErrorCorrectLevel.Q
else:
error_correct_level = ErrorCorrectLevel.H
qr = QRCode()
qr.setTypeNumber(type_number)
qr.setErrorCorrectLevel(error_correct_level)
qr.addData(data)
qr.make()
html = '<table id="qrcode-table">'
for r in range(qr.getModuleCount()):
html += "<tr>"
for c in range(qr.getModuleCount()):
if qr.isDark(r, c):
html += '<td class="dark" />'
else:
html += '<td class="white" />'
html += '</tr>'
html += '</table>'
return html
def POST(self, get_json=False):
url = web.input(url='').url.strip()
auth_token = web.input(auth='').strip()
print(settings.AUTH_TOKEN)
print(auth_token)
if not url:
return web.badrequest()
url = self.add_scheme(url)
if debug:
print(repr(url))
# 判断是否已存在相应的数据
exists = self.db.exist_expand(url)
if exists:
shorten = exists.shorten
else:
shorten = self.db.add_url(url).shorten
shorten = web.ctx.homedomain + '/' + shorten
if get_json:
# 返回 json 格式的数据
web.header('Content-Type', 'application/json')
return json.dumps({'shorten': shorten, 'expand': url})
else:
shortens = web.storage({'url': shorten,
'qr_table': self.qrcode_table(shorten),
})
return render.shorten(shortens)
class Expand(object):
"""短网址跳转到相应的长网址"""
def __init__(self):
self.db = db
def get_expand(self, shorten):
result = self.db.get_expand(shorten)
if result:
return result.expand
def GET(self, shorten):
"""解析短网址,并作 301 跳转"""
if not shorten:
return web.seeother('/')
expand = self.get_expand(shorten)
if debug:
print(repr(expand))
if expand:
return web.redirect(expand) # 301 跳转 | """解析短网址,返回 json 数据"""
shorten = web.input(shorten='').shorten.encode('utf8').strip()
web.header('Content-Type', 'application/json')
# 判断是否为有效短网址字符串
if shorten and re.match('[a-zA-Z0-9]{5,}$', str(shorten)):
expand = self.get_expand(shorten)
if debug:
print(repr(expand))
if expand:
shorten = web.ctx.homedomain + '/' + shorten
return json.dumps({'shorten': shorten, 'expand': expand})
else:
return json.dumps({'shorten': '', 'expand': ''})
else:
return json.dumps({'shorten': '', 'expand': ''})
if __name__ == '__main__':
# 下面这条语句用于在服务器端通过 nginx + fastcgi 部署 web.py 应用
# web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr)
app.run() | else:
return web.notfound()
def POST(self): |
reshape.rs | use crate::infer::*;
use crate::internal::*;
#[derive(Debug, Clone, new, Default, Hash)]
pub struct Reshape {}
tract_linalg::impl_dyn_hash!(Reshape);
impl Expansion for Reshape {
fn name(&self) -> Cow<str> {
"Reshape".into()
}
op_hir!();
fn rules<'r, 'p: 'r, 's: 'r>(
&'s self,
s: &mut Solver<'r>,
inputs: &'p [TensorProxy],
outputs: &'p [TensorProxy],
) -> InferenceResult {
s.equals(&outputs[0].datum_type, &inputs[0].datum_type)?;
s.given_2(&inputs[0].shape, &inputs[1].value, move |s, ishape, shape| {
let shape = shape.cast_to::<TDim>()?;
let shape = shape.as_slice::<TDim>()?;
let oshape = compute_shape(&ishape, &shape)?;
s.equals(&outputs[0].shape, ShapeFactoid::from(oshape))
})
}
fn wire(
&self,
prefix: &str,
model: &mut TypedModel,
inputs: &[OutletId],
) -> TractResult<TVec<OutletId>> {
if let Some(ref shape) = model.outlet_fact(inputs[1])?.konst {
let input_shape: TVec<TDim> = model.outlet_fact(inputs[0])?.shape.to_tvec();
let shape = shape.cast_to::<TDim>()?;
let shape = shape.as_slice::<TDim>()?;
let mut wire = tvec!(inputs[0]);
for (ix, op) in to_axis_ops(&input_shape, shape)?.into_iter().enumerate() {
wire = model.wire_node(format!("{}.{}", prefix, ix), op, &wire)?;
}
return Ok(wire);
}
bail!("shape input is variable")
}
}
fn compute_shape(input: &[TDim], shape_spec: &[TDim]) -> TractResult<TVec<TDim>> {
let mut shape: TVec<TDim> = shape_spec.into();
// deal with zeros, stop if we see a -1
fn deal_with_zero<'a>(
mut input_dims: std::iter::Peekable<impl Iterator<Item = &'a TDim>>,
shape: &mut [TDim],
) -> TractResult<()> |
deal_with_zero(input.iter().peekable(), &mut shape)?;
shape.reverse();
deal_with_zero(input.iter().rev().peekable(), &mut shape)?;
shape.reverse();
if let Some(pos) = shape.iter().position(|d| *d == (-1).into()) {
let input_vol = input.iter().try_fold(1.to_dim(), |a, b| a.maybe_mul(b))?;
let shape_vol = shape
.iter()
.filter(|d| **d != (-1).into())
.try_fold(1.to_dim(), |a, b| a.maybe_mul(b))?;
let div = input_vol.maybe_div(&shape_vol)?;
if div.1 != 1 {
bail!("invalid")
}
shape[pos] = div.0;
}
Ok(shape)
}
pub fn to_axis_ops(input_orig: &[TDim], output_spec: &[TDim]) -> TractResult<TVec<AxisOp>> {
let final_output = compute_shape(input_orig, output_spec)?;
let mut stack: TVec<AxisOp> = tvec!();
'top: loop {
let current_input = stack.iter().fold(TVec::from(input_orig), |shape, op| {
let mut shape = shape.into();
op.change_shape_array(&mut shape);
shape
});
if ¤t_input == &final_output {
return Ok(stack);
}
if let Some(common) =
current_input.iter().zip(final_output.iter()).position(|(a, b)| a != b)
{
if current_input[common].is_one() {
stack.push(AxisOp::Rm(common));
} else if final_output[common].is_one() {
stack.push(AxisOp::Add(common));
} else {
// actual regrouping. search for a match. this is quadratic, but
// rank is expected to be somewhat reasonable
for i in common..current_input.len() {
let i_group = ¤t_input[common..i + 1];
let i_volume: TDim =
if let Ok(v) = i_group.iter().maybe_product() { v } else { break };
for o in common..final_output.len() {
let o_group = &final_output[common..o + 1];
let o_volume: TDim =
if let Ok(v) = o_group.iter().maybe_product() { v } else { break };
if i_volume == o_volume {
stack.push(AxisOp::Reshape(common, i_group.into(), o_group.into()));
continue 'top;
}
}
}
todo!()
}
} else {
if final_output.len() > current_input.len() {
stack.push(AxisOp::Add(current_input.len()));
} else {
stack.push(AxisOp::Rm(current_input.len() - 1));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use AxisOp::*;
macro_rules! s {
($($a:expr),*) => {&[ $($a.into()),* ]}
}
macro_rules! r {
($at: expr ; $($from:expr),* => $($to:expr),*) => {
AxisOp::Reshape($at, tvec!($($from.into()),*), tvec!($($to.into()),*))
}
}
#[test]
fn compute_invalid() {
assert!(compute_shape(s![3, 4, 5], s!(100)).is_err());
}
#[test]
fn compute_with_leading_zero() {
assert_eq!(&*compute_shape(s![3, 4, 5], s!(0, 0, 5)).unwrap(), s![3, 4, 5])
}
#[test]
fn compute_with_leading_zero_with_flatten() {
assert_eq!(&*compute_shape(s![2, 3, 5, 7], s!(2, 0, 35)).unwrap(), s![2, 3, 35])
}
#[test]
fn compute_with_trailing_zero() {
assert_eq!(&*compute_shape(s![3, 4, 5], s!(3, -1, 0)).unwrap(), s![3, 4, 5])
}
#[test]
fn compute_bug_1() {
assert_eq!(
&*compute_shape(s![TDim::s(), 1, 2, 128], s!(0, 0, -1)).unwrap(),
s![TDim::s(), 1, 256]
)
}
#[test]
fn axis_op_rm_begin() {
assert_eq!(&*to_axis_ops(s![1, 2, 3], s!(2, 3)).unwrap(), &[Rm(0)])
}
#[test]
fn axis_op_rm_end() {
assert_eq!(&*to_axis_ops(s![2, 3, 1], s!(2, 3)).unwrap(), &[Rm(2)])
}
#[test]
fn axis_op_insert_begin() {
assert_eq!(&*to_axis_ops(s![2, 3], s!(1, 2, 3)).unwrap(), &[Add(0)])
}
#[test]
fn axis_op_insert_end() {
assert_eq!(&*to_axis_ops(s![2, 3], s!(2, 3, 1)).unwrap(), &[Add(2)])
}
#[test]
fn axis_op_merge() {
assert_eq!(&*to_axis_ops(s![2, 3, 5, 7], s!(2, 0, 35)).unwrap(), &[r!(2 ; 5,7 => 35 )])
}
#[test]
fn axis_op_complex() {
assert_eq!(
&*to_axis_ops(s![1, 2, 3, 5, 7], s!(2, 1, 3, 35, 1)).unwrap(),
&[Rm(0), Add(1), r!(3 ; 5,7 => 35 ), Add(4)]
)
}
}
| {
let mut remaining_dim_input = 1.to_dim();
for slot in shape.iter_mut() {
if *slot == (-1).into() {
break;
}
if *slot == 0.into() {
if remaining_dim_input != TDim::one() {
bail!("Invalid");
}
*slot = input_dims.peek().ok_or("Invalid")?.clone().clone();
}
loop {
let quotient = remaining_dim_input.maybe_div(slot);
if quotient.is_err() || quotient.as_ref().unwrap().1 != 1 {
remaining_dim_input =
remaining_dim_input.maybe_mul(input_dims.next().ok_or("Invalid")?)?;
} else {
break;
}
}
remaining_dim_input = remaining_dim_input.maybe_div(&slot)?.0;
}
Ok(())
} |
dadata.go | package dadata
import (
"net/url"
"github.com/ekomobile/dadata/v2/api/clean"
"github.com/ekomobile/dadata/v2/api/profile"
"github.com/ekomobile/dadata/v2/api/stat"
"github.com/ekomobile/dadata/v2/api/suggest"
"github.com/ekomobile/dadata/v2/client"
)
const (
// EndpointURL is a base API endpoint.
EndpointURL = "https://dadata.ru/api/v2/"
// EndpointURLSuggest is a suggestion API endpoint.
EndpointURLSuggest = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/"
)
var (
endpointURL *url.URL
endpointURLSuggest *url.URL
) |
endpointURL, err = url.Parse(EndpointURL)
if err != nil {
panic(err)
}
endpointURLSuggest, err = url.Parse(EndpointURLSuggest)
if err != nil {
panic(err)
}
}
// NewCleanApi provides "clean" API.
func NewCleanApi(opts ...client.Option) *clean.Api {
return &clean.Api{
Client: client.NewClient(endpointURL, opts...),
}
}
// NewSuggestApi provides suggestion API.
func NewSuggestApi(opts ...client.Option) *suggest.Api {
return &suggest.Api{
Client: client.NewClient(endpointURLSuggest, opts...),
}
}
// NewProfileApi provides profile related API.
func NewProfileApi(opts ...client.Option) *profile.Api {
return &profile.Api{
Client: client.NewClient(endpointURL, opts...),
}
}
// NewStatApi provides statistic API.
func NewStatApi(opts ...client.Option) *stat.Api {
return &stat.Api{
Client: client.NewClient(endpointURL, opts...),
}
} |
func init() {
var err error |
app.module.ts | import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeaderComponent } from './components/header/header.component';
import { FooterComponent } from './components/footer/footer.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { HomeComponent } from './components/home/home.component';
import { ContentThreeColumnsComponent } from './components/content-three-columns/content-three-columns.component';
import { ContentTableComponent } from './components/content-table/content-table.component';
import { FormContatoComponent } from './components/form-contato/form-contato.component';
import { HttpClientModule } from '@angular/common/http'
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [ | HomeComponent,
ContentThreeColumnsComponent,
ContentTableComponent,
FormContatoComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
NgbModule,
HttpClientModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { } | AppComponent,
HeaderComponent,
FooterComponent, |
representationUtil.js | "use strict";
const _ = require('underscore');
const commonMappers = require('../commonMappers');
const { globalSchemaObject } = require('../commonSchemaDefinitionsUtil');
const format = require('../replikering/bindings/format');
/*
* Computes the list of fieldMap that should be included in the CSV representation for the given type
*/
exports.flatCandidateFields = function (fields) {
return fields.filter(function (field) {
return !field.multi && field.selectable;
});
};
exports.fieldsWithNames = function (fields, names) {
return _.filter(fields, function (field) {
return _.contains(names, field.name);
});
};
exports.fieldsWithoutNames = function (fields, names) {
return _.reject(fields, function (field) {
return _.contains(names, field.name);
});
};
exports.defaultFlatMapper = function (flatFields) {
return function (row) {
const result = _.reduce(flatFields, function (memo, field) {
var modelValue = row[field.name];
var formattedValue;
if (field.formatter) {
formattedValue = field.formatter(modelValue);
}
else {
formattedValue = modelValue;
}
memo[field.name] = formattedValue;
return memo;
}, {});
return result;
};
};
exports.defaultFlatRepresentation = function (fields) {
var flatFields = exports.flatCandidateFields(fields);
return {
fields: flatFields,
outputFields: _.pluck(flatFields, 'name'),
mapper: function (baseUrl, params) {
return exports.defaultFlatMapper(flatFields);
}
};
};
exports.miniRepresentation = (miniFieldNames, allFields, miniSchema, hrefFormatter, betegnelseFormatter) =>{
const miniFieldNamesSet = new Set(miniFieldNames);
const allFieldNamesSet = new Set(allFields.map(field => field.name));
if(allFieldNamesSet.has('visueltcenter_x')) {
miniFieldNamesSet.add('visueltcenter_x');
miniFieldNamesSet.add('visueltcenter_y');
if(miniSchema) {
miniSchema.properties.visueltcenter_x = {
type: ['number', 'null'],
description: 'x-koordinat for det visuelle center. Kan f.eks. anvendes til at placere en label på et kort. Koordinatsystem styres med srid parameteren.'
};
miniSchema.properties.visueltcenter_y = {
type: ['number', 'null'],
description: 'y-koordinat for det visuelle center.'
};
miniSchema.docOrder.push('visueltcenter_x');
miniSchema.docOrder.push('visueltcenter_y');
}
}
const miniFields = allFields.filter(field => miniFieldNamesSet.has(field.name));
const outputFields = [...miniFields.map(field => field.name), 'href', 'betegnelse'];
return {
fields: miniFields,
outputFields,
schema: miniSchema,
mapper: function (baseUrl, params) {
const flatMapper = exports.defaultFlatMapper(miniFields.filter(field => !field.multi));
return row => {
const result = flatMapper(row);
result.href = hrefFormatter(baseUrl, row);
result.betegnelse = betegnelseFormatter(row);
return result;
}
}
};
} ;
exports.autocompleteRepresentation = (miniRepresentation, dataPropertyName) => {
const miniSchema = {
type: 'object',
properties: JSON.parse(JSON.stringify(miniRepresentation.schema.properties))
};
const schema = {
properties: {
tekst: miniSchema.properties.betegnelse
},
docOrder: ['tekst', dataPropertyName]
};
delete miniSchema.properties.tekst;
schema.properties[dataPropertyName] = miniSchema;
schema.properties[dataPropertyName].docOrder =
_.without(schema.properties[dataPropertyName].docOrder, 'betegnelse');
return {
fields: miniRepresentation.fields,
schema: globalSchemaObject(schema),
mapper: (baseUrl, params) => {
const miniMapper = miniRepresentation.mapper(baseUrl, params);
return row => {
const miniResult = miniMapper(row);
const result = {
tekst: miniResult.betegnelse
};
delete miniResult.betegnelse;
result[dataPropertyName] = miniResult;
return result;
};
}
}
};
function r | coordinates) {
if(coordinates.length === 0) {
return coordinates;
}
if(Array.isArray(coordinates[0])) {
return coordinates.map(removeZCoordinate).filter((coords, index, arr) => {
if(index === arr.length -1) {
return true;
}
const nextCoords = arr[index+1];
return coords[0] !== nextCoords[0] || coords[1] !== nextCoords[1];
});
}
else if(coordinates.length === 3) {
return coordinates.slice(0, 2);
}
return coordinates;
}
exports.removeZCoordinate = removeZCoordinate;
const extractGeometry = (attrBinding, row) => {
const dst = {};
format(attrBinding, row, dst);
return dst[attrBinding.attrName];
}
exports.geojsonRepresentationUsingBinding = (propertiesRepresentation, geometryAttrBinding) => {
return {
fields: [],
mapper: function (baseUrl, params, singleResult) {
const propertiesMapper = propertiesRepresentation.mapper(baseUrl, params, singleResult);
return function (row) {
var result = {};
result.type = 'Feature';
result.geometry = extractGeometry(geometryAttrBinding, row);
if(params.format === 'geojson' && result.geometry) {
result.geometry.coordinates = removeZCoordinate(result.geometry.coordinates);
}
if (singleResult) {
result.crs = {
type: 'name',
properties: {
name: 'EPSG:' + (params.srid || 4326)
}
};
}
result.properties = propertiesMapper(row);
if(result.properties.bbox_xmin) {
result.bbox = commonMappers.mapBbox(result.properties);
delete result.properties.bbox_xmin;
delete result.properties.bbox_ymin;
delete result.properties.bbox_xmax;
delete result.properties.bbox_ymax;
}
return result;
};
}
};
};
exports.geojsonRepresentation = function (geomJsonField, propertiesRepresentation) {
return {
fields: propertiesRepresentation.fields.concat([geomJsonField]),
mapper: function (baseUrl, params, singleResult) {
const propertiesMapper = propertiesRepresentation.mapper(baseUrl, params, singleResult);
return function (row) {
var result = {};
result.type = 'Feature';
if (row[geomJsonField.name]) {
result.geometry = JSON.parse(row[geomJsonField.name]);
if(params.format === 'geojson') {
result.geometry.coordinates = removeZCoordinate(result.geometry.coordinates);
}
}
else {
result.geometry = null;
}
if (singleResult) {
result.crs = {
type: 'name',
properties: {
name: 'EPSG:' + (params.srid || 4326)
}
};
}
result.properties = propertiesMapper(row);
if(result.properties.bbox_xmin) {
result.bbox = commonMappers.mapBbox(result.properties);
delete result.properties.bbox_xmin;
delete result.properties.bbox_ymin;
delete result.properties.bbox_xmax;
delete result.properties.bbox_ymax;
}
return result;
};
}
};
};
const geojsonCombinations = [['geojsonNested', 'json'], ['geojsonMini', 'mini'], ['geojson', 'flat']];
exports.addGeojsonRepresentationsUsingBinding = (representations, geometryBinding) => {
for(let [geojsonKey, repKey] of geojsonCombinations) {
if(representations[repKey]) {
representations[geojsonKey] = exports.geojsonRepresentationUsingBinding(representations[repKey], geometryBinding);
}
}
};
const addGeojsonRepresentations = (representations, geomjsonField) => {
for(let [geojsonKey, repKey] of geojsonCombinations) {
if(representations[repKey]) {
representations[geojsonKey] = exports.geojsonRepresentation(geomjsonField, representations[repKey]);
}
}
};
exports.addGeojsonRepresentations = addGeojsonRepresentations;
const insertAfter = (arr, elm, ins) => {
const index = arr.indexOf(elm) + 1;
arr.splice(index, 0, ins);
};
exports.adresseFlatRepresentation = function (fields, additionalFieldsMapper) {
var fieldsExcludedFromFlat = ['geom_json', 'x', 'y', 'vejpunkt_geom_json', 'adgangspunkt_geom_json'];
var defaultFlatFields = exports.fieldsWithoutNames(exports.flatCandidateFields(fields), fieldsExcludedFromFlat);
const requiredFlatFields = defaultFlatFields;
let outputFlatFields = _.pluck(defaultFlatFields, 'name');
// vi skal sikre, at nye felter tilføjes til sidst
const newFields = ['jordstykke_ejerlavkode', 'jordstykke_matrikelnr', 'jordstykke_esrejendomsnr'];
outputFlatFields = _.difference(outputFlatFields, newFields).concat(newFields);
const kvhField = exports.fieldsWithNames(fields, ['kvh', 'kvhx']).map(field => field.name)[0];
insertAfter(outputFlatFields, 'jordstykke_ejerlavnavn', kvhField);
var defaultFlatMapper = exports.defaultFlatMapper(defaultFlatFields);
return {
fields: requiredFlatFields,
outputFields: outputFlatFields,
mapper: function () {
return function (obj) {
let result = defaultFlatMapper(obj);
if (additionalFieldsMapper) {
result = _.extend(result, additionalFieldsMapper(obj));
}
// result.zone = zoneFormatter(obj.zonekode);
return result;
};
}
};
};
| emoveZCoordinate( |
shy.go | package code
import (
"path"
ice "github.com/shylinux/icebergs"
"github.com/shylinux/icebergs/base/mdb"
"github.com/shylinux/icebergs/base/nfs"
kit "github.com/shylinux/toolkits"
)
const SHY = "shy"
func init() | {
Index.Register(&ice.Context{Name: SHY, Help: "脚本",
Commands: map[string]*ice.Command{
ice.CTX_INIT: {Hand: func(m *ice.Message, c *ice.Context, cmd string, arg ...string) {
for _, cmd := range []string{mdb.PLUGIN, mdb.RENDER, mdb.ENGINE, mdb.SEARCH} {
m.Cmd(cmd, mdb.CREATE, SHY, m.Prefix(SHY))
}
LoadPlug(m, SHY)
}},
SHY: {Name: SHY, Help: "脚本", Action: map[string]*ice.Action{
mdb.PLUGIN: {Hand: func(m *ice.Message, arg ...string) {
m.Echo(m.Conf(SHY, kit.Keym(PLUG)))
}},
mdb.RENDER: {Hand: func(m *ice.Message, arg ...string) {
m.Cmdy(nfs.CAT, path.Join(arg[2], arg[1]))
}},
mdb.ENGINE: {Hand: func(m *ice.Message, arg ...string) {
m.Cmdy("web.wiki.word", path.Join(arg[2], arg[1]))
}},
mdb.SEARCH: {Hand: func(m *ice.Message, arg ...string) {
if arg[0] == kit.MDB_FOREACH {
return
}
_go_find(m, kit.Select(kit.MDB_MAIN, arg, 1))
_go_grep(m, kit.Select(kit.MDB_MAIN, arg, 1))
}},
}},
},
Configs: map[string]*ice.Config{
SHY: {Name: SHY, Help: "脚本", Value: kit.Data(
PLUG, kit.Dict(
PREFIX, kit.Dict("#", COMMENT),
PREPARE, kit.Dict(
KEYWORD, kit.Simple(
"title",
"premenu",
"chapter",
"section",
"source",
"refer",
"field",
"spark",
"image",
"label",
"chain",
),
),
KEYWORD, kit.Dict(),
),
)},
},
}, nil)
}
|
|
PageMap.go | package mango
import (
"log"
"sync"
)
// PageMap is map of *Page
type PageMap struct {
sync.RWMutex
m map[string]*Page
}
// NewPageMap - create and init as empty
func NewPageMap() *PageMap |
// MakeEmpty - init or clear map
func (pm *PageMap) MakeEmpty() {
pm.Lock()
pm.m = make(map[string]*Page, 0)
pm.Unlock()
}
// Get from local map by key
func (pm *PageMap) Get(key string) *Page {
pm.RLock()
defer pm.RUnlock()
return pm.m[key]
}
// Add new *Page to local map
// Can't use only Slug, because PageMap can be used for many purposes
func (pm *PageMap) Add(key string, page *Page) {
// key := page.Get("Slug")
pm.Lock()
pm.m[key] = page
pm.Unlock()
}
// Remove by key
func (pm *PageMap) Remove(key string) {
pm.Lock()
delete(pm.m, key)
pm.Unlock()
}
// Len - map item count
func (pm *PageMap) Len() int {
pm.RLock()
defer pm.RUnlock()
return len(pm.m)
}
// Filter - filter by custom func
func (pm *PageMap) Filter(fnCheck func(p *Page) bool) PageList {
pages := make(PageList, 0)
pm.RLock()
for _, p := range pm.m {
if p != nil && fnCheck(p) {
pages = append(pages, p)
}
}
pm.RUnlock()
return pages
}
// Print pages in list
func (pm *PageMap) Print() {
pages := pm.m
log.Printf("--- %d pages ------------------------------------------------", len(pages))
for _, p := range pages {
p.PrintRow()
}
log.Println()
}
| {
pm := &PageMap{}
pm.MakeEmpty()
return pm
} |
stateful_browser.py | from __future__ import print_function
from six.moves import urllib
from .browser import Browser
from .utils import LinkNotFoundError
from .form import Form
import sys
import re
import bs4
class _BrowserState:
def __init__(self, page=None, url=None, form=None, request=None):
self.page = page
self.url = url
self.form = form
self.request = request
class StatefulBrowser(Browser):
"""An extension of :class:`Browser` that stores the browser's state
and provides many convenient functions for interacting with HTML elements.
It is the primary tool in MechanicalSoup for interfacing with websites.
:param session: Attach a pre-existing requests Session instead of
constructing a new one.
:param soup_config: Configuration passed to BeautifulSoup to affect
the way HTML is parsed. Defaults to ``{'features': 'lxml'}``.
If overriden, it is highly recommended to `specify a parser
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#specifying-the-parser-to-use>`__.
Otherwise, BeautifulSoup will issue a warning and pick one for
you, but the parser it chooses may be different on different
machines.
:param requests_adapters: Configuration passed to requests, to affect
the way HTTP requests are performed.
:param raise_on_404: If True, raise :class:`LinkNotFoundError`
when visiting a page triggers a 404 Not Found error.
:param user_agent: Set the user agent header to this value.
All arguments are forwarded to :func:`Browser`.
Examples ::
browser = mechanicalsoup.StatefulBrowser(
soup_config={'features': 'lxml'}, # Use the lxml HTML parser
raise_on_404=True,
user_agent='MyBot/0.1: mysite.example.com/bot_info',
)
browser.open(url)
# ...
browser.close()
Once not used anymore, the browser can be closed
using :func:`~Browser.close`.
"""
def __init__(self, *args, **kwargs):
super(StatefulBrowser, self).__init__(*args, **kwargs)
self.__debug = False
self.__verbose = 0
self.__state = _BrowserState()
def set_debug(self, debug):
|
def get_debug(self):
"""Get the debug mode (off by default)."""
return self.__debug
def set_verbose(self, verbose):
"""Set the verbosity level (an integer).
* 0 means no verbose output.
* 1 shows one dot per visited page (looks like a progress bar)
* >= 2 shows each visited URL.
"""
self.__verbose = verbose
def get_verbose(self):
"""Get the verbosity level. See :func:`set_verbose()`."""
return self.__verbose
def get_url(self):
"""Get the URL of the currently visited page."""
return self.__state.url
def get_current_form(self):
"""Get the currently selected form as a :class:`Form` object.
See :func:`select_form`.
"""
return self.__state.form
def __setitem__(self, name, value):
"""Call item assignment on the currently selected form.
See :func:`Form.__setitem__`.
"""
self.get_current_form()[name] = value
def new_control(self, type, name, value, **kwargs):
"""Call :func:`Form.new_control` on the currently selected form."""
return self.get_current_form().new_control(type, name, value, **kwargs)
def get_current_page(self):
"""Get the current page as a soup object."""
return self.__state.page
def absolute_url(self, url):
"""Return the absolute URL made from the current URL and ``url``.
The current URL is only used to provide any missing components of
``url``, as in the `.urljoin() method of urllib.parse
<https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin>`__.
"""
return urllib.parse.urljoin(self.get_url(), url)
def open(self, url, *args, **kwargs):
"""Open the URL and store the Browser's state in this object.
All arguments are forwarded to :func:`Browser.get`.
:return: Forwarded from :func:`Browser.get`.
"""
if self.__verbose == 1:
sys.stdout.write('.')
sys.stdout.flush()
elif self.__verbose >= 2:
print(url)
resp = self.get(url, *args, **kwargs)
self.__state = _BrowserState(page=resp.soup, url=resp.url,
request=resp.request)
return resp
def open_fake_page(self, page_text, url=None, soup_config=None):
"""Mock version of :func:`open`.
Behave as if opening a page whose text is ``page_text``, but do not
perform any network access. If ``url`` is set, pretend it is the page's
URL. Useful mainly for testing.
"""
soup_config = soup_config or self.soup_config
self.__state = _BrowserState(
page=bs4.BeautifulSoup(page_text, **soup_config),
url=url)
def open_relative(self, url, *args, **kwargs):
"""Like :func:`open`, but ``url`` can be relative to the currently
visited page.
"""
return self.open(self.absolute_url(url), *args, **kwargs)
def refresh(self):
"""Reload the current page with the same request as originally done.
Any change (`select_form`, or any value filled-in in the form) made to
the current page before refresh is discarded.
:raise ValueError: Raised if no refreshable page is loaded, e.g., when
using the shallow ``Browser`` wrapper functions.
:return: Response of the request."""
old_request = self.__state.request
if old_request is None:
raise ValueError('The current page is not refreshable. Either no '
'page is opened or low-level browser methods '
'were used to do so')
resp = self.session.send(old_request)
Browser.add_soup(resp, self.soup_config)
self.__state = _BrowserState(page=resp.soup, url=resp.url,
request=resp.request)
return resp
def select_form(self, selector="form", nr=0):
"""Select a form in the current page.
:param selector: CSS selector or a bs4.element.Tag object to identify
the form to select.
If not specified, ``selector`` defaults to "form", which is
useful if, e.g., there is only one form on the page.
For ``selector`` syntax, see the `.select() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors>`__.
:param nr: A zero-based index specifying which form among those that
match ``selector`` will be selected. Useful when one or more forms
have the same attributes as the form you want to select, and its
position on the page is the only way to uniquely identify it.
Default is the first matching form (``nr=0``).
:return: The selected form as a soup object. It can also be
retrieved later with :func:`get_current_form`.
"""
if isinstance(selector, bs4.element.Tag):
if selector.name != "form":
raise LinkNotFoundError
self.__state.form = Form(selector)
else:
# nr is a 0-based index for consistency with mechanize
found_forms = self.get_current_page().select(selector,
limit=nr + 1)
if len(found_forms) != nr + 1:
if self.__debug:
print('select_form failed for', selector)
self.launch_browser()
raise LinkNotFoundError()
self.__state.form = Form(found_forms[-1])
return self.get_current_form()
def submit_selected(self, btnName=None, update_state=True,
*args, **kwargs):
"""Submit the form that was selected with :func:`select_form`.
:return: Forwarded from :func:`Browser.submit`.
If there are multiple submit input/button elements, passes ``btnName``
to :func:`Form.choose_submit` on the current form to choose between
them. If `update_state` is False, form will be submited but the browser
state will remain unchanged. This is useful for forms that result in
a download of a file. All other arguments are forwarded to
:func:`Browser.submit`.
"""
self.get_current_form().choose_submit(btnName)
referer = self.get_url()
if referer is not None:
if 'headers' in kwargs:
kwargs['headers']['Referer'] = referer
else:
kwargs['headers'] = {'Referer': referer}
resp = self.submit(self.__state.form, url=self.__state.url,
*args, **kwargs)
if update_state:
self.__state = _BrowserState(page=resp.soup, url=resp.url,
request=resp.request)
return resp
def list_links(self, *args, **kwargs):
"""Display the list of links in the current page. Arguments are
forwarded to :func:`links`.
"""
print("Links in the current page:")
for l in self.links(*args, **kwargs):
print(" ", l)
def links(self, url_regex=None, link_text=None, *args, **kwargs):
"""Return links in the page, as a list of bs4.element.Tag objects.
To return links matching specific criteria, specify ``url_regex``
to match the *href*-attribute, or ``link_text`` to match the
*text*-attribute of the Tag. All other arguments are forwarded to
the `.find_all() method in BeautifulSoup
<https://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all>`__.
"""
all_links = self.get_current_page().find_all(
'a', href=True, *args, **kwargs)
if url_regex is not None:
all_links = [a for a in all_links
if re.search(url_regex, a['href'])]
if link_text is not None:
all_links = [a for a in all_links
if a.text == link_text]
return all_links
def find_link(self, *args, **kwargs):
"""Find and return a link, as a bs4.element.Tag object.
The search can be refined by specifying any argument that is accepted
by :func:`links`. If several links match, return the first one found.
If no link is found, raise :class:`LinkNotFoundError`.
"""
links = self.links(*args, **kwargs)
if len(links) == 0:
raise LinkNotFoundError()
else:
return links[0]
def _find_link_internal(self, link, args, kwargs):
"""Wrapper around find_link that deals with convenience special-cases:
* If ``link`` has an *href*-attribute, then return it. If not,
consider it as a ``url_regex`` argument.
* If searching for the link fails and debug is active, launch
a browser.
"""
if hasattr(link, 'attrs') and 'href' in link.attrs:
return link
# Check if "link" parameter should be treated as "url_regex"
# but reject obtaining it from both places.
if link and 'url_regex' in kwargs:
raise ValueError('link parameter cannot be treated as '
'url_regex because url_regex is already '
'present in keyword arguments')
elif link:
kwargs['url_regex'] = link
try:
return self.find_link(*args, **kwargs)
except LinkNotFoundError:
if self.get_debug():
print('find_link failed for', kwargs)
self.list_links()
self.launch_browser()
raise
def follow_link(self, link=None, *args, **kwargs):
"""Follow a link.
If ``link`` is a bs4.element.Tag (i.e. from a previous call to
:func:`links` or :func:`find_link`), then follow the link.
If ``link`` doesn't have a *href*-attribute or is None, treat
``link`` as a url_regex and look it up with :func:`find_link`.
Any additional arguments specified are forwarded to this function.
If the link is not found, raise :class:`LinkNotFoundError`.
Before raising, if debug is activated, list available links in the
page and launch a browser.
:return: Forwarded from :func:`open_relative`.
"""
link = self._find_link_internal(link, args, kwargs)
referer = self.get_url()
headers = {'Referer': referer} if referer else None
return self.open_relative(link['href'], headers=headers)
def download_link(self, link=None, file=None, *args, **kwargs):
"""Downloads the contents of a link to a file. This function behaves
similarly to :func:`follow_link`, but the browser state will
not change when calling this function.
:param file: Filesystem path where the page contents will be
downloaded. If the file already exists, it will be overwritten.
Other arguments are the same as :func:`follow_link` (``link``
can either be a bs4.element.Tag or a URL regex, other
arguments are forwarded to :func:`find_link`).
:return: `requests.Response
<http://docs.python-requests.org/en/master/api/#requests.Response>`__
object.
"""
link = self._find_link_internal(link, args, kwargs)
url = self.absolute_url(link['href'])
referer = self.get_url()
headers = {'Referer': referer} if referer else None
response = self.session.get(url, headers=headers)
if self.raise_on_404 and response.status_code == 404:
raise LinkNotFoundError()
# Save the response content to file
if file is not None:
with open(file, 'wb') as f:
f.write(response.content)
return response
def launch_browser(self, soup=None):
"""Launch a browser to display a page, for debugging purposes.
:param: soup: Page contents to display, supplied as a bs4 soup object.
Defaults to the current page of the ``StatefulBrowser`` instance.
"""
if soup is None:
soup = self.get_current_page()
super(StatefulBrowser, self).launch_browser(soup)
| """Set the debug mode (off by default).
Set to True to enable debug mode. When active, some actions
will launch a browser on the current page on failure to let
you inspect the page content.
"""
self.__debug = debug |
tim12.rs | #![allow(non_snake_case, non_upper_case_globals)]
#![allow(non_camel_case_types)]
//! General purpose timers
#[cfg(not(feature = "nosync"))]
pub use crate::stm32f4::peripherals::tim9_v3::Instance;
pub use crate::stm32f4::peripherals::tim9_v3::{RegisterBlock, ResetValues};
pub use crate::stm32f4::peripherals::tim9_v3::{
ARR, CCER, CCMR1, CCR1, CCR2, CNT, CR1, DIER, EGR, PSC, SMCR, SR,
};
/// Access functions for the TIM12 peripheral instance
pub mod TIM12 {
use super::ResetValues;
#[cfg(not(feature = "nosync"))]
use super::Instance;
#[cfg(not(feature = "nosync"))]
const INSTANCE: Instance = Instance {
addr: 0x40001800,
_marker: ::core::marker::PhantomData,
};
/// Reset values for each field in TIM12
pub const reset: ResetValues = ResetValues {
CR1: 0x00000000,
SMCR: 0x00000000,
DIER: 0x00000000,
SR: 0x00000000,
EGR: 0x00000000,
CCMR1: 0x00000000,
CCER: 0x00000000,
CNT: 0x00000000,
PSC: 0x00000000,
ARR: 0x00000000,
CCR1: 0x00000000, | #[cfg(not(feature = "nosync"))]
#[allow(renamed_and_removed_lints)]
#[allow(private_no_mangle_statics)]
#[no_mangle]
static mut TIM12_TAKEN: bool = false;
/// Safe access to TIM12
///
/// This function returns `Some(Instance)` if this instance is not
/// currently taken, and `None` if it is. This ensures that if you
/// do get `Some(Instance)`, you are ensured unique access to
/// the peripheral and there cannot be data races (unless other
/// code uses `unsafe`, of course). You can then pass the
/// `Instance` around to other functions as required. When you're
/// done with it, you can call `release(instance)` to return it.
///
/// `Instance` itself dereferences to a `RegisterBlock`, which
/// provides access to the peripheral's registers.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn take() -> Option<Instance> {
external_cortex_m::interrupt::free(|_| unsafe {
if TIM12_TAKEN {
None
} else {
TIM12_TAKEN = true;
Some(INSTANCE)
}
})
}
/// Release exclusive access to TIM12
///
/// This function allows you to return an `Instance` so that it
/// is available to `take()` again. This function will panic if
/// you return a different `Instance` or if this instance is not
/// already taken.
#[cfg(not(feature = "nosync"))]
#[inline]
pub fn release(inst: Instance) {
external_cortex_m::interrupt::free(|_| unsafe {
if TIM12_TAKEN && inst.addr == INSTANCE.addr {
TIM12_TAKEN = false;
} else {
panic!("Released a peripheral which was not taken");
}
});
}
/// Unsafely steal TIM12
///
/// This function is similar to take() but forcibly takes the
/// Instance, marking it as taken irregardless of its previous
/// state.
#[cfg(not(feature = "nosync"))]
#[inline]
pub unsafe fn steal() -> Instance {
TIM12_TAKEN = true;
INSTANCE
}
}
/// Raw pointer to TIM12
///
/// Dereferencing this is unsafe because you are not ensured unique
/// access to the peripheral, so you may encounter data races with
/// other users of this peripheral. It is up to you to ensure you
/// will not cause data races.
///
/// This constant is provided for ease of use in unsafe code: you can
/// simply call for example `write_reg!(gpio, GPIOA, ODR, 1);`.
pub const TIM12: *const RegisterBlock = 0x40001800 as *const _; | CCR2: 0x00000000,
};
|
sdb.pb.gw.go | // Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: api/protobuf-spec/sdb.proto
/*
Package pb is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package pb
import (
"context"
"io"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"github.com/grpc-ecosystem/grpc-gateway/v2/utilities"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
// Suppress "imported and not used" errors
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var _ = metadata.Join
func request_SDB_Set_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SetRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Set(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_Set_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SetRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.Set(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_Get_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq GetRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Get(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_Get_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq GetRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.Get(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_Del_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Del(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_Del_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq DelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.Del(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_Incr_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq IncrRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Incr(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_Incr_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq IncrRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF |
msg, err := server.Incr(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_LPush_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LPushRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.LPush(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_LPush_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LPushRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.LPush(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_LPop_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LPopRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.LPop(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_LPop_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LPopRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.LPop(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_LRange_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LRangeRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.LRange(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_LRange_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LRangeRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.LRange(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_LExist_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LExistRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.LExist(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_LExist_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LExistRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.LExist(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_LDel_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LDelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.LDel(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_LDel_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LDelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.LDel(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_LCount_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LCountRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.LCount(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_LCount_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq LCountRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.LCount(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_SPush_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SPushRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.SPush(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_SPush_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SPushRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.SPush(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_SPop_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SPopRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.SPop(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_SPop_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SPopRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.SPop(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_SExist_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SExistRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.SExist(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_SExist_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SExistRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.SExist(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_SDel_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SDelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.SDel(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_SDel_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SDelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.SDel(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_SCount_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SCountRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.SCount(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_SCount_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq SCountRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.SCount(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_ZPush_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZPushRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ZPush(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_ZPush_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZPushRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ZPush(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_ZPop_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZPopRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ZPop(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_ZPop_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZPopRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ZPop(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_ZRange_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZRangeRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ZRange(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_ZRange_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZRangeRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ZRange(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_ZExist_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZExistRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ZExist(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_ZExist_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZExistRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ZExist(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_ZDel_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZDelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ZDel(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_ZDel_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZDelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ZDel(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_ZCount_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZCountRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.ZCount(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_ZCount_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ZCountRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.ZCount(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_BFCreate_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq BFCreateRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.BFCreate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_BFCreate_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq BFCreateRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.BFCreate(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_BFDel_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq BFDelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.BFDel(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_BFDel_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq BFDelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.BFDel(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_BFAdd_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq BFAddRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.BFAdd(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_BFAdd_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq BFAddRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.BFAdd(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_BFExist_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq BFExistRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.BFExist(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_BFExist_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq BFExistRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.BFExist(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_HLLCreate_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq HLLCreateRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.HLLCreate(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_HLLCreate_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq HLLCreateRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.HLLCreate(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_HLLDel_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq HLLDelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.HLLDel(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_HLLDel_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq HLLDelRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.HLLDel(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_HLLAdd_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq HLLAddRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.HLLAdd(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_HLLAdd_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq HLLAddRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.HLLAdd(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_HLLCount_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq HLLCountRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.HLLCount(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_HLLCount_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq HLLCountRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.HLLCount(ctx, &protoReq)
return msg, metadata, err
}
func request_SDB_Subscribe_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (SDB_SubscribeClient, runtime.ServerMetadata, error) {
var protoReq SubscribeRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
stream, err := client.Subscribe(ctx, &protoReq)
if err != nil {
return nil, metadata, err
}
header, err := stream.Header()
if err != nil {
return nil, metadata, err
}
metadata.HeaderMD = header
return stream, metadata, nil
}
func request_SDB_Publish_0(ctx context.Context, marshaler runtime.Marshaler, client SDBClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq PublishRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Publish(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_SDB_Publish_0(ctx context.Context, marshaler runtime.Marshaler, server SDBServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq PublishRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.Publish(ctx, &protoReq)
return msg, metadata, err
}
// RegisterSDBHandlerServer registers the http handlers for service SDB to "mux".
// UnaryRPC :call SDBServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterSDBHandlerFromEndpoint instead.
func RegisterSDBHandlerServer(ctx context.Context, mux *runtime.ServeMux, server SDBServer) error {
mux.Handle("POST", pattern_SDB_Set_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/Set", runtime.WithHTTPPathPattern("/v1/set"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_Set_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Set_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_Get_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/Get", runtime.WithHTTPPathPattern("/v1/get"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_Get_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Get_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_Del_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/Del", runtime.WithHTTPPathPattern("/v1/del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_Del_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Del_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_Incr_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/Incr", runtime.WithHTTPPathPattern("/v1/incr"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_Incr_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Incr_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LPush_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/LPush", runtime.WithHTTPPathPattern("/v1/l-push"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_LPush_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LPush_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LPop_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/LPop", runtime.WithHTTPPathPattern("/v1/l-pop"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_LPop_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LPop_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LRange_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/LRange", runtime.WithHTTPPathPattern("/v1/l-range"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_LRange_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LRange_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LExist_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/LExist", runtime.WithHTTPPathPattern("/v1/l-exist"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_LExist_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LExist_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LDel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/LDel", runtime.WithHTTPPathPattern("/v1/l-del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_LDel_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LDel_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LCount_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/LCount", runtime.WithHTTPPathPattern("/v1/l-count"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_LCount_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LCount_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_SPush_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/SPush", runtime.WithHTTPPathPattern("/v1/s-push"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_SPush_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_SPush_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_SPop_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/SPop", runtime.WithHTTPPathPattern("/v1/s-pop"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_SPop_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_SPop_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_SExist_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/SExist", runtime.WithHTTPPathPattern("/v1/s-exist"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_SExist_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_SExist_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_SDel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/SDel", runtime.WithHTTPPathPattern("/v1/s-del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_SDel_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_SDel_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_SCount_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/SCount", runtime.WithHTTPPathPattern("/v1/s-count"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_SCount_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_SCount_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZPush_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/ZPush", runtime.WithHTTPPathPattern("/v1/z-push"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_ZPush_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZPush_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZPop_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/ZPop", runtime.WithHTTPPathPattern("/v1/z-pop"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_ZPop_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZPop_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZRange_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/ZRange", runtime.WithHTTPPathPattern("/v1/z-range"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_ZRange_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZRange_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZExist_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/ZExist", runtime.WithHTTPPathPattern("/v1/z-exist"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_ZExist_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZExist_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZDel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/ZDel", runtime.WithHTTPPathPattern("/v1/z-del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_ZDel_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZDel_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZCount_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/ZCount", runtime.WithHTTPPathPattern("/v1/z-count"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_ZCount_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZCount_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_BFCreate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/BFCreate", runtime.WithHTTPPathPattern("/v1/bf-create"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_BFCreate_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_BFCreate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_BFDel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/BFDel", runtime.WithHTTPPathPattern("/v1/bf-del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_BFDel_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_BFDel_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_BFAdd_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/BFAdd", runtime.WithHTTPPathPattern("/v1/bf-add"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_BFAdd_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_BFAdd_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_BFExist_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/BFExist", runtime.WithHTTPPathPattern("/v1/bf-exist"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_BFExist_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_BFExist_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_HLLCreate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/HLLCreate", runtime.WithHTTPPathPattern("/v1/hll-create"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_HLLCreate_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_HLLCreate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_HLLDel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/HLLDel", runtime.WithHTTPPathPattern("/v1/hll-del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_HLLDel_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_HLLDel_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_HLLAdd_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/HLLAdd", runtime.WithHTTPPathPattern("/v1/hll-add"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_HLLAdd_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_HLLAdd_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_HLLCount_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/HLLCount", runtime.WithHTTPPathPattern("/v1/hll-count"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_HLLCount_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_HLLCount_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_Subscribe_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport")
_, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
})
mux.Handle("POST", pattern_SDB_Publish_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
var stream runtime.ServerTransportStream
ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/proto.SDB/Publish", runtime.WithHTTPPathPattern("/proto.SDB/Publish"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_SDB_Publish_0(rctx, inboundMarshaler, server, req, pathParams)
md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Publish_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
// RegisterSDBHandlerFromEndpoint is same as RegisterSDBHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterSDBHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterSDBHandler(ctx, mux, conn)
}
// RegisterSDBHandler registers the http handlers for service SDB to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterSDBHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterSDBHandlerClient(ctx, mux, NewSDBClient(conn))
}
// RegisterSDBHandlerClient registers the http handlers for service SDB
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "SDBClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "SDBClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "SDBClient" to call the correct interceptors.
func RegisterSDBHandlerClient(ctx context.Context, mux *runtime.ServeMux, client SDBClient) error {
mux.Handle("POST", pattern_SDB_Set_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/Set", runtime.WithHTTPPathPattern("/v1/set"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_Set_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Set_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_Get_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/Get", runtime.WithHTTPPathPattern("/v1/get"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_Get_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Get_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_Del_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/Del", runtime.WithHTTPPathPattern("/v1/del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_Del_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Del_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_Incr_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/Incr", runtime.WithHTTPPathPattern("/v1/incr"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_Incr_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Incr_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LPush_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/LPush", runtime.WithHTTPPathPattern("/v1/l-push"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_LPush_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LPush_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LPop_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/LPop", runtime.WithHTTPPathPattern("/v1/l-pop"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_LPop_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LPop_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LRange_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/LRange", runtime.WithHTTPPathPattern("/v1/l-range"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_LRange_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LRange_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LExist_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/LExist", runtime.WithHTTPPathPattern("/v1/l-exist"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_LExist_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LExist_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LDel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/LDel", runtime.WithHTTPPathPattern("/v1/l-del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_LDel_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LDel_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_LCount_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/LCount", runtime.WithHTTPPathPattern("/v1/l-count"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_LCount_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_LCount_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_SPush_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/SPush", runtime.WithHTTPPathPattern("/v1/s-push"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_SPush_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_SPush_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_SPop_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/SPop", runtime.WithHTTPPathPattern("/v1/s-pop"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_SPop_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_SPop_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_SExist_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/SExist", runtime.WithHTTPPathPattern("/v1/s-exist"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_SExist_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_SExist_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_SDel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/SDel", runtime.WithHTTPPathPattern("/v1/s-del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_SDel_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_SDel_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_SCount_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/SCount", runtime.WithHTTPPathPattern("/v1/s-count"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_SCount_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_SCount_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZPush_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/ZPush", runtime.WithHTTPPathPattern("/v1/z-push"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_ZPush_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZPush_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZPop_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/ZPop", runtime.WithHTTPPathPattern("/v1/z-pop"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_ZPop_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZPop_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZRange_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/ZRange", runtime.WithHTTPPathPattern("/v1/z-range"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_ZRange_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZRange_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZExist_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/ZExist", runtime.WithHTTPPathPattern("/v1/z-exist"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_ZExist_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZExist_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZDel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/ZDel", runtime.WithHTTPPathPattern("/v1/z-del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_ZDel_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZDel_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_ZCount_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/ZCount", runtime.WithHTTPPathPattern("/v1/z-count"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_ZCount_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_ZCount_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_BFCreate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/BFCreate", runtime.WithHTTPPathPattern("/v1/bf-create"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_BFCreate_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_BFCreate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_BFDel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/BFDel", runtime.WithHTTPPathPattern("/v1/bf-del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_BFDel_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_BFDel_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_BFAdd_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/BFAdd", runtime.WithHTTPPathPattern("/v1/bf-add"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_BFAdd_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_BFAdd_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_BFExist_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/BFExist", runtime.WithHTTPPathPattern("/v1/bf-exist"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_BFExist_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_BFExist_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_HLLCreate_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/HLLCreate", runtime.WithHTTPPathPattern("/v1/hll-create"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_HLLCreate_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_HLLCreate_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_HLLDel_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/HLLDel", runtime.WithHTTPPathPattern("/v1/hll-del"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_HLLDel_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_HLLDel_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_HLLAdd_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/HLLAdd", runtime.WithHTTPPathPattern("/v1/hll-add"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_HLLAdd_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_HLLAdd_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_HLLCount_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/HLLCount", runtime.WithHTTPPathPattern("/v1/hll-count"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_HLLCount_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_HLLCount_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_Subscribe_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/Subscribe", runtime.WithHTTPPathPattern("/proto.SDB/Subscribe"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_Subscribe_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Subscribe_0(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_SDB_Publish_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req, "/proto.SDB/Publish", runtime.WithHTTPPathPattern("/proto.SDB/Publish"))
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_SDB_Publish_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_SDB_Publish_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_SDB_Set_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "set"}, ""))
pattern_SDB_Get_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "get"}, ""))
pattern_SDB_Del_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "del"}, ""))
pattern_SDB_Incr_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "incr"}, ""))
pattern_SDB_LPush_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "l-push"}, ""))
pattern_SDB_LPop_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "l-pop"}, ""))
pattern_SDB_LRange_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "l-range"}, ""))
pattern_SDB_LExist_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "l-exist"}, ""))
pattern_SDB_LDel_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "l-del"}, ""))
pattern_SDB_LCount_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "l-count"}, ""))
pattern_SDB_SPush_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "s-push"}, ""))
pattern_SDB_SPop_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "s-pop"}, ""))
pattern_SDB_SExist_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "s-exist"}, ""))
pattern_SDB_SDel_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "s-del"}, ""))
pattern_SDB_SCount_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "s-count"}, ""))
pattern_SDB_ZPush_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "z-push"}, ""))
pattern_SDB_ZPop_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "z-pop"}, ""))
pattern_SDB_ZRange_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "z-range"}, ""))
pattern_SDB_ZExist_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "z-exist"}, ""))
pattern_SDB_ZDel_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "z-del"}, ""))
pattern_SDB_ZCount_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "z-count"}, ""))
pattern_SDB_BFCreate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "bf-create"}, ""))
pattern_SDB_BFDel_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "bf-del"}, ""))
pattern_SDB_BFAdd_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "bf-add"}, ""))
pattern_SDB_BFExist_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "bf-exist"}, ""))
pattern_SDB_HLLCreate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "hll-create"}, ""))
pattern_SDB_HLLDel_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "hll-del"}, ""))
pattern_SDB_HLLAdd_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "hll-add"}, ""))
pattern_SDB_HLLCount_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"v1", "hll-count"}, ""))
pattern_SDB_Subscribe_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"proto.SDB", "Subscribe"}, ""))
pattern_SDB_Publish_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1}, []string{"proto.SDB", "Publish"}, ""))
)
var (
forward_SDB_Set_0 = runtime.ForwardResponseMessage
forward_SDB_Get_0 = runtime.ForwardResponseMessage
forward_SDB_Del_0 = runtime.ForwardResponseMessage
forward_SDB_Incr_0 = runtime.ForwardResponseMessage
forward_SDB_LPush_0 = runtime.ForwardResponseMessage
forward_SDB_LPop_0 = runtime.ForwardResponseMessage
forward_SDB_LRange_0 = runtime.ForwardResponseMessage
forward_SDB_LExist_0 = runtime.ForwardResponseMessage
forward_SDB_LDel_0 = runtime.ForwardResponseMessage
forward_SDB_LCount_0 = runtime.ForwardResponseMessage
forward_SDB_SPush_0 = runtime.ForwardResponseMessage
forward_SDB_SPop_0 = runtime.ForwardResponseMessage
forward_SDB_SExist_0 = runtime.ForwardResponseMessage
forward_SDB_SDel_0 = runtime.ForwardResponseMessage
forward_SDB_SCount_0 = runtime.ForwardResponseMessage
forward_SDB_ZPush_0 = runtime.ForwardResponseMessage
forward_SDB_ZPop_0 = runtime.ForwardResponseMessage
forward_SDB_ZRange_0 = runtime.ForwardResponseMessage
forward_SDB_ZExist_0 = runtime.ForwardResponseMessage
forward_SDB_ZDel_0 = runtime.ForwardResponseMessage
forward_SDB_ZCount_0 = runtime.ForwardResponseMessage
forward_SDB_BFCreate_0 = runtime.ForwardResponseMessage
forward_SDB_BFDel_0 = runtime.ForwardResponseMessage
forward_SDB_BFAdd_0 = runtime.ForwardResponseMessage
forward_SDB_BFExist_0 = runtime.ForwardResponseMessage
forward_SDB_HLLCreate_0 = runtime.ForwardResponseMessage
forward_SDB_HLLDel_0 = runtime.ForwardResponseMessage
forward_SDB_HLLAdd_0 = runtime.ForwardResponseMessage
forward_SDB_HLLCount_0 = runtime.ForwardResponseMessage
forward_SDB_Subscribe_0 = runtime.ForwardResponseStream
forward_SDB_Publish_0 = runtime.ForwardResponseMessage
)
| {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
} |
projectbuilder.py | # -----------------------------------------------------------------------------
# Builder
# -----------------------------------------------------------------------------
# Team: DataHub
# -----------------------------------------------------------------------------
# Author: Maxime Sirois
# -----------------------------------------------------------------------------
"""Build the project
Takes various actions to build the project from the templates and parameters.
"""
# -----------------------------------------------------------------------------
from jinja2 import Template
import logging
from pathlib import Path
import subprocess
from . import constants as C
from . import utils
logger = logging.getLogger(__name__)
class Builder:
def __init__(self, properties, parameters=None):
self.parameters = parameters
self.properties = properties
| def _build_project(self):
"""
Build the Project in the target location.
"""
location = self.properties.location
for folder, body in self.parameters.items():
_create_folder_and_files(Path(location), folder, body)
def add_new_module(self):
location = self.properties.location
module_file_name = utils.slugify(self.properties.module_name) + '.py'
param = {
"template": "./lib/module.py",
"header": "./header_module.txt",
"template_string": {
"module_name": self.properties.module_name,
"team_name": self.properties.team_name,
"author_name": self.properties.author_name,
"module_name_styled": self.properties.module_name_styled
}
}
_create_file(module_file_name, param, location)
def _generate_file(content, location):
with open(location, 'w+') as f_out:
f_out.write(content)
if not content.endswith('\n'):
f_out.write('\n')
def _add_header(content, header_template):
header_content = header_template.read_text()
return header_content + '\n\n\n' + content
def _create_file(file_name, parameters, location):
content = ''
if parameters.get('template'):
template_name = parameters['template']
logging.info(f" - {file_name} :: template :: {template_name}")
# Get template
file_template = Path(C._TEMPLATE_FOLDER, template_name)
template_content = file_template.read_text()
# Check if there is a header to paste before content
if parameters.get('header'):
header_template = Path(C._TEMPLATE_FOLDER, parameters['header'])
template_content = _add_header(template_content, header_template)
# Change values of template
t = Template(template_content)
content = t.render(**parameters.get('template_string', {}))
# Generate the File (with Header if applicable)
_generate_file(content, location / file_name)
def _create_folder_and_files(location, folder, body):
location = location / folder
if folder == 'venv':
if body.get('exe'):
logging.info(f">>>> Creating VirtualEnv from {body.get('exe')}")
cmd = f"\"{body.get('exe')}\" \"{location}\""
subprocess.check_call(cmd, shell=True)
logging.info(f">>>> Pip Install Requirements.txt")
pip_exe = location / 'Scripts' / 'pip.exe'
requirements = location / '..' / 'requirements.txt'
cmd_pip = f'"{pip_exe}" install -r "{requirements}"'
subprocess.check_call(cmd_pip, shell=True)
return
else:
logging.info(f">> Creating {folder} @ {str(location)}")
location.mkdir()
if body.get('files'):
for file_name, file_param in body['files'].items():
_create_file(file_name, file_param, location)
if body.get('folders'):
for folder, body_ in body['folders'].items():
_create_folder_and_files(location, folder, body_) |
def start(self):
self._build_project()
|
data_structs.rs | use crate::plonk::circuit::curve::sw_affine::*;
use crate::plonk::circuit::bigint::field::*;
use crate::plonk::circuit::bigint::bigint::*;
use crate::plonk::circuit::allocated_num::*;
use crate::plonk::circuit::boolean::*;
use super::affine_point_wrapper::WrappedAffinePoint;
use super::affine_point_wrapper::aux_data::AuxData;
use crate::bellman::pairing::{
Engine,
CurveAffine,
CurveProjective,
};
use crate::bellman::pairing::ff::{
Field,
PrimeField,
BitIterator,
};
use crate::bellman::{
SynthesisError,
};
use crate::bellman::plonk::better_better_cs::cs::{
Variable,
ConstraintSystem,
PlonkConstraintSystemParams,
};
use crate::bellman::plonk::better_cs::keys::{Proof, VerificationKey};
use crate::bellman::plonk::better_cs::cs::PlonkConstraintSystemParams as OldCSParams;
#[derive(Clone, Debug)]
pub struct ProofGadget<'a, E: Engine, WP: WrappedAffinePoint<'a, E>> {
pub num_inputs: usize,
pub input_values: Vec<AllocatedNum<E>>,
pub wire_commitments: Vec<WP>,
pub grand_product_commitment: WP,
pub quotient_poly_commitments: Vec<WP>,
pub wire_values_at_z: Vec<AllocatedNum<E>>,
pub wire_values_at_z_omega: Vec<AllocatedNum<E>>,
pub grand_product_at_z_omega: AllocatedNum<E>,
pub quotient_polynomial_at_z: AllocatedNum<E>,
pub linearization_polynomial_at_z: AllocatedNum<E>,
pub permutation_polynomials_at_z: Vec<AllocatedNum<E>>,
pub opening_at_z_proof: WP,
pub opening_at_z_omega_proof: WP,
_m: &'a std::marker::PhantomData<()>,
}
impl<'a, E: Engine, WP: WrappedAffinePoint<'a, E>> ProofGadget<'a, E, WP> {
pub fn alloc<CS: ConstraintSystem<E>, P: OldCSParams<E>, AD: AuxData<E>>(
cs: &mut CS,
proof: Proof<E, P>,
params: &'a RnsParameters<E, <E::G1Affine as CurveAffine>::Base>,
aux_data: &AD,
) -> Result<Self, SynthesisError> {
let input_values = proof.input_values.iter().map(|x| {
AllocatedNum::alloc_input(cs, || Ok(*x))
}).collect::<Result<Vec<_>, _>>()?;
let wire_commitments = proof.wire_commitments.iter().map(|x| {
WrappedAffinePoint::alloc(cs, Some(*x), params, aux_data)
}).collect::<Result<Vec<_>, _>>()?;
let grand_product_commitment = WrappedAffinePoint::alloc(cs, Some(proof.grand_product_commitment), params, aux_data)?;
let quotient_poly_commitments = proof.quotient_poly_commitments.iter().map(|x| {
WrappedAffinePoint::alloc(cs, Some(*x), params, aux_data)
}).collect::<Result<Vec<_>, _>>()?;
let wire_values_at_z = proof.wire_values_at_z.iter().map(|x| {
AllocatedNum::alloc(cs, || Ok(*x))
}).collect::<Result<Vec<_>, _>>()?;
let wire_values_at_z_omega = proof.wire_values_at_z_omega.iter().map(|x| {
AllocatedNum::alloc(cs, || Ok(*x))
}).collect::<Result<Vec<_>, _>>()?;
let grand_product_at_z_omega = AllocatedNum::alloc(cs, || Ok(proof.grand_product_at_z_omega))?;
let quotient_polynomial_at_z = AllocatedNum::alloc(cs, || Ok(proof.quotient_polynomial_at_z))?;
let linearization_polynomial_at_z = AllocatedNum::alloc(cs, || Ok(proof.linearization_polynomial_at_z))?;
let permutation_polynomials_at_z = proof.permutation_polynomials_at_z.iter().map(|x| {
AllocatedNum::alloc(cs, || Ok(*x))
}).collect::<Result<Vec<_>, _>>()?;
let opening_at_z_proof = WrappedAffinePoint::alloc(cs, Some(proof.opening_at_z_proof), params, aux_data)?;
let opening_at_z_omega_proof = WrappedAffinePoint::alloc(cs, Some(proof.opening_at_z_omega_proof), params, aux_data)?;
Ok(ProofGadget {
num_inputs: proof.num_inputs,
input_values,
wire_commitments,
grand_product_commitment,
quotient_poly_commitments,
wire_values_at_z,
wire_values_at_z_omega,
grand_product_at_z_omega,
quotient_polynomial_at_z,
linearization_polynomial_at_z,
permutation_polynomials_at_z,
opening_at_z_proof,
opening_at_z_omega_proof,
_m: &std::marker::PhantomData::<()>,
})
}
pub fn alloc_from_witness<CS: ConstraintSystem<E>, P: OldCSParams<E>, AD: AuxData<E>>(
cs: &mut CS,
num_inputs: usize,
proof: &Option<Proof<E, P>>,
params: &'a RnsParameters<E, <E::G1Affine as CurveAffine>::Base>,
aux_data: &AD,
) -> Result<Self, SynthesisError> {
use crate::circuit::Assignment;
let state_width = P::STATE_WIDTH;
let num_quotient_commitments = P::STATE_WIDTH;
assert!(P::CAN_ACCESS_NEXT_TRACE_STEP);
assert!(!P::HAS_CUSTOM_GATES);
let mut input_values = vec![];
for idx in 0..num_inputs {
let wit = proof.as_ref().and_then(|el| Some(&el.input_values)).and_then(|el| Some(el[idx]));
let allocated = AllocatedNum::alloc(cs, || Ok(*wit.get()?))?;
input_values.push(allocated);
}
let mut wire_commitments = vec![];
for idx in 0..state_width {
let wit = proof.as_ref().and_then(|el| Some(&el.wire_commitments)).and_then(|el| Some(el[idx]));
let allocated = WrappedAffinePoint::alloc(cs, wit, params, aux_data)?;
wire_commitments.push(allocated);
}
let wit = proof.as_ref().and_then(|el| Some(el.grand_product_commitment));
let grand_product_commitment = WrappedAffinePoint::alloc(cs, wit, params, aux_data)?;
let mut quotient_poly_commitments = vec![];
for idx in 0..num_quotient_commitments {
let wit = proof.as_ref().and_then(|el| Some(&el.quotient_poly_commitments)).and_then(|el| Some(el[idx]));
let allocated = WrappedAffinePoint::alloc(cs, wit, params, aux_data)?;
quotient_poly_commitments.push(allocated);
}
let mut wire_values_at_z = vec![];
for idx in 0..state_width {
let wit = proof.as_ref().and_then(|el| Some(&el.wire_values_at_z)).and_then(|el| Some(el[idx]));
let allocated = AllocatedNum::alloc(cs, || Ok(*wit.get()?))?;
wire_values_at_z.push(allocated);
}
let mut wire_values_at_z_omega = vec![];
for idx in 0..1 {
let wit = proof.as_ref().and_then(|el| Some(&el.wire_values_at_z_omega)).and_then(|el| Some(el[idx]));
let allocated = AllocatedNum::alloc(cs, || Ok(*wit.get()?))?;
wire_values_at_z_omega.push(allocated);
}
let wit = proof.as_ref().and_then(|el| Some(el.grand_product_at_z_omega));
let grand_product_at_z_omega = AllocatedNum::alloc(cs, || Ok(*wit.get()?))?;
let wit = proof.as_ref().and_then(|el| Some(el.quotient_polynomial_at_z));
let quotient_polynomial_at_z = AllocatedNum::alloc(cs, || Ok(*wit.get()?))?;
let wit = proof.as_ref().and_then(|el| Some(el.linearization_polynomial_at_z));
let linearization_polynomial_at_z = AllocatedNum::alloc(cs, || Ok(*wit.get()?))?;
let mut permutation_polynomials_at_z = vec![];
for idx in 0..(state_width-1) {
let wit = proof.as_ref().and_then(|el| Some(&el.permutation_polynomials_at_z)).and_then(|el| Some(el[idx]));
let allocated = AllocatedNum::alloc(cs, || Ok(*wit.get()?))?;
permutation_polynomials_at_z.push(allocated);
}
let wit = proof.as_ref().and_then(|el| Some(el.opening_at_z_proof));
let opening_at_z_proof = WrappedAffinePoint::alloc(cs, wit, params, aux_data)?;
let wit = proof.as_ref().and_then(|el| Some(el.opening_at_z_omega_proof));
let opening_at_z_omega_proof = WrappedAffinePoint::alloc(cs, wit, params, aux_data)?;
Ok(ProofGadget {
num_inputs: num_inputs,
input_values,
wire_commitments,
grand_product_commitment,
quotient_poly_commitments,
wire_values_at_z,
wire_values_at_z_omega,
grand_product_at_z_omega,
quotient_polynomial_at_z,
linearization_polynomial_at_z,
permutation_polynomials_at_z,
opening_at_z_proof,
opening_at_z_omega_proof,
_m: &std::marker::PhantomData::<()>,
})
}
}
#[derive(Clone, Debug)]
pub struct VerificationKeyGagdet<'a, E: Engine, WP: WrappedAffinePoint<'a, E>> {
pub n: Option<usize>,
pub domain_size_as_allocated_num: Option<AllocatedNum<E>>,
pub omega_as_allocated_num: Option<AllocatedNum<E>>,
pub num_inputs: usize,
pub selector_commitments: Vec<WP>,
pub next_step_selector_commitments: Vec<WP>,
pub permutation_commitments: Vec<WP>,
pub non_residues: Vec<E::Fr>,
_m: &'a std::marker::PhantomData<()>,
}
impl<'a, E: Engine, WP: WrappedAffinePoint<'a, E>> VerificationKeyGagdet<'a, E, WP> {
pub fn alloc<CS: ConstraintSystem<E>, P: OldCSParams<E>, AD: AuxData<E>>(
cs: &mut CS,
vk: VerificationKey<E, P>,
params: &'a RnsParameters<E, <E::G1Affine as CurveAffine>::Base>,
aux_data: &AD,
) -> Result<Self, SynthesisError> {
let selector_commitments = vk.selector_commitments.iter().map(|x| {
WrappedAffinePoint::alloc(cs, Some(*x), params, aux_data)
}).collect::<Result<Vec<_>, _>>()?;
let next_step_selector_commitments = vk.next_step_selector_commitments.iter().map(|x| {
WrappedAffinePoint::alloc(cs, Some(*x), params, aux_data)
}).collect::<Result<Vec<_>, _>>()?;
let permutation_commitments = vk.permutation_commitments.iter().map(|x| {
WrappedAffinePoint::alloc(cs, Some(*x), params, aux_data)
}).collect::<Result<Vec<_>, _>>()?;
Ok(VerificationKeyGagdet {
n : Some(vk.n),
domain_size_as_allocated_num: None,
omega_as_allocated_num: None,
num_inputs : vk.num_inputs,
selector_commitments,
next_step_selector_commitments,
permutation_commitments,
non_residues: vk.non_residues,
_m: &std::marker::PhantomData::<()>,
})
}
pub fn alloc_from_limbs_witness<CS: ConstraintSystem<E>, P: OldCSParams<E>, AD: AuxData<E>>(
cs: &mut CS,
num_inputs: usize,
domain_size: &AllocatedNum<E>,
omega: &AllocatedNum<E>,
witness: &[AllocatedNum<E>],
params: &'a RnsParameters<E, <E::G1Affine as CurveAffine>::Base>,
non_residues: Vec<E::Fr>,
aux_data: &AD,
) -> Result<Self, SynthesisError> {
let num_selector_commitments = P::STATE_WIDTH + 2;
let num_next_step_selector_commitments = 1;
let num_permutation_commitments = P::STATE_WIDTH;
assert!(P::CAN_ACCESS_NEXT_TRACE_STEP);
assert!(!P::HAS_CUSTOM_GATES);
let mut w = witness;
let mut selector_commitments = vec![];
for _ in 0..num_selector_commitments {
let (point, rest) = WrappedAffinePoint::from_allocated_limb_witness(cs, w, params, aux_data)?;
w = rest;
selector_commitments.push(point);
}
let mut next_step_selector_commitments = vec![];
for _ in 0..num_next_step_selector_commitments {
let (point, rest) = WrappedAffinePoint::from_allocated_limb_witness(cs, w, params, aux_data)?;
w = rest;
next_step_selector_commitments.push(point);
}
let mut permutation_commitments = vec![];
for _ in 0..num_permutation_commitments {
let (point, rest) = WrappedAffinePoint::from_allocated_limb_witness(cs, w, params, aux_data)?;
w = rest;
permutation_commitments.push(point);
}
assert_eq!(w.len(), 0, "must consume all the witness");
Ok(VerificationKeyGagdet {
n : None,
domain_size_as_allocated_num: Some(domain_size.clone()),
omega_as_allocated_num: Some(omega.clone()),
num_inputs : num_inputs,
selector_commitments,
next_step_selector_commitments,
permutation_commitments,
non_residues: non_residues,
_m: &std::marker::PhantomData::<()>,
})
}
}
pub trait IntoLimbedWitness<E: Engine> {
fn into_witness(&self) -> Result<Vec<E::Fr>, SynthesisError> {
unimplemented!()
}
fn witness_size_for_params(params: &RnsParameters<E, <E::G1Affine as CurveAffine>::Base >) -> usize;
fn into_witness_for_params(&self, _params: &RnsParameters<E, <E::G1Affine as CurveAffine>::Base >) -> Result<Vec<E::Fr>, SynthesisError> {
unimplemented!()
}
}
impl<E: Engine, P: OldCSParams<E>> IntoLimbedWitness<E> for VerificationKey<E, P> {
fn witness_size_for_params(params: &RnsParameters<E, <E::G1Affine as CurveAffine>::Base >) -> usize {
let mut base = 2;
let per_coord = if params.can_allocate_from_double_limb_witness() {
let mut num_witness = params.num_limbs_for_in_field_representation / 2;
if params.num_limbs_for_in_field_representation % 2 != 0 {
num_witness += 1;
}
num_witness
} else {
params.num_limbs_for_in_field_representation
};
let num_selector_commitments = P::STATE_WIDTH + 2;
let num_next_step_selector_commitments = 1;
let num_permutation_commitments = P::STATE_WIDTH;
assert!(P::CAN_ACCESS_NEXT_TRACE_STEP);
assert!(!P::HAS_CUSTOM_GATES);
base += num_selector_commitments * 2 * per_coord;
base += num_next_step_selector_commitments * 2 * per_coord;
base += num_permutation_commitments * 2 * per_coord;
base
}
fn into_witness_for_params(&self, params: &RnsParameters<E, <E::G1Affine as CurveAffine>::Base>) -> Result<Vec<E::Fr>, SynthesisError> {
use super::utils::verification_key_into_allocated_limb_witnesses;
let as_limbs = verification_key_into_allocated_limb_witnesses(&self, params);
Ok(as_limbs)
}
}
impl<E: Engine, P: OldCSParams<E>> IntoLimbedWitness<E> for Proof<E, P> {
fn witness_size_for_params(_params: &RnsParameters<E, <E::G1Affine as CurveAffine>::Base >) -> usize {
unimplemented!();
// let mut base = 2;
// let per_coord = if params.can_allocate_from_double_limb_witness() {
// let mut num_witness = params.num_limbs_for_in_field_representation / 2;
// if params.num_limbs_for_in_field_representation % 2 != 0 {
// num_witness += 1;
// }
// num_witness
// } else {
// params.num_limbs_for_in_field_representation
// };
// let num_selector_commitments = P::STATE_WIDTH + 2;
// let num_next_step_selector_commitments = 1;
// let num_permutation_commitments = P::STATE_WIDTH;
// assert!(P::CAN_ACCESS_NEXT_TRACE_STEP);
// assert!(!P::HAS_CUSTOM_GATES);
// base += num_selector_commitments * 2 * per_coord;
// base += num_next_step_selector_commitments * 2 * per_coord;
// base += num_permutation_commitments * 2 * per_coord;
// base
}
fn into_witness_for_params(&self, params: &RnsParameters<E, <E::G1Affine as CurveAffine>::Base>) -> Result<Vec<E::Fr>, SynthesisError> {
use super::utils::proof_into_single_limb_witness;
let as_limbs = proof_into_single_limb_witness(&self, params);
Ok(as_limbs)
}
}
pub trait IntoLimbedCircuitWitness<E: Engine> {
fn into_witness<CS: ConstraintSystem<E>>(&self, _cs: &mut CS) -> Result<Vec<Num<E>>, SynthesisError> {
unimplemented!()
}
// fn into_witness_for_params<F: PrimeField, CS: ConstraintSystem<E>>(&self, cs: &mut CS, params: &RnsParameters<E, F>) -> Result<Vec<AllocatedNum<E>>, SynthesisError> {
// unimplemented!()
// }
}
impl<'a, E: Engine, WP: WrappedAffinePoint<'a, E>> IntoLimbedCircuitWitness<E> for ProofGadget<'a, E, WP> {
fn into_witness<CS: ConstraintSystem<E>>(&self, _cs: &mut CS) -> Result<Vec<Num<E>>, SynthesisError> {
let mut result = vec![];
add_scalar_field_elements(&self.input_values, &mut result);
add_points(&self.wire_commitments, &mut result);
add_points(&[self.grand_product_commitment.clone()], &mut result);
add_points(&self.quotient_poly_commitments, &mut result);
add_scalar_field_elements(&self.wire_values_at_z, &mut result);
add_scalar_field_elements(&self.wire_values_at_z_omega, &mut result);
add_scalar_field_elements(&[self.grand_product_at_z_omega.clone()], &mut result);
add_scalar_field_elements(&[self.quotient_polynomial_at_z.clone()], &mut result);
add_scalar_field_elements(&[self.linearization_polynomial_at_z.clone()], &mut result);
add_scalar_field_elements(&self.permutation_polynomials_at_z, &mut result);
add_points(&[self.opening_at_z_proof.clone(), self.opening_at_z_omega_proof.clone()], &mut result);
Ok(result)
}
}
impl<'a, E: Engine, WP: WrappedAffinePoint<'a, E>> IntoLimbedCircuitWitness<E> for VerificationKeyGagdet<'a, E, WP> {
fn into_witness<CS: ConstraintSystem<E>>(&self, _cs: &mut CS) -> Result<Vec<Num<E>>, SynthesisError> {
assert!(self.domain_size_as_allocated_num.is_some(), "can only be called on a gadget with variable parameters");
assert!(self.omega_as_allocated_num.is_some(), "can only be called on a gadget with variable parameters");
let mut result = vec![];
result.push(Num::Variable(self.domain_size_as_allocated_num.as_ref().unwrap().clone()));
result.push(Num::Variable(self.omega_as_allocated_num.as_ref().unwrap().clone()));
add_points(&self.selector_commitments, &mut result);
add_points(&self.next_step_selector_commitments, &mut result);
add_points(&self.permutation_commitments, &mut result);
Ok(result)
}
}
fn add_scalar_field_elements<E: Engine>(src: &[AllocatedNum<E>], dst: &mut Vec<Num<E>>) |
fn add_prime_field_elements<'a, E: Engine, F: PrimeField>(src: &[FieldElement<'a, E, F>], dst: &mut Vec<Num<E>>) {
for el in src.iter() {
for limb in el.binary_limbs.iter() {
let as_num = limb.term.into_num();
dst.push(as_num);
}
}
}
fn add_points<'a, E: Engine, WP: WrappedAffinePoint<'a, E>>(src: &[WP], dst: &mut Vec<Num<E>>) {
for el in src.iter() {
let p = el.get_point();
let x = p.x.clone();
let y = p.y.clone();
add_prime_field_elements(&[x, y], dst);
}
} | {
for el in src.iter() {
let num = Num::Variable(el.clone());
dst.push(num);
}
} |
models.py | import zlib
from datetime import datetime
from django.conf import settings
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.http import urlencode
from django.utils.timesince import timesince
from django.utils.translation import ugettext_lazy as _
from dateutil.relativedelta import relativedelta
from brouwers.general.utils import clean_username
from .fields import ForumToolsIDField
class ForumLinkBase(models.Model):
link_id = models.CharField(
_("link id"), max_length=128, help_text=_("HTML id of the base anchor.")
)
short_description = models.CharField(
_("short description"), max_length=64, blank=True
)
enabled = models.BooleanField(
_("enabled"), default=True, help_text=_("Enable the syncing of this link.")
)
from_date = models.DateField(
_("from date"), help_text=_("Start date from when this link is enabled.")
)
to_date = models.DateField(
_("to date"),
help_text=_("End date from when this link is enabled, this date included."),
)
class Meta:
verbose_name = _("base forum link")
verbose_name_plural = _("base forum links")
def __str__(self):
if self.short_description:
return _("base forum link: %(desc)s") % {"desc": self.short_description}
else:
return _("base forum link: %(id)s") % {"id": self.link_id}
class ForumLinkSynced(models.Model):
base = models.ForeignKey(
ForumLinkBase,
verbose_name=_("base link"),
help_text=_("Link this link syncs with."),
on_delete=models.CASCADE,
)
link_id = models.CharField(
_("link id"), max_length=128, help_text=_("HTML id of the anchor to be synced.")
)
class Meta:
verbose_name = _("synced forum link")
verbose_name_plural = _("synced forum links")
def __str__(self):
return u"%s -- %s" % (self.base, self.link_id)
class BuildReportsForum(models.Model):
"""Model which tells us which forums hold build reports"""
forum = ForumToolsIDField(_("forum"), type="forum")
class Meta:
verbose_name = _(u"build report forum")
verbose_name_plural = _(u"build report forums")
ordering = ["forum"]
def __str__(self):
return self.forum.forum_name if self.forum else _("(forum does not exist)")
class ForumCategory(models.Model):
name = models.CharField(_("name"), max_length=255)
forum = ForumToolsIDField(_("forum"), type="forum", blank=True, null=True)
icon_class = models.CharField(_("icon class"), max_length=50, blank=True)
class Meta:
verbose_name = _(u"forum category")
verbose_name_plural = _(u"forum categories")
ordering = ("name",)
def __str__(self):
return self.name
# Models to interact with the MYSQL database #############################
class ForumUser(models.Model):
"""MySQL phpBB3 user, managed by phpBB3"""
# mediumint(8) unsigned
user_id = models.AutoField(primary_key=True, help_text=_("Primary key"))
username = models.CharField(_("username"), max_length=255)
username_clean = models.CharField(_("username"), max_length=255)
user_posts = models.IntegerField()
user_email = models.CharField(_("email"), max_length=100)
# bigint(20)
user_email_hash = models.BigIntegerField(
db_column="user_email_hash",
default=0,
help_text=_("A hash of the user's email address."),
)
user_permissions = models.TextField(blank=True)
user_sig = models.TextField(blank=True)
user_interests = models.TextField(blank=True)
user_actkey = models.TextField(blank=True)
user_occ = models.TextField(blank=True)
class Meta:
managed = False
verbose_name = _("forum user")
verbose_name_plural = _("forum users")
ordering = ("username",)
db_table = u"%susers" % settings.PHPBB_TABLE_PREFIX
def __str__(self):
return self.username
def get_absolute_url(self):
qs = {
"mode": "viewprofile",
"u": self.user_id,
}
return "{0}?{1}".format(reverse("phpBB:memberlist"), urlencode(qs))
def get_email_hash(self):
email = self.user_email
h = zlib.crc32(email.lower().encode("ascii")) & 0xFFFFFFFF
return "%s%s" % (h, len(email))
def save(self, *args, **kwargs):
self.user_email_hash = self.get_email_hash()
if not self.username_clean:
self._clean_username()
super().save(*args, **kwargs)
def _clean_username(self):
self.username_clean = clean_username(self.username)
class Forum(models.Model):
"""
MySQL Forum, managed by phpBB3
"""
forum_id = models.AutoField(primary_key=True)
forum_name = models.CharField(max_length=60)
forum_topics = models.IntegerField(default=0)
forum_posts = models.IntegerField(default=0)
forum_desc = models.TextField()
parent = models.ForeignKey(
"self", | null=True,
blank=True,
default=None,
on_delete=models.CASCADE,
)
def __str__(self):
return self.forum_name
def get_absolute_url(self):
qs = {"f": self.forum_id}
return "{0}?{1}".format(reverse("phpBB:viewforum"), urlencode(qs))
class Meta:
managed = False
db_table = settings.PHPBB_TABLE_PREFIX + "forums"
ordering = ["forum_name"]
class Topic(models.Model):
topic_id = models.AutoField(primary_key=True)
forum = models.ForeignKey(Forum, on_delete=models.CASCADE)
topic_title = models.CharField(max_length=255)
last_post_time = models.BigIntegerField(db_column="topic_last_post_time", default=0)
create_time = models.BigIntegerField(db_column="topic_time", default=0)
author = models.ForeignKey(
ForumUser,
db_column="topic_poster",
null=True,
blank=True,
on_delete=models.SET_NULL,
)
class Meta:
managed = False
db_table = settings.PHPBB_TABLE_PREFIX + "topics"
ordering = ["topic_id"]
def __str__(self):
return self.topic_title
def get_absolute_url(self):
qs = {"t": self.topic_id}
if self.forum.pk:
qs["f"] = self.forum.pk
return "{0}?{1}".format(reverse("phpBB:viewtopic"), urlencode(qs))
@property
def created(self):
return datetime.utcfromtimestamp(self.create_time).replace(tzinfo=timezone.utc)
def get_last_post_time(self):
return datetime.utcfromtimestamp(self.last_post_time).replace(
tzinfo=timezone.utc
)
@property
def is_dead(self):
"""
If the last post is older than settings.TOPIC_DEAD_TIME, it's considered
dead.
"""
last = self.get_last_post_time()
lower = timezone.now() - relativedelta(months=settings.TOPIC_DEAD_TIME)
return last <= lower
@property
def age(self):
return timesince(self.get_last_post_time())
@property
def text_dead(self):
return _(
"This topic has been inactive for: {0}. Please consider "
"sending the author a private message instead of replying "
"and thus bumping the topic."
).format(self.age)
class ForumPostCountRestriction(models.Model):
"""Model to hold information on the minimum post-count and level of posting rights.
Managed by Django."""
POSTING_LEVELS = (
("T", _("Topic")),
("R", _("Reply")),
)
forum = ForumToolsIDField(_("forum id"), type="forum", blank=True, null=True)
min_posts = models.PositiveSmallIntegerField(_("minimum number of posts"))
posting_level = models.CharField(
_("posting level"), max_length=1, choices=POSTING_LEVELS
)
class Meta:
verbose_name = _("forum post count restriction")
verbose_name_plural = _("forum post count restrictions")
ordering = ["forum"]
def __str__(self):
return _("Restriction for %(forum)s") % {"forum": self.forum.forum_name}
class Report(models.Model):
"""MySQL Report model, managed by phpBB3"""
report_id = models.AutoField(primary_key=True, help_text="Primary key")
# reason_id = FK to reasons, not implement in Django yet
report_closed = models.BooleanField(
_("closed"),
default=False,
help_text=_("Closed reports need no more attention."),
)
report_time_int = models.IntegerField(
_("time"),
db_column="report_time",
help_text=_("UNIX time when the report was added."),
)
report_text = models.TextField("text", blank=True)
class Meta:
managed = False
verbose_name = _("report")
verbose_name_plural = _("reports")
db_table = u"%sreports" % settings.PHPBB_TABLE_PREFIX
permissions = (("can_see_reports", _("Can see (number of) open reports")),)
def __str__(self):
return _("Report %(id)s" % {"id": self.report_id})
def report_time(self):
return datetime.fromtimestamp(self.report_time_int) | related_name="child", |
main.go | /*
Copyright 2021 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"errors"
"flag"
"fmt"
"go/types"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"golang.org/x/tools/go/packages"
)
func main() { // nolint:funlen
source := flag.String("source", "../../proto/vtctlservice", "source package")
typeName := flag.String("type", "VtctldClient", "interface type to implement")
implType := flag.String("impl", "gRPCVtctldClient", "type implementing the interface")
pkgName := flag.String("targetpkg", "grpcvtctldclient", "package name to generate code for")
local := flag.Bool("local", false, "generate a local, in-process client rather than a grpcclient")
out := flag.String("out", "", "output destination. leave empty to use stdout")
flag.Parse()
if *source == "" {
panic("-source cannot be empty")
}
if *typeName == "" {
panic("-type cannot be empty")
}
if *implType == "" {
panic("-impl cannot be empty")
}
if *pkgName == "" {
panic("-targetpkg cannot be empty")
}
var output io.Writer = os.Stdout
if *out != "" {
f, err := os.Create(*out)
if err != nil {
panic(err)
}
defer f.Close()
output = f
}
pkg, err := loadPackage(*source)
if err != nil {
panic(err)
}
iface, err := extractSourceInterface(pkg, *typeName)
if err != nil {
panic(fmt.Errorf("error getting %s in %s: %w", *typeName, *source, err))
}
imports := map[string]string{
"context": "context",
}
importNames := []string{}
funcs := make(map[string]*Func, iface.NumExplicitMethods())
funcNames := make([]string, iface.NumExplicitMethods())
for i := 0; i < iface.NumExplicitMethods(); i++ {
m := iface.ExplicitMethod(i)
funcNames[i] = m.Name()
sig, ok := m.Type().(*types.Signature)
if !ok {
panic(fmt.Sprintf("could not derive signature from method %s, have %T", m.FullName(), m.Type()))
}
if sig.Params().Len() != 3 {
panic(fmt.Sprintf("all methods in a grpc client interface should have exactly 3 params; found\n=> %s", sig))
}
if sig.Results().Len() != 2 {
panic(fmt.Sprintf("all methods in a grpc client interface should have exactly 2 results; found\n=> %s", sig))
}
f := &Func{
Name: m.Name(),
}
funcs[f.Name] = f
// The first parameter is always context.Context. The third parameter is
// always a ...grpc.CallOption.
param := sig.Params().At(1)
localType, localImport, pkgPath, err := extractLocalPointerType(param)
if err != nil {
panic(err)
}
f.Param.Name = param.Name()
f.Param.Type = "*" + localImport + "." + localType
if _, ok := imports[localImport]; !ok {
importNames = append(importNames, localImport)
}
imports[localImport] = pkgPath
// (TODO|@amason): check which grpc lib CallOption is imported from in
// this interface; it could be either google.golang.org/grpc or
// github.com/golang/protobuf/grpc, although in vitess we currently
// always use the former.
// The second result is always error.
result := sig.Results().At(0)
localType, localImport, pkgPath, err = extractLocalPointerType(result) // (TODO|@amason): does not work for streaming rpcs
if err != nil {
panic(err)
}
f.Result.Name = result.Name()
f.Result.Type = "*" + localImport + "." + localType
if _, ok := imports[localImport]; !ok {
importNames = append(importNames, localImport)
}
imports[localImport] = pkgPath
}
sort.Strings(importNames)
sort.Strings(funcNames)
def := &ClientInterfaceDef{
PackageName: *pkgName,
Type: *implType,
ClientName: "grpcvtctldclient",
}
if *local {
def.ClientName = "localvtctldclient"
def.Local = true
}
for _, name := range importNames {
imp := &Import{
Path: imports[name],
}
if filepath.Base(imp.Path) != name {
imp.Alias = name
}
def.Imports = append(def.Imports, imp)
}
for _, name := range funcNames {
def.Methods = append(def.Methods, funcs[name])
}
if err := tmpl.Execute(output, def); err != nil {
panic(err)
}
}
// ClientInterfaceDef is a struct providing enough information to generate an
// implementation of a gRPC Client interface.
type ClientInterfaceDef struct {
PackageName string
Type string
Imports []*Import
Methods []*Func
Local bool
ClientName string
}
// Import contains the meta information about a Go import.
type Import struct {
Alias string
Path string
}
// Func is the variable part of a gRPC client interface method (i.e. not the
// context or dialopts arguments, or the error part of the result tuple).
type Func struct {
Name string
Param Param
Result Param
}
// Param represents an element of either a parameter list or result list. It
// contains an optional name, and a package-local type. This struct exists
// purely to power template execution, which is why the Type field is simply a
// bare string.
type Param struct {
Name string
// locally-qualified type, e.g. "grpc.CallOption", and not "google.golang.org/grpc.CallOption".
Type string
}
func loadPackage(source string) (*packages.Package, error) {
pkgs, err := packages.Load(&packages.Config{
Mode: packages.NeedTypes | packages.NeedSyntax | packages.NeedTypesInfo,
}, source)
if err != nil {
return nil, err
}
if len(pkgs) != 1 {
return nil, errors.New("must specify exactly one package")
}
pkg := pkgs[0]
if len(pkg.Errors) > 0 {
var err error
for _, e := range pkg.Errors {
switch err {
case nil:
err = fmt.Errorf("errors loading package %s: %s", source, e.Error())
default:
err = fmt.Errorf("%w; %s", err, e.Error())
}
}
return nil, err
}
return pkg, nil
}
func extractSourceInterface(pkg *packages.Package, name string) (*types.Interface, error) {
obj := pkg.Types.Scope().Lookup(name)
if obj == nil {
return nil, fmt.Errorf("no symbol found with name %s", name)
}
switch t := obj.Type().(type) {
case *types.Named:
iface, ok := t.Underlying().(*types.Interface)
if !ok {
return nil, fmt.Errorf("symbol %s was not an interface but %T", name, t.Underlying())
}
return iface, nil
case *types.Interface:
return t, nil
}
return nil, fmt.Errorf("symbol %s was not an interface but %T", name, obj.Type())
}
var vitessProtoRegexp = regexp.MustCompile(`^vitess.io.*/proto/.*`)
func rewriteProtoImports(pkg *types.Package) string {
if vitessProtoRegexp.MatchString(pkg.Path()) {
return pkg.Name() + "pb"
}
return pkg.Name()
}
func | (v *types.Var) (name string, localImport string, pkgPath string, err error) {
ptr, ok := v.Type().(*types.Pointer)
if !ok {
return "", "", "", fmt.Errorf("expected a pointer type for %s, got %v", v.Name(), v.Type())
}
typ, ok := ptr.Elem().(*types.Named)
if !ok {
return "", "", "", fmt.Errorf("expected an underlying named type for %s, got %v", v.Name(), ptr.Elem())
}
name = typ.Obj().Name()
localImport = rewriteProtoImports(typ.Obj().Pkg())
pkgPath = typ.Obj().Pkg().Path()
return name, localImport, pkgPath, nil
}
| extractLocalPointerType |
edge_cnn_ke.py | import argparse
import torch
import torch.nn.functional as F
from torch.nn import Sequential as Seq, Linear as Lin, ReLU, LeakyReLU
from torch_geometric.nn import DynamicEdgeConv, global_max_pool
from datasets import get_dataset
from train_eval import run
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=200)
parser.add_argument('--batch_size', type=int, default=24)
parser.add_argument('--lr', type=float, default=0.001)
parser.add_argument('--lr_decay_factor', type=float, default=0.5)
parser.add_argument('--lr_decay_step_size', type=int, default=50)
parser.add_argument('--weight_decay', type=float, default=0)
args = parser.parse_args()
class | (torch.nn.Module):
def __init__(self, num_classes):
super(Net, self).__init__()
nn = Seq(Lin(6, 64), LeakyReLU(negative_slope=0.2),
Lin(64, 64), LeakyReLU(negative_slope=0.2),
Lin(64, 64), LeakyReLU(negative_slope=0.2))
self.conv1 = DynamicEdgeConv(nn, k=20, aggr='max')
nn = Seq(
Lin(128, 128), LeakyReLU(negative_slope=0.2),
Lin(128, 128), LeakyReLU(negative_slope=0.2),
Lin(128, 256), LeakyReLU(negative_slope=0.2))
self.conv2 = DynamicEdgeConv(nn, k=20, aggr='max')
self.lin0 = Lin(256, 512)
self.lin1 = Lin(512, 256)
self.lin2 = Lin(256, 256)
self.lin3 = Lin(256, num_classes)
def forward(self, pos, batch):
x = self.conv1(pos, batch)
x = self.conv2(x, batch)
x = F.relu(self.lin0(x))
x = global_max_pool(x, batch)
x = F.relu(self.lin1(x))
x = F.relu(self.lin2(x))
x = F.dropout(x, p=0.5, training=self.training)
x = self.lin3(x)
return F.log_softmax(x, dim=-1)
train_dataset, test_dataset = get_dataset(num_points=1024)
model = Net(train_dataset.num_classes)
run(train_dataset, test_dataset, model, args.epochs, args.batch_size, args.lr,
args.lr_decay_factor, args.lr_decay_step_size, args.weight_decay)
| Net |
main.go | package main
import (
"fmt"
"game-dev-test/internal"
"github.com/veandco/go-sdl2/sdl"
)
func main() {
display, err := internal.MakeDisplay(sdl.WINDOW_OPENGL)
defer func() {
if display != nil{
display.Destroy()
}
}()
if err != nil{
fmt.Printf("SDL Init error:%v\n", err)
return
}
player, err := internal.MakePlayer(display, "sprites/player.bmp")
if err != nil {
fmt.Printf("Error loading assets:%v\n", err)
}
defer player.Destroy()
gameloop(display, player)
}
func | (d *internal.SDLDisplay, player *internal.Player) {
player.X = 40
player.Y = 20
for{
for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
switch event.(type) {
case *sdl.QuitEvent:
fmt.Println("Quiting... Good bye!")
return
}
}
d.Renderer.SetDrawColor(255,255,255,255)
d.Renderer.Clear()
player.Draw(d.Renderer)
d.Renderer.Present()
}
} | gameloop |
fullblocks_test.go | // Copyright (c) 2016 The Decred developers
// Copyright (c) 2016-2017 The btcsuite developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package blockchain_test
import (
"bytes"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/satindergrewal/btcd/blockchain"
"github.com/satindergrewal/btcd/blockchain/fullblocktests"
"github.com/satindergrewal/btcd/btcutil"
"github.com/satindergrewal/btcd/chaincfg"
"github.com/satindergrewal/btcd/chaincfg/chainhash"
"github.com/satindergrewal/btcd/database"
_ "github.com/satindergrewal/btcd/database/ffldb"
"github.com/satindergrewal/btcd/txscript"
"github.com/satindergrewal/btcd/wire"
)
const (
// testDbType is the database backend type to use for the tests.
testDbType = "ffldb"
// testDbRoot is the root directory used to create all test databases.
testDbRoot = "testdbs"
// blockDataNet is the expected network in the test block data.
blockDataNet = wire.MainNet
)
// filesExists returns whether or not the named file or directory exists.
func | (name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// isSupportedDbType returns whether or not the passed database type is
// currently supported.
func isSupportedDbType(dbType string) bool {
supportedDrivers := database.SupportedDrivers()
for _, driver := range supportedDrivers {
if dbType == driver {
return true
}
}
return false
}
// chainSetup is used to create a new db and chain instance with the genesis
// block already inserted. In addition to the new chain instance, it returns
// a teardown function the caller should invoke when done testing to clean up.
func chainSetup(dbName string, params *chaincfg.Params) (*blockchain.BlockChain, func(), error) {
if !isSupportedDbType(testDbType) {
return nil, nil, fmt.Errorf("unsupported db type %v", testDbType)
}
// Handle memory database specially since it doesn't need the disk
// specific handling.
var db database.DB
var teardown func()
if testDbType == "memdb" {
ndb, err := database.Create(testDbType)
if err != nil {
return nil, nil, fmt.Errorf("error creating db: %v", err)
}
db = ndb
// Setup a teardown function for cleaning up. This function is
// returned to the caller to be invoked when it is done testing.
teardown = func() {
db.Close()
}
} else {
// Create the root directory for test databases.
if !fileExists(testDbRoot) {
if err := os.MkdirAll(testDbRoot, 0700); err != nil {
err := fmt.Errorf("unable to create test db "+
"root: %v", err)
return nil, nil, err
}
}
// Create a new database to store the accepted blocks into.
dbPath := filepath.Join(testDbRoot, dbName)
_ = os.RemoveAll(dbPath)
ndb, err := database.Create(testDbType, dbPath, blockDataNet)
if err != nil {
return nil, nil, fmt.Errorf("error creating db: %v", err)
}
db = ndb
// Setup a teardown function for cleaning up. This function is
// returned to the caller to be invoked when it is done testing.
teardown = func() {
db.Close()
os.RemoveAll(dbPath)
os.RemoveAll(testDbRoot)
}
}
// Copy the chain params to ensure any modifications the tests do to
// the chain parameters do not affect the global instance.
paramsCopy := *params
// Create the main chain instance.
chain, err := blockchain.New(&blockchain.Config{
DB: db,
ChainParams: ¶msCopy,
Checkpoints: nil,
TimeSource: blockchain.NewMedianTime(),
SigCache: txscript.NewSigCache(1000),
})
if err != nil {
teardown()
err := fmt.Errorf("failed to create chain instance: %v", err)
return nil, nil, err
}
return chain, teardown, nil
}
// TestFullBlocks ensures all tests generated by the fullblocktests package
// have the expected result when processed via ProcessBlock.
func TestFullBlocks(t *testing.T) {
tests, err := fullblocktests.Generate(false)
if err != nil {
t.Fatalf("failed to generate tests: %v", err)
}
// Create a new database and chain instance to run tests against.
chain, teardownFunc, err := chainSetup("fullblocktest",
&chaincfg.RegressionNetParams)
if err != nil {
t.Errorf("Failed to setup chain instance: %v", err)
return
}
defer teardownFunc()
// testAcceptedBlock attempts to process the block in the provided test
// instance and ensures that it was accepted according to the flags
// specified in the test.
testAcceptedBlock := func(item fullblocktests.AcceptedBlock) {
blockHeight := item.Height
block := btcutil.NewBlock(item.Block)
block.SetHeight(blockHeight)
t.Logf("Testing block %s (hash %s, height %d)",
item.Name, block.Hash(), blockHeight)
isMainChain, isOrphan, err := chain.ProcessBlock(block,
blockchain.BFNone)
if err != nil {
t.Fatalf("block %q (hash %s, height %d) should "+
"have been accepted: %v", item.Name,
block.Hash(), blockHeight, err)
}
// Ensure the main chain and orphan flags match the values
// specified in the test.
if isMainChain != item.IsMainChain {
t.Fatalf("block %q (hash %s, height %d) unexpected main "+
"chain flag -- got %v, want %v", item.Name,
block.Hash(), blockHeight, isMainChain,
item.IsMainChain)
}
if isOrphan != item.IsOrphan {
t.Fatalf("block %q (hash %s, height %d) unexpected "+
"orphan flag -- got %v, want %v", item.Name,
block.Hash(), blockHeight, isOrphan,
item.IsOrphan)
}
}
// testRejectedBlock attempts to process the block in the provided test
// instance and ensures that it was rejected with the reject code
// specified in the test.
testRejectedBlock := func(item fullblocktests.RejectedBlock) {
blockHeight := item.Height
block := btcutil.NewBlock(item.Block)
block.SetHeight(blockHeight)
t.Logf("Testing block %s (hash %s, height %d)",
item.Name, block.Hash(), blockHeight)
_, _, err := chain.ProcessBlock(block, blockchain.BFNone)
if err == nil {
t.Fatalf("block %q (hash %s, height %d) should not "+
"have been accepted", item.Name, block.Hash(),
blockHeight)
}
// Ensure the error code is of the expected type and the reject
// code matches the value specified in the test instance.
rerr, ok := err.(blockchain.RuleError)
if !ok {
t.Fatalf("block %q (hash %s, height %d) returned "+
"unexpected error type -- got %T, want "+
"blockchain.RuleError", item.Name, block.Hash(),
blockHeight, err)
}
if rerr.ErrorCode != item.RejectCode {
t.Fatalf("block %q (hash %s, height %d) does not have "+
"expected reject code -- got %v, want %v",
item.Name, block.Hash(), blockHeight,
rerr.ErrorCode, item.RejectCode)
}
}
// testRejectedNonCanonicalBlock attempts to decode the block in the
// provided test instance and ensures that it failed to decode with a
// message error.
testRejectedNonCanonicalBlock := func(item fullblocktests.RejectedNonCanonicalBlock) {
headerLen := len(item.RawBlock)
if headerLen > 80 {
headerLen = 80
}
blockHash := chainhash.DoubleHashH(item.RawBlock[0:headerLen])
blockHeight := item.Height
t.Logf("Testing block %s (hash %s, height %d)", item.Name,
blockHash, blockHeight)
// Ensure there is an error due to deserializing the block.
var msgBlock wire.MsgBlock
err := msgBlock.BtcDecode(bytes.NewReader(item.RawBlock), 0, wire.BaseEncoding)
if _, ok := err.(*wire.MessageError); !ok {
t.Fatalf("block %q (hash %s, height %d) should have "+
"failed to decode", item.Name, blockHash,
blockHeight)
}
}
// testOrphanOrRejectedBlock attempts to process the block in the
// provided test instance and ensures that it was either accepted as an
// orphan or rejected with a rule violation.
testOrphanOrRejectedBlock := func(item fullblocktests.OrphanOrRejectedBlock) {
blockHeight := item.Height
block := btcutil.NewBlock(item.Block)
block.SetHeight(blockHeight)
t.Logf("Testing block %s (hash %s, height %d)",
item.Name, block.Hash(), blockHeight)
_, isOrphan, err := chain.ProcessBlock(block, blockchain.BFNone)
if err != nil {
// Ensure the error code is of the expected type.
if _, ok := err.(blockchain.RuleError); !ok {
t.Fatalf("block %q (hash %s, height %d) "+
"returned unexpected error type -- "+
"got %T, want blockchain.RuleError",
item.Name, block.Hash(), blockHeight,
err)
}
}
if !isOrphan {
t.Fatalf("block %q (hash %s, height %d) was accepted, "+
"but is not considered an orphan", item.Name,
block.Hash(), blockHeight)
}
}
// testExpectedTip ensures the current tip of the blockchain is the
// block specified in the provided test instance.
testExpectedTip := func(item fullblocktests.ExpectedTip) {
blockHeight := item.Height
block := btcutil.NewBlock(item.Block)
block.SetHeight(blockHeight)
t.Logf("Testing tip for block %s (hash %s, height %d)",
item.Name, block.Hash(), blockHeight)
// Ensure hash and height match.
best := chain.BestSnapshot()
if best.Hash != item.Block.BlockHash() ||
best.Height != blockHeight {
t.Fatalf("block %q (hash %s, height %d) should be "+
"the current tip -- got (hash %s, height %d)",
item.Name, block.Hash(), blockHeight, best.Hash,
best.Height)
}
}
for testNum, test := range tests {
for itemNum, item := range test {
switch item := item.(type) {
case fullblocktests.AcceptedBlock:
testAcceptedBlock(item)
case fullblocktests.RejectedBlock:
testRejectedBlock(item)
case fullblocktests.RejectedNonCanonicalBlock:
testRejectedNonCanonicalBlock(item)
case fullblocktests.OrphanOrRejectedBlock:
testOrphanOrRejectedBlock(item)
case fullblocktests.ExpectedTip:
testExpectedTip(item)
default:
t.Fatalf("test #%d, item #%d is not one of "+
"the supported test instance types -- "+
"got type: %T", testNum, itemNum, item)
}
}
}
}
| fileExists |
index.js | var express = require('express');
var router = express.Router();
const {
getClientConfig
} = require('./../../../config/config');
const {
getServerConfig
} = require('./../../../config/config');
/* GET index page. */
router.get('/', function (req, res, next) {
let {
APP_ID,
APP_SECRET,
CONNECT_URL,
CS_JS_SDK_URL,
CS_AC_SHIM_URL,
CS_VERSION,
ENABLE_JABRA_COLLECTION
} = getClientConfig();
const isProduction = getServerConfig().NODE_ENV === 'production' || getServerConfig().NODE_ENV === 'prod';
res.render('index', {
APP_ID: APP_ID,
APP_SECRET: APP_SECRET,
CONNECT_URL: CONNECT_URL,
CS_JS_SDK_URL: CS_JS_SDK_URL,
CS_AC_SHIM_URL: CS_AC_SHIM_URL,
IS_PRODUCTION: isProduction,
CS_VERSION: CS_VERSION,
ENABLE_JABRA_COLLECTION: ENABLE_JABRA_COLLECTION
});
});
module.exports = router; | ||
lib.rs | //! Retrieve type names during program execution on **stable** Rust.
#![doc(html_root_url = "https://docs.rs/crate/tyname/0.1.0")]
#[cfg(test)]
mod tests;
use std::fmt::Write;
/// The result type for this crate.
pub type Result = std::fmt::Result;
/// Types that implement this trait can write their name.
pub trait TypeName {
/// Applies the keccak hash of `self` for the given keccak hasher.
fn write_type_name<W>(writer: &mut W) -> Result
where
W: Write;
}
/// Returns the name of the given type.
pub fn type_name<T>() -> String
where
T: TypeName + ?Sized
{
let mut buffer = String::new();
T::write_type_name(&mut buffer)
.expect("[tyname::type_name] Encountered error while writing type name");
buffer
}
macro_rules! impl_tuple_signature_hash {
// Specialization for the unit type (void)
( ) => {
impl TypeName for () {
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str("()")
}
}
};
// Specialization for unary-tuples
( $head:ident ) => {
impl<$head> TypeName for ($head,)
where
$head: TypeName,
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str("(")?;
$head::write_type_name(w)?;
// Comma needed here to differentiate between
// parenthesized expressions and unary-tuples
w.write_str(",)")
}
}
impl_tuple_signature_hash!();
};
// Impl for generic tuples with at least two elements
( $head:ident $($tail:ident)+ ) => {
impl<$head, $($tail),*> TypeName for ( $head, $($tail),* )
where
$head: TypeName,
$( $tail: TypeName, )*
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str("(")?;
$head::write_type_name(w)?;
$(
w.write_str(", ")?;
$tail::write_type_name(w)?;
)*
w.write_str(")")
}
}
// Strip head and recurse the implementation.
impl_tuple_signature_hash!( $($tail)* );
}
}
impl_tuple_signature_hash!(
T0 T1 T2 T3 T4 T5 T6 T7 T8 T9
);
/// Implementation for raw function-pointer types.
///
/// # Note
///
/// The current implementation outputs the return type even for
/// functions that have a unit (`()`) return type and thus should
/// not display it - at least that's the behaviour of the intrinsic.
/// E.g. this currently writes `fn() -> ()` instead of just `fn()`.
macro_rules! impl_fn_signature_hash {
// Base case for no parameter types.
( $ret:ident ) => {
impl<$ret> TypeName for fn() -> $ret
where
$ret: TypeName
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str("fn() -> ")?;
$ret::write_type_name(w)
}
}
};
// Impl for generic parameters and return type.
( $ret:ident $head:ident $($tail:ident)* ) => {
impl<$ret, $head, $($tail),*> TypeName for fn($head, $($tail),*) -> $ret
where
$ret: TypeName,
$head: TypeName,
$( $tail: TypeName, )*
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str("fn(")?;
$head::write_type_name(w)?;
$(
w.write_str(",")?;
$tail::write_type_name(w)?;
)*
w.write_str(") -> ")?;
$ret::write_type_name(w)
}
}
// Strip head type and recurse to simplify caller.
impl_fn_signature_hash!( $ret $($tail)* );
}
}
impl_fn_signature_hash!(
T0 T1 T2 T3 T4 T5 T6 T7 T8 T9
);
macro_rules! impl_array_signature_hash {
( $($n:expr)* ) => {
$(
impl<T> TypeName for [T; $n]
where
T: TypeName
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str("[")?;
T::write_type_name(w)?;
w.write_str("; ")?;
write!(w, "{}", $n)?;
w.write_str("]")
}
}
)*
};
}
impl_array_signature_hash!(
// All from 1 to 32
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32
// Powers of two
64 128 256 512 1024 2048 4096
// Some specialized array lengths
160 192
);
impl<T> TypeName for [T]
where
T: TypeName
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str("[")?;
T::write_type_name(w)?;
w.write_str("]")
}
}
/// Implementation macro for raw-pointers and references.
macro_rules! impl_ptrref_signature_hash {
( $prefix:expr, $($ty:tt)+ ) => {
impl<T> TypeName for $($ty)+ T
where
T: TypeName + ?Sized
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str($prefix)?;
T::write_type_name(w)
}
}
}
}
impl_ptrref_signature_hash!("&", &);
impl_ptrref_signature_hash!("&mut ", &mut);
impl_ptrref_signature_hash!("*const ", *const);
impl_ptrref_signature_hash!("*mut ", *mut);
macro_rules! impl_smartptr_signature_hash {
( $head:ident $(:: $seg:ident)* , $repr:expr ) => {
impl<T> TypeName for $head $(:: $seg)* <T>
where
T: TypeName + ?Sized
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str($repr)?;
w.write_str("<")?;
T::write_type_name(w)?;
w.write_str(">")
}
}
}
}
impl_smartptr_signature_hash!(Box, "Box");
impl_smartptr_signature_hash!(std::rc::Rc, "Rc");
impl_smartptr_signature_hash!(std::sync::Arc, "Arc");
macro_rules! impl_collections_signature_hash {
( $head:ident $(:: $seg:ident)* , $repr:expr ) => {
impl<T> TypeName for $head $(:: $seg)* <T>
where
T: TypeName
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str($repr)?;
w.write_str("<")?;
T::write_type_name(w)?;
w.write_str(">")
}
}
}
}
impl_collections_signature_hash!( Option, "Option" );
impl_collections_signature_hash!( Vec, "Vec" );
impl_collections_signature_hash!( std::collections::VecDeque, "VecDeque" );
impl_collections_signature_hash!( std::collections::LinkedList, "LinkedList" ); | E: TypeName,
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str("Result<")?;
T::write_type_name(w)?;
w.write_str(", ")?;
E::write_type_name(w)?;
w.write_str(">")
}
}
impl<'a, B> TypeName for std::borrow::Cow<'a, B>
where
B: 'a + ToOwned + ?Sized + TypeName
{
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str("Cow<")?;
B::write_type_name(w)?;
w.write_str(">")
}
}
macro_rules! impl_naive_signature_hash {
( $ty:ident, $repr:expr ) => {
impl TypeName for $ty {
fn write_type_name<W>(w: &mut W) -> Result where W: Write {
w.write_str($repr)
}
}
}
}
impl_naive_signature_hash!(String, "String");
impl_naive_signature_hash!(str, "str");
impl_naive_signature_hash!(bool, "bool");
impl_naive_signature_hash!(char, "char");
impl_naive_signature_hash!(u8, "u8");
impl_naive_signature_hash!(u16, "u16");
impl_naive_signature_hash!(u32, "u32");
impl_naive_signature_hash!(u64, "u64");
impl_naive_signature_hash!(u128, "u128");
impl_naive_signature_hash!(usize, "usize");
impl_naive_signature_hash!(i8, "i8");
impl_naive_signature_hash!(i16, "i16");
impl_naive_signature_hash!(i32, "i32");
impl_naive_signature_hash!(i64, "i64");
impl_naive_signature_hash!(i128, "i128");
impl_naive_signature_hash!(isize, "isize");
impl_naive_signature_hash!(f32, "f32");
impl_naive_signature_hash!(f64, "f64"); |
impl<T, E> TypeName for std::result::Result<T, E>
where
T: TypeName, |
syscall_linux_amd64.go | // Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package syscall
const (
_SYS_dup = SYS_DUP2
_SYS_setgroups = SYS_SETGROUPS
)
//sys Dup2(oldfd int, newfd int) (err error)
//sys Fchown(fd int, uid int, gid int) (err error)
//sys Fstat(fd int, stat *Stat_t) (err error)
//sys Fstatfs(fd int, buf *Statfs_t) (err error)
//sys Ftruncate(fd int, length int64) (err error)
//sysnb Getegid() (egid int)
//sysnb Geteuid() (euid int)
//sysnb Getgid() (gid int)
//sysnb Getrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Getuid() (uid int)
//sysnb InotifyInit() (fd int, err error)
//sys Ioperm(from int, num int, on int) (err error)
//sys Iopl(level int) (err error)
//sys Listen(s int, n int) (err error)
//sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64
//sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK
//sys Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error)
//sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error)
//sys Setfsgid(gid int) (err error)
//sys Setfsuid(uid int) (err error)
//sysnb Setregid(rgid int, egid int) (err error)
//sysnb Setresgid(rgid int, egid int, sgid int) (err error)
//sysnb Setresuid(ruid int, euid int, suid int) (err error)
//sysnb Setrlimit(resource int, rlim *Rlimit) (err error)
//sysnb Setreuid(ruid int, euid int) (err error)
//sys Shutdown(fd int, how int) (err error)
//sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error)
//sys Statfs(path string, buf *Statfs_t) (err error)
//sys SyncFileRange(fd int, off int64, n int64, flags int) (err error)
//sys Truncate(path string, length int64) (err error)
//sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error)
//sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error)
//sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error)
//sys fstatat(fd int, path string, stat *Stat_t, flags int) (err error) = SYS_NEWFSTATAT
//sysnb getgroups(n int, list *_Gid_t) (nn int, err error)
//sysnb setgroups(n int, list *_Gid_t) (err error)
//sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error)
//sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error)
//sysnb socket(domain int, typ int, proto int) (fd int, err error)
//sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error)
//sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error)
//sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error)
//sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error)
//sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error)
//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
//sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error)
func Stat(path string, stat *Stat_t) (err error) {
return fstatat(_AT_FDCWD, path, stat, 0)
}
func Lchown(path string, uid int, gid int) (err error) {
return Fchownat(_AT_FDCWD, path, uid, gid, _AT_SYMLINK_NOFOLLOW)
}
func Lstat(path string, stat *Stat_t) (err error) {
return fstatat(_AT_FDCWD, path, stat, _AT_SYMLINK_NOFOLLOW)
}
//go:noescape
func gettimeofday(tv *Timeval) (err Errno)
func Gettimeofday(tv *Timeval) (err error) {
errno := gettimeofday(tv)
if errno != 0 {
return errno
}
return nil
}
func Time(t *Time_t) (tt Time_t, err error) {
var tv Timeval
errno := gettimeofday(&tv)
if errno != 0 {
return 0, errno
}
if t != nil {
*t = Time_t(tv.Sec)
}
return Time_t(tv.Sec), nil
}
func | (sec, nsec int64) Timespec {
return Timespec{Sec: sec, Nsec: nsec}
}
func setTimeval(sec, usec int64) Timeval {
return Timeval{Sec: sec, Usec: usec}
}
//sysnb pipe(p *[2]_C_int) (err error)
func Pipe(p []int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe(&pp)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
//sysnb pipe2(p *[2]_C_int, flags int) (err error)
func Pipe2(p []int, flags int) (err error) {
if len(p) != 2 {
return EINVAL
}
var pp [2]_C_int
err = pipe2(&pp, flags)
p[0] = int(pp[0])
p[1] = int(pp[1])
return
}
func (r *PtraceRegs) PC() uint64 { return r.Rip }
func (r *PtraceRegs) SetPC(pc uint64) { r.Rip = pc }
func (iov *Iovec) SetLen(length int) {
iov.Len = uint64(length)
}
func (msghdr *Msghdr) SetControllen(length int) {
msghdr.Controllen = uint64(length)
}
func (cmsg *Cmsghdr) SetLen(length int) {
cmsg.Len = uint64(length)
}
func rawVforkSyscall(trap, a1 uintptr) (r1 uintptr, err Errno)
| setTimespec |
cloud_scheduler_client_example_test.go | // Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// AUTO-GENERATED CODE. DO NOT EDIT.
package scheduler_test
import (
"context"
scheduler "cloud.google.com/go/scheduler/apiv1beta1"
"google.golang.org/api/iterator"
schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1beta1"
)
func ExampleNewCloudSchedulerClient() {
ctx := context.Background()
c, err := scheduler.NewCloudSchedulerClient(ctx)
if err != nil {
// TODO: Handle error.
}
// TODO: Use client.
_ = c
}
func ExampleCloudSchedulerClient_ListJobs() {
ctx := context.Background()
c, err := scheduler.NewCloudSchedulerClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &schedulerpb.ListJobsRequest{
// TODO: Fill request struct fields.
}
it := c.ListJobs(ctx, req)
for {
resp, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
}
func ExampleCloudSchedulerClient_GetJob() {
ctx := context.Background()
c, err := scheduler.NewCloudSchedulerClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &schedulerpb.GetJobRequest{
// TODO: Fill request struct fields.
}
resp, err := c.GetJob(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
func ExampleCloudSchedulerClient_CreateJob() {
ctx := context.Background()
c, err := scheduler.NewCloudSchedulerClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &schedulerpb.CreateJobRequest{
// TODO: Fill request struct fields.
}
resp, err := c.CreateJob(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
func ExampleCloudSchedulerClient_UpdateJob() {
ctx := context.Background()
c, err := scheduler.NewCloudSchedulerClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &schedulerpb.UpdateJobRequest{
// TODO: Fill request struct fields.
}
resp, err := c.UpdateJob(ctx, req)
if err != nil |
// TODO: Use resp.
_ = resp
}
func ExampleCloudSchedulerClient_DeleteJob() {
ctx := context.Background()
c, err := scheduler.NewCloudSchedulerClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &schedulerpb.DeleteJobRequest{
// TODO: Fill request struct fields.
}
err = c.DeleteJob(ctx, req)
if err != nil {
// TODO: Handle error.
}
}
func ExampleCloudSchedulerClient_PauseJob() {
ctx := context.Background()
c, err := scheduler.NewCloudSchedulerClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &schedulerpb.PauseJobRequest{
// TODO: Fill request struct fields.
}
resp, err := c.PauseJob(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
func ExampleCloudSchedulerClient_ResumeJob() {
ctx := context.Background()
c, err := scheduler.NewCloudSchedulerClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &schedulerpb.ResumeJobRequest{
// TODO: Fill request struct fields.
}
resp, err := c.ResumeJob(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
func ExampleCloudSchedulerClient_RunJob() {
ctx := context.Background()
c, err := scheduler.NewCloudSchedulerClient(ctx)
if err != nil {
// TODO: Handle error.
}
req := &schedulerpb.RunJobRequest{
// TODO: Fill request struct fields.
}
resp, err := c.RunJob(ctx, req)
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
| {
// TODO: Handle error.
} |
blockchain_fetcher.go | package fetcher
import (
"encoding/json"
"errors"
"io"
"io/ioutil"
"log"
"math/big"
"net/http"
// "strconv"
"github.com/KyberNetwork/server-go/ethereum"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/rpc"
)
type BlockchainFetcher struct {
client *rpc.Client
url string
TypeName string
}
func | (typeName string, endpoint string, apiKey string) (*BlockchainFetcher, error) {
client, err := rpc.DialHTTP(endpoint)
if err != nil {
log.Print(err)
return nil, err
}
blockchain := BlockchainFetcher{
client, endpoint, typeName,
}
return &blockchain, nil
}
func (self *BlockchainFetcher) EthCall(to string, data string) (string, error) {
params := make(map[string]string)
params["data"] = "0x" + data
params["to"] = to
var result string
err := self.client.Call(&result, "eth_call", params, "latest")
if err != nil {
log.Print(err)
return "", err
}
return result, nil
}
func (self *BlockchainFetcher) GetLatestBlock() (string, error) {
var blockNum *hexutil.Big
err := self.client.Call(&blockNum, "eth_blockNumber", "latest")
if err != nil {
return "", err
}
return blockNum.ToInt().String(), nil
}
type TopicParam struct {
FromBlock string `json:"fromBlock"`
ToBlock string `json:"toBlock"`
Address string `json:"address"`
Topics []string `json:"topics"`
}
// func (self *BlockchainFetcher) GetEvents(fromBlock string, toBlock string, network string, tradeTopic string) (*[]ethereum.EventRaw, error) {
// fromBlockInt, err := strconv.ParseUint(fromBlock, 10, 64)
// if err != nil {
// log.Print(err)
// return nil, err
// }
// toBlockInt, err := strconv.ParseUint(toBlock, 10, 64)
// if err != nil {
// log.Print(err)
// return nil, err
// }
// fromBlockHex := hexutil.EncodeUint64(fromBlockInt)
// toBlockHex := hexutil.EncodeUint64(toBlockInt)
// param := TopicParam{
// fromBlockHex, toBlockHex, network, []string{tradeTopic},
// }
// var result []ethereum.EventRaw
// err = self.client.Call(&result, "eth_getLogs", param)
// if err != nil {
// log.Print(err)
// return nil, err
// }
// return &result, nil
// }
func (self *BlockchainFetcher) GetRateUsd(tickers []string) ([]io.ReadCloser, error) {
outPut := make([]io.ReadCloser, 0)
for _, ticker := range tickers {
response, err := http.Get("https://api.coinmarketcap.com/v1/ticker/" + ticker)
if err != nil {
log.Print(err)
return nil, err
}
outPut = append(outPut, response.Body)
}
return outPut, nil
}
func (self *BlockchainFetcher) GetTypeName() string {
return self.TypeName
}
func (self *BlockchainFetcher) GetGasPrice() (*ethereum.GasPrice, error) {
response, err := http.Get("https://ethgasstation.info/json/ethgasAPI.json")
if err != nil {
log.Print(err)
return nil, err
}
if response.StatusCode != 200 {
return nil, errors.New("Status code is 200")
}
defer (response.Body).Close()
b, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Print(err)
return nil, err
}
var gasPrice GasStation
err = json.Unmarshal(b, &gasPrice)
if err != nil {
log.Print(err)
return nil, err
}
fast := big.NewFloat(gasPrice.Fast / 10)
standard := big.NewFloat((gasPrice.Fast + gasPrice.Standard) / 20)
low := big.NewFloat(gasPrice.Low / 10)
defaultGas := standard
return ðereum.GasPrice{
fast.String(), standard.String(), low.String(), defaultGas.String(),
}, nil
}
func (self *BlockchainFetcher) GetRateUsdEther() (string, error) {
response, err := http.Get("https://api.coinmarketcap.com/v1/ticker/ethereum")
if err != nil {
log.Print(err)
return "", err
}
defer (response.Body).Close()
b, err := ioutil.ReadAll(response.Body)
if err != nil {
log.Print(err)
return "", err
}
rateItem := make([]RateUSD, 0)
err = json.Unmarshal(b, &rateItem)
if err != nil {
log.Print(err)
return "", err
}
return rateItem[0].PriceUsd, nil
}
func (self *BlockchainFetcher) GetGeneralInfo(usdId string) (*ethereum.TokenGeneralInfo, error) {
err := errors.New("Blockchain is not support this api")
//log.Print(err)
return nil, err
}
func (self *BlockchainFetcher) GetTrackerData(trackerEndpoint string) (map[string]*ethereum.Rates, error) {
trackerData := map[string]*ethereum.Rates{}
err := errors.New("Blockchain is not support this api")
//log.Print(err)
return trackerData, err
}
| NewBlockchainFetcher |
Footer.js | import React from 'react';
class Footer extends React.Component{
render(){
let styles = {
fontSize: '18px',
color: '#fff',
backgroundColor: '#607D8B',
fontWeight: 'bold',
padding: '20px 10px',
marginTop: '30px',
textAlign: 'right'
}
return(
<div style={styles}>
XX公司
</div>
)
} | }
export default Footer; |
|
ediscoveryroot.go | package ediscovery
import (
i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91 "github.com/microsoft/kiota-abstractions-go/serialization"
ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be "github.com/microsoftgraph/msgraph-beta-sdk-go/models"
)
// Ediscoveryroot
type Ediscoveryroot struct {
ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.Entity
// The cases property
cases []Case_escapedable
}
// NewEdiscoveryroot instantiates a new ediscoveryroot and sets the default values.
func NewEdiscoveryroot()(*Ediscoveryroot) {
m := &Ediscoveryroot{
Entity: *ie233ee762e29b4ba6970aa2a2efce4b7fde11697ca9ea81099d0f8269309c1be.NewEntity(),
}
return m
}
// CreateEdiscoveryrootFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
func CreateEdiscoveryrootFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewEdiscoveryroot(), nil
}
// GetCases gets the cases property value. The cases property
func (m *Ediscoveryroot) GetCases()([]Case_escapedable) {
if m == nil {
return nil
} else {
return m.cases
}
}
// GetFieldDeserializers the deserialization information for the current model
func (m *Ediscoveryroot) GetFieldDeserializers()(map[string]func(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(error)) {
res := m.Entity.GetFieldDeserializers()
res["cases"] = func (n i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode) error {
val, err := n.GetCollectionOfObjectValues(CreateCase_escapedFromDiscriminatorValue)
if err != nil {
return err
}
if val != nil {
res := make([]Case_escapedable, len(val))
for i, v := range val {
res[i] = v.(Case_escapedable)
}
m.SetCases(res)
}
return nil
}
return res
}
// Serialize serializes information the current object
func (m *Ediscoveryroot) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {
err := m.Entity.Serialize(writer)
if err != nil {
return err
}
if m.GetCases() != nil {
cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCases()))
for i, v := range m.GetCases() {
cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)
}
err = writer.WriteCollectionOfObjectValues("cases", cast)
if err != nil {
return err
} | func (m *Ediscoveryroot) SetCases(value []Case_escapedable)() {
if m != nil {
m.cases = value
}
} | }
return nil
}
// SetCases sets the cases property value. The cases property |
purchasable_state.py | # coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file
# except in compliance with the License. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file 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 pprint
import re # noqa: F401
import six
import typing
from enum import Enum
if typing.TYPE_CHECKING:
from typing import Dict, List, Optional, Union, Any
from datetime import datetime
class PurchasableState(Enum):
"""
Whether or not the in-skill product is purchasable by customers. A product that is not purchasable will prevent new customers from being prompted to purchase the product. Customers who already own the product will see no effect and continue to have access to the product features.
Allowed enum values: [PURCHASABLE, NOT_PURCHASABLE]
"""
PURCHASABLE = "PURCHASABLE"
NOT_PURCHASABLE = "NOT_PURCHASABLE"
def to_dict(self):
# type: () -> Dict[str, Any]
|
def to_str(self):
# type: () -> str
"""Returns the string representation of the model"""
return pprint.pformat(self.value)
def __repr__(self):
# type: () -> str
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
# type: (Any) -> bool
"""Returns true if both objects are equal"""
if not isinstance(other, PurchasableState):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
# type: (Any) -> bool
"""Returns true if both objects are not equal"""
return not self == other
| """Returns the model properties as a dict"""
result = {self.name: self.value}
return result |
iterator.rs | // Copyright 2013-2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use cmp::Ordering;
use ops::Try;
use super::LoopState;
use super::{Chain, Cycle, Cloned, Enumerate, Filter, FilterMap, Fuse};
use super::{Flatten, FlatMap, flatten_compat};
use super::{Inspect, Map, Peekable, Scan, Skip, SkipWhile, StepBy, Take, TakeWhile, Rev};
use super::{Zip, Sum, Product};
use super::{ChainState, FromIterator, ZipImpl};
fn _assert_is_object_safe(_: &dyn Iterator<Item=()>) {}
/// An interface for dealing with iterators.
///
/// This is the main iterator trait. For more about the concept of iterators
/// generally, please see the [module-level documentation]. In particular, you
/// may want to know how to [implement `Iterator`][impl].
///
/// [module-level documentation]: index.html
/// [impl]: index.html#implementing-iterator
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_on_unimplemented(
on(
_Self="[std::ops::Range<Idx>; 1]",
label="if you meant to iterate between two values, remove the square brackets",
note="`[start..end]` is an array of one `Range`; you might have meant to have a `Range` \
without the brackets: `start..end`"
),
on(
_Self="[std::ops::RangeFrom<Idx>; 1]",
label="if you meant to iterate from a value onwards, remove the square brackets",
note="`[start..]` is an array of one `RangeFrom`; you might have meant to have a \
`RangeFrom` without the brackets: `start..`, keeping in mind that iterating over an \
unbounded iterator will run forever unless you `break` or `return` from within the \
loop"
),
on(
_Self="[std::ops::RangeTo<Idx>; 1]",
label="if you meant to iterate until a value, remove the square brackets and add a \
starting value",
note="`[..end]` is an array of one `RangeTo`; you might have meant to have a bounded \
`Range` without the brackets: `0..end`"
),
on(
_Self="[std::ops::RangeInclusive<Idx>; 1]",
label="if you meant to iterate between two values, remove the square brackets",
note="`[start..=end]` is an array of one `RangeInclusive`; you might have meant to have a \
`RangeInclusive` without the brackets: `start..=end`"
),
on(
_Self="[std::ops::RangeToInclusive<Idx>; 1]",
label="if you meant to iterate until a value (including it), remove the square brackets \
and add a starting value",
note="`[..=end]` is an array of one `RangeToInclusive`; you might have meant to have a \
bounded `RangeInclusive` without the brackets: `0..=end`"
),
on(
_Self="std::ops::RangeTo<Idx>",
label="if you meant to iterate until a value, add a starting value",
note="`..end` is a `RangeTo`, which cannot be iterated on; you might have meant to have a \
bounded `Range`: `0..end`"
),
on(
_Self="std::ops::RangeToInclusive<Idx>",
label="if you meant to iterate until a value (including it), add a starting value",
note="`..=end` is a `RangeToInclusive`, which cannot be iterated on; you might have meant \
to have a bounded `RangeInclusive`: `0..=end`"
),
on(
_Self="&str",
label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
),
on(
_Self="std::string::String",
label="`{Self}` is not an iterator; try calling `.chars()` or `.bytes()`"
),
on(
_Self="[]",
label="borrow the array with `&` or call `.iter()` on it to iterate over it",
note="arrays are not iterators, but slices like the following are: `&[1, 2, 3]`"
),
on(
_Self="{integral}",
note="if you want to iterate between `start` until a value `end`, use the exclusive range \
syntax `start..end` or the inclusive range syntax `start..=end`"
),
label="`{Self}` is not an iterator",
message="`{Self}` is not an iterator"
)]
#[doc(spotlight)]
#[must_use]
pub trait Iterator {
/// The type of the elements being iterated over.
#[stable(feature = "rust1", since = "1.0.0")]
type Item;
/// Advances the iterator and returns the next value.
///
/// Returns [`None`] when iteration is finished. Individual iterator
/// implementations may choose to resume iteration, and so calling `next()`
/// again may or may not eventually start returning [`Some(Item)`] again at some
/// point.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
/// [`Some(Item)`]: ../../std/option/enum.Option.html#variant.Some
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// // A call to next() returns the next value...
/// assert_eq!(Some(&1), iter.next());
/// assert_eq!(Some(&2), iter.next());
/// assert_eq!(Some(&3), iter.next());
///
/// // ... and then None once it's over.
/// assert_eq!(None, iter.next());
///
/// // More calls may or may not return None. Here, they always will.
/// assert_eq!(None, iter.next());
/// assert_eq!(None, iter.next());
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn next(&mut self) -> Option<Self::Item>;
/// Returns the bounds on the remaining length of the iterator.
///
/// Specifically, `size_hint()` returns a tuple where the first element
/// is the lower bound, and the second element is the upper bound.
///
/// The second half of the tuple that is returned is an [`Option`]`<`[`usize`]`>`.
/// A [`None`] here means that either there is no known upper bound, or the
/// upper bound is larger than [`usize`].
///
/// # Implementation notes
///
/// It is not enforced that an iterator implementation yields the declared
/// number of elements. A buggy iterator may yield less than the lower bound
/// or more than the upper bound of elements.
///
/// `size_hint()` is primarily intended to be used for optimizations such as
/// reserving space for the elements of the iterator, but must not be
/// trusted to e.g., omit bounds checks in unsafe code. An incorrect
/// implementation of `size_hint()` should not lead to memory safety
/// violations.
///
/// That said, the implementation should provide a correct estimation,
/// because otherwise it would be a violation of the trait's protocol.
///
/// The default implementation returns `(0, None)` which is correct for any
/// iterator.
///
/// [`usize`]: ../../std/primitive.usize.html
/// [`Option`]: ../../std/option/enum.Option.html
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// let iter = a.iter();
///
/// assert_eq!((3, Some(3)), iter.size_hint());
/// ```
///
/// A more complex example:
///
/// ```
/// // The even numbers from zero to ten.
/// let iter = (0..10).filter(|x| x % 2 == 0);
///
/// // We might iterate from zero to ten times. Knowing that it's five
/// // exactly wouldn't be possible without executing filter().
/// assert_eq!((0, Some(10)), iter.size_hint());
///
/// // Let's add five more numbers with chain()
/// let iter = (0..10).filter(|x| x % 2 == 0).chain(15..20);
///
/// // now both bounds are increased by five
/// assert_eq!((5, Some(15)), iter.size_hint());
/// ```
///
/// Returning `None` for an upper bound:
///
/// ```
/// // an infinite iterator has no upper bound
/// // and the maximum possible lower bound
/// let iter = 0..;
///
/// assert_eq!((usize::max_value(), None), iter.size_hint());
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn size_hint(&self) -> (usize, Option<usize>) { (0, None) }
/// Consumes the iterator, counting the number of iterations and returning it.
///
/// This method will evaluate the iterator until its [`next`] returns
/// [`None`]. Once [`None`] is encountered, `count()` returns the number of
/// times it called [`next`].
///
/// [`next`]: #tymethod.next
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so counting elements of
/// an iterator with more than [`usize::MAX`] elements either produces the
/// wrong result or panics. If debug assertions are enabled, a panic is
/// guaranteed.
///
/// # Panics
///
/// This function might panic if the iterator has more than [`usize::MAX`]
/// elements.
///
/// [`usize::MAX`]: ../../std/usize/constant.MAX.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().count(), 3);
///
/// let a = [1, 2, 3, 4, 5];
/// assert_eq!(a.iter().count(), 5);
/// ```
#[inline]
#[rustc_inherit_overflow_checks]
#[stable(feature = "rust1", since = "1.0.0")]
fn count(self) -> usize where Self: Sized {
// Might overflow.
self.fold(0, |cnt, _| cnt + 1)
}
/// Consumes the iterator, returning the last element.
///
/// This method will evaluate the iterator until it returns [`None`]. While
/// doing so, it keeps track of the current element. After [`None`] is
/// returned, `last()` will then return the last element it saw.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().last(), Some(&3));
///
/// let a = [1, 2, 3, 4, 5];
/// assert_eq!(a.iter().last(), Some(&5));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn last(self) -> Option<Self::Item> where Self: Sized {
let mut last = None;
for x in self { last = Some(x); }
last
}
/// Returns the `n`th element of the iterator.
///
/// Like most indexing operations, the count starts from zero, so `nth(0)`
/// returns the first value, `nth(1)` the second, and so on.
///
/// Note that all preceding elements, as well as the returned element, will be
/// consumed from the iterator. That means that the preceding elements will be
/// discarded, and also that calling `nth(0)` multiple times on the same iterator
/// will return different elements.
///
/// `nth()` will return [`None`] if `n` is greater than or equal to the length of the
/// iterator.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().nth(1), Some(&2));
/// ```
///
/// Calling `nth()` multiple times doesn't rewind the iterator:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert_eq!(iter.nth(1), Some(&2));
/// assert_eq!(iter.nth(1), None);
/// ```
///
/// Returning `None` if there are less than `n + 1` elements:
///
/// ```
/// let a = [1, 2, 3];
/// assert_eq!(a.iter().nth(10), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn nth(&mut self, mut n: usize) -> Option<Self::Item> {
for x in self {
if n == 0 { return Some(x) }
n -= 1;
}
None
}
/// Creates an iterator starting at the same point, but stepping by
/// the given amount at each iteration.
///
/// Note 1: The first element of the iterator will always be returned,
/// regardless of the step given.
///
/// Note 2: The time at which ignored elements are pulled is not fixed.
/// `StepBy` behaves like the sequence `next(), nth(step-1), nth(step-1), …`,
/// but is also free to behave like the sequence
/// `advance_n_and_return_first(step), advance_n_and_return_first(step), …`
/// Which way is used may change for some iterators for performance reasons.
/// The second way will advance the iterator earlier and may consume more items.
///
/// `advance_n_and_return_first` is the equivalent of:
/// ```
/// fn advance_n_and_return_first<I>(iter: &mut I, total_step: usize) -> Option<I::Item>
/// where
/// I: Iterator,
/// {
/// let next = iter.next();
/// if total_step > 1 {
/// iter.nth(total_step-2);
/// }
/// next
/// }
/// ```
///
/// # Panics
///
/// The method will panic if the given step is `0`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [0, 1, 2, 3, 4, 5];
/// let mut iter = a.into_iter().step_by(2);
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&4));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "iterator_step_by", since = "1.28.0")]
fn step_by(self, step: usize) -> StepBy<Self> where Self: Sized {
assert!(step != 0);
StepBy{iter: self, step: step - 1, first_take: true}
}
/// Takes two iterators and creates a new iterator over both in sequence.
///
/// `chain()` will return a new iterator which will first iterate over
/// values from the first iterator and then over values from the second
/// iterator.
///
/// In other words, it links two iterators together, in a chain. 🔗
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a1 = [1, 2, 3];
/// let a2 = [4, 5, 6];
///
/// let mut iter = a1.iter().chain(a2.iter());
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), Some(&4));
/// assert_eq!(iter.next(), Some(&5));
/// assert_eq!(iter.next(), Some(&6));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Since the argument to `chain()` uses [`IntoIterator`], we can pass
/// anything that can be converted into an [`Iterator`], not just an
/// [`Iterator`] itself. For example, slices (`&[T]`) implement
/// [`IntoIterator`], and so can be passed to `chain()` directly:
///
/// [`IntoIterator`]: trait.IntoIterator.html
/// [`Iterator`]: trait.Iterator.html
///
/// ```
/// let s1 = &[1, 2, 3];
/// let s2 = &[4, 5, 6];
///
/// let mut iter = s1.iter().chain(s2);
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), Some(&4));
/// assert_eq!(iter.next(), Some(&5));
/// assert_eq!(iter.next(), Some(&6));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn chain<U>(self, other: U) -> Chain<Self, U::IntoIter> where
Self: Sized, U: IntoIterator<Item=Self::Item>,
{
Chain{a: self, b: other.into_iter(), state: ChainState::Both}
}
/// 'Zips up' two iterators into a single iterator of pairs.
///
/// `zip()` returns a new iterator that will iterate over two other
/// iterators, returning a tuple where the first element comes from the
/// first iterator, and the second element comes from the second iterator.
///
/// In other words, it zips two iterators together, into a single one.
///
/// If either iterator returns [`None`], [`next`] from the zipped iterator
/// will return [`None`]. If the first iterator returns [`None`], `zip` will
/// short-circuit and `next` will not be called on the second iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a1 = [1, 2, 3];
/// let a2 = [4, 5, 6];
///
/// let mut iter = a1.iter().zip(a2.iter());
///
/// assert_eq!(iter.next(), Some((&1, &4)));
/// assert_eq!(iter.next(), Some((&2, &5)));
/// assert_eq!(iter.next(), Some((&3, &6)));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Since the argument to `zip()` uses [`IntoIterator`], we can pass
/// anything that can be converted into an [`Iterator`], not just an
/// [`Iterator`] itself. For example, slices (`&[T]`) implement
/// [`IntoIterator`], and so can be passed to `zip()` directly:
///
/// [`IntoIterator`]: trait.IntoIterator.html
/// [`Iterator`]: trait.Iterator.html
///
/// ```
/// let s1 = &[1, 2, 3];
/// let s2 = &[4, 5, 6];
///
/// let mut iter = s1.iter().zip(s2);
///
/// assert_eq!(iter.next(), Some((&1, &4)));
/// assert_eq!(iter.next(), Some((&2, &5)));
/// assert_eq!(iter.next(), Some((&3, &6)));
/// assert_eq!(iter.next(), None);
/// ```
///
/// `zip()` is often used to zip an infinite iterator to a finite one.
/// This works because the finite iterator will eventually return [`None`],
/// ending the zipper. Zipping with `(0..)` can look a lot like [`enumerate`]:
///
/// ```
/// let enumerate: Vec<_> = "foo".chars().enumerate().collect();
///
/// let zipper: Vec<_> = (0..).zip("foo".chars()).collect();
///
/// assert_eq!((0, 'f'), enumerate[0]);
/// assert_eq!((0, 'f'), zipper[0]);
///
/// assert_eq!((1, 'o'), enumerate[1]);
/// assert_eq!((1, 'o'), zipper[1]);
///
/// assert_eq!((2, 'o'), enumerate[2]);
/// assert_eq!((2, 'o'), zipper[2]);
/// ```
///
/// [`enumerate`]: trait.Iterator.html#method.enumerate
/// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
/// [`None`]: ../../std/option/enum.Option.html#variant.None
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn zip<U>(self, other: U) -> Zip<Self, U::IntoIter> where
Self: Sized, U: IntoIterator
{
Zip::new(self, other.into_iter())
}
/// Takes a closure and creates an iterator which calls that closure on each
/// element.
///
/// `map()` transforms one iterator into another, by means of its argument:
/// something that implements [`FnMut`]. It produces a new iterator which
/// calls this closure on each element of the original iterator.
///
/// If you are good at thinking in types, you can think of `map()` like this:
/// If you have an iterator that gives you elements of some type `A`, and
/// you want an iterator of some other type `B`, you can use `map()`,
/// passing a closure that takes an `A` and returns a `B`.
///
/// `map()` is conceptually similar to a [`for`] loop. However, as `map()` is
/// lazy, it is best used when you're already working with other iterators.
/// If you're doing some sort of looping for a side effect, it's considered
/// more idiomatic to use [`for`] than `map()`.
///
/// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
/// [`FnMut`]: ../../std/ops/trait.FnMut.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.into_iter().map(|x| 2 * x);
///
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.next(), Some(6));
/// assert_eq!(iter.next(), None);
/// ```
///
/// If you're doing some sort of side effect, prefer [`for`] to `map()`:
///
/// ```
/// # #![allow(unused_must_use)]
/// // don't do this:
/// (0..5).map(|x| println!("{}", x));
///
/// // it won't even execute, as it is lazy. Rust will warn you about this.
///
/// // Instead, use for:
/// for x in 0..5 {
/// println!("{}", x);
/// }
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn map<B, F>(self, f: F) -> Map<Self, F> where
Self: Sized, F: FnMut(Self::Item) -> B,
{
Map { iter: self, f }
}
/// Calls a closure on each element of an iterator.
///
/// This is equivalent to using a [`for`] loop on the iterator, although
/// `break` and `continue` are not possible from a closure. It's generally
/// more idiomatic to use a `for` loop, but `for_each` may be more legible
/// when processing items at the end of longer iterator chains. In some
/// cases `for_each` may also be faster than a loop, because it will use
/// internal iteration on adaptors like `Chain`.
///
/// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// use std::sync::mpsc::channel;
///
/// let (tx, rx) = channel();
/// (0..5).map(|x| x * 2 + 1)
/// .for_each(move |x| tx.send(x).unwrap());
///
/// let v: Vec<_> = rx.iter().collect();
/// assert_eq!(v, vec![1, 3, 5, 7, 9]);
/// ```
///
/// For such a small example, a `for` loop may be cleaner, but `for_each`
/// might be preferable to keep a functional style with longer iterators:
///
/// ```
/// (0..5).flat_map(|x| x * 100 .. x * 110)
/// .enumerate()
/// .filter(|&(i, x)| (i + x) % 3 == 0)
/// .for_each(|(i, x)| println!("{}:{}", i, x));
/// ```
#[inline]
#[stable(feature = "iterator_for_each", since = "1.21.0")]
fn for_each<F>(self, mut f: F) where
Self: Sized, F: FnMut(Self::Item),
{
self.fold((), move |(), item| f(item));
}
/// Creates an iterator which uses a closure to determine if an element
/// should be yielded.
///
/// The closure must return `true` or `false`. `filter()` creates an
/// iterator which calls this closure on each element. If the closure
/// returns `true`, then the element is returned. If the closure returns
/// `false`, it will try again, and call the closure on the next element,
/// seeing if it passes the test.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [0i32, 1, 2];
///
/// let mut iter = a.into_iter().filter(|x| x.is_positive());
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Because the closure passed to `filter()` takes a reference, and many
/// iterators iterate over references, this leads to a possibly confusing
/// situation, where the type of the closure is a double reference:
///
/// ```
/// let a = [0, 1, 2];
///
/// let mut iter = a.into_iter().filter(|x| **x > 1); // need two *s!
///
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// It's common to instead use destructuring on the argument to strip away
/// one:
///
/// ```
/// let a = [0, 1, 2];
///
/// let mut iter = a.into_iter().filter(|&x| *x > 1); // both & and *
///
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// or both:
///
/// ```
/// let a = [0, 1, 2];
///
/// let mut iter = a.into_iter().filter(|&&x| x > 1); // two &s
///
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// of these layers.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn filter<P>(self, predicate: P) -> Filter<Self, P> where
Self: Sized, P: FnMut(&Self::Item) -> bool,
{
Filter {iter: self, predicate }
}
/// Creates an iterator that both filters and maps.
///
/// The closure must return an [`Option<T>`]. `filter_map` creates an
/// iterator which calls this closure on each element. If the closure
/// returns [`Some(element)`][`Some`], then that element is returned. If the
/// closure returns [`None`], it will try again, and call the closure on the
/// next element, seeing if it will return [`Some`].
///
/// Why `filter_map` and not just [`filter`] and [`map`]? The key is in this
/// part:
///
/// [`filter`]: #method.filter
/// [`map`]: #method.map
///
/// > If the closure returns [`Some(element)`][`Some`], then that element is returned.
///
/// In other words, it removes the [`Option<T>`] layer automatically. If your
/// mapping is already returning an [`Option<T>`] and you want to skip over
/// [`None`]s, then `filter_map` is much, much nicer to use.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = ["1", "lol", "3", "NaN", "5"];
///
/// let mut iter = a.iter().filter_map(|s| s.parse().ok());
///
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(3));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Here's the same example, but with [`filter`] and [`map`]:
///
/// ```
/// let a = ["1", "lol", "3", "NaN", "5"];
/// let mut iter = a.iter().map(|s| s.parse()).filter(|s| s.is_ok()).map(|s| s.unwrap());
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(3));
/// assert_eq!(iter.next(), Some(5));
/// assert_eq!(iter.next(), None);
/// ```
///
/// [`Option<T>`]: ../../std/option/enum.Option.html
/// [`Some`]: ../../std/option/enum.Option.html#variant.Some
/// [`None`]: ../../std/option/enum.Option.html#variant.None
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, F> where
Self: Sized, F: FnMut(Self::Item) -> Option<B>,
{
FilterMap { iter: self, f }
}
/// Creates an iterator which gives the current iteration count as well as
/// the next value.
///
/// The iterator returned yields pairs `(i, val)`, where `i` is the
/// current index of iteration and `val` is the value returned by the
/// iterator.
///
/// `enumerate()` keeps its count as a [`usize`]. If you want to count by a
/// different sized integer, the [`zip`] function provides similar
/// functionality.
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so enumerating more than
/// [`usize::MAX`] elements either produces the wrong result or panics. If
/// debug assertions are enabled, a panic is guaranteed.
///
/// # Panics
///
/// The returned iterator might panic if the to-be-returned index would
/// overflow a [`usize`].
///
/// [`usize::MAX`]: ../../std/usize/constant.MAX.html
/// [`usize`]: ../../std/primitive.usize.html
/// [`zip`]: #method.zip
///
/// # Examples
///
/// ```
/// let a = ['a', 'b', 'c'];
///
/// let mut iter = a.iter().enumerate();
///
/// assert_eq!(iter.next(), Some((0, &'a')));
/// assert_eq!(iter.next(), Some((1, &'b')));
/// assert_eq!(iter.next(), Some((2, &'c')));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn enumerate(self) -> Enumerate<Self> where Self: Sized {
Enumerate { iter: self, count: 0 }
}
/// Creates an iterator which can use `peek` to look at the next element of
/// the iterator without consuming it.
///
/// Adds a [`peek`] method to an iterator. See its documentation for
/// more information.
///
/// Note that the underlying iterator is still advanced when [`peek`] is
/// called for the first time: In order to retrieve the next element,
/// [`next`] is called on the underlying iterator, hence any side effects (i.e.
/// anything other than fetching the next value) of the [`next`] method
/// will occur.
///
/// [`peek`]: struct.Peekable.html#method.peek
/// [`next`]: ../../std/iter/trait.Iterator.html#tymethod.next
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let xs = [1, 2, 3];
///
/// let mut iter = xs.iter().peekable();
///
/// // peek() lets us see into the future
/// assert_eq!(iter.peek(), Some(&&1));
/// assert_eq!(iter.next(), Some(&1));
///
/// assert_eq!(iter.next(), Some(&2));
///
/// // we can peek() multiple times, the iterator won't advance
/// assert_eq!(iter.peek(), Some(&&3));
/// assert_eq!(iter.peek(), Some(&&3));
///
/// assert_eq!(iter.next(), Some(&3));
///
/// // after the iterator is finished, so is peek()
/// assert_eq!(iter.peek(), None);
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn peekable(self) -> Peekable<Self> where Self: Sized {
Peekable{iter: self, peeked: None}
}
/// Creates an iterator that [`skip`]s elements based on a predicate.
///
/// [`skip`]: #method.skip
///
/// `skip_while()` takes a closure as an argument. It will call this
/// closure on each element of the iterator, and ignore elements
/// until it returns `false`.
///
/// After `false` is returned, `skip_while()`'s job is over, and the
/// rest of the elements are yielded.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [-1i32, 0, 1];
///
/// let mut iter = a.into_iter().skip_while(|x| x.is_negative());
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Because the closure passed to `skip_while()` takes a reference, and many
/// iterators iterate over references, this leads to a possibly confusing
/// situation, where the type of the closure is a double reference:
///
/// ```
/// let a = [-1, 0, 1];
///
/// let mut iter = a.into_iter().skip_while(|x| **x < 0); // need two *s!
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Stopping after an initial `false`:
///
/// ```
/// let a = [-1, 0, 1, -2];
///
/// let mut iter = a.into_iter().skip_while(|x| **x < 0);
///
/// assert_eq!(iter.next(), Some(&0));
/// assert_eq!(iter.next(), Some(&1));
///
/// // while this would have been false, since we already got a false,
/// // skip_while() isn't used any more
/// assert_eq!(iter.next(), Some(&-2));
///
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn skip_while<P>(self, predicate: P) -> SkipWhile<Self, P> where
Self: Sized, P: FnMut(&Self::Item) -> bool,
{
SkipWhile { iter: self, flag: false, predicate }
}
/// Creates an iterator that yields elements based on a predicate.
///
/// `take_while()` takes a closure as an argument. It will call this
/// closure on each element of the iterator, and yield elements
/// while it returns `true`.
///
/// After `false` is returned, `take_while()`'s job is over, and the
/// rest of the elements are ignored.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [-1i32, 0, 1];
///
/// let mut iter = a.into_iter().take_while(|x| x.is_negative());
///
/// assert_eq!(iter.next(), Some(&-1));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Because the closure passed to `take_while()` takes a reference, and many
/// iterators iterate over references, this leads to a possibly confusing
/// situation, where the type of the closure is a double reference:
///
/// ```
/// let a = [-1, 0, 1];
///
/// let mut iter = a.into_iter().take_while(|x| **x < 0); // need two *s!
///
/// assert_eq!(iter.next(), Some(&-1));
/// assert_eq!(iter.next(), None);
/// ```
///
/// Stopping after an initial `false`:
///
/// ```
/// let a = [-1, 0, 1, -2];
///
/// let mut iter = a.into_iter().take_while(|x| **x < 0);
///
/// assert_eq!(iter.next(), Some(&-1));
///
/// // We have more elements that are less than zero, but since we already
/// // got a false, take_while() isn't used any more
/// assert_eq!(iter.next(), None);
/// ```
///
/// Because `take_while()` needs to look at the value in order to see if it
/// should be included or not, consuming iterators will see that it is
/// removed:
///
/// ```
/// let a = [1, 2, 3, 4];
/// let mut iter = a.into_iter();
///
/// let result: Vec<i32> = iter.by_ref()
/// .take_while(|n| **n != 3)
/// .cloned()
/// .collect();
///
/// assert_eq!(result, &[1, 2]);
///
/// let result: Vec<i32> = iter.cloned().collect();
///
/// assert_eq!(result, &[4]);
/// ```
///
/// The `3` is no longer there, because it was consumed in order to see if
/// the iteration should stop, but wasn't placed back into the iterator or
/// some similar thing.
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn take_while<P>(self, predicate: P) -> TakeWhile<Self, P> where
Self: Sized, P: FnMut(&Self::Item) -> bool,
{
TakeWhile { iter: self, flag: false, predicate }
}
/// Creates an iterator that skips the first `n` elements.
///
/// After they have been consumed, the rest of the elements are yielded.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter().skip(2);
///
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn skip(self, n: usize) -> Skip<Self> where Self: Sized {
Skip { iter: self, n }
}
/// Creates an iterator that yields its first `n` elements.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter().take(2);
///
/// assert_eq!(iter.next(), Some(&1));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
///
/// `take()` is often used with an infinite iterator, to make it finite:
///
/// ```
/// let mut iter = (0..).take(3);
///
/// assert_eq!(iter.next(), Some(0));
/// assert_eq!(iter.next(), Some(1));
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn take(self, n: usize) -> Take<Self> where Self: Sized, {
Take { iter: self, n }
}
/// An iterator adaptor similar to [`fold`] that holds internal state and
/// produces a new iterator.
///
/// [`fold`]: #method.fold
///
/// `scan()` takes two arguments: an initial value which seeds the internal
/// state, and a closure with two arguments, the first being a mutable
/// reference to the internal state and the second an iterator element.
/// The closure can assign to the internal state to share state between
/// iterations.
///
/// On iteration, the closure will be applied to each element of the
/// iterator and the return value from the closure, an [`Option`], is
/// yielded by the iterator.
///
/// [`Option`]: ../../std/option/enum.Option.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter().scan(1, |state, &x| {
/// // each iteration, we'll multiply the state by the element
/// *state = *state * x;
///
/// // then, we'll yield the negation of the state
/// Some(-*state)
/// });
///
/// assert_eq!(iter.next(), Some(-1));
/// assert_eq!(iter.next(), Some(-2));
/// assert_eq!(iter.next(), Some(-6));
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn scan<St, B, F>(self, initial_state: St, f: F) -> Scan<Self, St, F>
where Self: Sized, F: FnMut(&mut St, Self::Item) -> Option<B>,
{
Scan { iter: self, f, state: initial_state }
}
/// Creates an iterator that works like map, but flattens nested structure.
///
/// The [`map`] adapter is very useful, but only when the closure
/// argument produces values. If it produces an iterator instead, there's
/// an extra layer of indirection. `flat_map()` will remove this extra layer
/// on its own.
///
/// You can think of `flat_map(f)` as the semantic equivalent
/// of [`map`]ping, and then [`flatten`]ing as in `map(f).flatten()`.
///
/// Another way of thinking about `flat_map()`: [`map`]'s closure returns
/// one item for each element, and `flat_map()`'s closure returns an
/// iterator for each element.
///
/// [`map`]: #method.map
/// [`flatten`]: #method.flatten
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let words = ["alpha", "beta", "gamma"];
///
/// // chars() returns an iterator
/// let merged: String = words.iter()
/// .flat_map(|s| s.chars())
/// .collect();
/// assert_eq!(merged, "alphabetagamma");
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn flat_map<U, F>(self, f: F) -> FlatMap<Self, U, F>
where Self: Sized, U: IntoIterator, F: FnMut(Self::Item) -> U,
{
FlatMap { inner: flatten_compat(self.map(f)) }
}
/// Creates an iterator that flattens nested structure.
///
/// This is useful when you have an iterator of iterators or an iterator of
/// things that can be turned into iterators and you want to remove one
/// level of indirection.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let data = vec![vec![1, 2, 3, 4], vec![5, 6]];
/// let flattened = data.into_iter().flatten().collect::<Vec<u8>>();
/// assert_eq!(flattened, &[1, 2, 3, 4, 5, 6]);
/// ```
///
/// Mapping and then flattening:
///
/// ```
/// let words = ["alpha", "beta", "gamma"];
///
/// // chars() returns an iterator
/// let merged: String = words.iter()
/// .map(|s| s.chars())
/// .flatten()
/// .collect();
/// assert_eq!(merged, "alphabetagamma");
/// ```
///
/// You can also rewrite this in terms of [`flat_map()`], which is preferable
/// in this case since it conveys intent more clearly:
///
/// ```
/// let words = ["alpha", "beta", "gamma"];
///
/// // chars() returns an iterator
/// let merged: String = words.iter()
/// .flat_map(|s| s.chars())
/// .collect();
/// assert_eq!(merged, "alphabetagamma");
/// ```
///
/// Flattening once only removes one level of nesting:
///
/// ```
/// let d3 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]];
///
/// let d2 = d3.iter().flatten().collect::<Vec<_>>();
/// assert_eq!(d2, [&[1, 2], &[3, 4], &[5, 6], &[7, 8]]);
///
/// let d1 = d3.iter().flatten().flatten().collect::<Vec<_>>();
/// assert_eq!(d1, [&1, &2, &3, &4, &5, &6, &7, &8]);
/// ```
///
/// Here we see that `flatten()` does not perform a "deep" flatten.
/// Instead, only one level of nesting is removed. That is, if you
/// `flatten()` a three-dimensional array the result will be
/// two-dimensional and not one-dimensional. To get a one-dimensional
/// structure, you have to `flatten()` again.
///
/// [`flat_map()`]: #method.flat_map
#[inline]
#[stable(feature = "iterator_flatten", since = "1.29.0")]
fn flatten | -> Flatten<Self>
where Self: Sized, Self::Item: IntoIterator {
Flatten { inner: flatten_compat(self) }
}
/// Creates an iterator which ends after the first [`None`].
///
/// After an iterator returns [`None`], future calls may or may not yield
/// [`Some(T)`] again. `fuse()` adapts an iterator, ensuring that after a
/// [`None`] is given, it will always return [`None`] forever.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
/// [`Some(T)`]: ../../std/option/enum.Option.html#variant.Some
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// // an iterator which alternates between Some and None
/// struct Alternate {
/// state: i32,
/// }
///
/// impl Iterator for Alternate {
/// type Item = i32;
///
/// fn next(&mut self) -> Option<i32> {
/// let val = self.state;
/// self.state = self.state + 1;
///
/// // if it's even, Some(i32), else None
/// if val % 2 == 0 {
/// Some(val)
/// } else {
/// None
/// }
/// }
/// }
///
/// let mut iter = Alternate { state: 0 };
///
/// // we can see our iterator going back and forth
/// assert_eq!(iter.next(), Some(0));
/// assert_eq!(iter.next(), None);
/// assert_eq!(iter.next(), Some(2));
/// assert_eq!(iter.next(), None);
///
/// // however, once we fuse it...
/// let mut iter = iter.fuse();
///
/// assert_eq!(iter.next(), Some(4));
/// assert_eq!(iter.next(), None);
///
/// // it will always return None after the first time.
/// assert_eq!(iter.next(), None);
/// assert_eq!(iter.next(), None);
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn fuse(self) -> Fuse<Self> where Self: Sized {
Fuse{iter: self, done: false}
}
/// Do something with each element of an iterator, passing the value on.
///
/// When using iterators, you'll often chain several of them together.
/// While working on such code, you might want to check out what's
/// happening at various parts in the pipeline. To do that, insert
/// a call to `inspect()`.
///
/// It's more common for `inspect()` to be used as a debugging tool than to
/// exist in your final code, but applications may find it useful in certain
/// situations when errors need to be logged before being discarded.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 4, 2, 3];
///
/// // this iterator sequence is complex.
/// let sum = a.iter()
/// .cloned()
/// .filter(|x| x % 2 == 0)
/// .fold(0, |sum, i| sum + i);
///
/// println!("{}", sum);
///
/// // let's add some inspect() calls to investigate what's happening
/// let sum = a.iter()
/// .cloned()
/// .inspect(|x| println!("about to filter: {}", x))
/// .filter(|x| x % 2 == 0)
/// .inspect(|x| println!("made it through filter: {}", x))
/// .fold(0, |sum, i| sum + i);
///
/// println!("{}", sum);
/// ```
///
/// This will print:
///
/// ```text
/// 6
/// about to filter: 1
/// about to filter: 4
/// made it through filter: 4
/// about to filter: 2
/// made it through filter: 2
/// about to filter: 3
/// 6
/// ```
///
/// Logging errors before discarding them:
///
/// ```
/// let lines = ["1", "2", "a"];
///
/// let sum: i32 = lines
/// .iter()
/// .map(|line| line.parse::<i32>())
/// .inspect(|num| {
/// if let Err(ref e) = *num {
/// println!("Parsing error: {}", e);
/// }
/// })
/// .filter_map(Result::ok)
/// .sum();
///
/// println!("Sum: {}", sum);
/// ```
///
/// This will print:
///
/// ```text
/// Parsing error: invalid digit found in string
/// Sum: 3
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn inspect<F>(self, f: F) -> Inspect<Self, F> where
Self: Sized, F: FnMut(&Self::Item),
{
Inspect { iter: self, f }
}
/// Borrows an iterator, rather than consuming it.
///
/// This is useful to allow applying iterator adaptors while still
/// retaining ownership of the original iterator.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let iter = a.into_iter();
///
/// let sum: i32 = iter.take(5).fold(0, |acc, i| acc + i );
///
/// assert_eq!(sum, 6);
///
/// // if we try to use iter again, it won't work. The following line
/// // gives "error: use of moved value: `iter`
/// // assert_eq!(iter.next(), None);
///
/// // let's try that again
/// let a = [1, 2, 3];
///
/// let mut iter = a.into_iter();
///
/// // instead, we add in a .by_ref()
/// let sum: i32 = iter.by_ref().take(2).fold(0, |acc, i| acc + i );
///
/// assert_eq!(sum, 3);
///
/// // now this is just fine:
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), None);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn by_ref(&mut self) -> &mut Self where Self: Sized { self }
/// Transforms an iterator into a collection.
///
/// `collect()` can take anything iterable, and turn it into a relevant
/// collection. This is one of the more powerful methods in the standard
/// library, used in a variety of contexts.
///
/// The most basic pattern in which `collect()` is used is to turn one
/// collection into another. You take a collection, call [`iter`] on it,
/// do a bunch of transformations, and then `collect()` at the end.
///
/// One of the keys to `collect()`'s power is that many things you might
/// not think of as 'collections' actually are. For example, a [`String`]
/// is a collection of [`char`]s. And a collection of
/// [`Result<T, E>`][`Result`] can be thought of as single
/// [`Result`]`<Collection<T>, E>`. See the examples below for more.
///
/// Because `collect()` is so general, it can cause problems with type
/// inference. As such, `collect()` is one of the few times you'll see
/// the syntax affectionately known as the 'turbofish': `::<>`. This
/// helps the inference algorithm understand specifically which collection
/// you're trying to collect into.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let doubled: Vec<i32> = a.iter()
/// .map(|&x| x * 2)
/// .collect();
///
/// assert_eq!(vec![2, 4, 6], doubled);
/// ```
///
/// Note that we needed the `: Vec<i32>` on the left-hand side. This is because
/// we could collect into, for example, a [`VecDeque<T>`] instead:
///
/// [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
///
/// ```
/// use std::collections::VecDeque;
///
/// let a = [1, 2, 3];
///
/// let doubled: VecDeque<i32> = a.iter().map(|&x| x * 2).collect();
///
/// assert_eq!(2, doubled[0]);
/// assert_eq!(4, doubled[1]);
/// assert_eq!(6, doubled[2]);
/// ```
///
/// Using the 'turbofish' instead of annotating `doubled`:
///
/// ```
/// let a = [1, 2, 3];
///
/// let doubled = a.iter().map(|x| x * 2).collect::<Vec<i32>>();
///
/// assert_eq!(vec![2, 4, 6], doubled);
/// ```
///
/// Because `collect()` only cares about what you're collecting into, you can
/// still use a partial type hint, `_`, with the turbofish:
///
/// ```
/// let a = [1, 2, 3];
///
/// let doubled = a.iter().map(|x| x * 2).collect::<Vec<_>>();
///
/// assert_eq!(vec![2, 4, 6], doubled);
/// ```
///
/// Using `collect()` to make a [`String`]:
///
/// ```
/// let chars = ['g', 'd', 'k', 'k', 'n'];
///
/// let hello: String = chars.iter()
/// .map(|&x| x as u8)
/// .map(|x| (x + 1) as char)
/// .collect();
///
/// assert_eq!("hello", hello);
/// ```
///
/// If you have a list of [`Result<T, E>`][`Result`]s, you can use `collect()` to
/// see if any of them failed:
///
/// ```
/// let results = [Ok(1), Err("nope"), Ok(3), Err("bad")];
///
/// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
///
/// // gives us the first error
/// assert_eq!(Err("nope"), result);
///
/// let results = [Ok(1), Ok(3)];
///
/// let result: Result<Vec<_>, &str> = results.iter().cloned().collect();
///
/// // gives us the list of answers
/// assert_eq!(Ok(vec![1, 3]), result);
/// ```
///
/// [`iter`]: ../../std/iter/trait.Iterator.html#tymethod.next
/// [`String`]: ../../std/string/struct.String.html
/// [`char`]: ../../std/primitive.char.html
/// [`Result`]: ../../std/result/enum.Result.html
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use = "if you really need to exhaust the iterator, consider `.for_each(drop)` instead"]
fn collect<B: FromIterator<Self::Item>>(self) -> B where Self: Sized {
FromIterator::from_iter(self)
}
/// Consumes an iterator, creating two collections from it.
///
/// The predicate passed to `partition()` can return `true`, or `false`.
/// `partition()` returns a pair, all of the elements for which it returned
/// `true`, and all of the elements for which it returned `false`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let (even, odd): (Vec<i32>, Vec<i32>) = a
/// .into_iter()
/// .partition(|&n| n % 2 == 0);
///
/// assert_eq!(even, vec![2]);
/// assert_eq!(odd, vec![1, 3]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn partition<B, F>(self, mut f: F) -> (B, B) where
Self: Sized,
B: Default + Extend<Self::Item>,
F: FnMut(&Self::Item) -> bool
{
let mut left: B = Default::default();
let mut right: B = Default::default();
for x in self {
if f(&x) {
left.extend(Some(x))
} else {
right.extend(Some(x))
}
}
(left, right)
}
/// An iterator method that applies a function as long as it returns
/// successfully, producing a single, final value.
///
/// `try_fold()` takes two arguments: an initial value, and a closure with
/// two arguments: an 'accumulator', and an element. The closure either
/// returns successfully, with the value that the accumulator should have
/// for the next iteration, or it returns failure, with an error value that
/// is propagated back to the caller immediately (short-circuiting).
///
/// The initial value is the value the accumulator will have on the first
/// call. If applying the closure succeeded against every element of the
/// iterator, `try_fold()` returns the final accumulator as success.
///
/// Folding is useful whenever you have a collection of something, and want
/// to produce a single value from it.
///
/// # Note to Implementors
///
/// Most of the other (forward) methods have default implementations in
/// terms of this one, so try to implement this explicitly if it can
/// do something better than the default `for` loop implementation.
///
/// In particular, try to have this call `try_fold()` on the internal parts
/// from which this iterator is composed. If multiple calls are needed,
/// the `?` operator may be convenient for chaining the accumulator value
/// along, but beware any invariants that need to be upheld before those
/// early returns. This is a `&mut self` method, so iteration needs to be
/// resumable after hitting an error here.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// // the checked sum of all of the elements of the array
/// let sum = a.iter().try_fold(0i8, |acc, &x| acc.checked_add(x));
///
/// assert_eq!(sum, Some(6));
/// ```
///
/// Short-circuiting:
///
/// ```
/// let a = [10, 20, 30, 100, 40, 50];
/// let mut it = a.iter();
///
/// // This sum overflows when adding the 100 element
/// let sum = it.try_fold(0i8, |acc, &x| acc.checked_add(x));
/// assert_eq!(sum, None);
///
/// // Because it short-circuited, the remaining elements are still
/// // available through the iterator.
/// assert_eq!(it.len(), 2);
/// assert_eq!(it.next(), Some(&40));
/// ```
#[inline]
#[stable(feature = "iterator_try_fold", since = "1.27.0")]
fn try_fold<B, F, R>(&mut self, init: B, mut f: F) -> R where
Self: Sized, F: FnMut(B, Self::Item) -> R, R: Try<Ok=B>
{
let mut accum = init;
while let Some(x) = self.next() {
accum = f(accum, x)?;
}
Try::from_ok(accum)
}
/// An iterator method that applies a fallible function to each item in the
/// iterator, stopping at the first error and returning that error.
///
/// This can also be thought of as the fallible form of [`for_each()`]
/// or as the stateless version of [`try_fold()`].
///
/// [`for_each()`]: #method.for_each
/// [`try_fold()`]: #method.try_fold
///
/// # Examples
///
/// ```
/// use std::fs::rename;
/// use std::io::{stdout, Write};
/// use std::path::Path;
///
/// let data = ["no_tea.txt", "stale_bread.json", "torrential_rain.png"];
///
/// let res = data.iter().try_for_each(|x| writeln!(stdout(), "{}", x));
/// assert!(res.is_ok());
///
/// let mut it = data.iter().cloned();
/// let res = it.try_for_each(|x| rename(x, Path::new(x).with_extension("old")));
/// assert!(res.is_err());
/// // It short-circuited, so the remaining items are still in the iterator:
/// assert_eq!(it.next(), Some("stale_bread.json"));
/// ```
#[inline]
#[stable(feature = "iterator_try_fold", since = "1.27.0")]
fn try_for_each<F, R>(&mut self, mut f: F) -> R where
Self: Sized, F: FnMut(Self::Item) -> R, R: Try<Ok=()>
{
self.try_fold((), move |(), x| f(x))
}
/// An iterator method that applies a function, producing a single, final value.
///
/// `fold()` takes two arguments: an initial value, and a closure with two
/// arguments: an 'accumulator', and an element. The closure returns the value that
/// the accumulator should have for the next iteration.
///
/// The initial value is the value the accumulator will have on the first
/// call.
///
/// After applying this closure to every element of the iterator, `fold()`
/// returns the accumulator.
///
/// This operation is sometimes called 'reduce' or 'inject'.
///
/// Folding is useful whenever you have a collection of something, and want
/// to produce a single value from it.
///
/// Note: `fold()`, and similar methods that traverse the entire iterator,
/// may not terminate for infinite iterators, even on traits for which a
/// result is determinable in finite time.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// // the sum of all of the elements of the array
/// let sum = a.iter().fold(0, |acc, x| acc + x);
///
/// assert_eq!(sum, 6);
/// ```
///
/// Let's walk through each step of the iteration here:
///
/// | element | acc | x | result |
/// |---------|-----|---|--------|
/// | | 0 | | |
/// | 1 | 0 | 1 | 1 |
/// | 2 | 1 | 2 | 3 |
/// | 3 | 3 | 3 | 6 |
///
/// And so, our final result, `6`.
///
/// It's common for people who haven't used iterators a lot to
/// use a `for` loop with a list of things to build up a result. Those
/// can be turned into `fold()`s:
///
/// [`for`]: ../../book/ch03-05-control-flow.html#looping-through-a-collection-with-for
///
/// ```
/// let numbers = [1, 2, 3, 4, 5];
///
/// let mut result = 0;
///
/// // for loop:
/// for i in &numbers {
/// result = result + i;
/// }
///
/// // fold:
/// let result2 = numbers.iter().fold(0, |acc, &x| acc + x);
///
/// // they're the same
/// assert_eq!(result, result2);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn fold<B, F>(mut self, init: B, mut f: F) -> B where
Self: Sized, F: FnMut(B, Self::Item) -> B,
{
self.try_fold(init, move |acc, x| Ok::<B, !>(f(acc, x))).unwrap()
}
/// Tests if every element of the iterator matches a predicate.
///
/// `all()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the iterator, and if they all return
/// `true`, then so does `all()`. If any of them return `false`, it
/// returns `false`.
///
/// `all()` is short-circuiting; in other words, it will stop processing
/// as soon as it finds a `false`, given that no matter what else happens,
/// the result will also be `false`.
///
/// An empty iterator returns `true`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// assert!(a.iter().all(|&x| x > 0));
///
/// assert!(!a.iter().all(|&x| x > 2));
/// ```
///
/// Stopping at the first `false`:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert!(!iter.all(|&x| x != 2));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(&3));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn all<F>(&mut self, mut f: F) -> bool where
Self: Sized, F: FnMut(Self::Item) -> bool
{
self.try_for_each(move |x| {
if f(x) { LoopState::Continue(()) }
else { LoopState::Break(()) }
}) == LoopState::Continue(())
}
/// Tests if any element of the iterator matches a predicate.
///
/// `any()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the iterator, and if any of them return
/// `true`, then so does `any()`. If they all return `false`, it
/// returns `false`.
///
/// `any()` is short-circuiting; in other words, it will stop processing
/// as soon as it finds a `true`, given that no matter what else happens,
/// the result will also be `true`.
///
/// An empty iterator returns `false`.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// assert!(a.iter().any(|&x| x > 0));
///
/// assert!(!a.iter().any(|&x| x > 5));
/// ```
///
/// Stopping at the first `true`:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert!(iter.any(|&x| x != 2));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(&2));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn any<F>(&mut self, mut f: F) -> bool where
Self: Sized,
F: FnMut(Self::Item) -> bool
{
self.try_for_each(move |x| {
if f(x) { LoopState::Break(()) }
else { LoopState::Continue(()) }
}) == LoopState::Break(())
}
/// Searches for an element of an iterator that satisfies a predicate.
///
/// `find()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the iterator, and if any of them return
/// `true`, then `find()` returns [`Some(element)`]. If they all return
/// `false`, it returns [`None`].
///
/// `find()` is short-circuiting; in other words, it will stop processing
/// as soon as the closure returns `true`.
///
/// Because `find()` takes a reference, and many iterators iterate over
/// references, this leads to a possibly confusing situation where the
/// argument is a double reference. You can see this effect in the
/// examples below, with `&&x`.
///
/// [`Some(element)`]: ../../std/option/enum.Option.html#variant.Some
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// assert_eq!(a.iter().find(|&&x| x == 2), Some(&2));
///
/// assert_eq!(a.iter().find(|&&x| x == 5), None);
/// ```
///
/// Stopping at the first `true`:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert_eq!(iter.find(|&&x| x == 2), Some(&2));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(&3));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn find<P>(&mut self, mut predicate: P) -> Option<Self::Item> where
Self: Sized,
P: FnMut(&Self::Item) -> bool,
{
self.try_for_each(move |x| {
if predicate(&x) { LoopState::Break(x) }
else { LoopState::Continue(()) }
}).break_value()
}
/// Applies function to the elements of iterator and returns
/// the first non-none result.
///
/// `iter.find_map(f)` is equivalent to `iter.filter_map(f).next()`.
///
///
/// # Examples
///
/// ```
/// let a = ["lol", "NaN", "2", "5"];
///
/// let first_number = a.iter().find_map(|s| s.parse().ok());
///
/// assert_eq!(first_number, Some(2));
/// ```
#[inline]
#[stable(feature = "iterator_find_map", since = "1.30.0")]
fn find_map<B, F>(&mut self, mut f: F) -> Option<B> where
Self: Sized,
F: FnMut(Self::Item) -> Option<B>,
{
self.try_for_each(move |x| {
match f(x) {
Some(x) => LoopState::Break(x),
None => LoopState::Continue(()),
}
}).break_value()
}
/// Searches for an element in an iterator, returning its index.
///
/// `position()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the iterator, and if one of them
/// returns `true`, then `position()` returns [`Some(index)`]. If all of
/// them return `false`, it returns [`None`].
///
/// `position()` is short-circuiting; in other words, it will stop
/// processing as soon as it finds a `true`.
///
/// # Overflow Behavior
///
/// The method does no guarding against overflows, so if there are more
/// than [`usize::MAX`] non-matching elements, it either produces the wrong
/// result or panics. If debug assertions are enabled, a panic is
/// guaranteed.
///
/// # Panics
///
/// This function might panic if the iterator has more than `usize::MAX`
/// non-matching elements.
///
/// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
/// [`None`]: ../../std/option/enum.Option.html#variant.None
/// [`usize::MAX`]: ../../std/usize/constant.MAX.html
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// assert_eq!(a.iter().position(|&x| x == 2), Some(1));
///
/// assert_eq!(a.iter().position(|&x| x == 5), None);
/// ```
///
/// Stopping at the first `true`:
///
/// ```
/// let a = [1, 2, 3, 4];
///
/// let mut iter = a.iter();
///
/// assert_eq!(iter.position(|&x| x >= 2), Some(1));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(&3));
///
/// // The returned index depends on iterator state
/// assert_eq!(iter.position(|&x| x == 4), Some(0));
///
/// ```
#[inline]
#[rustc_inherit_overflow_checks]
#[stable(feature = "rust1", since = "1.0.0")]
fn position<P>(&mut self, mut predicate: P) -> Option<usize> where
Self: Sized,
P: FnMut(Self::Item) -> bool,
{
// The addition might panic on overflow
self.try_fold(0, move |i, x| {
if predicate(x) { LoopState::Break(i) }
else { LoopState::Continue(i + 1) }
}).break_value()
}
/// Searches for an element in an iterator from the right, returning its
/// index.
///
/// `rposition()` takes a closure that returns `true` or `false`. It applies
/// this closure to each element of the iterator, starting from the end,
/// and if one of them returns `true`, then `rposition()` returns
/// [`Some(index)`]. If all of them return `false`, it returns [`None`].
///
/// `rposition()` is short-circuiting; in other words, it will stop
/// processing as soon as it finds a `true`.
///
/// [`Some(index)`]: ../../std/option/enum.Option.html#variant.Some
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// assert_eq!(a.iter().rposition(|&x| x == 3), Some(2));
///
/// assert_eq!(a.iter().rposition(|&x| x == 5), None);
/// ```
///
/// Stopping at the first `true`:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter();
///
/// assert_eq!(iter.rposition(|&x| x == 2), Some(1));
///
/// // we can still use `iter`, as there are more elements.
/// assert_eq!(iter.next(), Some(&1));
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn rposition<P>(&mut self, mut predicate: P) -> Option<usize> where
P: FnMut(Self::Item) -> bool,
Self: Sized + ExactSizeIterator + DoubleEndedIterator
{
// No need for an overflow check here, because `ExactSizeIterator`
// implies that the number of elements fits into a `usize`.
let n = self.len();
self.try_rfold(n, move |i, x| {
let i = i - 1;
if predicate(x) { LoopState::Break(i) }
else { LoopState::Continue(i) }
}).break_value()
}
/// Returns the maximum element of an iterator.
///
/// If several elements are equally maximum, the last element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// let b: Vec<u32> = Vec::new();
///
/// assert_eq!(a.iter().max(), Some(&3));
/// assert_eq!(b.iter().max(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn max(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
{
select_fold1(self,
|_| (),
// switch to y even if it is only equal, to preserve
// stability.
|_, x, _, y| *x <= *y)
.map(|(_, x)| x)
}
/// Returns the minimum element of an iterator.
///
/// If several elements are equally minimum, the first element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// let b: Vec<u32> = Vec::new();
///
/// assert_eq!(a.iter().min(), Some(&1));
/// assert_eq!(b.iter().min(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn min(self) -> Option<Self::Item> where Self: Sized, Self::Item: Ord
{
select_fold1(self,
|_| (),
// only switch to y if it is strictly smaller, to
// preserve stability.
|_, x, _, y| *x > *y)
.map(|(_, x)| x)
}
/// Returns the element that gives the maximum value from the
/// specified function.
///
/// If several elements are equally maximum, the last element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// ```
/// let a = [-3_i32, 0, 1, 5, -10];
/// assert_eq!(*a.iter().max_by_key(|x| x.abs()).unwrap(), -10);
/// ```
#[inline]
#[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
fn max_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
where Self: Sized, F: FnMut(&Self::Item) -> B,
{
select_fold1(self,
f,
// switch to y even if it is only equal, to preserve
// stability.
|x_p, _, y_p, _| x_p <= y_p)
.map(|(_, x)| x)
}
/// Returns the element that gives the maximum value with respect to the
/// specified comparison function.
///
/// If several elements are equally maximum, the last element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// ```
/// let a = [-3_i32, 0, 1, 5, -10];
/// assert_eq!(*a.iter().max_by(|x, y| x.cmp(y)).unwrap(), 5);
/// ```
#[inline]
#[stable(feature = "iter_max_by", since = "1.15.0")]
fn max_by<F>(self, mut compare: F) -> Option<Self::Item>
where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
select_fold1(self,
|_| (),
// switch to y even if it is only equal, to preserve
// stability.
|_, x, _, y| Ordering::Greater != compare(x, y))
.map(|(_, x)| x)
}
/// Returns the element that gives the minimum value from the
/// specified function.
///
/// If several elements are equally minimum, the first element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// ```
/// let a = [-3_i32, 0, 1, 5, -10];
/// assert_eq!(*a.iter().min_by_key(|x| x.abs()).unwrap(), 0);
/// ```
#[stable(feature = "iter_cmp_by_key", since = "1.6.0")]
fn min_by_key<B: Ord, F>(self, f: F) -> Option<Self::Item>
where Self: Sized, F: FnMut(&Self::Item) -> B,
{
select_fold1(self,
f,
// only switch to y if it is strictly smaller, to
// preserve stability.
|x_p, _, y_p, _| x_p > y_p)
.map(|(_, x)| x)
}
/// Returns the element that gives the minimum value with respect to the
/// specified comparison function.
///
/// If several elements are equally minimum, the first element is
/// returned. If the iterator is empty, [`None`] is returned.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// ```
/// let a = [-3_i32, 0, 1, 5, -10];
/// assert_eq!(*a.iter().min_by(|x, y| x.cmp(y)).unwrap(), -10);
/// ```
#[inline]
#[stable(feature = "iter_min_by", since = "1.15.0")]
fn min_by<F>(self, mut compare: F) -> Option<Self::Item>
where Self: Sized, F: FnMut(&Self::Item, &Self::Item) -> Ordering,
{
select_fold1(self,
|_| (),
// switch to y even if it is strictly smaller, to
// preserve stability.
|_, x, _, y| Ordering::Greater == compare(x, y))
.map(|(_, x)| x)
}
/// Reverses an iterator's direction.
///
/// Usually, iterators iterate from left to right. After using `rev()`,
/// an iterator will instead iterate from right to left.
///
/// This is only possible if the iterator has an end, so `rev()` only
/// works on [`DoubleEndedIterator`]s.
///
/// [`DoubleEndedIterator`]: trait.DoubleEndedIterator.html
///
/// # Examples
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut iter = a.iter().rev();
///
/// assert_eq!(iter.next(), Some(&3));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), Some(&1));
///
/// assert_eq!(iter.next(), None);
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
fn rev(self) -> Rev<Self> where Self: Sized + DoubleEndedIterator {
Rev{iter: self}
}
/// Converts an iterator of pairs into a pair of containers.
///
/// `unzip()` consumes an entire iterator of pairs, producing two
/// collections: one from the left elements of the pairs, and one
/// from the right elements.
///
/// This function is, in some sense, the opposite of [`zip`].
///
/// [`zip`]: #method.zip
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [(1, 2), (3, 4)];
///
/// let (left, right): (Vec<_>, Vec<_>) = a.iter().cloned().unzip();
///
/// assert_eq!(left, [1, 3]);
/// assert_eq!(right, [2, 4]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn unzip<A, B, FromA, FromB>(self) -> (FromA, FromB) where
FromA: Default + Extend<A>,
FromB: Default + Extend<B>,
Self: Sized + Iterator<Item=(A, B)>,
{
let mut ts: FromA = Default::default();
let mut us: FromB = Default::default();
self.for_each(|(t, u)| {
ts.extend(Some(t));
us.extend(Some(u));
});
(ts, us)
}
/// Creates an iterator which [`clone`]s all of its elements.
///
/// This is useful when you have an iterator over `&T`, but you need an
/// iterator over `T`.
///
/// [`clone`]: ../../std/clone/trait.Clone.html#tymethod.clone
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let v_cloned: Vec<_> = a.iter().cloned().collect();
///
/// // cloned is the same as .map(|&x| x), for integers
/// let v_map: Vec<_> = a.iter().map(|&x| x).collect();
///
/// assert_eq!(v_cloned, vec![1, 2, 3]);
/// assert_eq!(v_map, vec![1, 2, 3]);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
fn cloned<'a, T: 'a>(self) -> Cloned<Self>
where Self: Sized + Iterator<Item=&'a T>, T: Clone
{
Cloned { it: self }
}
/// Repeats an iterator endlessly.
///
/// Instead of stopping at [`None`], the iterator will instead start again,
/// from the beginning. After iterating again, it will start at the
/// beginning again. And again. And again. Forever.
///
/// [`None`]: ../../std/option/enum.Option.html#variant.None
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
///
/// let mut it = a.iter().cycle();
///
/// assert_eq!(it.next(), Some(&1));
/// assert_eq!(it.next(), Some(&2));
/// assert_eq!(it.next(), Some(&3));
/// assert_eq!(it.next(), Some(&1));
/// assert_eq!(it.next(), Some(&2));
/// assert_eq!(it.next(), Some(&3));
/// assert_eq!(it.next(), Some(&1));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
fn cycle(self) -> Cycle<Self> where Self: Sized + Clone {
Cycle{orig: self.clone(), iter: self}
}
/// Sums the elements of an iterator.
///
/// Takes each element, adds them together, and returns the result.
///
/// An empty iterator returns the zero value of the type.
///
/// # Panics
///
/// When calling `sum()` and a primitive integer type is being returned, this
/// method will panic if the computation overflows and debug assertions are
/// enabled.
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// let a = [1, 2, 3];
/// let sum: i32 = a.iter().sum();
///
/// assert_eq!(sum, 6);
/// ```
#[stable(feature = "iter_arith", since = "1.11.0")]
fn sum<S>(self) -> S
where Self: Sized,
S: Sum<Self::Item>,
{
Sum::sum(self)
}
/// Iterates over the entire iterator, multiplying all the elements
///
/// An empty iterator returns the one value of the type.
///
/// # Panics
///
/// When calling `product()` and a primitive integer type is being returned,
/// method will panic if the computation overflows and debug assertions are
/// enabled.
///
/// # Examples
///
/// ```
/// fn factorial(n: u32) -> u32 {
/// (1..).take_while(|&i| i <= n).product()
/// }
/// assert_eq!(factorial(0), 1);
/// assert_eq!(factorial(1), 1);
/// assert_eq!(factorial(5), 120);
/// ```
#[stable(feature = "iter_arith", since = "1.11.0")]
fn product<P>(self) -> P
where Self: Sized,
P: Product<Self::Item>,
{
Product::product(self)
}
/// Lexicographically compares the elements of this `Iterator` with those
/// of another.
#[stable(feature = "iter_order", since = "1.5.0")]
fn cmp<I>(mut self, other: I) -> Ordering where
I: IntoIterator<Item = Self::Item>,
Self::Item: Ord,
Self: Sized,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => if other.next().is_none() {
return Ordering::Equal
} else {
return Ordering::Less
},
Some(val) => val,
};
let y = match other.next() {
None => return Ordering::Greater,
Some(val) => val,
};
match x.cmp(&y) {
Ordering::Equal => (),
non_eq => return non_eq,
}
}
}
/// Lexicographically compares the elements of this `Iterator` with those
/// of another.
#[stable(feature = "iter_order", since = "1.5.0")]
fn partial_cmp<I>(mut self, other: I) -> Option<Ordering> where
I: IntoIterator,
Self::Item: PartialOrd<I::Item>,
Self: Sized,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => if other.next().is_none() {
return Some(Ordering::Equal)
} else {
return Some(Ordering::Less)
},
Some(val) => val,
};
let y = match other.next() {
None => return Some(Ordering::Greater),
Some(val) => val,
};
match x.partial_cmp(&y) {
Some(Ordering::Equal) => (),
non_eq => return non_eq,
}
}
}
/// Determines if the elements of this `Iterator` are equal to those of
/// another.
#[stable(feature = "iter_order", since = "1.5.0")]
fn eq<I>(mut self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialEq<I::Item>,
Self: Sized,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => return other.next().is_none(),
Some(val) => val,
};
let y = match other.next() {
None => return false,
Some(val) => val,
};
if x != y { return false }
}
}
/// Determines if the elements of this `Iterator` are unequal to those of
/// another.
#[stable(feature = "iter_order", since = "1.5.0")]
fn ne<I>(mut self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialEq<I::Item>,
Self: Sized,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => return other.next().is_some(),
Some(val) => val,
};
let y = match other.next() {
None => return true,
Some(val) => val,
};
if x != y { return true }
}
}
/// Determines if the elements of this `Iterator` are lexicographically
/// less than those of another.
#[stable(feature = "iter_order", since = "1.5.0")]
fn lt<I>(mut self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<I::Item>,
Self: Sized,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => return other.next().is_some(),
Some(val) => val,
};
let y = match other.next() {
None => return false,
Some(val) => val,
};
match x.partial_cmp(&y) {
Some(Ordering::Less) => return true,
Some(Ordering::Equal) => (),
Some(Ordering::Greater) => return false,
None => return false,
}
}
}
/// Determines if the elements of this `Iterator` are lexicographically
/// less or equal to those of another.
#[stable(feature = "iter_order", since = "1.5.0")]
fn le<I>(mut self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<I::Item>,
Self: Sized,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => { other.next(); return true; },
Some(val) => val,
};
let y = match other.next() {
None => return false,
Some(val) => val,
};
match x.partial_cmp(&y) {
Some(Ordering::Less) => return true,
Some(Ordering::Equal) => (),
Some(Ordering::Greater) => return false,
None => return false,
}
}
}
/// Determines if the elements of this `Iterator` are lexicographically
/// greater than those of another.
#[stable(feature = "iter_order", since = "1.5.0")]
fn gt<I>(mut self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<I::Item>,
Self: Sized,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => { other.next(); return false; },
Some(val) => val,
};
let y = match other.next() {
None => return true,
Some(val) => val,
};
match x.partial_cmp(&y) {
Some(Ordering::Less) => return false,
Some(Ordering::Equal) => (),
Some(Ordering::Greater) => return true,
None => return false,
}
}
}
/// Determines if the elements of this `Iterator` are lexicographically
/// greater than or equal to those of another.
#[stable(feature = "iter_order", since = "1.5.0")]
fn ge<I>(mut self, other: I) -> bool where
I: IntoIterator,
Self::Item: PartialOrd<I::Item>,
Self: Sized,
{
let mut other = other.into_iter();
loop {
let x = match self.next() {
None => return other.next().is_none(),
Some(val) => val,
};
let y = match other.next() {
None => return true,
Some(val) => val,
};
match x.partial_cmp(&y) {
Some(Ordering::Less) => return false,
Some(Ordering::Equal) => (),
Some(Ordering::Greater) => return true,
None => return false,
}
}
}
}
/// Select an element from an iterator based on the given "projection"
/// and "comparison" function.
///
/// This is an idiosyncratic helper to try to factor out the
/// commonalities of {max,min}{,_by}. In particular, this avoids
/// having to implement optimizations several times.
#[inline]
fn select_fold1<I, B, FProj, FCmp>(mut it: I,
mut f_proj: FProj,
mut f_cmp: FCmp) -> Option<(B, I::Item)>
where I: Iterator,
FProj: FnMut(&I::Item) -> B,
FCmp: FnMut(&B, &I::Item, &B, &I::Item) -> bool
{
// start with the first element as our selection. This avoids
// having to use `Option`s inside the loop, translating to a
// sizeable performance gain (6x in one case).
it.next().map(|first| {
let first_p = f_proj(&first);
it.fold((first_p, first), |(sel_p, sel), x| {
let x_p = f_proj(&x);
if f_cmp(&sel_p, &sel, &x_p, &x) {
(x_p, x)
} else {
(sel_p, sel)
}
})
})
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<I: Iterator + ?Sized> Iterator for &mut I {
type Item = I::Item;
fn next(&mut self) -> Option<I::Item> { (**self).next() }
fn size_hint(&self) -> (usize, Option<usize>) { (**self).size_hint() }
fn nth(&mut self, n: usize) -> Option<Self::Item> {
(**self).nth(n)
}
}
| (self) |
domain_mappings.create_domain_mapping.js | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
function | () {
// [START appengine_v1_generated_DomainMappings_CreateDomainMapping_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Name of the parent Application resource. Example: `apps/myapp`.
*/
// const parent = 'abc123'
/**
* Domain mapping configuration.
*/
// const domainMapping = {}
/**
* Whether the domain creation should override any existing mappings for this
* domain. By default, overrides are rejected.
*/
// const overrideStrategy = {}
// Imports the Appengine library
const {DomainMappingsClient} = require('@google-cloud/appengine-admin').v1;
// Instantiates a client
const appengineClient = new DomainMappingsClient();
async function callCreateDomainMapping() {
// Construct request
const request = {};
// Run request
const [operation] = await appengineClient.createDomainMapping(request);
const [response] = await operation.promise();
console.log(response);
}
callCreateDomainMapping();
// [END appengine_v1_generated_DomainMappings_CreateDomainMapping_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
| main |
main.min.js | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){"use strict";require("./vendor/modernizr.js");require("slick-carousel");var $=require("jquery");$(".js-toggle-nav.header__toggle").click(function(){$(this).toggleClass("is-active");$(".header__nav").toggleClass("is-active-nav");$("body").toggleClass("mobile-menu--active")});function closeHeaderMenu(){$(".js-toggle-nav.header__toggle").removeClass("is-active");$(".header__nav").removeClass("is-active-nav");$("body").removeClass("mobile-menu--active")}document.addEventListener("keyup",function(event){var keyName=event.key;if(keyName==="Escape"){if($("body").hasClass("mobile-menu--active")){closeHeaderMenu()}}});function handleMenuClick(event){if($("body").hasClass("mobile-menu--active")){if(event.target.closest(".header__nav")==null&&event.target.closest(".header__toggle")==null){closeHeaderMenu()}}}document.addEventListener("click",function(event){handleMenuClick(event)});document.addEventListener("touchend",function(event){handleMenuClick(event)})},{"./vendor/modernizr.js":2,jquery:3,"slick-carousel":4}],2:[function(require,module,exports){"use strict";var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj};!function(e,t,n){function r(e,t){return(typeof e==="undefined"?"undefined":_typeof(e))===t}function o(){var e,t,n,o,i,s,a;for(var l in S){if(S.hasOwnProperty(l)){if(e=[],t=S[l],t.name&&(e.push(t.name.toLowerCase()),t.options&&t.options.aliases&&t.options.aliases.length))for(n=0;n<t.options.aliases.length;n++){e.push(t.options.aliases[n].toLowerCase())}for(o=r(t.fn,"function")?t.fn():t.fn,i=0;i<e.length;i++){s=e[i],a=s.split("."),1===a.length?Modernizr[a[0]]=o:(!Modernizr[a[0]]||Modernizr[a[0]]instanceof Boolean||(Modernizr[a[0]]=new Boolean(Modernizr[a[0]])),Modernizr[a[0]][a[1]]=o),C.push((o?"":"no-")+a.join("-"))}}}}function i(e){var t=b.className,n=Modernizr._config.classPrefix||"";if(E&&(t=t.baseVal),Modernizr._config.enableJSClass){var r=new RegExp("(^|\\s)"+n+"no-js(\\s|$)");t=t.replace(r,"$1"+n+"js$2")}Modernizr._config.enableClasses&&(t+=" "+n+e.join(" "+n),E?b.className.baseVal=t:b.className=t)}function s(){return"function"!=typeof t.createElement?t.createElement(arguments[0]):E?t.createElementNS.call(t,"http://www.w3.org/2000/svg",arguments[0]):t.createElement.apply(t,arguments)}function a(){var e=t.body;return e||(e=s(E?"svg":"body"),e.fake=!0),e}function l(e,n,r,o){var i,l,c,u,f="modernizr",d=s("div"),p=a();if(parseInt(r,10))for(;r--;){c=s("div"),c.id=o?o[r]:f+(r+1),d.appendChild(c)}return i=s("style"),i.type="text/css",i.id="s"+f,(p.fake?p:d).appendChild(i),p.appendChild(d),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(t.createTextNode(e)),d.id=f,p.fake&&(p.style.background="",p.style.overflow="hidden",u=b.style.overflow,b.style.overflow="hidden",b.appendChild(p)),l=n(d,e),p.fake?(p.parentNode.removeChild(p),b.style.overflow=u,b.offsetHeight):d.parentNode.removeChild(d),!!l}function c(e,t){return!!~(""+e).indexOf(t)}function u(e){return e.replace(/([a-z])-([a-z])/g,function(e,t,n){return t+n.toUpperCase()}).replace(/^-/,"")}function f(e,t){return function(){return e.apply(t,arguments)}}function d(e,t,n){var o;for(var i in e){if(e[i]in t)return n===!1?e[i]:(o=t[e[i]],r(o,"function")?f(o,n||t):o)}return!1}function p(e){return e.replace(/([A-Z])/g,function(e,t){return"-"+t.toLowerCase()}).replace(/^ms-/,"-ms-")}function m(t,n,r){var o;if("getComputedStyle"in e){o=getComputedStyle.call(e,t,n);var i=e.console;if(null!==o)r&&(o=o.getPropertyValue(r));else if(i){var s=i.error?"error":"log";i[s].call(i,"getComputedStyle returning null, its possible modernizr test results are inaccurate")}}else o=!n&&t.currentStyle&&t.currentStyle[r];return o}function h(t,r){var o=t.length;if("CSS"in e&&"supports"in e.CSS){for(;o--;){if(e.CSS.supports(p(t[o]),r))return!0}return!1}if("CSSSupportsRule"in e){for(var i=[];o--;){i.push("("+p(t[o])+":"+r+")")}return i=i.join(" or "),l("@supports ("+i+") { #modernizr { position: absolute; } }",function(e){return"absolute"==m(e,null,"position")})}return n}function | (e,t,o,i){function a(){f&&(delete F.style,delete F.modElem)}if(i=r(i,"undefined")?!1:i,!r(o,"undefined")){var l=h(e,o);if(!r(l,"undefined"))return l}for(var f,d,p,m,g,v=["modernizr","tspan","samp"];!F.style&&v.length;){f=!0,F.modElem=s(v.shift()),F.style=F.modElem.style}for(p=e.length,d=0;p>d;d++){if(m=e[d],g=F.style[m],c(m,"-")&&(m=u(m)),F.style[m]!==n){if(i||r(o,"undefined"))return a(),"pfx"==t?m:!0;try{F.style[m]=o}catch(y){}if(F.style[m]!=g)return a(),"pfx"==t?m:!0}}return a(),!1}function v(e,t,n,o,i){var s=e.charAt(0).toUpperCase()+e.slice(1),a=(e+" "+z.join(s+" ")+s).split(" ");return r(t,"string")||r(t,"undefined")?g(a,t,o,i):(a=(e+" "+P.join(s+" ")+s).split(" "),d(a,t,n))}function y(e,t,r){return v(e,n,n,t,r)}var C=[],S=[],x={_version:"3.5.0",_config:{classPrefix:"test--",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function on(e,t){var n=this;setTimeout(function(){t(n[e])},0)},addTest:function addTest(e,t,n){S.push({name:e,fn:t,options:n})},addAsyncTest:function addAsyncTest(e){S.push({name:null,fn:e})}},Modernizr=function Modernizr(){};Modernizr.prototype=x,Modernizr=new Modernizr;var b=t.documentElement,E="svg"===b.nodeName.toLowerCase();E||!function(e,t){function n(e,t){var n=e.createElement("p"),r=e.getElementsByTagName("head")[0]||e.documentElement;return n.innerHTML="x<style>"+t+"</style>",r.insertBefore(n.lastChild,r.firstChild)}function r(){var e=C.elements;return"string"==typeof e?e.split(" "):e}function o(e,t){var n=C.elements;"string"!=typeof n&&(n=n.join(" ")),"string"!=typeof e&&(e=e.join(" ")),C.elements=n+" "+e,c(t)}function i(e){var t=y[e[g]];return t||(t={},v++,e[g]=v,y[v]=t),t}function s(e,n,r){if(n||(n=t),f)return n.createElement(e);r||(r=i(n));var o;return o=r.cache[e]?r.cache[e].cloneNode():h.test(e)?(r.cache[e]=r.createElem(e)).cloneNode():r.createElem(e),!o.canHaveChildren||m.test(e)||o.tagUrn?o:r.frag.appendChild(o)}function a(e,n){if(e||(e=t),f)return e.createDocumentFragment();n=n||i(e);for(var o=n.frag.cloneNode(),s=0,a=r(),l=a.length;l>s;s++){o.createElement(a[s])}return o}function l(e,t){t.cache||(t.cache={},t.createElem=e.createElement,t.createFrag=e.createDocumentFragment,t.frag=t.createFrag()),e.createElement=function(n){return C.shivMethods?s(n,e,t):t.createElem(n)},e.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+r().join().replace(/[\w\-:]+/g,function(e){return t.createElem(e),t.frag.createElement(e),'c("'+e+'")'})+");return n}")(C,t.frag)}function c(e){e||(e=t);var r=i(e);return!C.shivCSS||u||r.hasCSS||(r.hasCSS=!!n(e,"article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}")),f||l(e,r),e}var u,f,d="3.7.3",p=e.html5||{},m=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,h=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,g="_html5shiv",v=0,y={};!function(){try{var e=t.createElement("a");e.innerHTML="<xyz></xyz>",u="hidden"in e,f=1==e.childNodes.length||function(){t.createElement("a");var e=t.createDocumentFragment();return"undefined"==typeof e.cloneNode||"undefined"==typeof e.createDocumentFragment||"undefined"==typeof e.createElement}()}catch(n){u=!0,f=!0}}();var C={elements:p.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video",version:d,shivCSS:p.shivCSS!==!1,supportsUnknownElements:f,shivMethods:p.shivMethods!==!1,type:"default",shivDocument:c,createElement:s,createDocumentFragment:a,addElements:o};e.html5=C,c(t),"object"==(typeof module==="undefined"?"undefined":_typeof(module))&&module.exports&&(module.exports=C)}("undefined"!=typeof e?e:this,t);var w=x._config.usePrefixes?" -webkit- -moz- -o- -ms- ".split(" "):["",""];x._prefixes=w,Modernizr.addTest("opacity",function(){var e=s("a").style;return e.cssText=w.join("opacity:.55;"),/^0.55$/.test(e.opacity)});var _="CSS"in e&&"supports"in e.CSS,T="supportsCSS"in e;Modernizr.addTest("supports",_||T);var k=x.testStyles=l,N="Moz O ms Webkit",z=x._config.usePrefixes?N.split(" "):[];x._cssomPrefixes=z;var P=x._config.usePrefixes?N.toLowerCase().split(" "):[];x._domPrefixes=P;var j={elem:s("modernizr")};Modernizr._q.push(function(){delete j.elem});var F={style:j.elem.style};Modernizr._q.unshift(function(){delete F.style}),x.testAllProps=v,x.testAllProps=y,Modernizr.addTest("flexbox",y("flexBasis","1px",!0)),Modernizr.addTest("cssmask",y("maskRepeat","repeat-x",!0)),Modernizr.addTest("csstransforms",function(){return-1===navigator.userAgent.indexOf("Android 2.")&&y("transform","scale(1)",!0)}),Modernizr.addTest("csstransforms3d",function(){var e=!!y("perspective","1px",!0),t=Modernizr._config.usePrefixes;if(e&&(!t||"webkitPerspective"in b.style)){var n,r="#modernizr{width:0;height:0}";Modernizr.supports?n="@supports (perspective: 1px)":(n="@media (transform-3d)",t&&(n+=",(-webkit-transform-3d)")),n+="{#modernizr{width:7px;height:18px;margin:0;padding:0;border:0}}",k(r+n,function(t){e=7===t.offsetWidth&&18===t.offsetHeight})}return e}),o(),i(C),delete x.addTest,delete x.addAsyncTest;for(var A=0;A<Modernizr._q.length;A++){Modernizr._q[A]()}e.Modernizr=Modernizr}(window,document)},{}],3:[function(require,module,exports){(function(global,factory){"use strict";if(typeof module==="object"&&typeof module.exports==="object"){module.exports=global.document?factory(global,true):function(w){if(!w.document){throw new Error("jQuery requires a window with a document")}return factory(w)}}else{factory(global)}})(typeof window!=="undefined"?window:this,function(window,noGlobal){"use strict";var arr=[];var document=window.document;var getProto=Object.getPrototypeOf;var slice=arr.slice;var concat=arr.concat;var push=arr.push;var indexOf=arr.indexOf;var class2type={};var toString=class2type.toString;var hasOwn=class2type.hasOwnProperty;var fnToString=hasOwn.toString;var ObjectFunctionString=fnToString.call(Object);var support={};function DOMEval(code,doc){doc=doc||document;var script=doc.createElement("script");script.text=code;doc.head.appendChild(script).parentNode.removeChild(script)}var version="3.2.1",jQuery=function(selector,context){return new jQuery.fn.init(selector,context)},rtrim=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,rmsPrefix=/^-ms-/,rdashAlpha=/-([a-z])/g,fcamelCase=function(all,letter){return letter.toUpperCase()};jQuery.fn=jQuery.prototype={jquery:version,constructor:jQuery,length:0,toArray:function(){return slice.call(this)},get:function(num){if(num==null){return slice.call(this)}return num<0?this[num+this.length]:this[num]},pushStack:function(elems){var ret=jQuery.merge(this.constructor(),elems);ret.prevObject=this;return ret},each:function(callback){return jQuery.each(this,callback)},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem)}))},slice:function(){return this.pushStack(slice.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(i){var len=this.length,j=+i+(i<0?len:0);return this.pushStack(j>=0&&j<len?[this[j]]:[])},end:function(){return this.prevObject||this.constructor()},push:push,sort:arr.sort,splice:arr.splice};jQuery.extend=jQuery.fn.extend=function(){var options,name,src,copy,copyIsArray,clone,target=arguments[0]||{},i=1,length=arguments.length,deep=false;if(typeof target==="boolean"){deep=target;target=arguments[i]||{};i++}if(typeof target!=="object"&&!jQuery.isFunction(target)){target={}}if(i===length){target=this;i--}for(;i<length;i++){if((options=arguments[i])!=null){for(name in options){src=target[name];copy=options[name];if(target===copy){continue}if(deep&©&&(jQuery.isPlainObject(copy)||(copyIsArray=Array.isArray(copy)))){if(copyIsArray){copyIsArray=false;clone=src&&Array.isArray(src)?src:[]}else{clone=src&&jQuery.isPlainObject(src)?src:{}}target[name]=jQuery.extend(deep,clone,copy)}else if(copy!==undefined){target[name]=copy}}}}return target};jQuery.extend({expando:"jQuery"+(version+Math.random()).replace(/\D/g,""),isReady:true,error:function(msg){throw new Error(msg)},noop:function(){},isFunction:function(obj){return jQuery.type(obj)==="function"},isWindow:function(obj){return obj!=null&&obj===obj.window},isNumeric:function(obj){var type=jQuery.type(obj);return(type==="number"||type==="string")&&!isNaN(obj-parseFloat(obj))},isPlainObject:function(obj){var proto,Ctor;if(!obj||toString.call(obj)!=="[object Object]"){return false}proto=getProto(obj);if(!proto){return true}Ctor=hasOwn.call(proto,"constructor")&&proto.constructor;return typeof Ctor==="function"&&fnToString.call(Ctor)===ObjectFunctionString},isEmptyObject:function(obj){var name;for(name in obj){return false}return true},type:function(obj){if(obj==null){return obj+""}return typeof obj==="object"||typeof obj==="function"?class2type[toString.call(obj)]||"object":typeof obj},globalEval:function(code){DOMEval(code)},camelCase:function(string){return string.replace(rmsPrefix,"ms-").replace(rdashAlpha,fcamelCase)},each:function(obj,callback){var length,i=0;if(isArrayLike(obj)){length=obj.length;for(;i<length;i++){if(callback.call(obj[i],i,obj[i])===false){break}}}else{for(i in obj){if(callback.call(obj[i],i,obj[i])===false){break}}}return obj},trim:function(text){return text==null?"":(text+"").replace(rtrim,"")},makeArray:function(arr,results){var ret=results||[];if(arr!=null){if(isArrayLike(Object(arr))){jQuery.merge(ret,typeof arr==="string"?[arr]:arr)}else{push.call(ret,arr)}}return ret},inArray:function(elem,arr,i){return arr==null?-1:indexOf.call(arr,elem,i)},merge:function(first,second){var len=+second.length,j=0,i=first.length;for(;j<len;j++){first[i++]=second[j]}first.length=i;return first},grep:function(elems,callback,invert){var callbackInverse,matches=[],i=0,length=elems.length,callbackExpect=!invert;for(;i<length;i++){callbackInverse=!callback(elems[i],i);if(callbackInverse!==callbackExpect){matches.push(elems[i])}}return matches},map:function(elems,callback,arg){var length,value,i=0,ret=[];if(isArrayLike(elems)){length=elems.length;for(;i<length;i++){value=callback(elems[i],i,arg);if(value!=null){ret.push(value)}}}else{for(i in elems){value=callback(elems[i],i,arg);if(value!=null){ret.push(value)}}}return concat.apply([],ret)},guid:1,proxy:function(fn,context){var tmp,args,proxy;if(typeof context==="string"){tmp=fn[context];context=fn;fn=tmp}if(!jQuery.isFunction(fn)){return undefined}args=slice.call(arguments,2);proxy=function(){return fn.apply(context||this,args.concat(slice.call(arguments)))};proxy.guid=fn.guid=fn.guid||jQuery.guid++;return proxy},now:Date.now,support:support});if(typeof Symbol==="function"){jQuery.fn[Symbol.iterator]=arr[Symbol.iterator]}jQuery.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(i,name){class2type["[object "+name+"]"]=name.toLowerCase()});function isArrayLike(obj){var length=!!obj&&"length"in obj&&obj.length,type=jQuery.type(obj);if(type==="function"||jQuery.isWindow(obj)){return false}return type==="array"||length===0||typeof length==="number"&&length>0&&length-1 in obj}var Sizzle=function(window){var i,support,Expr,getText,isXML,tokenize,compile,select,outermostContext,sortInput,hasDuplicate,setDocument,document,docElem,documentIsHTML,rbuggyQSA,rbuggyMatches,matches,contains,expando="sizzle"+1*new Date,preferredDoc=window.document,dirruns=0,done=0,classCache=createCache(),tokenCache=createCache(),compilerCache=createCache(),sortOrder=function(a,b){if(a===b){hasDuplicate=true}return 0},hasOwn={}.hasOwnProperty,arr=[],pop=arr.pop,push_native=arr.push,push=arr.push,slice=arr.slice,indexOf=function(list,elem){var i=0,len=list.length;for(;i<len;i++){if(list[i]===elem){return i}}return-1},booleans="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",whitespace="[\\x20\\t\\r\\n\\f]",identifier="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",attributes="\\["+whitespace+"*("+identifier+")(?:"+whitespace+"*([*^$|!~]?=)"+whitespace+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+identifier+"))|)"+whitespace+"*\\]",pseudos=":("+identifier+")(?:\\(("+"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|"+"((?:\\\\.|[^\\\\()[\\]]|"+attributes+")*)|"+".*"+")\\)|)",rwhitespace=new RegExp(whitespace+"+","g"),rtrim=new RegExp("^"+whitespace+"+|((?:^|[^\\\\])(?:\\\\.)*)"+whitespace+"+$","g"),rcomma=new RegExp("^"+whitespace+"*,"+whitespace+"*"),rcombinators=new RegExp("^"+whitespace+"*([>+~]|"+whitespace+")"+whitespace+"*"),rattributeQuotes=new RegExp("="+whitespace+"*([^\\]'\"]*?)"+whitespace+"*\\]","g"),rpseudo=new RegExp(pseudos),ridentifier=new RegExp("^"+identifier+"$"),matchExpr={ID:new RegExp("^#("+identifier+")"),CLASS:new RegExp("^\\.("+identifier+")"),TAG:new RegExp("^("+identifier+"|[*])"),ATTR:new RegExp("^"+attributes),PSEUDO:new RegExp("^"+pseudos),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+whitespace+"*(even|odd|(([+-]|)(\\d*)n|)"+whitespace+"*(?:([+-]|)"+whitespace+"*(\\d+)|))"+whitespace+"*\\)|)","i"),bool:new RegExp("^(?:"+booleans+")$","i"),needsContext:new RegExp("^"+whitespace+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+whitespace+"*((?:-\\d)?\\d*)"+whitespace+"*\\)|)(?=[^-]|$)","i")},rinputs=/^(?:input|select|textarea|button)$/i,rheader=/^h\d$/i,rnative=/^[^{]+\{\s*\[native \w/,rquickExpr=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,rsibling=/[+~]/,runescape=new RegExp("\\\\([\\da-f]{1,6}"+whitespace+"?|("+whitespace+")|.)","ig"),funescape=function(_,escaped,escapedWhitespace){var high="0x"+escaped-65536;return high!==high||escapedWhitespace?escaped:high<0?String.fromCharCode(high+65536):String.fromCharCode(high>>10|55296,high&1023|56320)},rcssescape=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,fcssescape=function(ch,asCodePoint){if(asCodePoint){if(ch==="\0"){return"�"}return ch.slice(0,-1)+"\\"+ch.charCodeAt(ch.length-1).toString(16)+" "}return"\\"+ch},unloadHandler=function(){setDocument()},disabledAncestor=addCombinator(function(elem){return elem.disabled===true&&("form"in elem||"label"in elem)},{dir:"parentNode",next:"legend"});try{push.apply(arr=slice.call(preferredDoc.childNodes),preferredDoc.childNodes);arr[preferredDoc.childNodes.length].nodeType}catch(e){push={apply:arr.length?function(target,els){push_native.apply(target,slice.call(els))}:function(target,els){var j=target.length,i=0;while(target[j++]=els[i++]){}target.length=j-1}}}function Sizzle(selector,context,results,seed){var m,i,elem,nid,match,groups,newSelector,newContext=context&&context.ownerDocument,nodeType=context?context.nodeType:9;results=results||[];if(typeof selector!=="string"||!selector||nodeType!==1&&nodeType!==9&&nodeType!==11){return results}if(!seed){if((context?context.ownerDocument||context:preferredDoc)!==document){setDocument(context)}context=context||document;if(documentIsHTML){if(nodeType!==11&&(match=rquickExpr.exec(selector))){if(m=match[1]){if(nodeType===9){if(elem=context.getElementById(m)){if(elem.id===m){results.push(elem);return results}}else{return results}}else{if(newContext&&(elem=newContext.getElementById(m))&&contains(context,elem)&&elem.id===m){results.push(elem);return results}}}else if(match[2]){push.apply(results,context.getElementsByTagName(selector));return results}else if((m=match[3])&&support.getElementsByClassName&&context.getElementsByClassName){push.apply(results,context.getElementsByClassName(m));return results}}if(support.qsa&&!compilerCache[selector+" "]&&(!rbuggyQSA||!rbuggyQSA.test(selector))){if(nodeType!==1){newContext=context;newSelector=selector}else if(context.nodeName.toLowerCase()!=="object"){if(nid=context.getAttribute("id")){nid=nid.replace(rcssescape,fcssescape)}else{context.setAttribute("id",nid=expando)}groups=tokenize(selector);i=groups.length;while(i--){groups[i]="#"+nid+" "+toSelector(groups[i])}newSelector=groups.join(",");newContext=rsibling.test(selector)&&testContext(context.parentNode)||context}if(newSelector){try{push.apply(results,newContext.querySelectorAll(newSelector));return results}catch(qsaError){}finally{if(nid===expando){context.removeAttribute("id")}}}}}}return select(selector.replace(rtrim,"$1"),context,results,seed)}function createCache(){var keys=[];function cache(key,value){if(keys.push(key+" ")>Expr.cacheLength){delete cache[keys.shift()]}return cache[key+" "]=value}return cache}function markFunction(fn){fn[expando]=true;return fn}function assert(fn){var el=document.createElement("fieldset");try{return!!fn(el)}catch(e){return false}finally{if(el.parentNode){el.parentNode.removeChild(el)}el=null}}function addHandle(attrs,handler){var arr=attrs.split("|"),i=arr.length;while(i--){Expr.attrHandle[arr[i]]=handler}}function siblingCheck(a,b){var cur=b&&a,diff=cur&&a.nodeType===1&&b.nodeType===1&&a.sourceIndex-b.sourceIndex;if(diff){return diff}if(cur){while(cur=cur.nextSibling){if(cur===b){return-1}}}return a?1:-1}function createInputPseudo(type){return function(elem){var name=elem.nodeName.toLowerCase();return name==="input"&&elem.type===type}}function createButtonPseudo(type){return function(elem){var name=elem.nodeName.toLowerCase();return(name==="input"||name==="button")&&elem.type===type}}function createDisabledPseudo(disabled){return function(elem){if("form"in elem){if(elem.parentNode&&elem.disabled===false){if("label"in elem){if("label"in elem.parentNode){return elem.parentNode.disabled===disabled}else{return elem.disabled===disabled}}return elem.isDisabled===disabled||elem.isDisabled!==!disabled&&disabledAncestor(elem)===disabled}return elem.disabled===disabled}else if("label"in elem){return elem.disabled===disabled}return false}}function createPositionalPseudo(fn){return markFunction(function(argument){argument=+argument;return markFunction(function(seed,matches){var j,matchIndexes=fn([],seed.length,argument),i=matchIndexes.length;while(i--){if(seed[j=matchIndexes[i]]){seed[j]=!(matches[j]=seed[j])}}})})}function testContext(context){return context&&typeof context.getElementsByTagName!=="undefined"&&context}support=Sizzle.support={};isXML=Sizzle.isXML=function(elem){var documentElement=elem&&(elem.ownerDocument||elem).documentElement;return documentElement?documentElement.nodeName!=="HTML":false};setDocument=Sizzle.setDocument=function(node){var hasCompare,subWindow,doc=node?node.ownerDocument||node:preferredDoc;if(doc===document||doc.nodeType!==9||!doc.documentElement){return document}document=doc;docElem=document.documentElement;documentIsHTML=!isXML(document);if(preferredDoc!==document&&(subWindow=document.defaultView)&&subWindow.top!==subWindow){if(subWindow.addEventListener){subWindow.addEventListener("unload",unloadHandler,false)}else if(subWindow.attachEvent){subWindow.attachEvent("onunload",unloadHandler)}}support.attributes=assert(function(el){el.className="i";return!el.getAttribute("className")});support.getElementsByTagName=assert(function(el){el.appendChild(document.createComment(""));return!el.getElementsByTagName("*").length});support.getElementsByClassName=rnative.test(document.getElementsByClassName);support.getById=assert(function(el){docElem.appendChild(el).id=expando;return!document.getElementsByName||!document.getElementsByName(expando).length});if(support.getById){Expr.filter["ID"]=function(id){var attrId=id.replace(runescape,funescape);return function(elem){return elem.getAttribute("id")===attrId}};Expr.find["ID"]=function(id,context){if(typeof context.getElementById!=="undefined"&&documentIsHTML){var elem=context.getElementById(id);return elem?[elem]:[]}}}else{Expr.filter["ID"]=function(id){var attrId=id.replace(runescape,funescape);return function(elem){var node=typeof elem.getAttributeNode!=="undefined"&&elem.getAttributeNode("id");return node&&node.value===attrId}};Expr.find["ID"]=function(id,context){if(typeof context.getElementById!=="undefined"&&documentIsHTML){var node,i,elems,elem=context.getElementById(id);if(elem){node=elem.getAttributeNode("id");if(node&&node.value===id){return[elem]}elems=context.getElementsByName(id);i=0;while(elem=elems[i++]){node=elem.getAttributeNode("id");if(node&&node.value===id){return[elem]}}}return[]}}}Expr.find["TAG"]=support.getElementsByTagName?function(tag,context){if(typeof context.getElementsByTagName!=="undefined"){return context.getElementsByTagName(tag)}else if(support.qsa){return context.querySelectorAll(tag)}}:function(tag,context){var elem,tmp=[],i=0,results=context.getElementsByTagName(tag);if(tag==="*"){while(elem=results[i++]){if(elem.nodeType===1){tmp.push(elem)}}return tmp}return results};Expr.find["CLASS"]=support.getElementsByClassName&&function(className,context){if(typeof context.getElementsByClassName!=="undefined"&&documentIsHTML){return context.getElementsByClassName(className)}};rbuggyMatches=[];rbuggyQSA=[];if(support.qsa=rnative.test(document.querySelectorAll)){assert(function(el){docElem.appendChild(el).innerHTML="<a id='"+expando+"'></a>"+"<select id='"+expando+"-\r\\' msallowcapture=''>"+"<option selected=''></option></select>";if(el.querySelectorAll("[msallowcapture^='']").length){rbuggyQSA.push("[*^$]="+whitespace+"*(?:''|\"\")")}if(!el.querySelectorAll("[selected]").length){rbuggyQSA.push("\\["+whitespace+"*(?:value|"+booleans+")")}if(!el.querySelectorAll("[id~="+expando+"-]").length){rbuggyQSA.push("~=")}if(!el.querySelectorAll(":checked").length){rbuggyQSA.push(":checked")}if(!el.querySelectorAll("a#"+expando+"+*").length){rbuggyQSA.push(".#.+[+~]")}});assert(function(el){el.innerHTML="<a href='' disabled='disabled'></a>"+"<select disabled='disabled'><option/></select>";var input=document.createElement("input");input.setAttribute("type","hidden");el.appendChild(input).setAttribute("name","D");if(el.querySelectorAll("[name=d]").length){rbuggyQSA.push("name"+whitespace+"*[*^$|!~]?=")}if(el.querySelectorAll(":enabled").length!==2){rbuggyQSA.push(":enabled",":disabled")}docElem.appendChild(el).disabled=true;if(el.querySelectorAll(":disabled").length!==2){rbuggyQSA.push(":enabled",":disabled")}el.querySelectorAll("*,:x");rbuggyQSA.push(",.*:")})}if(support.matchesSelector=rnative.test(matches=docElem.matches||docElem.webkitMatchesSelector||docElem.mozMatchesSelector||docElem.oMatchesSelector||docElem.msMatchesSelector)){assert(function(el){support.disconnectedMatch=matches.call(el,"*");matches.call(el,"[s!='']:x");rbuggyMatches.push("!=",pseudos)})}rbuggyQSA=rbuggyQSA.length&&new RegExp(rbuggyQSA.join("|"));rbuggyMatches=rbuggyMatches.length&&new RegExp(rbuggyMatches.join("|"));hasCompare=rnative.test(docElem.compareDocumentPosition);contains=hasCompare||rnative.test(docElem.contains)?function(a,b){var adown=a.nodeType===9?a.documentElement:a,bup=b&&b.parentNode;return a===bup||!!(bup&&bup.nodeType===1&&(adown.contains?adown.contains(bup):a.compareDocumentPosition&&a.compareDocumentPosition(bup)&16))}:function(a,b){if(b){while(b=b.parentNode){if(b===a){return true}}}return false};sortOrder=hasCompare?function(a,b){if(a===b){hasDuplicate=true;return 0}var compare=!a.compareDocumentPosition-!b.compareDocumentPosition;if(compare){return compare}compare=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1;if(compare&1||!support.sortDetached&&b.compareDocumentPosition(a)===compare){if(a===document||a.ownerDocument===preferredDoc&&contains(preferredDoc,a)){return-1}if(b===document||b.ownerDocument===preferredDoc&&contains(preferredDoc,b)){return 1}return sortInput?indexOf(sortInput,a)-indexOf(sortInput,b):0}return compare&4?-1:1}:function(a,b){if(a===b){hasDuplicate=true;return 0}var cur,i=0,aup=a.parentNode,bup=b.parentNode,ap=[a],bp=[b];if(!aup||!bup){return a===document?-1:b===document?1:aup?-1:bup?1:sortInput?indexOf(sortInput,a)-indexOf(sortInput,b):0}else if(aup===bup){return siblingCheck(a,b)}cur=a;while(cur=cur.parentNode){ap.unshift(cur)}cur=b;while(cur=cur.parentNode){bp.unshift(cur)}while(ap[i]===bp[i]){i++}return i?siblingCheck(ap[i],bp[i]):ap[i]===preferredDoc?-1:bp[i]===preferredDoc?1:0};return document};Sizzle.matches=function(expr,elements){return Sizzle(expr,null,null,elements)};Sizzle.matchesSelector=function(elem,expr){if((elem.ownerDocument||elem)!==document){setDocument(elem)}expr=expr.replace(rattributeQuotes,"='$1']");if(support.matchesSelector&&documentIsHTML&&!compilerCache[expr+" "]&&(!rbuggyMatches||!rbuggyMatches.test(expr))&&(!rbuggyQSA||!rbuggyQSA.test(expr))){try{var ret=matches.call(elem,expr);if(ret||support.disconnectedMatch||elem.document&&elem.document.nodeType!==11){return ret}}catch(e){}}return Sizzle(expr,document,null,[elem]).length>0};Sizzle.contains=function(context,elem){if((context.ownerDocument||context)!==document){setDocument(context)}return contains(context,elem)};Sizzle.attr=function(elem,name){if((elem.ownerDocument||elem)!==document){setDocument(elem)}var fn=Expr.attrHandle[name.toLowerCase()],val=fn&&hasOwn.call(Expr.attrHandle,name.toLowerCase())?fn(elem,name,!documentIsHTML):undefined;return val!==undefined?val:support.attributes||!documentIsHTML?elem.getAttribute(name):(val=elem.getAttributeNode(name))&&val.specified?val.value:null};Sizzle.escape=function(sel){return(sel+"").replace(rcssescape,fcssescape)};Sizzle.error=function(msg){throw new Error("Syntax error, unrecognized expression: "+msg)};Sizzle.uniqueSort=function(results){var elem,duplicates=[],j=0,i=0;hasDuplicate=!support.detectDuplicates;sortInput=!support.sortStable&&results.slice(0);results.sort(sortOrder);if(hasDuplicate){while(elem=results[i++]){if(elem===results[i]){j=duplicates.push(i)}}while(j--){results.splice(duplicates[j],1)}}sortInput=null;return results};getText=Sizzle.getText=function(elem){var node,ret="",i=0,nodeType=elem.nodeType;if(!nodeType){while(node=elem[i++]){ret+=getText(node)}}else if(nodeType===1||nodeType===9||nodeType===11){if(typeof elem.textContent==="string"){return elem.textContent}else{for(elem=elem.firstChild;elem;elem=elem.nextSibling){ret+=getText(elem)}}}else if(nodeType===3||nodeType===4){return elem.nodeValue}return ret};Expr=Sizzle.selectors={cacheLength:50,createPseudo:markFunction,match:matchExpr,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(match){match[1]=match[1].replace(runescape,funescape);match[3]=(match[3]||match[4]||match[5]||"").replace(runescape,funescape);if(match[2]==="~="){match[3]=" "+match[3]+" "}return match.slice(0,4)},CHILD:function(match){match[1]=match[1].toLowerCase();if(match[1].slice(0,3)==="nth"){if(!match[3]){Sizzle.error(match[0])}match[4]=+(match[4]?match[5]+(match[6]||1):2*(match[3]==="even"||match[3]==="odd"));match[5]=+(match[7]+match[8]||match[3]==="odd")}else if(match[3]){Sizzle.error(match[0])}return match},PSEUDO:function(match){var excess,unquoted=!match[6]&&match[2];if(matchExpr["CHILD"].test(match[0])){return null}if(match[3]){match[2]=match[4]||match[5]||""}else if(unquoted&&rpseudo.test(unquoted)&&(excess=tokenize(unquoted,true))&&(excess=unquoted.indexOf(")",unquoted.length-excess)-unquoted.length)){match[0]=match[0].slice(0,excess);match[2]=unquoted.slice(0,excess)}return match.slice(0,3)}},filter:{TAG:function(nodeNameSelector){var nodeName=nodeNameSelector.replace(runescape,funescape).toLowerCase();return nodeNameSelector==="*"?function(){return true}:function(elem){return elem.nodeName&&elem.nodeName.toLowerCase()===nodeName}},CLASS:function(className){var pattern=classCache[className+" "];return pattern||(pattern=new RegExp("(^|"+whitespace+")"+className+"("+whitespace+"|$)"))&&classCache(className,function(elem){return pattern.test(typeof elem.className==="string"&&elem.className||typeof elem.getAttribute!=="undefined"&&elem.getAttribute("class")||"")})},ATTR:function(name,operator,check){return function(elem){var result=Sizzle.attr(elem,name);if(result==null){return operator==="!="}if(!operator){return true}result+="";return operator==="="?result===check:operator==="!="?result!==check:operator==="^="?check&&result.indexOf(check)===0:operator==="*="?check&&result.indexOf(check)>-1:operator==="$="?check&&result.slice(-check.length)===check:operator==="~="?(" "+result.replace(rwhitespace," ")+" ").indexOf(check)>-1:operator==="|="?result===check||result.slice(0,check.length+1)===check+"-":false}},CHILD:function(type,what,argument,first,last){var simple=type.slice(0,3)!=="nth",forward=type.slice(-4)!=="last",ofType=what==="of-type";return first===1&&last===0?function(elem){return!!elem.parentNode}:function(elem,context,xml){var cache,uniqueCache,outerCache,node,nodeIndex,start,dir=simple!==forward?"nextSibling":"previousSibling",parent=elem.parentNode,name=ofType&&elem.nodeName.toLowerCase(),useCache=!xml&&!ofType,diff=false;if(parent){if(simple){while(dir){node=elem;while(node=node[dir]){if(ofType?node.nodeName.toLowerCase()===name:node.nodeType===1){return false}}start=dir=type==="only"&&!start&&"nextSibling"}return true}start=[forward?parent.firstChild:parent.lastChild];if(forward&&useCache){node=parent;outerCache=node[expando]||(node[expando]={});uniqueCache=outerCache[node.uniqueID]||(outerCache[node.uniqueID]={});cache=uniqueCache[type]||[];nodeIndex=cache[0]===dirruns&&cache[1];diff=nodeIndex&&cache[2];node=nodeIndex&&parent.childNodes[nodeIndex];while(node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop()){if(node.nodeType===1&&++diff&&node===elem){uniqueCache[type]=[dirruns,nodeIndex,diff];break}}}else{if(useCache){node=elem;outerCache=node[expando]||(node[expando]={});uniqueCache=outerCache[node.uniqueID]||(outerCache[node.uniqueID]={});cache=uniqueCache[type]||[];nodeIndex=cache[0]===dirruns&&cache[1];diff=nodeIndex}if(diff===false){while(node=++nodeIndex&&node&&node[dir]||(diff=nodeIndex=0)||start.pop()){if((ofType?node.nodeName.toLowerCase()===name:node.nodeType===1)&&++diff){if(useCache){outerCache=node[expando]||(node[expando]={});uniqueCache=outerCache[node.uniqueID]||(outerCache[node.uniqueID]={});uniqueCache[type]=[dirruns,diff]}if(node===elem){break}}}}}diff-=last;return diff===first||diff%first===0&&diff/first>=0}}},PSEUDO:function(pseudo,argument){var args,fn=Expr.pseudos[pseudo]||Expr.setFilters[pseudo.toLowerCase()]||Sizzle.error("unsupported pseudo: "+pseudo);if(fn[expando]){return fn(argument)}if(fn.length>1){args=[pseudo,pseudo,"",argument];return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase())?markFunction(function(seed,matches){var idx,matched=fn(seed,argument),i=matched.length;while(i--){idx=indexOf(seed,matched[i]);seed[idx]=!(matches[idx]=matched[i])}}):function(elem){return fn(elem,0,args)}}return fn}},pseudos:{not:markFunction(function(selector){var input=[],results=[],matcher=compile(selector.replace(rtrim,"$1"));return matcher[expando]?markFunction(function(seed,matches,context,xml){var elem,unmatched=matcher(seed,null,xml,[]),i=seed.length;while(i--){if(elem=unmatched[i]){seed[i]=!(matches[i]=elem)}}}):function(elem,context,xml){input[0]=elem;matcher(input,null,xml,results);input[0]=null;return!results.pop()}}),has:markFunction(function(selector){return function(elem){return Sizzle(selector,elem).length>0}}),contains:markFunction(function(text){text=text.replace(runescape,funescape);return function(elem){return(elem.textContent||elem.innerText||getText(elem)).indexOf(text)>-1}}),lang:markFunction(function(lang){if(!ridentifier.test(lang||"")){Sizzle.error("unsupported lang: "+lang)}lang=lang.replace(runescape,funescape).toLowerCase();return function(elem){var elemLang;do{if(elemLang=documentIsHTML?elem.lang:elem.getAttribute("xml:lang")||elem.getAttribute("lang")){elemLang=elemLang.toLowerCase();return elemLang===lang||elemLang.indexOf(lang+"-")===0}}while((elem=elem.parentNode)&&elem.nodeType===1);return false}}),target:function(elem){var hash=window.location&&window.location.hash;return hash&&hash.slice(1)===elem.id},root:function(elem){return elem===docElem},focus:function(elem){return elem===document.activeElement&&(!document.hasFocus||document.hasFocus())&&!!(elem.type||elem.href||~elem.tabIndex)},enabled:createDisabledPseudo(false),disabled:createDisabledPseudo(true),checked:function(elem){var nodeName=elem.nodeName.toLowerCase();return nodeName==="input"&&!!elem.checked||nodeName==="option"&&!!elem.selected},selected:function(elem){if(elem.parentNode){elem.parentNode.selectedIndex}return elem.selected===true},empty:function(elem){for(elem=elem.firstChild;elem;elem=elem.nextSibling){if(elem.nodeType<6){return false}}return true},parent:function(elem){return!Expr.pseudos["empty"](elem)},header:function(elem){return rheader.test(elem.nodeName)},input:function(elem){return rinputs.test(elem.nodeName)},button:function(elem){var name=elem.nodeName.toLowerCase();return name==="input"&&elem.type==="button"||name==="button"},text:function(elem){var attr;return elem.nodeName.toLowerCase()==="input"&&elem.type==="text"&&((attr=elem.getAttribute("type"))==null||attr.toLowerCase()==="text")},first:createPositionalPseudo(function(){return[0]}),last:createPositionalPseudo(function(matchIndexes,length){return[length-1]}),eq:createPositionalPseudo(function(matchIndexes,length,argument){return[argument<0?argument+length:argument]}),even:createPositionalPseudo(function(matchIndexes,length){var i=0;for(;i<length;i+=2){matchIndexes.push(i)}return matchIndexes}),odd:createPositionalPseudo(function(matchIndexes,length){var i=1;for(;i<length;i+=2){matchIndexes.push(i)}return matchIndexes}),lt:createPositionalPseudo(function(matchIndexes,length,argument){var i=argument<0?argument+length:argument;for(;--i>=0;){matchIndexes.push(i)}return matchIndexes}),gt:createPositionalPseudo(function(matchIndexes,length,argument){var i=argument<0?argument+length:argument;for(;++i<length;){matchIndexes.push(i)}return matchIndexes})}};Expr.pseudos["nth"]=Expr.pseudos["eq"];for(i in{radio:true,checkbox:true,file:true,password:true,image:true}){Expr.pseudos[i]=createInputPseudo(i)}for(i in{submit:true,reset:true}){Expr.pseudos[i]=createButtonPseudo(i)}function setFilters(){}setFilters.prototype=Expr.filters=Expr.pseudos;Expr.setFilters=new setFilters;tokenize=Sizzle.tokenize=function(selector,parseOnly){var matched,match,tokens,type,soFar,groups,preFilters,cached=tokenCache[selector+" "];if(cached){return parseOnly?0:cached.slice(0)}soFar=selector;groups=[];preFilters=Expr.preFilter;while(soFar){if(!matched||(match=rcomma.exec(soFar))){if(match){soFar=soFar.slice(match[0].length)||soFar}groups.push(tokens=[])}matched=false;if(match=rcombinators.exec(soFar)){matched=match.shift();tokens.push({value:matched,type:match[0].replace(rtrim," ")});soFar=soFar.slice(matched.length)}for(type in Expr.filter){if((match=matchExpr[type].exec(soFar))&&(!preFilters[type]||(match=preFilters[type](match)))){matched=match.shift();tokens.push({value:matched,type:type,matches:match});soFar=soFar.slice(matched.length)}}if(!matched){break}}return parseOnly?soFar.length:soFar?Sizzle.error(selector):tokenCache(selector,groups).slice(0)};function toSelector(tokens){var i=0,len=tokens.length,selector="";for(;i<len;i++){selector+=tokens[i].value}return selector}function addCombinator(matcher,combinator,base){var dir=combinator.dir,skip=combinator.next,key=skip||dir,checkNonElements=base&&key==="parentNode",doneName=done++;return combinator.first?function(elem,context,xml){while(elem=elem[dir]){if(elem.nodeType===1||checkNonElements){return matcher(elem,context,xml)}}return false}:function(elem,context,xml){var oldCache,uniqueCache,outerCache,newCache=[dirruns,doneName];if(xml){while(elem=elem[dir]){if(elem.nodeType===1||checkNonElements){if(matcher(elem,context,xml)){return true}}}}else{while(elem=elem[dir]){if(elem.nodeType===1||checkNonElements){outerCache=elem[expando]||(elem[expando]={});uniqueCache=outerCache[elem.uniqueID]||(outerCache[elem.uniqueID]={});if(skip&&skip===elem.nodeName.toLowerCase()){elem=elem[dir]||elem}else if((oldCache=uniqueCache[key])&&oldCache[0]===dirruns&&oldCache[1]===doneName){return newCache[2]=oldCache[2]}else{uniqueCache[key]=newCache;if(newCache[2]=matcher(elem,context,xml)){return true}}}}}return false}}function elementMatcher(matchers){return matchers.length>1?function(elem,context,xml){var i=matchers.length;while(i--){if(!matchers[i](elem,context,xml)){return false}}return true}:matchers[0]}function multipleContexts(selector,contexts,results){var i=0,len=contexts.length;for(;i<len;i++){Sizzle(selector,contexts[i],results)}return results}function condense(unmatched,map,filter,context,xml){var elem,newUnmatched=[],i=0,len=unmatched.length,mapped=map!=null;for(;i<len;i++){if(elem=unmatched[i]){if(!filter||filter(elem,context,xml)){newUnmatched.push(elem);if(mapped){map.push(i)}}}}return newUnmatched}function setMatcher(preFilter,selector,matcher,postFilter,postFinder,postSelector){if(postFilter&&!postFilter[expando]){postFilter=setMatcher(postFilter)}if(postFinder&&!postFinder[expando]){postFinder=setMatcher(postFinder,postSelector)}return markFunction(function(seed,results,context,xml){var temp,i,elem,preMap=[],postMap=[],preexisting=results.length,elems=seed||multipleContexts(selector||"*",context.nodeType?[context]:context,[]),matcherIn=preFilter&&(seed||!selector)?condense(elems,preMap,preFilter,context,xml):elems,matcherOut=matcher?postFinder||(seed?preFilter:preexisting||postFilter)?[]:results:matcherIn;if(matcher){matcher(matcherIn,matcherOut,context,xml)}if(postFilter){temp=condense(matcherOut,postMap);postFilter(temp,[],context,xml);i=temp.length;while(i--){if(elem=temp[i]){matcherOut[postMap[i]]=!(matcherIn[postMap[i]]=elem)}}}if(seed){if(postFinder||preFilter){if(postFinder){temp=[];i=matcherOut.length;while(i--){if(elem=matcherOut[i]){temp.push(matcherIn[i]=elem)}}postFinder(null,matcherOut=[],temp,xml)}i=matcherOut.length;while(i--){if((elem=matcherOut[i])&&(temp=postFinder?indexOf(seed,elem):preMap[i])>-1){seed[temp]=!(results[temp]=elem)}}}}else{matcherOut=condense(matcherOut===results?matcherOut.splice(preexisting,matcherOut.length):matcherOut);if(postFinder){postFinder(null,results,matcherOut,xml)}else{push.apply(results,matcherOut)}}})}function matcherFromTokens(tokens){var checkContext,matcher,j,len=tokens.length,leadingRelative=Expr.relative[tokens[0].type],implicitRelative=leadingRelative||Expr.relative[" "],i=leadingRelative?1:0,matchContext=addCombinator(function(elem){return elem===checkContext},implicitRelative,true),matchAnyContext=addCombinator(function(elem){return indexOf(checkContext,elem)>-1},implicitRelative,true),matchers=[function(elem,context,xml){var ret=!leadingRelative&&(xml||context!==outermostContext)||((checkContext=context).nodeType?matchContext(elem,context,xml):matchAnyContext(elem,context,xml));checkContext=null;return ret}];for(;i<len;i++){if(matcher=Expr.relative[tokens[i].type]){matchers=[addCombinator(elementMatcher(matchers),matcher)]}else{matcher=Expr.filter[tokens[i].type].apply(null,tokens[i].matches);if(matcher[expando]){j=++i;for(;j<len;j++){if(Expr.relative[tokens[j].type]){break}}return setMatcher(i>1&&elementMatcher(matchers),i>1&&toSelector(tokens.slice(0,i-1).concat({value:tokens[i-2].type===" "?"*":""})).replace(rtrim,"$1"),matcher,i<j&&matcherFromTokens(tokens.slice(i,j)),j<len&&matcherFromTokens(tokens=tokens.slice(j)),j<len&&toSelector(tokens))}matchers.push(matcher)}}return elementMatcher(matchers)}function matcherFromGroupMatchers(elementMatchers,setMatchers){var bySet=setMatchers.length>0,byElement=elementMatchers.length>0,superMatcher=function(seed,context,xml,results,outermost){var elem,j,matcher,matchedCount=0,i="0",unmatched=seed&&[],setMatched=[],contextBackup=outermostContext,elems=seed||byElement&&Expr.find["TAG"]("*",outermost),dirrunsUnique=dirruns+=contextBackup==null?1:Math.random()||.1,len=elems.length;if(outermost){outermostContext=context===document||context||outermost}for(;i!==len&&(elem=elems[i])!=null;i++){if(byElement&&elem){j=0;if(!context&&elem.ownerDocument!==document){setDocument(elem);xml=!documentIsHTML}while(matcher=elementMatchers[j++]){if(matcher(elem,context||document,xml)){results.push(elem);break}}if(outermost){dirruns=dirrunsUnique}}if(bySet){if(elem=!matcher&&elem){matchedCount--}if(seed){unmatched.push(elem)}}}matchedCount+=i;if(bySet&&i!==matchedCount){j=0;while(matcher=setMatchers[j++]){matcher(unmatched,setMatched,context,xml)}if(seed){if(matchedCount>0){while(i--){if(!(unmatched[i]||setMatched[i])){setMatched[i]=pop.call(results)}}}setMatched=condense(setMatched)}push.apply(results,setMatched);if(outermost&&!seed&&setMatched.length>0&&matchedCount+setMatchers.length>1){Sizzle.uniqueSort(results)}}if(outermost){dirruns=dirrunsUnique;outermostContext=contextBackup}return unmatched};return bySet?markFunction(superMatcher):superMatcher}compile=Sizzle.compile=function(selector,match){var i,setMatchers=[],elementMatchers=[],cached=compilerCache[selector+" "];if(!cached){if(!match){match=tokenize(selector)}i=match.length;while(i--){cached=matcherFromTokens(match[i]);if(cached[expando]){setMatchers.push(cached)}else{elementMatchers.push(cached)}}cached=compilerCache(selector,matcherFromGroupMatchers(elementMatchers,setMatchers));cached.selector=selector}return cached};select=Sizzle.select=function(selector,context,results,seed){var i,tokens,token,type,find,compiled=typeof selector==="function"&&selector,match=!seed&&tokenize(selector=compiled.selector||selector);results=results||[];if(match.length===1){tokens=match[0]=match[0].slice(0);if(tokens.length>2&&(token=tokens[0]).type==="ID"&&context.nodeType===9&&documentIsHTML&&Expr.relative[tokens[1].type]){context=(Expr.find["ID"](token.matches[0].replace(runescape,funescape),context)||[])[0];if(!context){return results}else if(compiled){context=context.parentNode}selector=selector.slice(tokens.shift().value.length)}i=matchExpr["needsContext"].test(selector)?0:tokens.length;while(i--){token=tokens[i];if(Expr.relative[type=token.type]){break}if(find=Expr.find[type]){if(seed=find(token.matches[0].replace(runescape,funescape),rsibling.test(tokens[0].type)&&testContext(context.parentNode)||context)){tokens.splice(i,1);selector=seed.length&&toSelector(tokens);if(!selector){push.apply(results,seed);return results}break}}}}(compiled||compile(selector,match))(seed,context,!documentIsHTML,results,!context||rsibling.test(selector)&&testContext(context.parentNode)||context);return results};support.sortStable=expando.split("").sort(sortOrder).join("")===expando;support.detectDuplicates=!!hasDuplicate;setDocument();support.sortDetached=assert(function(el){return el.compareDocumentPosition(document.createElement("fieldset"))&1});if(!assert(function(el){el.innerHTML="<a href='#'></a>";return el.firstChild.getAttribute("href")==="#"})){addHandle("type|href|height|width",function(elem,name,isXML){if(!isXML){return elem.getAttribute(name,name.toLowerCase()==="type"?1:2)}})}if(!support.attributes||!assert(function(el){el.innerHTML="<input/>";el.firstChild.setAttribute("value","");return el.firstChild.getAttribute("value")===""})){addHandle("value",function(elem,name,isXML){if(!isXML&&elem.nodeName.toLowerCase()==="input"){return elem.defaultValue}})}if(!assert(function(el){return el.getAttribute("disabled")==null})){addHandle(booleans,function(elem,name,isXML){var val;if(!isXML){return elem[name]===true?name.toLowerCase():(val=elem.getAttributeNode(name))&&val.specified?val.value:null}})}return Sizzle}(window);jQuery.find=Sizzle;jQuery.expr=Sizzle.selectors;jQuery.expr[":"]=jQuery.expr.pseudos;jQuery.uniqueSort=jQuery.unique=Sizzle.uniqueSort;jQuery.text=Sizzle.getText;jQuery.isXMLDoc=Sizzle.isXML;jQuery.contains=Sizzle.contains;jQuery.escapeSelector=Sizzle.escape;var dir=function(elem,dir,until){var matched=[],truncate=until!==undefined;while((elem=elem[dir])&&elem.nodeType!==9){if(elem.nodeType===1){if(truncate&&jQuery(elem).is(until)){break}matched.push(elem)}}return matched};var siblings=function(n,elem){var matched=[];for(;n;n=n.nextSibling){if(n.nodeType===1&&n!==elem){matched.push(n)}}return matched};var rneedsContext=jQuery.expr.match.needsContext;function nodeName(elem,name){return elem.nodeName&&elem.nodeName.toLowerCase()===name.toLowerCase()}var rsingleTag=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;var risSimple=/^.[^:#\[\.,]*$/;function winnow(elements,qualifier,not){if(jQuery.isFunction(qualifier)){return jQuery.grep(elements,function(elem,i){return!!qualifier.call(elem,i,elem)!==not})}if(qualifier.nodeType){return jQuery.grep(elements,function(elem){return elem===qualifier!==not})}if(typeof qualifier!=="string"){return jQuery.grep(elements,function(elem){return indexOf.call(qualifier,elem)>-1!==not})}if(risSimple.test(qualifier)){return jQuery.filter(qualifier,elements,not)}qualifier=jQuery.filter(qualifier,elements);return jQuery.grep(elements,function(elem){return indexOf.call(qualifier,elem)>-1!==not&&elem.nodeType===1})}jQuery.filter=function(expr,elems,not){var elem=elems[0];if(not){expr=":not("+expr+")"}if(elems.length===1&&elem.nodeType===1){return jQuery.find.matchesSelector(elem,expr)?[elem]:[]}return jQuery.find.matches(expr,jQuery.grep(elems,function(elem){return elem.nodeType===1}))};jQuery.fn.extend({find:function(selector){var i,ret,len=this.length,self=this;if(typeof selector!=="string"){return this.pushStack(jQuery(selector).filter(function(){for(i=0;i<len;i++){if(jQuery.contains(self[i],this)){return true}}}))}ret=this.pushStack([]);for(i=0;i<len;i++){jQuery.find(selector,self[i],ret)}return len>1?jQuery.uniqueSort(ret):ret},filter:function(selector){return this.pushStack(winnow(this,selector||[],false))},not:function(selector){return this.pushStack(winnow(this,selector||[],true))},is:function(selector){return!!winnow(this,typeof selector==="string"&&rneedsContext.test(selector)?jQuery(selector):selector||[],false).length}});var rootjQuery,rquickExpr=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,init=jQuery.fn.init=function(selector,context,root){var match,elem;if(!selector){return this}root=root||rootjQuery;if(typeof selector==="string"){if(selector[0]==="<"&&selector[selector.length-1]===">"&&selector.length>=3){match=[null,selector,null]}else{match=rquickExpr.exec(selector)}if(match&&(match[1]||!context)){if(match[1]){context=context instanceof jQuery?context[0]:context;jQuery.merge(this,jQuery.parseHTML(match[1],context&&context.nodeType?context.ownerDocument||context:document,true));if(rsingleTag.test(match[1])&&jQuery.isPlainObject(context)){for(match in context){if(jQuery.isFunction(this[match])){this[match](context[match])}else{this.attr(match,context[match])}}}return this}else{elem=document.getElementById(match[2]);if(elem){this[0]=elem;this.length=1}return this}}else if(!context||context.jquery){return(context||root).find(selector)}else{return this.constructor(context).find(selector)}}else if(selector.nodeType){this[0]=selector;this.length=1;return this}else if(jQuery.isFunction(selector)){return root.ready!==undefined?root.ready(selector):selector(jQuery)}return jQuery.makeArray(selector,this)};init.prototype=jQuery.fn;rootjQuery=jQuery(document);var rparentsprev=/^(?:parents|prev(?:Until|All))/,guaranteedUnique={children:true,contents:true,next:true,prev:true};jQuery.fn.extend({has:function(target){var targets=jQuery(target,this),l=targets.length;return this.filter(function(){var i=0;for(;i<l;i++){if(jQuery.contains(this,targets[i])){return true}}})},closest:function(selectors,context){var cur,i=0,l=this.length,matched=[],targets=typeof selectors!=="string"&&jQuery(selectors);if(!rneedsContext.test(selectors)){for(;i<l;i++){for(cur=this[i];cur&&cur!==context;cur=cur.parentNode){if(cur.nodeType<11&&(targets?targets.index(cur)>-1:cur.nodeType===1&&jQuery.find.matchesSelector(cur,selectors))){matched.push(cur);break}}}}return this.pushStack(matched.length>1?jQuery.uniqueSort(matched):matched)},index:function(elem){if(!elem){return this[0]&&this[0].parentNode?this.first().prevAll().length:-1}if(typeof elem==="string"){return indexOf.call(jQuery(elem),this[0])}return indexOf.call(this,elem.jquery?elem[0]:elem)},add:function(selector,context){return this.pushStack(jQuery.uniqueSort(jQuery.merge(this.get(),jQuery(selector,context))))},addBack:function(selector){return this.add(selector==null?this.prevObject:this.prevObject.filter(selector))}});function sibling(cur,dir){while((cur=cur[dir])&&cur.nodeType!==1){}return cur}jQuery.each({parent:function(elem){var parent=elem.parentNode;return parent&&parent.nodeType!==11?parent:null},parents:function(elem){return dir(elem,"parentNode")},parentsUntil:function(elem,i,until){return dir(elem,"parentNode",until)},next:function(elem){return sibling(elem,"nextSibling")},prev:function(elem){return sibling(elem,"previousSibling")},nextAll:function(elem){return dir(elem,"nextSibling")},prevAll:function(elem){return dir(elem,"previousSibling")},nextUntil:function(elem,i,until){return dir(elem,"nextSibling",until)},prevUntil:function(elem,i,until){return dir(elem,"previousSibling",until)},siblings:function(elem){return siblings((elem.parentNode||{}).firstChild,elem)},children:function(elem){return siblings(elem.firstChild)},contents:function(elem){if(nodeName(elem,"iframe")){return elem.contentDocument}if(nodeName(elem,"template")){elem=elem.content||elem}return jQuery.merge([],elem.childNodes)}},function(name,fn){jQuery.fn[name]=function(until,selector){var matched=jQuery.map(this,fn,until);if(name.slice(-5)!=="Until"){selector=until}if(selector&&typeof selector==="string"){matched=jQuery.filter(selector,matched)}if(this.length>1){if(!guaranteedUnique[name]){jQuery.uniqueSort(matched)}if(rparentsprev.test(name)){matched.reverse()}}return this.pushStack(matched)}});var rnothtmlwhite=/[^\x20\t\r\n\f]+/g;function createOptions(options){var object={};jQuery.each(options.match(rnothtmlwhite)||[],function(_,flag){object[flag]=true});return object}jQuery.Callbacks=function(options){options=typeof options==="string"?createOptions(options):jQuery.extend({},options);var firing,memory,fired,locked,list=[],queue=[],firingIndex=-1,fire=function(){locked=locked||options.once;fired=firing=true;for(;queue.length;firingIndex=-1){memory=queue.shift();while(++firingIndex<list.length){if(list[firingIndex].apply(memory[0],memory[1])===false&&options.stopOnFalse){firingIndex=list.length;memory=false}}}if(!options.memory){memory=false}firing=false;if(locked){if(memory){list=[]}else{list=""}}},self={add:function(){if(list){if(memory&&!firing){firingIndex=list.length-1;queue.push(memory)}(function add(args){jQuery.each(args,function(_,arg){if(jQuery.isFunction(arg)){if(!options.unique||!self.has(arg)){list.push(arg)}}else if(arg&&arg.length&&jQuery.type(arg)!=="string"){add(arg)}})})(arguments);if(memory&&!firing){fire()}}return this},remove:function(){jQuery.each(arguments,function(_,arg){var index;while((index=jQuery.inArray(arg,list,index))>-1){list.splice(index,1);if(index<=firingIndex){firingIndex--}}});return this},has:function(fn){return fn?jQuery.inArray(fn,list)>-1:list.length>0},empty:function(){if(list){list=[]}return this},disable:function(){locked=queue=[];list=memory="";return this},disabled:function(){return!list},lock:function(){locked=queue=[];if(!memory&&!firing){list=memory=""}return this},locked:function(){return!!locked},fireWith:function(context,args){if(!locked){args=args||[];args=[context,args.slice?args.slice():args];queue.push(args);if(!firing){fire()}}return this},fire:function(){self.fireWith(this,arguments);return this},fired:function(){return!!fired}};return self};function Identity(v){return v}function Thrower(ex){throw ex}function adoptValue(value,resolve,reject,noValue){var method;try{if(value&&jQuery.isFunction(method=value.promise)){method.call(value).done(resolve).fail(reject)}else if(value&&jQuery.isFunction(method=value.then)){method.call(value,resolve,reject)}else{resolve.apply(undefined,[value].slice(noValue))}}catch(value){reject.apply(undefined,[value])}}jQuery.extend({Deferred:function(func){var tuples=[["notify","progress",jQuery.Callbacks("memory"),jQuery.Callbacks("memory"),2],["resolve","done",jQuery.Callbacks("once memory"),jQuery.Callbacks("once memory"),0,"resolved"],["reject","fail",jQuery.Callbacks("once memory"),jQuery.Callbacks("once memory"),1,"rejected"]],state="pending",promise={state:function(){return state},always:function(){deferred.done(arguments).fail(arguments);return this},catch:function(fn){return promise.then(null,fn)},pipe:function(){var fns=arguments;return jQuery.Deferred(function(newDefer){jQuery.each(tuples,function(i,tuple){var fn=jQuery.isFunction(fns[tuple[4]])&&fns[tuple[4]];deferred[tuple[1]](function(){var returned=fn&&fn.apply(this,arguments);if(returned&&jQuery.isFunction(returned.promise)){returned.promise().progress(newDefer.notify).done(newDefer.resolve).fail(newDefer.reject)}else{newDefer[tuple[0]+"With"](this,fn?[returned]:arguments)}})});fns=null}).promise()},then:function(onFulfilled,onRejected,onProgress){var maxDepth=0;function resolve(depth,deferred,handler,special){return function(){var that=this,args=arguments,mightThrow=function(){var returned,then;if(depth<maxDepth){return}returned=handler.apply(that,args);if(returned===deferred.promise()){throw new TypeError("Thenable self-resolution")}then=returned&&(typeof returned==="object"||typeof returned==="function")&&returned.then;if(jQuery.isFunction(then)){if(special){then.call(returned,resolve(maxDepth,deferred,Identity,special),resolve(maxDepth,deferred,Thrower,special))}else{maxDepth++;then.call(returned,resolve(maxDepth,deferred,Identity,special),resolve(maxDepth,deferred,Thrower,special),resolve(maxDepth,deferred,Identity,deferred.notifyWith))}}else{if(handler!==Identity){that=undefined;args=[returned]}(special||deferred.resolveWith)(that,args)}},process=special?mightThrow:function(){try{mightThrow()}catch(e){if(jQuery.Deferred.exceptionHook){jQuery.Deferred.exceptionHook(e,process.stackTrace)}if(depth+1>=maxDepth){if(handler!==Thrower){that=undefined;args=[e]}deferred.rejectWith(that,args)}}};if(depth){process()}else{if(jQuery.Deferred.getStackHook){process.stackTrace=jQuery.Deferred.getStackHook()}window.setTimeout(process)}}}return jQuery.Deferred(function(newDefer){tuples[0][3].add(resolve(0,newDefer,jQuery.isFunction(onProgress)?onProgress:Identity,newDefer.notifyWith));tuples[1][3].add(resolve(0,newDefer,jQuery.isFunction(onFulfilled)?onFulfilled:Identity));tuples[2][3].add(resolve(0,newDefer,jQuery.isFunction(onRejected)?onRejected:Thrower))}).promise()},promise:function(obj){return obj!=null?jQuery.extend(obj,promise):promise}},deferred={};jQuery.each(tuples,function(i,tuple){var list=tuple[2],stateString=tuple[5];promise[tuple[1]]=list.add;if(stateString){list.add(function(){state=stateString},tuples[3-i][2].disable,tuples[0][2].lock)}list.add(tuple[3].fire);deferred[tuple[0]]=function(){deferred[tuple[0]+"With"](this===deferred?undefined:this,arguments);return this};deferred[tuple[0]+"With"]=list.fireWith});promise.promise(deferred);if(func){func.call(deferred,deferred)}return deferred},when:function(singleValue){var remaining=arguments.length,i=remaining,resolveContexts=Array(i),resolveValues=slice.call(arguments),master=jQuery.Deferred(),updateFunc=function(i){return function(value){resolveContexts[i]=this;resolveValues[i]=arguments.length>1?slice.call(arguments):value;if(!--remaining){master.resolveWith(resolveContexts,resolveValues)}}};if(remaining<=1){adoptValue(singleValue,master.done(updateFunc(i)).resolve,master.reject,!remaining);if(master.state()==="pending"||jQuery.isFunction(resolveValues[i]&&resolveValues[i].then)){return master.then()}}while(i--){adoptValue(resolveValues[i],updateFunc(i),master.reject)}return master.promise()}});var rerrorNames=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;jQuery.Deferred.exceptionHook=function(error,stack){if(window.console&&window.console.warn&&error&&rerrorNames.test(error.name)){window.console.warn("jQuery.Deferred exception: "+error.message,error.stack,stack)}};jQuery.readyException=function(error){window.setTimeout(function(){throw error})};var readyList=jQuery.Deferred();jQuery.fn.ready=function(fn){readyList.then(fn).catch(function(error){jQuery.readyException(error)});return this};jQuery.extend({isReady:false,readyWait:1,ready:function(wait){if(wait===true?--jQuery.readyWait:jQuery.isReady){return}jQuery.isReady=true;if(wait!==true&&--jQuery.readyWait>0){return}readyList.resolveWith(document,[jQuery])}});jQuery.ready.then=readyList.then;function completed(){document.removeEventListener("DOMContentLoaded",completed);window.removeEventListener("load",completed);jQuery.ready()}if(document.readyState==="complete"||document.readyState!=="loading"&&!document.documentElement.doScroll){window.setTimeout(jQuery.ready)}else{document.addEventListener("DOMContentLoaded",completed);window.addEventListener("load",completed)}var access=function(elems,fn,key,value,chainable,emptyGet,raw){var i=0,len=elems.length,bulk=key==null;if(jQuery.type(key)==="object"){chainable=true;for(i in key){access(elems,fn,i,key[i],true,emptyGet,raw)}}else if(value!==undefined){chainable=true;if(!jQuery.isFunction(value)){raw=true}if(bulk){if(raw){fn.call(elems,value);fn=null}else{bulk=fn;fn=function(elem,key,value){return bulk.call(jQuery(elem),value)}}}if(fn){for(;i<len;i++){fn(elems[i],key,raw?value:value.call(elems[i],i,fn(elems[i],key)))}}}if(chainable){return elems}if(bulk){return fn.call(elems)}return len?fn(elems[0],key):emptyGet};var acceptData=function(owner){return owner.nodeType===1||owner.nodeType===9||!+owner.nodeType};function Data(){this.expando=jQuery.expando+Data.uid++}Data.uid=1;Data.prototype={cache:function(owner){var value=owner[this.expando];if(!value){value={};if(acceptData(owner)){if(owner.nodeType){owner[this.expando]=value}else{Object.defineProperty(owner,this.expando,{value:value,configurable:true})}}}return value},set:function(owner,data,value){var prop,cache=this.cache(owner);if(typeof data==="string"){cache[jQuery.camelCase(data)]=value}else{for(prop in data){cache[jQuery.camelCase(prop)]=data[prop]}}return cache},get:function(owner,key){return key===undefined?this.cache(owner):owner[this.expando]&&owner[this.expando][jQuery.camelCase(key)]},access:function(owner,key,value){if(key===undefined||key&&typeof key==="string"&&value===undefined){return this.get(owner,key)}this.set(owner,key,value);return value!==undefined?value:key},remove:function(owner,key){var i,cache=owner[this.expando];if(cache===undefined){return}if(key!==undefined){if(Array.isArray(key)){key=key.map(jQuery.camelCase)}else{key=jQuery.camelCase(key);key=key in cache?[key]:key.match(rnothtmlwhite)||[]}i=key.length;while(i--){delete cache[key[i]]}}if(key===undefined||jQuery.isEmptyObject(cache)){if(owner.nodeType){owner[this.expando]=undefined}else{delete owner[this.expando]}}},hasData:function(owner){var cache=owner[this.expando];return cache!==undefined&&!jQuery.isEmptyObject(cache)}};var dataPriv=new Data;var dataUser=new Data;var rbrace=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,rmultiDash=/[A-Z]/g;function getData(data){if(data==="true"){return true}if(data==="false"){return false}if(data==="null"){return null}if(data===+data+""){return+data}if(rbrace.test(data)){return JSON.parse(data)}return data}function dataAttr(elem,key,data){var name;if(data===undefined&&elem.nodeType===1){name="data-"+key.replace(rmultiDash,"-$&").toLowerCase();data=elem.getAttribute(name);if(typeof data==="string"){try{data=getData(data)}catch(e){}dataUser.set(elem,key,data)}else{data=undefined}}return data}jQuery.extend({hasData:function(elem){return dataUser.hasData(elem)||dataPriv.hasData(elem)},data:function(elem,name,data){return dataUser.access(elem,name,data)},removeData:function(elem,name){dataUser.remove(elem,name)},_data:function(elem,name,data){return dataPriv.access(elem,name,data)},_removeData:function(elem,name){dataPriv.remove(elem,name)}});jQuery.fn.extend({data:function(key,value){var i,name,data,elem=this[0],attrs=elem&&elem.attributes;if(key===undefined){if(this.length){data=dataUser.get(elem);if(elem.nodeType===1&&!dataPriv.get(elem,"hasDataAttrs")){i=attrs.length;while(i--){if(attrs[i]){name=attrs[i].name;if(name.indexOf("data-")===0){name=jQuery.camelCase(name.slice(5));dataAttr(elem,name,data[name])}}}dataPriv.set(elem,"hasDataAttrs",true)}}return data}if(typeof key==="object"){return this.each(function(){dataUser.set(this,key)})}return access(this,function(value){var data;if(elem&&value===undefined){data=dataUser.get(elem,key);if(data!==undefined){return data}data=dataAttr(elem,key);if(data!==undefined){return data}return}this.each(function(){dataUser.set(this,key,value)})},null,value,arguments.length>1,null,true)},removeData:function(key){return this.each(function(){dataUser.remove(this,key)})}});jQuery.extend({queue:function(elem,type,data){var queue;if(elem){type=(type||"fx")+"queue";queue=dataPriv.get(elem,type);if(data){if(!queue||Array.isArray(data)){queue=dataPriv.access(elem,type,jQuery.makeArray(data))}else{queue.push(data)}}return queue||[]}},dequeue:function(elem,type){type=type||"fx";var queue=jQuery.queue(elem,type),startLength=queue.length,fn=queue.shift(),hooks=jQuery._queueHooks(elem,type),next=function(){jQuery.dequeue(elem,type)};if(fn==="inprogress"){fn=queue.shift();startLength--}if(fn){if(type==="fx"){queue.unshift("inprogress")}delete hooks.stop;fn.call(elem,next,hooks)}if(!startLength&&hooks){hooks.empty.fire()}},_queueHooks:function(elem,type){var key=type+"queueHooks";return dataPriv.get(elem,key)||dataPriv.access(elem,key,{empty:jQuery.Callbacks("once memory").add(function(){dataPriv.remove(elem,[type+"queue",key])})})}});jQuery.fn.extend({queue:function(type,data){var setter=2;if(typeof type!=="string"){data=type;type="fx";setter--}if(arguments.length<setter){return jQuery.queue(this[0],type)}return data===undefined?this:this.each(function(){var queue=jQuery.queue(this,type,data);jQuery._queueHooks(this,type);if(type==="fx"&&queue[0]!=="inprogress"){jQuery.dequeue(this,type)}})},dequeue:function(type){return this.each(function(){jQuery.dequeue(this,type)})},clearQueue:function(type){return this.queue(type||"fx",[])},promise:function(type,obj){var tmp,count=1,defer=jQuery.Deferred(),elements=this,i=this.length,resolve=function(){if(!--count){defer.resolveWith(elements,[elements])}};if(typeof type!=="string"){obj=type;type=undefined}type=type||"fx";while(i--){tmp=dataPriv.get(elements[i],type+"queueHooks");if(tmp&&tmp.empty){count++;tmp.empty.add(resolve)}}resolve();return defer.promise(obj)}});var pnum=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source;var rcssNum=new RegExp("^(?:([+-])=|)("+pnum+")([a-z%]*)$","i");var cssExpand=["Top","Right","Bottom","Left"];var isHiddenWithinTree=function(elem,el){elem=el||elem;return elem.style.display==="none"||elem.style.display===""&&jQuery.contains(elem.ownerDocument,elem)&&jQuery.css(elem,"display")==="none"};var swap=function(elem,options,callback,args){var ret,name,old={};for(name in options){old[name]=elem.style[name];elem.style[name]=options[name]}ret=callback.apply(elem,args||[]);for(name in options){elem.style[name]=old[name]}return ret};function adjustCSS(elem,prop,valueParts,tween){var adjusted,scale=1,maxIterations=20,currentValue=tween?function(){return tween.cur()}:function(){return jQuery.css(elem,prop,"")},initial=currentValue(),unit=valueParts&&valueParts[3]||(jQuery.cssNumber[prop]?"":"px"),initialInUnit=(jQuery.cssNumber[prop]||unit!=="px"&&+initial)&&rcssNum.exec(jQuery.css(elem,prop));if(initialInUnit&&initialInUnit[3]!==unit){unit=unit||initialInUnit[3];valueParts=valueParts||[];initialInUnit=+initial||1;do{scale=scale||".5";initialInUnit=initialInUnit/scale;jQuery.style(elem,prop,initialInUnit+unit)}while(scale!==(scale=currentValue()/initial)&&scale!==1&&--maxIterations)}if(valueParts){initialInUnit=+initialInUnit||+initial||0;adjusted=valueParts[1]?initialInUnit+(valueParts[1]+1)*valueParts[2]:+valueParts[2];if(tween){tween.unit=unit;tween.start=initialInUnit;tween.end=adjusted}}return adjusted}var defaultDisplayMap={};function getDefaultDisplay(elem){var temp,doc=elem.ownerDocument,nodeName=elem.nodeName,display=defaultDisplayMap[nodeName];if(display){return display}temp=doc.body.appendChild(doc.createElement(nodeName));display=jQuery.css(temp,"display");temp.parentNode.removeChild(temp);if(display==="none"){display="block"}defaultDisplayMap[nodeName]=display;return display}function showHide(elements,show){var display,elem,values=[],index=0,length=elements.length;for(;index<length;index++){elem=elements[index];if(!elem.style){continue}display=elem.style.display;if(show){if(display==="none"){values[index]=dataPriv.get(elem,"display")||null;if(!values[index]){elem.style.display=""}}if(elem.style.display===""&&isHiddenWithinTree(elem)){values[index]=getDefaultDisplay(elem)}}else{if(display!=="none"){values[index]="none";dataPriv.set(elem,"display",display)}}}for(index=0;index<length;index++){if(values[index]!=null){elements[index].style.display=values[index]}}return elements}jQuery.fn.extend({show:function(){return showHide(this,true)},hide:function(){return showHide(this)},toggle:function(state){if(typeof state==="boolean"){return state?this.show():this.hide()}return this.each(function(){if(isHiddenWithinTree(this)){jQuery(this).show()}else{jQuery(this).hide()}})}});var rcheckableType=/^(?:checkbox|radio)$/i;var rtagName=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i;var rscriptType=/^$|\/(?:java|ecma)script/i;var wrapMap={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};wrapMap.optgroup=wrapMap.option;wrapMap.tbody=wrapMap.tfoot=wrapMap.colgroup=wrapMap.caption=wrapMap.thead;wrapMap.th=wrapMap.td;function getAll(context,tag){var ret;if(typeof context.getElementsByTagName!=="undefined"){ret=context.getElementsByTagName(tag||"*")}else if(typeof context.querySelectorAll!=="undefined"){ret=context.querySelectorAll(tag||"*")}else{ret=[]}if(tag===undefined||tag&&nodeName(context,tag)){return jQuery.merge([context],ret)}return ret}function setGlobalEval(elems,refElements){var i=0,l=elems.length;for(;i<l;i++){dataPriv.set(elems[i],"globalEval",!refElements||dataPriv.get(refElements[i],"globalEval"))}}var rhtml=/<|&#?\w+;/;function buildFragment(elems,context,scripts,selection,ignored){var elem,tmp,tag,wrap,contains,j,fragment=context.createDocumentFragment(),nodes=[],i=0,l=elems.length;for(;i<l;i++){elem=elems[i];if(elem||elem===0){if(jQuery.type(elem)==="object"){jQuery.merge(nodes,elem.nodeType?[elem]:elem)}else if(!rhtml.test(elem)){nodes.push(context.createTextNode(elem))}else{tmp=tmp||fragment.appendChild(context.createElement("div"));tag=(rtagName.exec(elem)||["",""])[1].toLowerCase();wrap=wrapMap[tag]||wrapMap._default;tmp.innerHTML=wrap[1]+jQuery.htmlPrefilter(elem)+wrap[2];j=wrap[0];while(j--){tmp=tmp.lastChild}jQuery.merge(nodes,tmp.childNodes);tmp=fragment.firstChild;tmp.textContent=""}}}fragment.textContent="";i=0;while(elem=nodes[i++]){if(selection&&jQuery.inArray(elem,selection)>-1){if(ignored){ignored.push(elem)}continue}contains=jQuery.contains(elem.ownerDocument,elem);tmp=getAll(fragment.appendChild(elem),"script");if(contains){setGlobalEval(tmp)}if(scripts){j=0;while(elem=tmp[j++]){if(rscriptType.test(elem.type||"")){scripts.push(elem)}}}}return fragment}(function(){var fragment=document.createDocumentFragment(),div=fragment.appendChild(document.createElement("div")),input=document.createElement("input");input.setAttribute("type","radio");input.setAttribute("checked","checked");input.setAttribute("name","t");div.appendChild(input);support.checkClone=div.cloneNode(true).cloneNode(true).lastChild.checked;div.innerHTML="<textarea>x</textarea>";support.noCloneChecked=!!div.cloneNode(true).lastChild.defaultValue})();var documentElement=document.documentElement;var rkeyEvent=/^key/,rmouseEvent=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,rtypenamespace=/^([^.]*)(?:\.(.+)|)/;function returnTrue(){return true}function returnFalse(){return false}function safeActiveElement(){try{return document.activeElement}catch(err){}}function on(elem,types,selector,data,fn,one){var origFn,type;if(typeof types==="object"){if(typeof selector!=="string"){data=data||selector;selector=undefined}for(type in types){on(elem,type,selector,data,types[type],one)}return elem}if(data==null&&fn==null){fn=selector;data=selector=undefined}else if(fn==null){if(typeof selector==="string"){fn=data;data=undefined}else{fn=data;data=selector;selector=undefined}}if(fn===false){fn=returnFalse}else if(!fn){return elem}if(one===1){origFn=fn;fn=function(event){jQuery().off(event);return origFn.apply(this,arguments)};fn.guid=origFn.guid||(origFn.guid=jQuery.guid++)}return elem.each(function(){jQuery.event.add(this,types,fn,data,selector)})}jQuery.event={global:{},add:function(elem,types,handler,data,selector){var handleObjIn,eventHandle,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=dataPriv.get(elem);if(!elemData){return}if(handler.handler){handleObjIn=handler;handler=handleObjIn.handler;selector=handleObjIn.selector}if(selector){jQuery.find.matchesSelector(documentElement,selector)}if(!handler.guid){handler.guid=jQuery.guid++}if(!(events=elemData.events)){events=elemData.events={}}if(!(eventHandle=elemData.handle)){eventHandle=elemData.handle=function(e){return typeof jQuery!=="undefined"&&jQuery.event.triggered!==e.type?jQuery.event.dispatch.apply(elem,arguments):undefined}}types=(types||"").match(rnothtmlwhite)||[""];t=types.length;while(t--){tmp=rtypenamespace.exec(types[t])||[];type=origType=tmp[1];namespaces=(tmp[2]||"").split(".").sort();if(!type){continue}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;special=jQuery.event.special[type]||{};handleObj=jQuery.extend({type:type,origType:origType,data:data,handler:handler,guid:handler.guid,selector:selector,needsContext:selector&&jQuery.expr.match.needsContext.test(selector),namespace:namespaces.join(".")},handleObjIn);if(!(handlers=events[type])){handlers=events[type]=[];handlers.delegateCount=0;if(!special.setup||special.setup.call(elem,data,namespaces,eventHandle)===false){if(elem.addEventListener){elem.addEventListener(type,eventHandle)}}}if(special.add){special.add.call(elem,handleObj);if(!handleObj.handler.guid){handleObj.handler.guid=handler.guid}}if(selector){handlers.splice(handlers.delegateCount++,0,handleObj)}else{handlers.push(handleObj)}jQuery.event.global[type]=true}},remove:function(elem,types,handler,selector,mappedTypes){var j,origCount,tmp,events,t,handleObj,special,handlers,type,namespaces,origType,elemData=dataPriv.hasData(elem)&&dataPriv.get(elem);if(!elemData||!(events=elemData.events)){return}types=(types||"").match(rnothtmlwhite)||[""];t=types.length;while(t--){tmp=rtypenamespace.exec(types[t])||[];type=origType=tmp[1];namespaces=(tmp[2]||"").split(".").sort();if(!type){for(type in events){jQuery.event.remove(elem,type+types[t],handler,selector,true)}continue}special=jQuery.event.special[type]||{};type=(selector?special.delegateType:special.bindType)||type;handlers=events[type]||[];tmp=tmp[2]&&new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)");origCount=j=handlers.length;while(j--){handleObj=handlers[j];if((mappedTypes||origType===handleObj.origType)&&(!handler||handler.guid===handleObj.guid)&&(!tmp||tmp.test(handleObj.namespace))&&(!selector||selector===handleObj.selector||selector==="**"&&handleObj.selector)){handlers.splice(j,1);if(handleObj.selector){handlers.delegateCount--}if(special.remove){special.remove.call(elem,handleObj)}}}if(origCount&&!handlers.length){if(!special.teardown||special.teardown.call(elem,namespaces,elemData.handle)===false){jQuery.removeEvent(elem,type,elemData.handle)}delete events[type]}}if(jQuery.isEmptyObject(events)){dataPriv.remove(elem,"handle events")}},dispatch:function(nativeEvent){var event=jQuery.event.fix(nativeEvent);var i,j,ret,matched,handleObj,handlerQueue,args=new Array(arguments.length),handlers=(dataPriv.get(this,"events")||{})[event.type]||[],special=jQuery.event.special[event.type]||{};args[0]=event;for(i=1;i<arguments.length;i++){args[i]=arguments[i]}event.delegateTarget=this;if(special.preDispatch&&special.preDispatch.call(this,event)===false){return}handlerQueue=jQuery.event.handlers.call(this,event,handlers);i=0;while((matched=handlerQueue[i++])&&!event.isPropagationStopped()){event.currentTarget=matched.elem;j=0;while((handleObj=matched.handlers[j++])&&!event.isImmediatePropagationStopped()){if(!event.rnamespace||event.rnamespace.test(handleObj.namespace)){event.handleObj=handleObj;event.data=handleObj.data;ret=((jQuery.event.special[handleObj.origType]||{}).handle||handleObj.handler).apply(matched.elem,args);if(ret!==undefined){if((event.result=ret)===false){event.preventDefault();event.stopPropagation()}}}}}if(special.postDispatch){special.postDispatch.call(this,event)}return event.result},handlers:function(event,handlers){var i,handleObj,sel,matchedHandlers,matchedSelectors,handlerQueue=[],delegateCount=handlers.delegateCount,cur=event.target;if(delegateCount&&cur.nodeType&&!(event.type==="click"&&event.button>=1)){for(;cur!==this;cur=cur.parentNode||this){if(cur.nodeType===1&&!(event.type==="click"&&cur.disabled===true)){matchedHandlers=[];matchedSelectors={};for(i=0;i<delegateCount;i++){handleObj=handlers[i];sel=handleObj.selector+" ";if(matchedSelectors[sel]===undefined){matchedSelectors[sel]=handleObj.needsContext?jQuery(sel,this).index(cur)>-1:jQuery.find(sel,this,null,[cur]).length}if(matchedSelectors[sel]){matchedHandlers.push(handleObj)}}if(matchedHandlers.length){handlerQueue.push({elem:cur,handlers:matchedHandlers})}}}}cur=this;if(delegateCount<handlers.length){handlerQueue.push({elem:cur,handlers:handlers.slice(delegateCount)})}return handlerQueue},addProp:function(name,hook){Object.defineProperty(jQuery.Event.prototype,name,{enumerable:true,configurable:true,get:jQuery.isFunction(hook)?function(){if(this.originalEvent){return hook(this.originalEvent)}}:function(){if(this.originalEvent){return this.originalEvent[name]}},set:function(value){Object.defineProperty(this,name,{enumerable:true,configurable:true,writable:true,value:value})}})},fix:function(originalEvent){return originalEvent[jQuery.expando]?originalEvent:new jQuery.Event(originalEvent)},special:{load:{noBubble:true},focus:{trigger:function(){if(this!==safeActiveElement()&&this.focus){this.focus();return false}},delegateType:"focusin"},blur:{trigger:function(){if(this===safeActiveElement()&&this.blur){this.blur();return false}},delegateType:"focusout"},click:{trigger:function(){if(this.type==="checkbox"&&this.click&&nodeName(this,"input")){this.click();return false}},_default:function(event){return nodeName(event.target,"a")}},beforeunload:{postDispatch:function(event){if(event.result!==undefined&&event.originalEvent){event.originalEvent.returnValue=event.result}}}}};jQuery.removeEvent=function(elem,type,handle){if(elem.removeEventListener){elem.removeEventListener(type,handle)}};jQuery.Event=function(src,props){if(!(this instanceof jQuery.Event)){return new jQuery.Event(src,props)}if(src&&src.type){this.originalEvent=src;this.type=src.type;this.isDefaultPrevented=src.defaultPrevented||src.defaultPrevented===undefined&&src.returnValue===false?returnTrue:returnFalse;this.target=src.target&&src.target.nodeType===3?src.target.parentNode:src.target;this.currentTarget=src.currentTarget;this.relatedTarget=src.relatedTarget}else{this.type=src}if(props){jQuery.extend(this,props)}this.timeStamp=src&&src.timeStamp||jQuery.now();this[jQuery.expando]=true};jQuery.Event.prototype={constructor:jQuery.Event,isDefaultPrevented:returnFalse,isPropagationStopped:returnFalse,isImmediatePropagationStopped:returnFalse,isSimulated:false,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=returnTrue;if(e&&!this.isSimulated){e.preventDefault()}},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=returnTrue;if(e&&!this.isSimulated){e.stopPropagation()}},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=returnTrue;if(e&&!this.isSimulated){e.stopImmediatePropagation()}this.stopPropagation()}};jQuery.each({altKey:true,bubbles:true,cancelable:true,changedTouches:true,ctrlKey:true,detail:true,eventPhase:true,metaKey:true,pageX:true,pageY:true,shiftKey:true,view:true,char:true,charCode:true,key:true,keyCode:true,button:true,buttons:true,clientX:true,clientY:true,offsetX:true,offsetY:true,pointerId:true,pointerType:true,screenX:true,screenY:true,targetTouches:true,toElement:true,touches:true,which:function(event){var button=event.button;if(event.which==null&&rkeyEvent.test(event.type)){return event.charCode!=null?event.charCode:event.keyCode}if(!event.which&&button!==undefined&&rmouseEvent.test(event.type)){if(button&1){return 1}if(button&2){return 3}if(button&4){return 2}return 0}return event.which}},jQuery.event.addProp);jQuery.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(orig,fix){jQuery.event.special[orig]={delegateType:fix,bindType:fix,handle:function(event){var ret,target=this,related=event.relatedTarget,handleObj=event.handleObj;if(!related||related!==target&&!jQuery.contains(target,related)){event.type=handleObj.origType;ret=handleObj.handler.apply(this,arguments);event.type=fix}return ret}}});jQuery.fn.extend({on:function(types,selector,data,fn){return on(this,types,selector,data,fn)},one:function(types,selector,data,fn){return on(this,types,selector,data,fn,1)},off:function(types,selector,fn){var handleObj,type;if(types&&types.preventDefault&&types.handleObj){handleObj=types.handleObj;jQuery(types.delegateTarget).off(handleObj.namespace?handleObj.origType+"."+handleObj.namespace:handleObj.origType,handleObj.selector,handleObj.handler);return this}if(typeof types==="object"){for(type in types){this.off(type,selector,types[type])}return this}if(selector===false||typeof selector==="function"){fn=selector;selector=undefined}if(fn===false){fn=returnFalse}return this.each(function(){jQuery.event.remove(this,types,fn,selector)})}});var rxhtmlTag=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,rnoInnerhtml=/<script|<style|<link/i,rchecked=/checked\s*(?:[^=]|=\s*.checked.)/i,rscriptTypeMasked=/^true\/(.*)/,rcleanScript=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function manipulationTarget(elem,content){if(nodeName(elem,"table")&&nodeName(content.nodeType!==11?content:content.firstChild,"tr")){return jQuery(">tbody",elem)[0]||elem}return elem}function disableScript(elem){elem.type=(elem.getAttribute("type")!==null)+"/"+elem.type;return elem}function restoreScript(elem){var match=rscriptTypeMasked.exec(elem.type);if(match){elem.type=match[1]}else{elem.removeAttribute("type")}return elem}function cloneCopyEvent(src,dest){var i,l,type,pdataOld,pdataCur,udataOld,udataCur,events;if(dest.nodeType!==1){return}if(dataPriv.hasData(src)){pdataOld=dataPriv.access(src);pdataCur=dataPriv.set(dest,pdataOld);events=pdataOld.events;if(events){delete pdataCur.handle;pdataCur.events={};for(type in events){for(i=0,l=events[type].length;i<l;i++){jQuery.event.add(dest,type,events[type][i])}}}}if(dataUser.hasData(src)){udataOld=dataUser.access(src);udataCur=jQuery.extend({},udataOld);dataUser.set(dest,udataCur)}}function fixInput(src,dest){var nodeName=dest.nodeName.toLowerCase();if(nodeName==="input"&&rcheckableType.test(src.type)){dest.checked=src.checked}else if(nodeName==="input"||nodeName==="textarea"){dest.defaultValue=src.defaultValue}}function domManip(collection,args,callback,ignored){args=concat.apply([],args);var fragment,first,scripts,hasScripts,node,doc,i=0,l=collection.length,iNoClone=l-1,value=args[0],isFunction=jQuery.isFunction(value);if(isFunction||l>1&&typeof value==="string"&&!support.checkClone&&rchecked.test(value)){return collection.each(function(index){var self=collection.eq(index);if(isFunction){args[0]=value.call(this,index,self.html())}domManip(self,args,callback,ignored)})}if(l){fragment=buildFragment(args,collection[0].ownerDocument,false,collection,ignored);first=fragment.firstChild;if(fragment.childNodes.length===1){fragment=first}if(first||ignored){scripts=jQuery.map(getAll(fragment,"script"),disableScript);hasScripts=scripts.length;for(;i<l;i++){node=fragment;if(i!==iNoClone){node=jQuery.clone(node,true,true);if(hasScripts){jQuery.merge(scripts,getAll(node,"script"))}}callback.call(collection[i],node,i)}if(hasScripts){doc=scripts[scripts.length-1].ownerDocument;jQuery.map(scripts,restoreScript);for(i=0;i<hasScripts;i++){node=scripts[i];if(rscriptType.test(node.type||"")&&!dataPriv.access(node,"globalEval")&&jQuery.contains(doc,node)){if(node.src){if(jQuery._evalUrl){jQuery._evalUrl(node.src)}}else{DOMEval(node.textContent.replace(rcleanScript,""),doc)}}}}}}return collection}function remove(elem,selector,keepData){var node,nodes=selector?jQuery.filter(selector,elem):elem,i=0;for(;(node=nodes[i])!=null;i++){if(!keepData&&node.nodeType===1){jQuery.cleanData(getAll(node))}if(node.parentNode){if(keepData&&jQuery.contains(node.ownerDocument,node)){setGlobalEval(getAll(node,"script"))}node.parentNode.removeChild(node)}}return elem}jQuery.extend({htmlPrefilter:function(html){return html.replace(rxhtmlTag,"<$1></$2>")},clone:function(elem,dataAndEvents,deepDataAndEvents){var i,l,srcElements,destElements,clone=elem.cloneNode(true),inPage=jQuery.contains(elem.ownerDocument,elem);if(!support.noCloneChecked&&(elem.nodeType===1||elem.nodeType===11)&&!jQuery.isXMLDoc(elem)){destElements=getAll(clone);srcElements=getAll(elem);for(i=0,l=srcElements.length;i<l;i++){fixInput(srcElements[i],destElements[i])}}if(dataAndEvents){if(deepDataAndEvents){srcElements=srcElements||getAll(elem);destElements=destElements||getAll(clone);for(i=0,l=srcElements.length;i<l;i++){cloneCopyEvent(srcElements[i],destElements[i])}}else{cloneCopyEvent(elem,clone)}}destElements=getAll(clone,"script");if(destElements.length>0){setGlobalEval(destElements,!inPage&&getAll(elem,"script"))}return clone},cleanData:function(elems){var data,elem,type,special=jQuery.event.special,i=0;for(;(elem=elems[i])!==undefined;i++){if(acceptData(elem)){if(data=elem[dataPriv.expando]){if(data.events){for(type in data.events){if(special[type]){jQuery.event.remove(elem,type)}else{jQuery.removeEvent(elem,type,data.handle)}}}elem[dataPriv.expando]=undefined}if(elem[dataUser.expando]){elem[dataUser.expando]=undefined}}}}});jQuery.fn.extend({detach:function(selector){return remove(this,selector,true)},remove:function(selector){return remove(this,selector)},text:function(value){return access(this,function(value){return value===undefined?jQuery.text(this):this.empty().each(function(){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){this.textContent=value}})},null,value,arguments.length)},append:function(){return domManip(this,arguments,function(elem){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var target=manipulationTarget(this,elem);target.appendChild(elem)}})},prepend:function(){return domManip(this,arguments,function(elem){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var target=manipulationTarget(this,elem);target.insertBefore(elem,target.firstChild)}})},before:function(){return domManip(this,arguments,function(elem){if(this.parentNode){this.parentNode.insertBefore(elem,this)}})},after:function(){return domManip(this,arguments,function(elem){if(this.parentNode){this.parentNode.insertBefore(elem,this.nextSibling)}})},empty:function(){var elem,i=0;for(;(elem=this[i])!=null;i++){if(elem.nodeType===1){jQuery.cleanData(getAll(elem,false));elem.textContent=""}}return this},clone:function(dataAndEvents,deepDataAndEvents){dataAndEvents=dataAndEvents==null?false:dataAndEvents;deepDataAndEvents=deepDataAndEvents==null?dataAndEvents:deepDataAndEvents;return this.map(function(){return jQuery.clone(this,dataAndEvents,deepDataAndEvents)})},html:function(value){return access(this,function(value){var elem=this[0]||{},i=0,l=this.length;if(value===undefined&&elem.nodeType===1){return elem.innerHTML}if(typeof value==="string"&&!rnoInnerhtml.test(value)&&!wrapMap[(rtagName.exec(value)||["",""])[1].toLowerCase()]){value=jQuery.htmlPrefilter(value);try{for(;i<l;i++){elem=this[i]||{};if(elem.nodeType===1){jQuery.cleanData(getAll(elem,false));elem.innerHTML=value}}elem=0}catch(e){}}if(elem){this.empty().append(value)}},null,value,arguments.length)},replaceWith:function(){var ignored=[];return domManip(this,arguments,function(elem){var parent=this.parentNode;if(jQuery.inArray(this,ignored)<0){jQuery.cleanData(getAll(this));if(parent){parent.replaceChild(elem,this)}}},ignored)}});jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(name,original){jQuery.fn[name]=function(selector){var elems,ret=[],insert=jQuery(selector),last=insert.length-1,i=0;for(;i<=last;i++){elems=i===last?this:this.clone(true);jQuery(insert[i])[original](elems);push.apply(ret,elems.get())}return this.pushStack(ret)}});var rmargin=/^margin/;var rnumnonpx=new RegExp("^("+pnum+")(?!px)[a-z%]+$","i");var getStyles=function(elem){var view=elem.ownerDocument.defaultView;if(!view||!view.opener){view=window}return view.getComputedStyle(elem)};(function(){function computeStyleTests(){if(!div){return}div.style.cssText="box-sizing:border-box;"+"position:relative;display:block;"+"margin:auto;border:1px;padding:1px;"+"top:1%;width:50%";div.innerHTML="";documentElement.appendChild(container);var divStyle=window.getComputedStyle(div);pixelPositionVal=divStyle.top!=="1%";reliableMarginLeftVal=divStyle.marginLeft==="2px";boxSizingReliableVal=divStyle.width==="4px";div.style.marginRight="50%";pixelMarginRightVal=divStyle.marginRight==="4px";documentElement.removeChild(container);div=null}var pixelPositionVal,boxSizingReliableVal,pixelMarginRightVal,reliableMarginLeftVal,container=document.createElement("div"),div=document.createElement("div");if(!div.style){return}div.style.backgroundClip="content-box";div.cloneNode(true).style.backgroundClip="";support.clearCloneStyle=div.style.backgroundClip==="content-box";container.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;"+"padding:0;margin-top:1px;position:absolute";container.appendChild(div);jQuery.extend(support,{pixelPosition:function(){computeStyleTests();return pixelPositionVal},boxSizingReliable:function(){computeStyleTests();return boxSizingReliableVal},pixelMarginRight:function(){computeStyleTests();return pixelMarginRightVal},reliableMarginLeft:function(){computeStyleTests();return reliableMarginLeftVal}})})();function curCSS(elem,name,computed){var width,minWidth,maxWidth,ret,style=elem.style;computed=computed||getStyles(elem);if(computed){ret=computed.getPropertyValue(name)||computed[name];if(ret===""&&!jQuery.contains(elem.ownerDocument,elem)){ret=jQuery.style(elem,name)}if(!support.pixelMarginRight()&&rnumnonpx.test(ret)&&rmargin.test(name)){width=style.width;minWidth=style.minWidth;maxWidth=style.maxWidth;style.minWidth=style.maxWidth=style.width=ret;ret=computed.width;style.width=width;style.minWidth=minWidth;style.maxWidth=maxWidth}}return ret!==undefined?ret+"":ret}function addGetHookIf(conditionFn,hookFn){return{get:function(){if(conditionFn()){delete this.get;return}return(this.get=hookFn).apply(this,arguments)}}}var rdisplayswap=/^(none|table(?!-c[ea]).+)/,rcustomProp=/^--/,cssShow={position:"absolute",visibility:"hidden",display:"block"},cssNormalTransform={letterSpacing:"0",fontWeight:"400"},cssPrefixes=["Webkit","Moz","ms"],emptyStyle=document.createElement("div").style;function vendorPropName(name){if(name in emptyStyle){return name}var capName=name[0].toUpperCase()+name.slice(1),i=cssPrefixes.length;while(i--){name=cssPrefixes[i]+capName;if(name in emptyStyle){return name}}}function finalPropName(name){var ret=jQuery.cssProps[name];if(!ret){ret=jQuery.cssProps[name]=vendorPropName(name)||name}return ret}function setPositiveNumber(elem,value,subtract){var matches=rcssNum.exec(value);return matches?Math.max(0,matches[2]-(subtract||0))+(matches[3]||"px"):value}function augmentWidthOrHeight(elem,name,extra,isBorderBox,styles){var i,val=0;if(extra===(isBorderBox?"border":"content")){i=4}else{i=name==="width"?1:0}for(;i<4;i+=2){if(extra==="margin"){val+=jQuery.css(elem,extra+cssExpand[i],true,styles)}if(isBorderBox){if(extra==="content"){val-=jQuery.css(elem,"padding"+cssExpand[i],true,styles)}if(extra!=="margin"){val-=jQuery.css(elem,"border"+cssExpand[i]+"Width",true,styles)}}else{val+=jQuery.css(elem,"padding"+cssExpand[i],true,styles);if(extra!=="padding"){val+=jQuery.css(elem,"border"+cssExpand[i]+"Width",true,styles)}}}return val}function getWidthOrHeight(elem,name,extra){var valueIsBorderBox,styles=getStyles(elem),val=curCSS(elem,name,styles),isBorderBox=jQuery.css(elem,"boxSizing",false,styles)==="border-box";if(rnumnonpx.test(val)){return val}valueIsBorderBox=isBorderBox&&(support.boxSizingReliable()||val===elem.style[name]);if(val==="auto"){val=elem["offset"+name[0].toUpperCase()+name.slice(1)]}val=parseFloat(val)||0;return val+augmentWidthOrHeight(elem,name,extra||(isBorderBox?"border":"content"),valueIsBorderBox,styles)+"px"}jQuery.extend({cssHooks:{opacity:{get:function(elem,computed){if(computed){var ret=curCSS(elem,"opacity");return ret===""?"1":ret}}}},cssNumber:{animationIterationCount:true,columnCount:true,fillOpacity:true,flexGrow:true,flexShrink:true,fontWeight:true,lineHeight:true,opacity:true,order:true,orphans:true,widows:true,zIndex:true,zoom:true},cssProps:{float:"cssFloat"},style:function(elem,name,value,extra){if(!elem||elem.nodeType===3||elem.nodeType===8||!elem.style){return}var ret,type,hooks,origName=jQuery.camelCase(name),isCustomProp=rcustomProp.test(name),style=elem.style;if(!isCustomProp){name=finalPropName(origName)}hooks=jQuery.cssHooks[name]||jQuery.cssHooks[origName];if(value!==undefined){type=typeof value;if(type==="string"&&(ret=rcssNum.exec(value))&&ret[1]){value=adjustCSS(elem,name,ret);type="number"}if(value==null||value!==value){return}if(type==="number"){value+=ret&&ret[3]||(jQuery.cssNumber[origName]?"":"px")}if(!support.clearCloneStyle&&value===""&&name.indexOf("background")===0){style[name]="inherit"}if(!hooks||!("set"in hooks)||(value=hooks.set(elem,value,extra))!==undefined){if(isCustomProp){style.setProperty(name,value)}else{style[name]=value}}}else{if(hooks&&"get"in hooks&&(ret=hooks.get(elem,false,extra))!==undefined){return ret}return style[name]}},css:function(elem,name,extra,styles){var val,num,hooks,origName=jQuery.camelCase(name),isCustomProp=rcustomProp.test(name);if(!isCustomProp){name=finalPropName(origName)}hooks=jQuery.cssHooks[name]||jQuery.cssHooks[origName];if(hooks&&"get"in hooks){val=hooks.get(elem,true,extra)}if(val===undefined){val=curCSS(elem,name,styles)}if(val==="normal"&&name in cssNormalTransform){val=cssNormalTransform[name]}if(extra===""||extra){num=parseFloat(val);return extra===true||isFinite(num)?num||0:val}return val}});jQuery.each(["height","width"],function(i,name){jQuery.cssHooks[name]={get:function(elem,computed,extra){if(computed){return rdisplayswap.test(jQuery.css(elem,"display"))&&(!elem.getClientRects().length||!elem.getBoundingClientRect().width)?swap(elem,cssShow,function(){return getWidthOrHeight(elem,name,extra)}):getWidthOrHeight(elem,name,extra)}},set:function(elem,value,extra){var matches,styles=extra&&getStyles(elem),subtract=extra&&augmentWidthOrHeight(elem,name,extra,jQuery.css(elem,"boxSizing",false,styles)==="border-box",styles);if(subtract&&(matches=rcssNum.exec(value))&&(matches[3]||"px")!=="px"){elem.style[name]=value;value=jQuery.css(elem,name)}return setPositiveNumber(elem,value,subtract)}}});jQuery.cssHooks.marginLeft=addGetHookIf(support.reliableMarginLeft,function(elem,computed){if(computed){return(parseFloat(curCSS(elem,"marginLeft"))||elem.getBoundingClientRect().left-swap(elem,{marginLeft:0},function(){return elem.getBoundingClientRect().left}))+"px"}});jQuery.each({margin:"",padding:"",border:"Width"},function(prefix,suffix){jQuery.cssHooks[prefix+suffix]={expand:function(value){var i=0,expanded={},parts=typeof value==="string"?value.split(" "):[value];for(;i<4;i++){expanded[prefix+cssExpand[i]+suffix]=parts[i]||parts[i-2]||parts[0]}return expanded}};if(!rmargin.test(prefix)){jQuery.cssHooks[prefix+suffix].set=setPositiveNumber}});jQuery.fn.extend({css:function(name,value){return access(this,function(elem,name,value){var styles,len,map={},i=0;if(Array.isArray(name)){styles=getStyles(elem);len=name.length;for(;i<len;i++){map[name[i]]=jQuery.css(elem,name[i],false,styles)}return map}return value!==undefined?jQuery.style(elem,name,value):jQuery.css(elem,name)},name,value,arguments.length>1)}});function Tween(elem,options,prop,end,easing){return new Tween.prototype.init(elem,options,prop,end,easing)}jQuery.Tween=Tween;Tween.prototype={constructor:Tween,init:function(elem,options,prop,end,easing,unit){this.elem=elem;this.prop=prop;this.easing=easing||jQuery.easing._default;this.options=options;this.start=this.now=this.cur();this.end=end;this.unit=unit||(jQuery.cssNumber[prop]?"":"px")},cur:function(){var hooks=Tween.propHooks[this.prop];return hooks&&hooks.get?hooks.get(this):Tween.propHooks._default.get(this)},run:function(percent){var eased,hooks=Tween.propHooks[this.prop];if(this.options.duration){this.pos=eased=jQuery.easing[this.easing](percent,this.options.duration*percent,0,1,this.options.duration)}else{this.pos=eased=percent}this.now=(this.end-this.start)*eased+this.start;if(this.options.step){this.options.step.call(this.elem,this.now,this)}if(hooks&&hooks.set){hooks.set(this)}else{Tween.propHooks._default.set(this)}return this}};Tween.prototype.init.prototype=Tween.prototype;Tween.propHooks={_default:{get:function(tween){var result;if(tween.elem.nodeType!==1||tween.elem[tween.prop]!=null&&tween.elem.style[tween.prop]==null){return tween.elem[tween.prop]}result=jQuery.css(tween.elem,tween.prop,"");return!result||result==="auto"?0:result},set:function(tween){if(jQuery.fx.step[tween.prop]){jQuery.fx.step[tween.prop](tween)}else if(tween.elem.nodeType===1&&(tween.elem.style[jQuery.cssProps[tween.prop]]!=null||jQuery.cssHooks[tween.prop])){jQuery.style(tween.elem,tween.prop,tween.now+tween.unit)}else{tween.elem[tween.prop]=tween.now}}}};Tween.propHooks.scrollTop=Tween.propHooks.scrollLeft={set:function(tween){if(tween.elem.nodeType&&tween.elem.parentNode){tween.elem[tween.prop]=tween.now}}};jQuery.easing={linear:function(p){return p},swing:function(p){return.5-Math.cos(p*Math.PI)/2},_default:"swing"};jQuery.fx=Tween.prototype.init;jQuery.fx.step={};var fxNow,inProgress,rfxtypes=/^(?:toggle|show|hide)$/,rrun=/queueHooks$/;function schedule(){if(inProgress){if(document.hidden===false&&window.requestAnimationFrame){window.requestAnimationFrame(schedule)}else{window.setTimeout(schedule,jQuery.fx.interval)}jQuery.fx.tick()}}function createFxNow(){window.setTimeout(function(){fxNow=undefined});return fxNow=jQuery.now()}function genFx(type,includeWidth){var which,i=0,attrs={height:type};includeWidth=includeWidth?1:0;for(;i<4;i+=2-includeWidth){which=cssExpand[i];attrs["margin"+which]=attrs["padding"+which]=type}if(includeWidth){attrs.opacity=attrs.width=type}return attrs}function createTween(value,prop,animation){var tween,collection=(Animation.tweeners[prop]||[]).concat(Animation.tweeners["*"]),index=0,length=collection.length;for(;index<length;index++){if(tween=collection[index].call(animation,prop,value)){return tween}}}function defaultPrefilter(elem,props,opts){var prop,value,toggle,hooks,oldfire,propTween,restoreDisplay,display,isBox="width"in props||"height"in props,anim=this,orig={},style=elem.style,hidden=elem.nodeType&&isHiddenWithinTree(elem),dataShow=dataPriv.get(elem,"fxshow");if(!opts.queue){hooks=jQuery._queueHooks(elem,"fx");if(hooks.unqueued==null){hooks.unqueued=0;oldfire=hooks.empty.fire;hooks.empty.fire=function(){if(!hooks.unqueued){oldfire()}}}hooks.unqueued++;anim.always(function(){anim.always(function(){hooks.unqueued--;if(!jQuery.queue(elem,"fx").length){hooks.empty.fire()}})})}for(prop in props){value=props[prop];if(rfxtypes.test(value)){delete props[prop];toggle=toggle||value==="toggle";if(value===(hidden?"hide":"show")){if(value==="show"&&dataShow&&dataShow[prop]!==undefined){hidden=true}else{continue}}orig[prop]=dataShow&&dataShow[prop]||jQuery.style(elem,prop)}}propTween=!jQuery.isEmptyObject(props);if(!propTween&&jQuery.isEmptyObject(orig)){return}if(isBox&&elem.nodeType===1){opts.overflow=[style.overflow,style.overflowX,style.overflowY];restoreDisplay=dataShow&&dataShow.display;if(restoreDisplay==null){restoreDisplay=dataPriv.get(elem,"display")}display=jQuery.css(elem,"display");if(display==="none"){if(restoreDisplay){display=restoreDisplay}else{showHide([elem],true);restoreDisplay=elem.style.display||restoreDisplay;display=jQuery.css(elem,"display");showHide([elem])}}if(display==="inline"||display==="inline-block"&&restoreDisplay!=null){if(jQuery.css(elem,"float")==="none"){if(!propTween){anim.done(function(){style.display=restoreDisplay});if(restoreDisplay==null){display=style.display;restoreDisplay=display==="none"?"":display}}style.display="inline-block"}}}if(opts.overflow){style.overflow="hidden";anim.always(function(){style.overflow=opts.overflow[0];style.overflowX=opts.overflow[1];style.overflowY=opts.overflow[2]})}propTween=false;for(prop in orig){if(!propTween){if(dataShow){if("hidden"in dataShow){hidden=dataShow.hidden}}else{dataShow=dataPriv.access(elem,"fxshow",{display:restoreDisplay})}if(toggle){dataShow.hidden=!hidden}if(hidden){showHide([elem],true)}anim.done(function(){if(!hidden){showHide([elem])}dataPriv.remove(elem,"fxshow");for(prop in orig){jQuery.style(elem,prop,orig[prop])}})}propTween=createTween(hidden?dataShow[prop]:0,prop,anim);if(!(prop in dataShow)){dataShow[prop]=propTween.start;if(hidden){propTween.end=propTween.start;propTween.start=0}}}}function propFilter(props,specialEasing){var index,name,easing,value,hooks;for(index in props){name=jQuery.camelCase(index);easing=specialEasing[name];value=props[index];if(Array.isArray(value)){easing=value[1];value=props[index]=value[0]}if(index!==name){props[name]=value;delete props[index]}hooks=jQuery.cssHooks[name];if(hooks&&"expand"in hooks){value=hooks.expand(value);delete props[name];for(index in value){if(!(index in props)){props[index]=value[index];specialEasing[index]=easing}}}else{specialEasing[name]=easing}}}function Animation(elem,properties,options){var result,stopped,index=0,length=Animation.prefilters.length,deferred=jQuery.Deferred().always(function(){delete tick.elem}),tick=function(){if(stopped){return false}var currentTime=fxNow||createFxNow(),remaining=Math.max(0,animation.startTime+animation.duration-currentTime),temp=remaining/animation.duration||0,percent=1-temp,index=0,length=animation.tweens.length;for(;index<length;index++){animation.tweens[index].run(percent)}deferred.notifyWith(elem,[animation,percent,remaining]);if(percent<1&&length){return remaining}if(!length){deferred.notifyWith(elem,[animation,1,0])}deferred.resolveWith(elem,[animation]);return false},animation=deferred.promise({elem:elem,props:jQuery.extend({},properties),opts:jQuery.extend(true,{specialEasing:{},easing:jQuery.easing._default},options),originalProperties:properties,originalOptions:options,startTime:fxNow||createFxNow(),duration:options.duration,tweens:[],createTween:function(prop,end){var tween=jQuery.Tween(elem,animation.opts,prop,end,animation.opts.specialEasing[prop]||animation.opts.easing);animation.tweens.push(tween);return tween},stop:function(gotoEnd){var index=0,length=gotoEnd?animation.tweens.length:0;if(stopped){return this}stopped=true;for(;index<length;index++){animation.tweens[index].run(1)}if(gotoEnd){deferred.notifyWith(elem,[animation,1,0]);deferred.resolveWith(elem,[animation,gotoEnd])}else{deferred.rejectWith(elem,[animation,gotoEnd])}return this}}),props=animation.props;propFilter(props,animation.opts.specialEasing);for(;index<length;index++){result=Animation.prefilters[index].call(animation,elem,props,animation.opts);if(result){if(jQuery.isFunction(result.stop)){jQuery._queueHooks(animation.elem,animation.opts.queue).stop=jQuery.proxy(result.stop,result)}return result}}jQuery.map(props,createTween,animation);if(jQuery.isFunction(animation.opts.start)){animation.opts.start.call(elem,animation)}animation.progress(animation.opts.progress).done(animation.opts.done,animation.opts.complete).fail(animation.opts.fail).always(animation.opts.always);jQuery.fx.timer(jQuery.extend(tick,{elem:elem,anim:animation,queue:animation.opts.queue}));return animation}jQuery.Animation=jQuery.extend(Animation,{tweeners:{"*":[function(prop,value){var tween=this.createTween(prop,value);adjustCSS(tween.elem,prop,rcssNum.exec(value),tween);return tween}]},tweener:function(props,callback){if(jQuery.isFunction(props)){callback=props;props=["*"]}else{props=props.match(rnothtmlwhite)}var prop,index=0,length=props.length;for(;index<length;index++){prop=props[index];Animation.tweeners[prop]=Animation.tweeners[prop]||[];Animation.tweeners[prop].unshift(callback)}},prefilters:[defaultPrefilter],prefilter:function(callback,prepend){if(prepend){Animation.prefilters.unshift(callback)}else{Animation.prefilters.push(callback)}}});jQuery.speed=function(speed,easing,fn){var opt=speed&&typeof speed==="object"?jQuery.extend({},speed):{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&!jQuery.isFunction(easing)&&easing};if(jQuery.fx.off){opt.duration=0}else{if(typeof opt.duration!=="number"){if(opt.duration in jQuery.fx.speeds){opt.duration=jQuery.fx.speeds[opt.duration]}else{opt.duration=jQuery.fx.speeds._default}}}if(opt.queue==null||opt.queue===true){opt.queue="fx"}opt.old=opt.complete;opt.complete=function(){if(jQuery.isFunction(opt.old)){opt.old.call(this)}if(opt.queue){jQuery.dequeue(this,opt.queue)}};return opt};jQuery.fn.extend({fadeTo:function(speed,to,easing,callback){return this.filter(isHiddenWithinTree).css("opacity",0).show().end().animate({opacity:to},speed,easing,callback)},animate:function(prop,speed,easing,callback){var empty=jQuery.isEmptyObject(prop),optall=jQuery.speed(speed,easing,callback),doAnimation=function(){var anim=Animation(this,jQuery.extend({},prop),optall);if(empty||dataPriv.get(this,"finish")){anim.stop(true)}};doAnimation.finish=doAnimation;return empty||optall.queue===false?this.each(doAnimation):this.queue(optall.queue,doAnimation)},stop:function(type,clearQueue,gotoEnd){var stopQueue=function(hooks){var stop=hooks.stop;delete hooks.stop;stop(gotoEnd)};if(typeof type!=="string"){gotoEnd=clearQueue;clearQueue=type;type=undefined}if(clearQueue&&type!==false){this.queue(type||"fx",[])}return this.each(function(){var dequeue=true,index=type!=null&&type+"queueHooks",timers=jQuery.timers,data=dataPriv.get(this);if(index){if(data[index]&&data[index].stop){stopQueue(data[index])}}else{for(index in data){if(data[index]&&data[index].stop&&rrun.test(index)){stopQueue(data[index])}}}for(index=timers.length;index--;){if(timers[index].elem===this&&(type==null||timers[index].queue===type)){timers[index].anim.stop(gotoEnd);dequeue=false;timers.splice(index,1)}}if(dequeue||!gotoEnd){jQuery.dequeue(this,type)}})},finish:function(type){if(type!==false){type=type||"fx"}return this.each(function(){var index,data=dataPriv.get(this),queue=data[type+"queue"],hooks=data[type+"queueHooks"],timers=jQuery.timers,length=queue?queue.length:0;data.finish=true;jQuery.queue(this,type,[]);if(hooks&&hooks.stop){hooks.stop.call(this,true)}for(index=timers.length;index--;){if(timers[index].elem===this&&timers[index].queue===type){timers[index].anim.stop(true);timers.splice(index,1)}}for(index=0;index<length;index++){if(queue[index]&&queue[index].finish){queue[index].finish.call(this)}}delete data.finish})}});jQuery.each(["toggle","show","hide"],function(i,name){var cssFn=jQuery.fn[name];jQuery.fn[name]=function(speed,easing,callback){return speed==null||typeof speed==="boolean"?cssFn.apply(this,arguments):this.animate(genFx(name,true),speed,easing,callback)}});jQuery.each({slideDown:genFx("show"),slideUp:genFx("hide"),slideToggle:genFx("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(name,props){jQuery.fn[name]=function(speed,easing,callback){return this.animate(props,speed,easing,callback)}});jQuery.timers=[];jQuery.fx.tick=function(){var timer,i=0,timers=jQuery.timers;fxNow=jQuery.now();for(;i<timers.length;i++){timer=timers[i];if(!timer()&&timers[i]===timer){timers.splice(i--,1)}}if(!timers.length){jQuery.fx.stop()}fxNow=undefined};jQuery.fx.timer=function(timer){jQuery.timers.push(timer);jQuery.fx.start()};jQuery.fx.interval=13;jQuery.fx.start=function(){if(inProgress){return}inProgress=true;schedule()};jQuery.fx.stop=function(){inProgress=null};jQuery.fx.speeds={slow:600,fast:200,_default:400};jQuery.fn.delay=function(time,type){time=jQuery.fx?jQuery.fx.speeds[time]||time:time;type=type||"fx";return this.queue(type,function(next,hooks){var timeout=window.setTimeout(next,time);hooks.stop=function(){window.clearTimeout(timeout)}})};(function(){var input=document.createElement("input"),select=document.createElement("select"),opt=select.appendChild(document.createElement("option"));input.type="checkbox";support.checkOn=input.value!=="";support.optSelected=opt.selected;input=document.createElement("input");input.value="t";input.type="radio";support.radioValue=input.value==="t"})();var boolHook,attrHandle=jQuery.expr.attrHandle;jQuery.fn.extend({attr:function(name,value){return access(this,jQuery.attr,name,value,arguments.length>1)},removeAttr:function(name){return this.each(function(){jQuery.removeAttr(this,name)})}});jQuery.extend({attr:function(elem,name,value){var ret,hooks,nType=elem.nodeType;if(nType===3||nType===8||nType===2){return}if(typeof elem.getAttribute==="undefined"){return jQuery.prop(elem,name,value)}if(nType!==1||!jQuery.isXMLDoc(elem)){hooks=jQuery.attrHooks[name.toLowerCase()]||(jQuery.expr.match.bool.test(name)?boolHook:undefined)}if(value!==undefined){if(value===null){jQuery.removeAttr(elem,name);return}if(hooks&&"set"in hooks&&(ret=hooks.set(elem,value,name))!==undefined){return ret}elem.setAttribute(name,value+"");return value}if(hooks&&"get"in hooks&&(ret=hooks.get(elem,name))!==null){return ret}ret=jQuery.find.attr(elem,name);return ret==null?undefined:ret},attrHooks:{type:{set:function(elem,value){if(!support.radioValue&&value==="radio"&&nodeName(elem,"input")){var val=elem.value;elem.setAttribute("type",value);if(val){elem.value=val}return value}}}},removeAttr:function(elem,value){var name,i=0,attrNames=value&&value.match(rnothtmlwhite);if(attrNames&&elem.nodeType===1){while(name=attrNames[i++]){elem.removeAttribute(name)}}}});boolHook={set:function(elem,value,name){if(value===false){jQuery.removeAttr(elem,name)}else{elem.setAttribute(name,name)}return name}};jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g),function(i,name){var getter=attrHandle[name]||jQuery.find.attr;attrHandle[name]=function(elem,name,isXML){var ret,handle,lowercaseName=name.toLowerCase();if(!isXML){handle=attrHandle[lowercaseName];attrHandle[lowercaseName]=ret;ret=getter(elem,name,isXML)!=null?lowercaseName:null;attrHandle[lowercaseName]=handle}return ret}});var rfocusable=/^(?:input|select|textarea|button)$/i,rclickable=/^(?:a|area)$/i;jQuery.fn.extend({prop:function(name,value){return access(this,jQuery.prop,name,value,arguments.length>1)},removeProp:function(name){return this.each(function(){delete this[jQuery.propFix[name]||name]})}});jQuery.extend({prop:function(elem,name,value){var ret,hooks,nType=elem.nodeType;if(nType===3||nType===8||nType===2){return}if(nType!==1||!jQuery.isXMLDoc(elem)){name=jQuery.propFix[name]||name;hooks=jQuery.propHooks[name]}if(value!==undefined){if(hooks&&"set"in hooks&&(ret=hooks.set(elem,value,name))!==undefined){return ret}return elem[name]=value}if(hooks&&"get"in hooks&&(ret=hooks.get(elem,name))!==null){return ret}return elem[name]},propHooks:{tabIndex:{get:function(elem){var tabindex=jQuery.find.attr(elem,"tabindex");if(tabindex){return parseInt(tabindex,10)}if(rfocusable.test(elem.nodeName)||rclickable.test(elem.nodeName)&&elem.href){return 0}return-1}}},propFix:{for:"htmlFor",class:"className"}});if(!support.optSelected){jQuery.propHooks.selected={get:function(elem){var parent=elem.parentNode;if(parent&&parent.parentNode){parent.parentNode.selectedIndex}return null},set:function(elem){var parent=elem.parentNode;if(parent){parent.selectedIndex;if(parent.parentNode){parent.parentNode.selectedIndex}}}}}jQuery.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){jQuery.propFix[this.toLowerCase()]=this});function stripAndCollapse(value){var tokens=value.match(rnothtmlwhite)||[];return tokens.join(" ")}function getClass(elem){return elem.getAttribute&&elem.getAttribute("class")||""}jQuery.fn.extend({addClass:function(value){var classes,elem,cur,curValue,clazz,j,finalValue,i=0;if(jQuery.isFunction(value)){return this.each(function(j){jQuery(this).addClass(value.call(this,j,getClass(this)))})}if(typeof value==="string"&&value){classes=value.match(rnothtmlwhite)||[];while(elem=this[i++]){curValue=getClass(elem);cur=elem.nodeType===1&&" "+stripAndCollapse(curValue)+" ";if(cur){j=0;while(clazz=classes[j++]){if(cur.indexOf(" "+clazz+" ")<0){cur+=clazz+" "}}finalValue=stripAndCollapse(cur);if(curValue!==finalValue){elem.setAttribute("class",finalValue)}}}}return this},removeClass:function(value){var classes,elem,cur,curValue,clazz,j,finalValue,i=0;if(jQuery.isFunction(value)){return this.each(function(j){jQuery(this).removeClass(value.call(this,j,getClass(this)))})}if(!arguments.length){return this.attr("class","")}if(typeof value==="string"&&value){classes=value.match(rnothtmlwhite)||[];while(elem=this[i++]){curValue=getClass(elem);cur=elem.nodeType===1&&" "+stripAndCollapse(curValue)+" ";if(cur){j=0;while(clazz=classes[j++]){while(cur.indexOf(" "+clazz+" ")>-1){cur=cur.replace(" "+clazz+" "," ")}}finalValue=stripAndCollapse(cur);if(curValue!==finalValue){elem.setAttribute("class",finalValue)}}}}return this},toggleClass:function(value,stateVal){var type=typeof value;if(typeof stateVal==="boolean"&&type==="string"){return stateVal?this.addClass(value):this.removeClass(value)}if(jQuery.isFunction(value)){return this.each(function(i){jQuery(this).toggleClass(value.call(this,i,getClass(this),stateVal),stateVal)})}return this.each(function(){var className,i,self,classNames;if(type==="string"){i=0;self=jQuery(this);classNames=value.match(rnothtmlwhite)||[];while(className=classNames[i++]){if(self.hasClass(className)){self.removeClass(className)}else{self.addClass(className)}}}else if(value===undefined||type==="boolean"){className=getClass(this);if(className){dataPriv.set(this,"__className__",className)}if(this.setAttribute){this.setAttribute("class",className||value===false?"":dataPriv.get(this,"__className__")||"")}}})},hasClass:function(selector){var className,elem,i=0;className=" "+selector+" ";while(elem=this[i++]){if(elem.nodeType===1&&(" "+stripAndCollapse(getClass(elem))+" ").indexOf(className)>-1){return true}}return false}});var rreturn=/\r/g;jQuery.fn.extend({val:function(value){var hooks,ret,isFunction,elem=this[0];if(!arguments.length){if(elem){hooks=jQuery.valHooks[elem.type]||jQuery.valHooks[elem.nodeName.toLowerCase()];if(hooks&&"get"in hooks&&(ret=hooks.get(elem,"value"))!==undefined){return ret}ret=elem.value;if(typeof ret==="string"){return ret.replace(rreturn,"")}return ret==null?"":ret}return}isFunction=jQuery.isFunction(value);return this.each(function(i){var val;if(this.nodeType!==1){return}if(isFunction){val=value.call(this,i,jQuery(this).val())}else{val=value}if(val==null){val=""}else if(typeof val==="number"){val+=""}else if(Array.isArray(val)){val=jQuery.map(val,function(value){return value==null?"":value+""})}hooks=jQuery.valHooks[this.type]||jQuery.valHooks[this.nodeName.toLowerCase()];if(!hooks||!("set"in hooks)||hooks.set(this,val,"value")===undefined){this.value=val}})}});jQuery.extend({valHooks:{option:{get:function(elem){var val=jQuery.find.attr(elem,"value");return val!=null?val:stripAndCollapse(jQuery.text(elem))}},select:{get:function(elem){var value,option,i,options=elem.options,index=elem.selectedIndex,one=elem.type==="select-one",values=one?null:[],max=one?index+1:options.length;if(index<0){i=max}else{i=one?index:0}for(;i<max;i++){option=options[i];if((option.selected||i===index)&&!option.disabled&&(!option.parentNode.disabled||!nodeName(option.parentNode,"optgroup"))){value=jQuery(option).val();if(one){return value}values.push(value)}}return values},set:function(elem,value){var optionSet,option,options=elem.options,values=jQuery.makeArray(value),i=options.length;while(i--){option=options[i];if(option.selected=jQuery.inArray(jQuery.valHooks.option.get(option),values)>-1){optionSet=true}}if(!optionSet){elem.selectedIndex=-1}return values}}}});jQuery.each(["radio","checkbox"],function(){jQuery.valHooks[this]={set:function(elem,value){if(Array.isArray(value)){return elem.checked=jQuery.inArray(jQuery(elem).val(),value)>-1}}};if(!support.checkOn){jQuery.valHooks[this].get=function(elem){return elem.getAttribute("value")===null?"on":elem.value}}});var rfocusMorph=/^(?:focusinfocus|focusoutblur)$/;jQuery.extend(jQuery.event,{trigger:function(event,data,elem,onlyHandlers){var i,cur,tmp,bubbleType,ontype,handle,special,eventPath=[elem||document],type=hasOwn.call(event,"type")?event.type:event,namespaces=hasOwn.call(event,"namespace")?event.namespace.split("."):[];cur=tmp=elem=elem||document;if(elem.nodeType===3||elem.nodeType===8){return}if(rfocusMorph.test(type+jQuery.event.triggered)){return}if(type.indexOf(".")>-1){namespaces=type.split(".");type=namespaces.shift();namespaces.sort()}ontype=type.indexOf(":")<0&&"on"+type;event=event[jQuery.expando]?event:new jQuery.Event(type,typeof event==="object"&&event);event.isTrigger=onlyHandlers?2:3;event.namespace=namespaces.join(".");event.rnamespace=event.namespace?new RegExp("(^|\\.)"+namespaces.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;event.result=undefined;if(!event.target){event.target=elem}data=data==null?[event]:jQuery.makeArray(data,[event]);special=jQuery.event.special[type]||{};if(!onlyHandlers&&special.trigger&&special.trigger.apply(elem,data)===false){return}if(!onlyHandlers&&!special.noBubble&&!jQuery.isWindow(elem)){bubbleType=special.delegateType||type;if(!rfocusMorph.test(bubbleType+type)){cur=cur.parentNode}for(;cur;cur=cur.parentNode){eventPath.push(cur);tmp=cur}if(tmp===(elem.ownerDocument||document)){eventPath.push(tmp.defaultView||tmp.parentWindow||window)}}i=0;while((cur=eventPath[i++])&&!event.isPropagationStopped()){event.type=i>1?bubbleType:special.bindType||type;handle=(dataPriv.get(cur,"events")||{})[event.type]&&dataPriv.get(cur,"handle");if(handle){handle.apply(cur,data)}handle=ontype&&cur[ontype];if(handle&&handle.apply&&acceptData(cur)){event.result=handle.apply(cur,data);if(event.result===false){event.preventDefault()}}}event.type=type;if(!onlyHandlers&&!event.isDefaultPrevented()){if((!special._default||special._default.apply(eventPath.pop(),data)===false)&&acceptData(elem)){if(ontype&&jQuery.isFunction(elem[type])&&!jQuery.isWindow(elem)){tmp=elem[ontype];if(tmp){elem[ontype]=null}jQuery.event.triggered=type;elem[type]();jQuery.event.triggered=undefined;if(tmp){elem[ontype]=tmp}}}}return event.result},simulate:function(type,elem,event){var e=jQuery.extend(new jQuery.Event,event,{type:type,isSimulated:true});jQuery.event.trigger(e,null,elem)}});jQuery.fn.extend({trigger:function(type,data){return this.each(function(){jQuery.event.trigger(type,data,this)})},triggerHandler:function(type,data){var elem=this[0];if(elem){return jQuery.event.trigger(type,data,elem,true)}}});jQuery.each(("blur focus focusin focusout resize scroll click dblclick "+"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave "+"change select submit keydown keypress keyup contextmenu").split(" "),function(i,name){jQuery.fn[name]=function(data,fn){return arguments.length>0?this.on(name,null,data,fn):this.trigger(name)}});jQuery.fn.extend({hover:function(fnOver,fnOut){return this.mouseenter(fnOver).mouseleave(fnOut||fnOver)}});support.focusin="onfocusin"in window;if(!support.focusin){jQuery.each({focus:"focusin",blur:"focusout"},function(orig,fix){var handler=function(event){jQuery.event.simulate(fix,event.target,jQuery.event.fix(event))};jQuery.event.special[fix]={setup:function(){var doc=this.ownerDocument||this,attaches=dataPriv.access(doc,fix);if(!attaches){doc.addEventListener(orig,handler,true)}dataPriv.access(doc,fix,(attaches||0)+1)},teardown:function(){var doc=this.ownerDocument||this,attaches=dataPriv.access(doc,fix)-1;if(!attaches){doc.removeEventListener(orig,handler,true);dataPriv.remove(doc,fix)}else{dataPriv.access(doc,fix,attaches)}}}})}var location=window.location;var nonce=jQuery.now();var rquery=/\?/;jQuery.parseXML=function(data){var xml;if(!data||typeof data!=="string"){return null}try{xml=(new window.DOMParser).parseFromString(data,"text/xml")}catch(e){xml=undefined}if(!xml||xml.getElementsByTagName("parsererror").length){jQuery.error("Invalid XML: "+data)}return xml};var rbracket=/\[\]$/,rCRLF=/\r?\n/g,rsubmitterTypes=/^(?:submit|button|image|reset|file)$/i,rsubmittable=/^(?:input|select|textarea|keygen)/i;function buildParams(prefix,obj,traditional,add){var name;if(Array.isArray(obj)){jQuery.each(obj,function(i,v){if(traditional||rbracket.test(prefix)){add(prefix,v)}else{buildParams(prefix+"["+(typeof v==="object"&&v!=null?i:"")+"]",v,traditional,add)}})}else if(!traditional&&jQuery.type(obj)==="object"){for(name in obj){buildParams(prefix+"["+name+"]",obj[name],traditional,add)}}else{add(prefix,obj)}}jQuery.param=function(a,traditional){var prefix,s=[],add=function(key,valueOrFunction){var value=jQuery.isFunction(valueOrFunction)?valueOrFunction():valueOrFunction;s[s.length]=encodeURIComponent(key)+"="+encodeURIComponent(value==null?"":value)};if(Array.isArray(a)||a.jquery&&!jQuery.isPlainObject(a)){jQuery.each(a,function(){add(this.name,this.value)})}else{for(prefix in a){buildParams(prefix,a[prefix],traditional,add)}}return s.join("&")};jQuery.fn.extend({serialize:function(){return jQuery.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var elements=jQuery.prop(this,"elements");return elements?jQuery.makeArray(elements):this}).filter(function(){var type=this.type;return this.name&&!jQuery(this).is(":disabled")&&rsubmittable.test(this.nodeName)&&!rsubmitterTypes.test(type)&&(this.checked||!rcheckableType.test(type))}).map(function(i,elem){var val=jQuery(this).val();if(val==null){return null}if(Array.isArray(val)){return jQuery.map(val,function(val){return{name:elem.name,value:val.replace(rCRLF,"\r\n")}})}return{name:elem.name,value:val.replace(rCRLF,"\r\n")}}).get()}});var r20=/%20/g,rhash=/#.*$/,rantiCache=/([?&])_=[^&]*/,rheaders=/^(.*?):[ \t]*([^\r\n]*)$/gm,rlocalProtocol=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,rnoContent=/^(?:GET|HEAD)$/,rprotocol=/^\/\//,prefilters={},transports={},allTypes="*/".concat("*"),originAnchor=document.createElement("a");originAnchor.href=location.href;function addToPrefiltersOrTransports(structure){return function(dataTypeExpression,func){if(typeof dataTypeExpression!=="string"){func=dataTypeExpression;dataTypeExpression="*"}var dataType,i=0,dataTypes=dataTypeExpression.toLowerCase().match(rnothtmlwhite)||[];if(jQuery.isFunction(func)){while(dataType=dataTypes[i++]){if(dataType[0]==="+"){dataType=dataType.slice(1)||"*";(structure[dataType]=structure[dataType]||[]).unshift(func)}else{(structure[dataType]=structure[dataType]||[]).push(func)}}}}}function inspectPrefiltersOrTransports(structure,options,originalOptions,jqXHR){var inspected={},seekingTransport=structure===transports;function inspect(dataType){var selected;inspected[dataType]=true;jQuery.each(structure[dataType]||[],function(_,prefilterOrFactory){var dataTypeOrTransport=prefilterOrFactory(options,originalOptions,jqXHR);if(typeof dataTypeOrTransport==="string"&&!seekingTransport&&!inspected[dataTypeOrTransport]){options.dataTypes.unshift(dataTypeOrTransport);inspect(dataTypeOrTransport);return false}else if(seekingTransport){return!(selected=dataTypeOrTransport)}});return selected}return inspect(options.dataTypes[0])||!inspected["*"]&&inspect("*")}function ajaxExtend(target,src){var key,deep,flatOptions=jQuery.ajaxSettings.flatOptions||{};for(key in src){if(src[key]!==undefined){(flatOptions[key]?target:deep||(deep={}))[key]=src[key]}}if(deep){jQuery.extend(true,target,deep)}return target}function ajaxHandleResponses(s,jqXHR,responses){var ct,type,finalDataType,firstDataType,contents=s.contents,dataTypes=s.dataTypes;while(dataTypes[0]==="*"){dataTypes.shift();if(ct===undefined){ct=s.mimeType||jqXHR.getResponseHeader("Content-Type")}}if(ct){for(type in contents){if(contents[type]&&contents[type].test(ct)){dataTypes.unshift(type);break}}}if(dataTypes[0]in responses){finalDataType=dataTypes[0]}else{for(type in responses){if(!dataTypes[0]||s.converters[type+" "+dataTypes[0]]){finalDataType=type;break}if(!firstDataType){firstDataType=type}}finalDataType=finalDataType||firstDataType}if(finalDataType){if(finalDataType!==dataTypes[0]){dataTypes.unshift(finalDataType)}return responses[finalDataType]}}function ajaxConvert(s,response,jqXHR,isSuccess){var conv2,current,conv,tmp,prev,converters={},dataTypes=s.dataTypes.slice();if(dataTypes[1]){for(conv in s.converters){converters[conv.toLowerCase()]=s.converters[conv]}}current=dataTypes.shift();while(current){if(s.responseFields[current]){jqXHR[s.responseFields[current]]=response}if(!prev&&isSuccess&&s.dataFilter){response=s.dataFilter(response,s.dataType)}prev=current;current=dataTypes.shift();if(current){if(current==="*"){current=prev}else if(prev!=="*"&&prev!==current){conv=converters[prev+" "+current]||converters["* "+current];if(!conv){for(conv2 in converters){tmp=conv2.split(" ");if(tmp[1]===current){conv=converters[prev+" "+tmp[0]]||converters["* "+tmp[0]];if(conv){if(conv===true){conv=converters[conv2]}else if(converters[conv2]!==true){current=tmp[0];dataTypes.unshift(tmp[1])}break}}}}if(conv!==true){if(conv&&s.throws){response=conv(response)}else{try{response=conv(response)}catch(e){return{state:"parsererror",error:conv?e:"No conversion from "+prev+" to "+current}}}}}}}return{state:"success",data:response}}jQuery.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:location.href,type:"GET",isLocal:rlocalProtocol.test(location.protocol),global:true,processData:true,async:true,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":allTypes,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":true,"text json":JSON.parse,"text xml":jQuery.parseXML},flatOptions:{url:true,context:true}},ajaxSetup:function(target,settings){return settings?ajaxExtend(ajaxExtend(target,jQuery.ajaxSettings),settings):ajaxExtend(jQuery.ajaxSettings,target)},ajaxPrefilter:addToPrefiltersOrTransports(prefilters),ajaxTransport:addToPrefiltersOrTransports(transports),ajax:function(url,options){if(typeof url==="object"){options=url;url=undefined}options=options||{};var transport,cacheURL,responseHeadersString,responseHeaders,timeoutTimer,urlAnchor,completed,fireGlobals,i,uncached,s=jQuery.ajaxSetup({},options),callbackContext=s.context||s,globalEventContext=s.context&&(callbackContext.nodeType||callbackContext.jquery)?jQuery(callbackContext):jQuery.event,deferred=jQuery.Deferred(),completeDeferred=jQuery.Callbacks("once memory"),statusCode=s.statusCode||{},requestHeaders={},requestHeadersNames={},strAbort="canceled",jqXHR={readyState:0,getResponseHeader:function(key){var match;if(completed){if(!responseHeaders){responseHeaders={};while(match=rheaders.exec(responseHeadersString)){responseHeaders[match[1].toLowerCase()]=match[2]}}match=responseHeaders[key.toLowerCase()]}return match==null?null:match},getAllResponseHeaders:function(){return completed?responseHeadersString:null},setRequestHeader:function(name,value){if(completed==null){name=requestHeadersNames[name.toLowerCase()]=requestHeadersNames[name.toLowerCase()]||name;requestHeaders[name]=value}return this},overrideMimeType:function(type){if(completed==null){s.mimeType=type}return this},statusCode:function(map){var code;if(map){if(completed){jqXHR.always(map[jqXHR.status])}else{for(code in map){statusCode[code]=[statusCode[code],map[code]]}}}return this},abort:function(statusText){var finalText=statusText||strAbort;if(transport){transport.abort(finalText)}done(0,finalText);return this}};deferred.promise(jqXHR);s.url=((url||s.url||location.href)+"").replace(rprotocol,location.protocol+"//");s.type=options.method||options.type||s.method||s.type;s.dataTypes=(s.dataType||"*").toLowerCase().match(rnothtmlwhite)||[""];if(s.crossDomain==null){urlAnchor=document.createElement("a");try{urlAnchor.href=s.url;urlAnchor.href=urlAnchor.href;s.crossDomain=originAnchor.protocol+"//"+originAnchor.host!==urlAnchor.protocol+"//"+urlAnchor.host}catch(e){s.crossDomain=true}}if(s.data&&s.processData&&typeof s.data!=="string"){s.data=jQuery.param(s.data,s.traditional)}inspectPrefiltersOrTransports(prefilters,s,options,jqXHR);if(completed){return jqXHR}fireGlobals=jQuery.event&&s.global;if(fireGlobals&&jQuery.active++===0){jQuery.event.trigger("ajaxStart")}s.type=s.type.toUpperCase();s.hasContent=!rnoContent.test(s.type);cacheURL=s.url.replace(rhash,"");if(!s.hasContent){uncached=s.url.slice(cacheURL.length);if(s.data){cacheURL+=(rquery.test(cacheURL)?"&":"?")+s.data;delete s.data}if(s.cache===false){cacheURL=cacheURL.replace(rantiCache,"$1");uncached=(rquery.test(cacheURL)?"&":"?")+"_="+nonce+++uncached}s.url=cacheURL+uncached}else if(s.data&&s.processData&&(s.contentType||"").indexOf("application/x-www-form-urlencoded")===0){s.data=s.data.replace(r20,"+")}if(s.ifModified){if(jQuery.lastModified[cacheURL]){jqXHR.setRequestHeader("If-Modified-Since",jQuery.lastModified[cacheURL])}if(jQuery.etag[cacheURL]){jqXHR.setRequestHeader("If-None-Match",jQuery.etag[cacheURL])}}if(s.data&&s.hasContent&&s.contentType!==false||options.contentType){jqXHR.setRequestHeader("Content-Type",s.contentType)}jqXHR.setRequestHeader("Accept",s.dataTypes[0]&&s.accepts[s.dataTypes[0]]?s.accepts[s.dataTypes[0]]+(s.dataTypes[0]!=="*"?", "+allTypes+"; q=0.01":""):s.accepts["*"]);for(i in s.headers){jqXHR.setRequestHeader(i,s.headers[i])}if(s.beforeSend&&(s.beforeSend.call(callbackContext,jqXHR,s)===false||completed)){return jqXHR.abort()}strAbort="abort";completeDeferred.add(s.complete);jqXHR.done(s.success);jqXHR.fail(s.error);transport=inspectPrefiltersOrTransports(transports,s,options,jqXHR);if(!transport){done(-1,"No Transport")}else{jqXHR.readyState=1;if(fireGlobals){globalEventContext.trigger("ajaxSend",[jqXHR,s])}if(completed){return jqXHR}if(s.async&&s.timeout>0){timeoutTimer=window.setTimeout(function(){jqXHR.abort("timeout")},s.timeout)}try{completed=false;transport.send(requestHeaders,done)}catch(e){if(completed){throw e}done(-1,e)}}function done(status,nativeStatusText,responses,headers){var isSuccess,success,error,response,modified,statusText=nativeStatusText;if(completed){return}completed=true;if(timeoutTimer){window.clearTimeout(timeoutTimer)}transport=undefined;responseHeadersString=headers||"";jqXHR.readyState=status>0?4:0;isSuccess=status>=200&&status<300||status===304;if(responses){response=ajaxHandleResponses(s,jqXHR,responses)}response=ajaxConvert(s,response,jqXHR,isSuccess);if(isSuccess){if(s.ifModified){modified=jqXHR.getResponseHeader("Last-Modified");if(modified){jQuery.lastModified[cacheURL]=modified}modified=jqXHR.getResponseHeader("etag");if(modified){jQuery.etag[cacheURL]=modified}}if(status===204||s.type==="HEAD"){statusText="nocontent"}else if(status===304){statusText="notmodified"}else{statusText=response.state;success=response.data;error=response.error;isSuccess=!error}}else{error=statusText;if(status||!statusText){statusText="error";if(status<0){status=0}}}jqXHR.status=status;jqXHR.statusText=(nativeStatusText||statusText)+"";if(isSuccess){deferred.resolveWith(callbackContext,[success,statusText,jqXHR])}else{deferred.rejectWith(callbackContext,[jqXHR,statusText,error])}jqXHR.statusCode(statusCode);statusCode=undefined;if(fireGlobals){globalEventContext.trigger(isSuccess?"ajaxSuccess":"ajaxError",[jqXHR,s,isSuccess?success:error])}completeDeferred.fireWith(callbackContext,[jqXHR,statusText]);if(fireGlobals){globalEventContext.trigger("ajaxComplete",[jqXHR,s]);if(!--jQuery.active){jQuery.event.trigger("ajaxStop")}}}return jqXHR},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json")},getScript:function(url,callback){return jQuery.get(url,undefined,callback,"script")}});jQuery.each(["get","post"],function(i,method){jQuery[method]=function(url,data,callback,type){if(jQuery.isFunction(data)){type=type||callback;callback=data;data=undefined}return jQuery.ajax(jQuery.extend({url:url,type:method,dataType:type,data:data,success:callback},jQuery.isPlainObject(url)&&url))}});jQuery._evalUrl=function(url){return jQuery.ajax({url:url,type:"GET",dataType:"script",cache:true,async:false,global:false,throws:true})};jQuery.fn.extend({wrapAll:function(html){var wrap;if(this[0]){if(jQuery.isFunction(html)){html=html.call(this[0])}wrap=jQuery(html,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){wrap.insertBefore(this[0])}wrap.map(function(){var elem=this;while(elem.firstElementChild){elem=elem.firstElementChild}return elem}).append(this)}return this},wrapInner:function(html){if(jQuery.isFunction(html)){return this.each(function(i){jQuery(this).wrapInner(html.call(this,i))})}return this.each(function(){var self=jQuery(this),contents=self.contents();if(contents.length){contents.wrapAll(html)}else{self.append(html)}})},wrap:function(html){var isFunction=jQuery.isFunction(html);return this.each(function(i){jQuery(this).wrapAll(isFunction?html.call(this,i):html)})},unwrap:function(selector){this.parent(selector).not("body").each(function(){jQuery(this).replaceWith(this.childNodes)});return this}});jQuery.expr.pseudos.hidden=function(elem){return!jQuery.expr.pseudos.visible(elem)};jQuery.expr.pseudos.visible=function(elem){return!!(elem.offsetWidth||elem.offsetHeight||elem.getClientRects().length)};jQuery.ajaxSettings.xhr=function(){try{return new window.XMLHttpRequest}catch(e){}};var xhrSuccessStatus={0:200,1223:204},xhrSupported=jQuery.ajaxSettings.xhr();support.cors=!!xhrSupported&&"withCredentials"in xhrSupported;support.ajax=xhrSupported=!!xhrSupported;jQuery.ajaxTransport(function(options){var callback,errorCallback;if(support.cors||xhrSupported&&!options.crossDomain){return{send:function(headers,complete){var i,xhr=options.xhr();xhr.open(options.type,options.url,options.async,options.username,options.password);if(options.xhrFields){for(i in options.xhrFields){xhr[i]=options.xhrFields[i]}}if(options.mimeType&&xhr.overrideMimeType){xhr.overrideMimeType(options.mimeType)}if(!options.crossDomain&&!headers["X-Requested-With"]){headers["X-Requested-With"]="XMLHttpRequest"}for(i in headers){xhr.setRequestHeader(i,headers[i])}callback=function(type){return function(){if(callback){callback=errorCallback=xhr.onload=xhr.onerror=xhr.onabort=xhr.onreadystatechange=null;if(type==="abort"){xhr.abort()}else if(type==="error"){if(typeof xhr.status!=="number"){complete(0,"error")}else{complete(xhr.status,xhr.statusText)}}else{complete(xhrSuccessStatus[xhr.status]||xhr.status,xhr.statusText,(xhr.responseType||"text")!=="text"||typeof xhr.responseText!=="string"?{binary:xhr.response}:{text:xhr.responseText},xhr.getAllResponseHeaders())}}}};xhr.onload=callback();errorCallback=xhr.onerror=callback("error");if(xhr.onabort!==undefined){xhr.onabort=errorCallback}else{xhr.onreadystatechange=function(){if(xhr.readyState===4){window.setTimeout(function(){if(callback){errorCallback()}})}}}callback=callback("abort");try{xhr.send(options.hasContent&&options.data||null)}catch(e){if(callback){throw e}}},abort:function(){if(callback){callback()}}}}});jQuery.ajaxPrefilter(function(s){if(s.crossDomain){s.contents.script=false}});jQuery.ajaxSetup({accepts:{script:"text/javascript, application/javascript, "+"application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(text){jQuery.globalEval(text);return text}}});jQuery.ajaxPrefilter("script",function(s){if(s.cache===undefined){s.cache=false}if(s.crossDomain){s.type="GET"}});jQuery.ajaxTransport("script",function(s){if(s.crossDomain){var script,callback;return{send:function(_,complete){script=jQuery("<script>").prop({charset:s.scriptCharset,src:s.url}).on("load error",callback=function(evt){script.remove();callback=null;if(evt){complete(evt.type==="error"?404:200,evt.type)}});document.head.appendChild(script[0])},abort:function(){if(callback){callback()}}}}});var oldCallbacks=[],rjsonp=/(=)\?(?=&|$)|\?\?/;jQuery.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var callback=oldCallbacks.pop()||jQuery.expando+"_"+nonce++;this[callback]=true;return callback}});jQuery.ajaxPrefilter("json jsonp",function(s,originalSettings,jqXHR){var callbackName,overwritten,responseContainer,jsonProp=s.jsonp!==false&&(rjsonp.test(s.url)?"url":typeof s.data==="string"&&(s.contentType||"").indexOf("application/x-www-form-urlencoded")===0&&rjsonp.test(s.data)&&"data");if(jsonProp||s.dataTypes[0]==="jsonp"){callbackName=s.jsonpCallback=jQuery.isFunction(s.jsonpCallback)?s.jsonpCallback():s.jsonpCallback;if(jsonProp){s[jsonProp]=s[jsonProp].replace(rjsonp,"$1"+callbackName)}else if(s.jsonp!==false){s.url+=(rquery.test(s.url)?"&":"?")+s.jsonp+"="+callbackName}s.converters["script json"]=function(){if(!responseContainer){jQuery.error(callbackName+" was not called")}return responseContainer[0]};s.dataTypes[0]="json";overwritten=window[callbackName];window[callbackName]=function(){responseContainer=arguments};jqXHR.always(function(){if(overwritten===undefined){jQuery(window).removeProp(callbackName)}else{window[callbackName]=overwritten}if(s[callbackName]){s.jsonpCallback=originalSettings.jsonpCallback;oldCallbacks.push(callbackName)}if(responseContainer&&jQuery.isFunction(overwritten)){overwritten(responseContainer[0])}responseContainer=overwritten=undefined});return"script"}});support.createHTMLDocument=function(){var body=document.implementation.createHTMLDocument("").body;body.innerHTML="<form></form><form></form>";return body.childNodes.length===2}();jQuery.parseHTML=function(data,context,keepScripts){if(typeof data!=="string"){return[]}if(typeof context==="boolean"){keepScripts=context;context=false}var base,parsed,scripts;if(!context){if(support.createHTMLDocument){context=document.implementation.createHTMLDocument("");base=context.createElement("base");base.href=document.location.href;context.head.appendChild(base)}else{context=document}}parsed=rsingleTag.exec(data);scripts=!keepScripts&&[];if(parsed){return[context.createElement(parsed[1])]}parsed=buildFragment([data],context,scripts);if(scripts&&scripts.length){jQuery(scripts).remove()}return jQuery.merge([],parsed.childNodes)};jQuery.fn.load=function(url,params,callback){var selector,type,response,self=this,off=url.indexOf(" ");if(off>-1){selector=stripAndCollapse(url.slice(off));url=url.slice(0,off)}if(jQuery.isFunction(params)){callback=params;params=undefined}else if(params&&typeof params==="object"){type="POST"}if(self.length>0){jQuery.ajax({url:url,type:type||"GET",dataType:"html",data:params}).done(function(responseText){response=arguments;self.html(selector?jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector):responseText)}).always(callback&&function(jqXHR,status){self.each(function(){callback.apply(this,response||[jqXHR.responseText,status,jqXHR])})})}return this};jQuery.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(i,type){jQuery.fn[type]=function(fn){return this.on(type,fn)}});jQuery.expr.pseudos.animated=function(elem){return jQuery.grep(jQuery.timers,function(fn){return elem===fn.elem}).length};jQuery.offset={setOffset:function(elem,options,i){var curPosition,curLeft,curCSSTop,curTop,curOffset,curCSSLeft,calculatePosition,position=jQuery.css(elem,"position"),curElem=jQuery(elem),props={};if(position==="static"){elem.style.position="relative"}curOffset=curElem.offset();curCSSTop=jQuery.css(elem,"top");curCSSLeft=jQuery.css(elem,"left");calculatePosition=(position==="absolute"||position==="fixed")&&(curCSSTop+curCSSLeft).indexOf("auto")>-1;if(calculatePosition){curPosition=curElem.position();curTop=curPosition.top;curLeft=curPosition.left}else{curTop=parseFloat(curCSSTop)||0;curLeft=parseFloat(curCSSLeft)||0}if(jQuery.isFunction(options)){options=options.call(elem,i,jQuery.extend({},curOffset))}if(options.top!=null){props.top=options.top-curOffset.top+curTop}if(options.left!=null){props.left=options.left-curOffset.left+curLeft}if("using"in options){options.using.call(elem,props)}else{curElem.css(props)}}};jQuery.fn.extend({offset:function(options){if(arguments.length){return options===undefined?this:this.each(function(i){jQuery.offset.setOffset(this,options,i)})}var doc,docElem,rect,win,elem=this[0];if(!elem){return}if(!elem.getClientRects().length){return{top:0,left:0}}rect=elem.getBoundingClientRect();doc=elem.ownerDocument;docElem=doc.documentElement;win=doc.defaultView;return{top:rect.top+win.pageYOffset-docElem.clientTop,left:rect.left+win.pageXOffset-docElem.clientLeft}},position:function(){if(!this[0]){return}var offsetParent,offset,elem=this[0],parentOffset={top:0,left:0};if(jQuery.css(elem,"position")==="fixed"){offset=elem.getBoundingClientRect()}else{offsetParent=this.offsetParent();offset=this.offset();if(!nodeName(offsetParent[0],"html")){parentOffset=offsetParent.offset()}parentOffset={top:parentOffset.top+jQuery.css(offsetParent[0],"borderTopWidth",true),left:parentOffset.left+jQuery.css(offsetParent[0],"borderLeftWidth",true)}}return{top:offset.top-parentOffset.top-jQuery.css(elem,"marginTop",true),left:offset.left-parentOffset.left-jQuery.css(elem,"marginLeft",true)}},offsetParent:function(){return this.map(function(){var offsetParent=this.offsetParent;while(offsetParent&&jQuery.css(offsetParent,"position")==="static"){offsetParent=offsetParent.offsetParent}return offsetParent||documentElement})}});jQuery.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(method,prop){var top="pageYOffset"===prop;jQuery.fn[method]=function(val){return access(this,function(elem,method,val){var win;if(jQuery.isWindow(elem)){win=elem}else if(elem.nodeType===9){win=elem.defaultView}if(val===undefined){return win?win[prop]:elem[method]}if(win){win.scrollTo(!top?val:win.pageXOffset,top?val:win.pageYOffset)}else{elem[method]=val}},method,val,arguments.length)}});jQuery.each(["top","left"],function(i,prop){jQuery.cssHooks[prop]=addGetHookIf(support.pixelPosition,function(elem,computed){if(computed){computed=curCSS(elem,prop);return rnumnonpx.test(computed)?jQuery(elem).position()[prop]+"px":computed}})});jQuery.each({Height:"height",Width:"width"},function(name,type){jQuery.each({padding:"inner"+name,content:type,"":"outer"+name},function(defaultExtra,funcName){jQuery.fn[funcName]=function(margin,value){var chainable=arguments.length&&(defaultExtra||typeof margin!=="boolean"),extra=defaultExtra||(margin===true||value===true?"margin":"border");return access(this,function(elem,type,value){var doc;if(jQuery.isWindow(elem)){return funcName.indexOf("outer")===0?elem["inner"+name]:elem.document.documentElement["client"+name]}if(elem.nodeType===9){doc=elem.documentElement;return Math.max(elem.body["scroll"+name],doc["scroll"+name],elem.body["offset"+name],doc["offset"+name],doc["client"+name])}return value===undefined?jQuery.css(elem,type,extra):jQuery.style(elem,type,value,extra)},type,chainable?margin:undefined,chainable)}})});jQuery.fn.extend({bind:function(types,data,fn){return this.on(types,null,data,fn)},unbind:function(types,fn){return this.off(types,null,fn)},delegate:function(selector,types,data,fn){return this.on(types,selector,data,fn)},undelegate:function(selector,types,fn){return arguments.length===1?this.off(selector,"**"):this.off(types,selector||"**",fn)}});jQuery.holdReady=function(hold){if(hold){jQuery.readyWait++}else{jQuery.ready(true)}};jQuery.isArray=Array.isArray;jQuery.parseJSON=JSON.parse;jQuery.nodeName=nodeName;if(typeof define==="function"&&define.amd){define("jquery",[],function(){return jQuery})}var _jQuery=window.jQuery,_$=window.$;jQuery.noConflict=function(deep){if(window.$===jQuery){window.$=_$}if(deep&&window.jQuery===jQuery){window.jQuery=_jQuery}return jQuery};if(!noGlobal){window.jQuery=window.$=jQuery}return jQuery})},{}],4:[function(require,module,exports){(function(factory){"use strict";if(typeof define==="function"&&define.amd){define(["jquery"],factory)}else if(typeof exports!=="undefined"){module.exports=factory(require("jquery"))}else{factory(jQuery)}})(function($){"use strict";var Slick=window.Slick||{};Slick=function(){var instanceUid=0;function Slick(element,settings){var _=this,dataSettings;_.defaults={accessibility:true,adaptiveHeight:false,appendArrows:$(element),appendDots:$(element),arrows:true,asNavFor:null,prevArrow:'<button class="slick-prev" aria-label="Previous" type="button">Previous</button>',nextArrow:'<button class="slick-next" aria-label="Next" type="button">Next</button>',autoplay:false,autoplaySpeed:3e3,centerMode:false,centerPadding:"50px",cssEase:"ease",customPaging:function(slider,i){return $('<button type="button" />').text(i+1)},dots:false,dotsClass:"slick-dots",draggable:true,easing:"linear",edgeFriction:.35,fade:false,focusOnSelect:false,focusOnChange:false,infinite:true,initialSlide:0,lazyLoad:"ondemand",mobileFirst:false,pauseOnHover:true,pauseOnFocus:true,pauseOnDotsHover:false,respondTo:"window",responsive:null,rows:1,rtl:false,slide:"",slidesPerRow:1,slidesToShow:1,slidesToScroll:1,speed:500,swipe:true,swipeToSlide:false,touchMove:true,touchThreshold:5,useCSS:true,useTransform:true,variableWidth:false,vertical:false,verticalSwiping:false,waitForAnimate:true,zIndex:1e3};_.initials={animating:false,dragging:false,autoPlayTimer:null,currentDirection:0,currentLeft:null,currentSlide:0,direction:1,$dots:null,listWidth:null,listHeight:null,loadIndex:0,$nextArrow:null,$prevArrow:null,scrolling:false,slideCount:null,slideWidth:null,$slideTrack:null,$slides:null,sliding:false,slideOffset:0,swipeLeft:null,swiping:false,$list:null,touchObject:{},transformsEnabled:false,unslicked:false};$.extend(_,_.initials);_.activeBreakpoint=null;_.animType=null;_.animProp=null;_.breakpoints=[];_.breakpointSettings=[];_.cssTransitions=false;_.focussed=false;_.interrupted=false;_.hidden="hidden";_.paused=true;_.positionProp=null;_.respondTo=null;_.rowCount=1;_.shouldClick=true;_.$slider=$(element);_.$slidesCache=null;_.transformType=null;_.transitionType=null;_.visibilityChange="visibilitychange";_.windowWidth=0;_.windowTimer=null;dataSettings=$(element).data("slick")||{};_.options=$.extend({},_.defaults,settings,dataSettings);_.currentSlide=_.options.initialSlide;_.originalSettings=_.options;if(typeof document.mozHidden!=="undefined"){_.hidden="mozHidden";_.visibilityChange="mozvisibilitychange"}else if(typeof document.webkitHidden!=="undefined"){_.hidden="webkitHidden";_.visibilityChange="webkitvisibilitychange"}_.autoPlay=$.proxy(_.autoPlay,_);_.autoPlayClear=$.proxy(_.autoPlayClear,_);_.autoPlayIterator=$.proxy(_.autoPlayIterator,_);_.changeSlide=$.proxy(_.changeSlide,_);_.clickHandler=$.proxy(_.clickHandler,_);_.selectHandler=$.proxy(_.selectHandler,_);_.setPosition=$.proxy(_.setPosition,_);_.swipeHandler=$.proxy(_.swipeHandler,_);_.dragHandler=$.proxy(_.dragHandler,_);_.keyHandler=$.proxy(_.keyHandler,_);_.instanceUid=instanceUid++;_.htmlExpr=/^(?:\s*(<[\w\W]+>)[^>]*)$/;_.registerBreakpoints();_.init(true)}return Slick}();Slick.prototype.activateADA=function(){var _=this;_.$slideTrack.find(".slick-active").attr({"aria-hidden":"false"}).find("a, input, button, select").attr({tabindex:"0"})};Slick.prototype.addSlide=Slick.prototype.slickAdd=function(markup,index,addBefore){var _=this;if(typeof index==="boolean"){addBefore=index;index=null}else if(index<0||index>=_.slideCount){return false}_.unload();if(typeof index==="number"){if(index===0&&_.$slides.length===0){$(markup).appendTo(_.$slideTrack)}else if(addBefore){$(markup).insertBefore(_.$slides.eq(index))}else{$(markup).insertAfter(_.$slides.eq(index))}}else{if(addBefore===true){$(markup).prependTo(_.$slideTrack)}else{$(markup).appendTo(_.$slideTrack)}}_.$slides=_.$slideTrack.children(this.options.slide);_.$slideTrack.children(this.options.slide).detach();_.$slideTrack.append(_.$slides);_.$slides.each(function(index,element){$(element).attr("data-slick-index",index)});_.$slidesCache=_.$slides;_.reinit()};Slick.prototype.animateHeight=function(){var _=this;if(_.options.slidesToShow===1&&_.options.adaptiveHeight===true&&_.options.vertical===false){var targetHeight=_.$slides.eq(_.currentSlide).outerHeight(true);_.$list.animate({height:targetHeight},_.options.speed)}};Slick.prototype.animateSlide=function(targetLeft,callback){var animProps={},_=this;_.animateHeight();if(_.options.rtl===true&&_.options.vertical===false){targetLeft=-targetLeft}if(_.transformsEnabled===false){if(_.options.vertical===false){_.$slideTrack.animate({left:targetLeft},_.options.speed,_.options.easing,callback)}else{_.$slideTrack.animate({top:targetLeft},_.options.speed,_.options.easing,callback)}}else{if(_.cssTransitions===false){if(_.options.rtl===true){_.currentLeft=-_.currentLeft}$({animStart:_.currentLeft}).animate({animStart:targetLeft},{duration:_.options.speed,easing:_.options.easing,step:function(now){now=Math.ceil(now);if(_.options.vertical===false){animProps[_.animType]="translate("+now+"px, 0px)";_.$slideTrack.css(animProps)}else{animProps[_.animType]="translate(0px,"+now+"px)";_.$slideTrack.css(animProps)}},complete:function(){if(callback){callback.call()}}})}else{_.applyTransition();targetLeft=Math.ceil(targetLeft);if(_.options.vertical===false){animProps[_.animType]="translate3d("+targetLeft+"px, 0px, 0px)"}else{animProps[_.animType]="translate3d(0px,"+targetLeft+"px, 0px)"}_.$slideTrack.css(animProps);if(callback){setTimeout(function(){_.disableTransition();callback.call()},_.options.speed)}}}};Slick.prototype.getNavTarget=function(){var _=this,asNavFor=_.options.asNavFor;if(asNavFor&&asNavFor!==null){asNavFor=$(asNavFor).not(_.$slider)}return asNavFor};Slick.prototype.asNavFor=function(index){var _=this,asNavFor=_.getNavTarget();if(asNavFor!==null&&typeof asNavFor==="object"){asNavFor.each(function(){var target=$(this).slick("getSlick");if(!target.unslicked){target.slideHandler(index,true)}})}};Slick.prototype.applyTransition=function(slide){var _=this,transition={};if(_.options.fade===false){transition[_.transitionType]=_.transformType+" "+_.options.speed+"ms "+_.options.cssEase}else{transition[_.transitionType]="opacity "+_.options.speed+"ms "+_.options.cssEase}if(_.options.fade===false){_.$slideTrack.css(transition)}else{_.$slides.eq(slide).css(transition)}};Slick.prototype.autoPlay=function(){var _=this;_.autoPlayClear();if(_.slideCount>_.options.slidesToShow){_.autoPlayTimer=setInterval(_.autoPlayIterator,_.options.autoplaySpeed)}};Slick.prototype.autoPlayClear=function(){var _=this;if(_.autoPlayTimer){clearInterval(_.autoPlayTimer)}};Slick.prototype.autoPlayIterator=function(){var _=this,slideTo=_.currentSlide+_.options.slidesToScroll;if(!_.paused&&!_.interrupted&&!_.focussed){if(_.options.infinite===false){if(_.direction===1&&_.currentSlide+1===_.slideCount-1){_.direction=0}else if(_.direction===0){slideTo=_.currentSlide-_.options.slidesToScroll;if(_.currentSlide-1===0){_.direction=1}}}_.slideHandler(slideTo)}};Slick.prototype.buildArrows=function(){var _=this;if(_.options.arrows===true){_.$prevArrow=$(_.options.prevArrow).addClass("slick-arrow");_.$nextArrow=$(_.options.nextArrow).addClass("slick-arrow");if(_.slideCount>_.options.slidesToShow){_.$prevArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex");_.$nextArrow.removeClass("slick-hidden").removeAttr("aria-hidden tabindex");if(_.htmlExpr.test(_.options.prevArrow)){_.$prevArrow.prependTo(_.options.appendArrows)}if(_.htmlExpr.test(_.options.nextArrow)){_.$nextArrow.appendTo(_.options.appendArrows)}if(_.options.infinite!==true){_.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true")}}else{_.$prevArrow.add(_.$nextArrow).addClass("slick-hidden").attr({"aria-disabled":"true",tabindex:"-1"})}}};Slick.prototype.buildDots=function(){var _=this,i,dot;if(_.options.dots===true&&_.slideCount>_.options.slidesToShow){_.$slider.addClass("slick-dotted");dot=$("<ul />").addClass(_.options.dotsClass);for(i=0;i<=_.getDotCount();i+=1){dot.append($("<li />").append(_.options.customPaging.call(this,_,i)))}_.$dots=dot.appendTo(_.options.appendDots);_.$dots.find("li").first().addClass("slick-active")}};Slick.prototype.buildOut=function(){var _=this;_.$slides=_.$slider.children(_.options.slide+":not(.slick-cloned)").addClass("slick-slide");_.slideCount=_.$slides.length;_.$slides.each(function(index,element){$(element).attr("data-slick-index",index).data("originalStyling",$(element).attr("style")||"")});_.$slider.addClass("slick-slider");_.$slideTrack=_.slideCount===0?$('<div class="slick-track"/>').appendTo(_.$slider):_.$slides.wrapAll('<div class="slick-track"/>').parent();_.$list=_.$slideTrack.wrap('<div class="slick-list"/>').parent();_.$slideTrack.css("opacity",0);if(_.options.centerMode===true||_.options.swipeToSlide===true){_.options.slidesToScroll=1}$("img[data-lazy]",_.$slider).not("[src]").addClass("slick-loading");_.setupInfinite();_.buildArrows();_.buildDots();_.updateDots();_.setSlideClasses(typeof _.currentSlide==="number"?_.currentSlide:0);if(_.options.draggable===true){_.$list.addClass("draggable")}};Slick.prototype.buildRows=function(){var _=this,a,b,c,newSlides,numOfSlides,originalSlides,slidesPerSection;newSlides=document.createDocumentFragment();originalSlides=_.$slider.children();if(_.options.rows>0){slidesPerSection=_.options.slidesPerRow*_.options.rows;numOfSlides=Math.ceil(originalSlides.length/slidesPerSection);for(a=0;a<numOfSlides;a++){var slide=document.createElement("div");for(b=0;b<_.options.rows;b++){var row=document.createElement("div");for(c=0;c<_.options.slidesPerRow;c++){var target=a*slidesPerSection+(b*_.options.slidesPerRow+c);if(originalSlides.get(target)){row.appendChild(originalSlides.get(target))}}slide.appendChild(row)}newSlides.appendChild(slide)}_.$slider.empty().append(newSlides);_.$slider.children().children().children().css({width:100/_.options.slidesPerRow+"%",display:"inline-block"})}};Slick.prototype.checkResponsive=function(initial,forceUpdate){var _=this,breakpoint,targetBreakpoint,respondToWidth,triggerBreakpoint=false;var sliderWidth=_.$slider.width();var windowWidth=window.innerWidth||$(window).width();if(_.respondTo==="window"){respondToWidth=windowWidth}else if(_.respondTo==="slider"){respondToWidth=sliderWidth}else if(_.respondTo==="min"){respondToWidth=Math.min(windowWidth,sliderWidth)}if(_.options.responsive&&_.options.responsive.length&&_.options.responsive!==null){targetBreakpoint=null;for(breakpoint in _.breakpoints){if(_.breakpoints.hasOwnProperty(breakpoint)){if(_.originalSettings.mobileFirst===false){if(respondToWidth<_.breakpoints[breakpoint]){targetBreakpoint=_.breakpoints[breakpoint]}}else{if(respondToWidth>_.breakpoints[breakpoint]){targetBreakpoint=_.breakpoints[breakpoint]}}}}if(targetBreakpoint!==null){if(_.activeBreakpoint!==null){if(targetBreakpoint!==_.activeBreakpoint||forceUpdate){_.activeBreakpoint=targetBreakpoint;if(_.breakpointSettings[targetBreakpoint]==="unslick"){_.unslick(targetBreakpoint)}else{_.options=$.extend({},_.originalSettings,_.breakpointSettings[targetBreakpoint]);if(initial===true){_.currentSlide=_.options.initialSlide}_.refresh(initial)}triggerBreakpoint=targetBreakpoint}}else{_.activeBreakpoint=targetBreakpoint;if(_.breakpointSettings[targetBreakpoint]==="unslick"){_.unslick(targetBreakpoint)}else{_.options=$.extend({},_.originalSettings,_.breakpointSettings[targetBreakpoint]);if(initial===true){_.currentSlide=_.options.initialSlide}_.refresh(initial)}triggerBreakpoint=targetBreakpoint}}else{if(_.activeBreakpoint!==null){_.activeBreakpoint=null;_.options=_.originalSettings;if(initial===true){_.currentSlide=_.options.initialSlide}_.refresh(initial);triggerBreakpoint=targetBreakpoint}}if(!initial&&triggerBreakpoint!==false){_.$slider.trigger("breakpoint",[_,triggerBreakpoint])}}};Slick.prototype.changeSlide=function(event,dontAnimate){var _=this,$target=$(event.currentTarget),indexOffset,slideOffset,unevenOffset;if($target.is("a")){event.preventDefault()}if(!$target.is("li")){$target=$target.closest("li")}unevenOffset=_.slideCount%_.options.slidesToScroll!==0;indexOffset=unevenOffset?0:(_.slideCount-_.currentSlide)%_.options.slidesToScroll;switch(event.data.message){case"previous":slideOffset=indexOffset===0?_.options.slidesToScroll:_.options.slidesToShow-indexOffset;if(_.slideCount>_.options.slidesToShow){_.slideHandler(_.currentSlide-slideOffset,false,dontAnimate)}break;case"next":slideOffset=indexOffset===0?_.options.slidesToScroll:indexOffset;if(_.slideCount>_.options.slidesToShow){_.slideHandler(_.currentSlide+slideOffset,false,dontAnimate)}break;case"index":var index=event.data.index===0?0:event.data.index||$target.index()*_.options.slidesToScroll;_.slideHandler(_.checkNavigable(index),false,dontAnimate);$target.children().trigger("focus");break;default:return}};Slick.prototype.checkNavigable=function(index){var _=this,navigables,prevNavigable;navigables=_.getNavigableIndexes();prevNavigable=0;if(index>navigables[navigables.length-1]){index=navigables[navigables.length-1]}else{for(var n in navigables){if(index<navigables[n]){index=prevNavigable;break}prevNavigable=navigables[n]}}return index};Slick.prototype.cleanUpEvents=function(){var _=this;if(_.options.dots&&_.$dots!==null){$("li",_.$dots).off("click.slick",_.changeSlide).off("mouseenter.slick",$.proxy(_.interrupt,_,true)).off("mouseleave.slick",$.proxy(_.interrupt,_,false));if(_.options.accessibility===true){_.$dots.off("keydown.slick",_.keyHandler)}}_.$slider.off("focus.slick blur.slick");if(_.options.arrows===true&&_.slideCount>_.options.slidesToShow){_.$prevArrow&&_.$prevArrow.off("click.slick",_.changeSlide);_.$nextArrow&&_.$nextArrow.off("click.slick",_.changeSlide);if(_.options.accessibility===true){_.$prevArrow&&_.$prevArrow.off("keydown.slick",_.keyHandler);_.$nextArrow&&_.$nextArrow.off("keydown.slick",_.keyHandler)}}_.$list.off("touchstart.slick mousedown.slick",_.swipeHandler);_.$list.off("touchmove.slick mousemove.slick",_.swipeHandler);_.$list.off("touchend.slick mouseup.slick",_.swipeHandler);_.$list.off("touchcancel.slick mouseleave.slick",_.swipeHandler);_.$list.off("click.slick",_.clickHandler);$(document).off(_.visibilityChange,_.visibility);_.cleanUpSlideEvents();if(_.options.accessibility===true){_.$list.off("keydown.slick",_.keyHandler)}if(_.options.focusOnSelect===true){$(_.$slideTrack).children().off("click.slick",_.selectHandler)}$(window).off("orientationchange.slick.slick-"+_.instanceUid,_.orientationChange);$(window).off("resize.slick.slick-"+_.instanceUid,_.resize);$("[draggable!=true]",_.$slideTrack).off("dragstart",_.preventDefault);$(window).off("load.slick.slick-"+_.instanceUid,_.setPosition)};Slick.prototype.cleanUpSlideEvents=function(){var _=this;_.$list.off("mouseenter.slick",$.proxy(_.interrupt,_,true));_.$list.off("mouseleave.slick",$.proxy(_.interrupt,_,false))};Slick.prototype.cleanUpRows=function(){var _=this,originalSlides;if(_.options.rows>0){originalSlides=_.$slides.children().children();originalSlides.removeAttr("style");_.$slider.empty().append(originalSlides)}};Slick.prototype.clickHandler=function(event){var _=this;if(_.shouldClick===false){event.stopImmediatePropagation();event.stopPropagation();event.preventDefault()}};Slick.prototype.destroy=function(refresh){var _=this;_.autoPlayClear();_.touchObject={};_.cleanUpEvents();$(".slick-cloned",_.$slider).detach();if(_.$dots){_.$dots.remove()}if(_.$prevArrow&&_.$prevArrow.length){_.$prevArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display","");if(_.htmlExpr.test(_.options.prevArrow)){_.$prevArrow.remove()}}if(_.$nextArrow&&_.$nextArrow.length){_.$nextArrow.removeClass("slick-disabled slick-arrow slick-hidden").removeAttr("aria-hidden aria-disabled tabindex").css("display","");if(_.htmlExpr.test(_.options.nextArrow)){_.$nextArrow.remove()}}if(_.$slides){_.$slides.removeClass("slick-slide slick-active slick-center slick-visible slick-current").removeAttr("aria-hidden").removeAttr("data-slick-index").each(function(){$(this).attr("style",$(this).data("originalStyling"))});_.$slideTrack.children(this.options.slide).detach();_.$slideTrack.detach();_.$list.detach();_.$slider.append(_.$slides)}_.cleanUpRows();_.$slider.removeClass("slick-slider");_.$slider.removeClass("slick-initialized");_.$slider.removeClass("slick-dotted");_.unslicked=true;if(!refresh){_.$slider.trigger("destroy",[_])}};Slick.prototype.disableTransition=function(slide){var _=this,transition={};transition[_.transitionType]="";if(_.options.fade===false){_.$slideTrack.css(transition)}else{_.$slides.eq(slide).css(transition)}};Slick.prototype.fadeSlide=function(slideIndex,callback){var _=this;if(_.cssTransitions===false){_.$slides.eq(slideIndex).css({zIndex:_.options.zIndex});_.$slides.eq(slideIndex).animate({opacity:1},_.options.speed,_.options.easing,callback)}else{_.applyTransition(slideIndex);_.$slides.eq(slideIndex).css({opacity:1,zIndex:_.options.zIndex});if(callback){setTimeout(function(){_.disableTransition(slideIndex);callback.call()},_.options.speed)}}};Slick.prototype.fadeSlideOut=function(slideIndex){var _=this;if(_.cssTransitions===false){_.$slides.eq(slideIndex).animate({opacity:0,zIndex:_.options.zIndex-2},_.options.speed,_.options.easing)}else{_.applyTransition(slideIndex);_.$slides.eq(slideIndex).css({opacity:0,zIndex:_.options.zIndex-2})}};Slick.prototype.filterSlides=Slick.prototype.slickFilter=function(filter){var _=this;if(filter!==null){_.$slidesCache=_.$slides;_.unload();_.$slideTrack.children(this.options.slide).detach();_.$slidesCache.filter(filter).appendTo(_.$slideTrack);_.reinit()}};Slick.prototype.focusHandler=function(){var _=this;_.$slider.off("focus.slick blur.slick").on("focus.slick blur.slick","*",function(event){event.stopImmediatePropagation();var $sf=$(this);setTimeout(function(){if(_.options.pauseOnFocus){_.focussed=$sf.is(":focus");_.autoPlay()}},0)})};Slick.prototype.getCurrent=Slick.prototype.slickCurrentSlide=function(){var _=this;return _.currentSlide};Slick.prototype.getDotCount=function(){var _=this;var breakPoint=0;var counter=0;var pagerQty=0;if(_.options.infinite===true){if(_.slideCount<=_.options.slidesToShow){++pagerQty}else{while(breakPoint<_.slideCount){++pagerQty;breakPoint=counter+_.options.slidesToScroll;counter+=_.options.slidesToScroll<=_.options.slidesToShow?_.options.slidesToScroll:_.options.slidesToShow}}}else if(_.options.centerMode===true){pagerQty=_.slideCount}else if(!_.options.asNavFor){pagerQty=1+Math.ceil((_.slideCount-_.options.slidesToShow)/_.options.slidesToScroll)}else{while(breakPoint<_.slideCount){++pagerQty;breakPoint=counter+_.options.slidesToScroll;counter+=_.options.slidesToScroll<=_.options.slidesToShow?_.options.slidesToScroll:_.options.slidesToShow}}return pagerQty-1};Slick.prototype.getLeft=function(slideIndex){var _=this,targetLeft,verticalHeight,verticalOffset=0,targetSlide,coef;_.slideOffset=0;verticalHeight=_.$slides.first().outerHeight(true);if(_.options.infinite===true){if(_.slideCount>_.options.slidesToShow){_.slideOffset=_.slideWidth*_.options.slidesToShow*-1;coef=-1;if(_.options.vertical===true&&_.options.centerMode===true){if(_.options.slidesToShow===2){coef=-1.5}else if(_.options.slidesToShow===1){coef=-2}}verticalOffset=verticalHeight*_.options.slidesToShow*coef}if(_.slideCount%_.options.slidesToScroll!==0){if(slideIndex+_.options.slidesToScroll>_.slideCount&&_.slideCount>_.options.slidesToShow){if(slideIndex>_.slideCount){_.slideOffset=(_.options.slidesToShow-(slideIndex-_.slideCount))*_.slideWidth*-1;verticalOffset=(_.options.slidesToShow-(slideIndex-_.slideCount))*verticalHeight*-1}else{_.slideOffset=_.slideCount%_.options.slidesToScroll*_.slideWidth*-1;verticalOffset=_.slideCount%_.options.slidesToScroll*verticalHeight*-1}}}}else{if(slideIndex+_.options.slidesToShow>_.slideCount){_.slideOffset=(slideIndex+_.options.slidesToShow-_.slideCount)*_.slideWidth;verticalOffset=(slideIndex+_.options.slidesToShow-_.slideCount)*verticalHeight}}if(_.slideCount<=_.options.slidesToShow){_.slideOffset=0;verticalOffset=0}if(_.options.centerMode===true&&_.slideCount<=_.options.slidesToShow){_.slideOffset=_.slideWidth*Math.floor(_.options.slidesToShow)/2-_.slideWidth*_.slideCount/2}else if(_.options.centerMode===true&&_.options.infinite===true){_.slideOffset+=_.slideWidth*Math.floor(_.options.slidesToShow/2)-_.slideWidth}else if(_.options.centerMode===true){_.slideOffset=0;_.slideOffset+=_.slideWidth*Math.floor(_.options.slidesToShow/2)}if(_.options.vertical===false){targetLeft=slideIndex*_.slideWidth*-1+_.slideOffset}else{targetLeft=slideIndex*verticalHeight*-1+verticalOffset}if(_.options.variableWidth===true){if(_.slideCount<=_.options.slidesToShow||_.options.infinite===false){targetSlide=_.$slideTrack.children(".slick-slide").eq(slideIndex)}else{targetSlide=_.$slideTrack.children(".slick-slide").eq(slideIndex+_.options.slidesToShow)}if(_.options.rtl===true){if(targetSlide[0]){targetLeft=(_.$slideTrack.width()-targetSlide[0].offsetLeft-targetSlide.width())*-1}else{targetLeft=0}}else{targetLeft=targetSlide[0]?targetSlide[0].offsetLeft*-1:0}if(_.options.centerMode===true){if(_.slideCount<=_.options.slidesToShow||_.options.infinite===false){targetSlide=_.$slideTrack.children(".slick-slide").eq(slideIndex)}else{targetSlide=_.$slideTrack.children(".slick-slide").eq(slideIndex+_.options.slidesToShow+1)}if(_.options.rtl===true){if(targetSlide[0]){targetLeft=(_.$slideTrack.width()-targetSlide[0].offsetLeft-targetSlide.width())*-1}else{targetLeft=0}}else{targetLeft=targetSlide[0]?targetSlide[0].offsetLeft*-1:0}targetLeft+=(_.$list.width()-targetSlide.outerWidth())/2}}return targetLeft};Slick.prototype.getOption=Slick.prototype.slickGetOption=function(option){var _=this;return _.options[option]};Slick.prototype.getNavigableIndexes=function(){var _=this,breakPoint=0,counter=0,indexes=[],max;if(_.options.infinite===false){max=_.slideCount}else{breakPoint=_.options.slidesToScroll*-1;counter=_.options.slidesToScroll*-1;max=_.slideCount*2}while(breakPoint<max){indexes.push(breakPoint);breakPoint=counter+_.options.slidesToScroll;counter+=_.options.slidesToScroll<=_.options.slidesToShow?_.options.slidesToScroll:_.options.slidesToShow}return indexes};Slick.prototype.getSlick=function(){return this};Slick.prototype.getSlideCount=function(){var _=this,slidesTraversed,swipedSlide,centerOffset;centerOffset=_.options.centerMode===true?_.slideWidth*Math.floor(_.options.slidesToShow/2):0;if(_.options.swipeToSlide===true){_.$slideTrack.find(".slick-slide").each(function(index,slide){if(slide.offsetLeft-centerOffset+$(slide).outerWidth()/2>_.swipeLeft*-1){swipedSlide=slide;return false}});slidesTraversed=Math.abs($(swipedSlide).attr("data-slick-index")-_.currentSlide)||1;return slidesTraversed}else{return _.options.slidesToScroll}};Slick.prototype.goTo=Slick.prototype.slickGoTo=function(slide,dontAnimate){var _=this;_.changeSlide({data:{message:"index",index:parseInt(slide)}},dontAnimate)};Slick.prototype.init=function(creation){var _=this;if(!$(_.$slider).hasClass("slick-initialized")){$(_.$slider).addClass("slick-initialized");_.buildRows();_.buildOut();_.setProps();_.startLoad();_.loadSlider();_.initializeEvents();_.updateArrows();_.updateDots();_.checkResponsive(true);_.focusHandler()}if(creation){_.$slider.trigger("init",[_])}if(_.options.accessibility===true){_.initADA()}if(_.options.autoplay){_.paused=false;_.autoPlay()}};Slick.prototype.initADA=function(){var _=this,numDotGroups=Math.ceil(_.slideCount/_.options.slidesToShow),tabControlIndexes=_.getNavigableIndexes().filter(function(val){return val>=0&&val<_.slideCount});_.$slides.add(_.$slideTrack.find(".slick-cloned")).attr({"aria-hidden":"true",tabindex:"-1"}).find("a, input, button, select").attr({tabindex:"-1"});if(_.$dots!==null){_.$slides.not(_.$slideTrack.find(".slick-cloned")).each(function(i){var slideControlIndex=tabControlIndexes.indexOf(i);$(this).attr({role:"tabpanel",id:"slick-slide"+_.instanceUid+i,tabindex:-1});if(slideControlIndex!==-1){var ariaButtonControl="slick-slide-control"+_.instanceUid+slideControlIndex;if($("#"+ariaButtonControl).length){$(this).attr({"aria-describedby":ariaButtonControl})}}});_.$dots.attr("role","tablist").find("li").each(function(i){var mappedSlideIndex=tabControlIndexes[i];$(this).attr({role:"presentation"});$(this).find("button").first().attr({role:"tab",id:"slick-slide-control"+_.instanceUid+i,"aria-controls":"slick-slide"+_.instanceUid+mappedSlideIndex,"aria-label":i+1+" of "+numDotGroups,"aria-selected":null,tabindex:"-1"})}).eq(_.currentSlide).find("button").attr({"aria-selected":"true",tabindex:"0"}).end()}for(var i=_.currentSlide,max=i+_.options.slidesToShow;i<max;i++){if(_.options.focusOnChange){_.$slides.eq(i).attr({tabindex:"0"})}else{_.$slides.eq(i).removeAttr("tabindex")}}_.activateADA()};Slick.prototype.initArrowEvents=function(){var _=this;if(_.options.arrows===true&&_.slideCount>_.options.slidesToShow){_.$prevArrow.off("click.slick").on("click.slick",{message:"previous"},_.changeSlide);_.$nextArrow.off("click.slick").on("click.slick",{message:"next"},_.changeSlide);if(_.options.accessibility===true){_.$prevArrow.on("keydown.slick",_.keyHandler);_.$nextArrow.on("keydown.slick",_.keyHandler)}}};Slick.prototype.initDotEvents=function(){var _=this;if(_.options.dots===true&&_.slideCount>_.options.slidesToShow){$("li",_.$dots).on("click.slick",{message:"index"},_.changeSlide);if(_.options.accessibility===true){_.$dots.on("keydown.slick",_.keyHandler)}}if(_.options.dots===true&&_.options.pauseOnDotsHover===true&&_.slideCount>_.options.slidesToShow){$("li",_.$dots).on("mouseenter.slick",$.proxy(_.interrupt,_,true)).on("mouseleave.slick",$.proxy(_.interrupt,_,false))}};Slick.prototype.initSlideEvents=function(){var _=this;if(_.options.pauseOnHover){_.$list.on("mouseenter.slick",$.proxy(_.interrupt,_,true));_.$list.on("mouseleave.slick",$.proxy(_.interrupt,_,false))}};Slick.prototype.initializeEvents=function(){var _=this;_.initArrowEvents();_.initDotEvents();_.initSlideEvents();_.$list.on("touchstart.slick mousedown.slick",{action:"start"},_.swipeHandler);_.$list.on("touchmove.slick mousemove.slick",{action:"move"},_.swipeHandler);_.$list.on("touchend.slick mouseup.slick",{action:"end"},_.swipeHandler);_.$list.on("touchcancel.slick mouseleave.slick",{action:"end"},_.swipeHandler);_.$list.on("click.slick",_.clickHandler);$(document).on(_.visibilityChange,$.proxy(_.visibility,_));if(_.options.accessibility===true){_.$list.on("keydown.slick",_.keyHandler)}if(_.options.focusOnSelect===true){$(_.$slideTrack).children().on("click.slick",_.selectHandler)}$(window).on("orientationchange.slick.slick-"+_.instanceUid,$.proxy(_.orientationChange,_));$(window).on("resize.slick.slick-"+_.instanceUid,$.proxy(_.resize,_));$("[draggable!=true]",_.$slideTrack).on("dragstart",_.preventDefault);$(window).on("load.slick.slick-"+_.instanceUid,_.setPosition);$(_.setPosition)};Slick.prototype.initUI=function(){var _=this;if(_.options.arrows===true&&_.slideCount>_.options.slidesToShow){_.$prevArrow.show();_.$nextArrow.show()}if(_.options.dots===true&&_.slideCount>_.options.slidesToShow){_.$dots.show()}};Slick.prototype.keyHandler=function(event){var _=this;if(!event.target.tagName.match("TEXTAREA|INPUT|SELECT")){if(event.keyCode===37&&_.options.accessibility===true){_.changeSlide({data:{message:_.options.rtl===true?"next":"previous"}})}else if(event.keyCode===39&&_.options.accessibility===true){_.changeSlide({data:{message:_.options.rtl===true?"previous":"next"}})}}};Slick.prototype.lazyLoad=function(){var _=this,loadRange,cloneRange,rangeStart,rangeEnd;function loadImages(imagesScope){$("img[data-lazy]",imagesScope).each(function(){var image=$(this),imageSource=$(this).attr("data-lazy"),imageSrcSet=$(this).attr("data-srcset"),imageSizes=$(this).attr("data-sizes")||_.$slider.attr("data-sizes"),imageToLoad=document.createElement("img");imageToLoad.onload=function(){image.animate({opacity:0},100,function(){if(imageSrcSet){image.attr("srcset",imageSrcSet);if(imageSizes){image.attr("sizes",imageSizes)}}image.attr("src",imageSource).animate({opacity:1},200,function(){image.removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading")});_.$slider.trigger("lazyLoaded",[_,image,imageSource])})};imageToLoad.onerror=function(){image.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error");_.$slider.trigger("lazyLoadError",[_,image,imageSource])};imageToLoad.src=imageSource})}if(_.options.centerMode===true){if(_.options.infinite===true){rangeStart=_.currentSlide+(_.options.slidesToShow/2+1);rangeEnd=rangeStart+_.options.slidesToShow+2}else{rangeStart=Math.max(0,_.currentSlide-(_.options.slidesToShow/2+1));rangeEnd=2+(_.options.slidesToShow/2+1)+_.currentSlide}}else{rangeStart=_.options.infinite?_.options.slidesToShow+_.currentSlide:_.currentSlide;rangeEnd=Math.ceil(rangeStart+_.options.slidesToShow);if(_.options.fade===true){if(rangeStart>0)rangeStart--;if(rangeEnd<=_.slideCount)rangeEnd++}}loadRange=_.$slider.find(".slick-slide").slice(rangeStart,rangeEnd);if(_.options.lazyLoad==="anticipated"){var prevSlide=rangeStart-1,nextSlide=rangeEnd,$slides=_.$slider.find(".slick-slide");for(var i=0;i<_.options.slidesToScroll;i++){if(prevSlide<0)prevSlide=_.slideCount-1;loadRange=loadRange.add($slides.eq(prevSlide));loadRange=loadRange.add($slides.eq(nextSlide));prevSlide--;nextSlide++}}loadImages(loadRange);if(_.slideCount<=_.options.slidesToShow){cloneRange=_.$slider.find(".slick-slide");loadImages(cloneRange)}else if(_.currentSlide>=_.slideCount-_.options.slidesToShow){cloneRange=_.$slider.find(".slick-cloned").slice(0,_.options.slidesToShow);loadImages(cloneRange)}else if(_.currentSlide===0){cloneRange=_.$slider.find(".slick-cloned").slice(_.options.slidesToShow*-1);loadImages(cloneRange)}};Slick.prototype.loadSlider=function(){var _=this;_.setPosition();_.$slideTrack.css({opacity:1});_.$slider.removeClass("slick-loading");_.initUI();if(_.options.lazyLoad==="progressive"){_.progressiveLazyLoad()}};Slick.prototype.next=Slick.prototype.slickNext=function(){var _=this;_.changeSlide({data:{message:"next"}})};Slick.prototype.orientationChange=function(){var _=this;_.checkResponsive();_.setPosition()};Slick.prototype.pause=Slick.prototype.slickPause=function(){var _=this;_.autoPlayClear();_.paused=true};Slick.prototype.play=Slick.prototype.slickPlay=function(){var _=this;_.autoPlay();_.options.autoplay=true;_.paused=false;_.focussed=false;_.interrupted=false};Slick.prototype.postSlide=function(index){var _=this;if(!_.unslicked){_.$slider.trigger("afterChange",[_,index]);_.animating=false;if(_.slideCount>_.options.slidesToShow){_.setPosition()}_.swipeLeft=null;if(_.options.autoplay){_.autoPlay()}if(_.options.accessibility===true){_.initADA();if(_.options.focusOnChange){var $currentSlide=$(_.$slides.get(_.currentSlide));$currentSlide.attr("tabindex",0).focus()}}}};Slick.prototype.prev=Slick.prototype.slickPrev=function(){var _=this;_.changeSlide({data:{message:"previous"}})};Slick.prototype.preventDefault=function(event){event.preventDefault()};Slick.prototype.progressiveLazyLoad=function(tryCount){tryCount=tryCount||1;var _=this,$imgsToLoad=$("img[data-lazy]",_.$slider),image,imageSource,imageSrcSet,imageSizes,imageToLoad;if($imgsToLoad.length){image=$imgsToLoad.first();imageSource=image.attr("data-lazy");imageSrcSet=image.attr("data-srcset");imageSizes=image.attr("data-sizes")||_.$slider.attr("data-sizes");imageToLoad=document.createElement("img");imageToLoad.onload=function(){if(imageSrcSet){image.attr("srcset",imageSrcSet);if(imageSizes){image.attr("sizes",imageSizes)}}image.attr("src",imageSource).removeAttr("data-lazy data-srcset data-sizes").removeClass("slick-loading");if(_.options.adaptiveHeight===true){_.setPosition()}_.$slider.trigger("lazyLoaded",[_,image,imageSource]);_.progressiveLazyLoad()};imageToLoad.onerror=function(){if(tryCount<3){setTimeout(function(){_.progressiveLazyLoad(tryCount+1)},500)}else{image.removeAttr("data-lazy").removeClass("slick-loading").addClass("slick-lazyload-error");_.$slider.trigger("lazyLoadError",[_,image,imageSource]);_.progressiveLazyLoad()}};imageToLoad.src=imageSource}else{_.$slider.trigger("allImagesLoaded",[_])}};Slick.prototype.refresh=function(initializing){var _=this,currentSlide,lastVisibleIndex;lastVisibleIndex=_.slideCount-_.options.slidesToShow;if(!_.options.infinite&&_.currentSlide>lastVisibleIndex){_.currentSlide=lastVisibleIndex}if(_.slideCount<=_.options.slidesToShow){_.currentSlide=0}currentSlide=_.currentSlide;_.destroy(true);$.extend(_,_.initials,{currentSlide:currentSlide});_.init();if(!initializing){_.changeSlide({data:{message:"index",index:currentSlide}},false)}};Slick.prototype.registerBreakpoints=function(){var _=this,breakpoint,currentBreakpoint,l,responsiveSettings=_.options.responsive||null;if($.type(responsiveSettings)==="array"&&responsiveSettings.length){_.respondTo=_.options.respondTo||"window";for(breakpoint in responsiveSettings){l=_.breakpoints.length-1;if(responsiveSettings.hasOwnProperty(breakpoint)){currentBreakpoint=responsiveSettings[breakpoint].breakpoint;while(l>=0){if(_.breakpoints[l]&&_.breakpoints[l]===currentBreakpoint){_.breakpoints.splice(l,1)}l--}_.breakpoints.push(currentBreakpoint);_.breakpointSettings[currentBreakpoint]=responsiveSettings[breakpoint].settings}}_.breakpoints.sort(function(a,b){return _.options.mobileFirst?a-b:b-a})}};Slick.prototype.reinit=function(){var _=this;_.$slides=_.$slideTrack.children(_.options.slide).addClass("slick-slide");_.slideCount=_.$slides.length;if(_.currentSlide>=_.slideCount&&_.currentSlide!==0){_.currentSlide=_.currentSlide-_.options.slidesToScroll}if(_.slideCount<=_.options.slidesToShow){_.currentSlide=0}_.registerBreakpoints();_.setProps();_.setupInfinite();_.buildArrows();_.updateArrows();_.initArrowEvents();_.buildDots();_.updateDots();_.initDotEvents();_.cleanUpSlideEvents();_.initSlideEvents();_.checkResponsive(false,true);if(_.options.focusOnSelect===true){$(_.$slideTrack).children().on("click.slick",_.selectHandler)}_.setSlideClasses(typeof _.currentSlide==="number"?_.currentSlide:0);_.setPosition();_.focusHandler();_.paused=!_.options.autoplay;_.autoPlay();_.$slider.trigger("reInit",[_])};Slick.prototype.resize=function(){var _=this;if($(window).width()!==_.windowWidth){clearTimeout(_.windowDelay);_.windowDelay=window.setTimeout(function(){_.windowWidth=$(window).width();_.checkResponsive();if(!_.unslicked){_.setPosition()}},50)}};Slick.prototype.removeSlide=Slick.prototype.slickRemove=function(index,removeBefore,removeAll){var _=this;if(typeof index==="boolean"){removeBefore=index;index=removeBefore===true?0:_.slideCount-1}else{index=removeBefore===true?--index:index}if(_.slideCount<1||index<0||index>_.slideCount-1){return false}_.unload();if(removeAll===true){_.$slideTrack.children().remove()}else{_.$slideTrack.children(this.options.slide).eq(index).remove()}_.$slides=_.$slideTrack.children(this.options.slide);_.$slideTrack.children(this.options.slide).detach();_.$slideTrack.append(_.$slides);_.$slidesCache=_.$slides;_.reinit()};Slick.prototype.setCSS=function(position){var _=this,positionProps={},x,y;if(_.options.rtl===true){position=-position}x=_.positionProp=="left"?Math.ceil(position)+"px":"0px";y=_.positionProp=="top"?Math.ceil(position)+"px":"0px";positionProps[_.positionProp]=position;if(_.transformsEnabled===false){_.$slideTrack.css(positionProps)}else{positionProps={};if(_.cssTransitions===false){positionProps[_.animType]="translate("+x+", "+y+")";_.$slideTrack.css(positionProps)}else{positionProps[_.animType]="translate3d("+x+", "+y+", 0px)";_.$slideTrack.css(positionProps)}}};Slick.prototype.setDimensions=function(){var _=this;if(_.options.vertical===false){if(_.options.centerMode===true){_.$list.css({padding:"0px "+_.options.centerPadding})}}else{_.$list.height(_.$slides.first().outerHeight(true)*_.options.slidesToShow);if(_.options.centerMode===true){_.$list.css({padding:_.options.centerPadding+" 0px"})}}_.listWidth=_.$list.width();_.listHeight=_.$list.height();if(_.options.vertical===false&&_.options.variableWidth===false){_.slideWidth=Math.ceil(_.listWidth/_.options.slidesToShow);_.$slideTrack.width(Math.ceil(_.slideWidth*_.$slideTrack.children(".slick-slide").length))}else if(_.options.variableWidth===true){_.$slideTrack.width(5e3*_.slideCount)}else{_.slideWidth=Math.ceil(_.listWidth);_.$slideTrack.height(Math.ceil(_.$slides.first().outerHeight(true)*_.$slideTrack.children(".slick-slide").length))}var offset=_.$slides.first().outerWidth(true)-_.$slides.first().width();if(_.options.variableWidth===false)_.$slideTrack.children(".slick-slide").width(_.slideWidth-offset)};Slick.prototype.setFade=function(){var _=this,targetLeft;_.$slides.each(function(index,element){targetLeft=_.slideWidth*index*-1;if(_.options.rtl===true){$(element).css({position:"relative",right:targetLeft,top:0,zIndex:_.options.zIndex-2,opacity:0})}else{$(element).css({position:"relative",left:targetLeft,top:0,zIndex:_.options.zIndex-2,opacity:0})}});_.$slides.eq(_.currentSlide).css({zIndex:_.options.zIndex-1,opacity:1})};Slick.prototype.setHeight=function(){var _=this;if(_.options.slidesToShow===1&&_.options.adaptiveHeight===true&&_.options.vertical===false){var targetHeight=_.$slides.eq(_.currentSlide).outerHeight(true);_.$list.css("height",targetHeight)}};Slick.prototype.setOption=Slick.prototype.slickSetOption=function(){var _=this,l,item,option,value,refresh=false,type;if($.type(arguments[0])==="object"){option=arguments[0];refresh=arguments[1];type="multiple"}else if($.type(arguments[0])==="string"){option=arguments[0];value=arguments[1];refresh=arguments[2];if(arguments[0]==="responsive"&&$.type(arguments[1])==="array"){type="responsive"}else if(typeof arguments[1]!=="undefined"){type="single"}}if(type==="single"){_.options[option]=value}else if(type==="multiple"){$.each(option,function(opt,val){_.options[opt]=val})}else if(type==="responsive"){for(item in value){if($.type(_.options.responsive)!=="array"){_.options.responsive=[value[item]]}else{l=_.options.responsive.length-1;while(l>=0){if(_.options.responsive[l].breakpoint===value[item].breakpoint){_.options.responsive.splice(l,1)}l--}_.options.responsive.push(value[item])}}}if(refresh){_.unload();_.reinit()}};Slick.prototype.setPosition=function(){var _=this;_.setDimensions();_.setHeight();if(_.options.fade===false){_.setCSS(_.getLeft(_.currentSlide))}else{_.setFade()}_.$slider.trigger("setPosition",[_])};Slick.prototype.setProps=function(){var _=this,bodyStyle=document.body.style;_.positionProp=_.options.vertical===true?"top":"left";if(_.positionProp==="top"){_.$slider.addClass("slick-vertical")}else{_.$slider.removeClass("slick-vertical")}if(bodyStyle.WebkitTransition!==undefined||bodyStyle.MozTransition!==undefined||bodyStyle.msTransition!==undefined){if(_.options.useCSS===true){_.cssTransitions=true}}if(_.options.fade){if(typeof _.options.zIndex==="number"){if(_.options.zIndex<3){_.options.zIndex=3}}else{_.options.zIndex=_.defaults.zIndex}}if(bodyStyle.OTransform!==undefined){_.animType="OTransform";_.transformType="-o-transform";_.transitionType="OTransition";if(bodyStyle.perspectiveProperty===undefined&&bodyStyle.webkitPerspective===undefined)_.animType=false}if(bodyStyle.MozTransform!==undefined){_.animType="MozTransform";_.transformType="-moz-transform";_.transitionType="MozTransition";if(bodyStyle.perspectiveProperty===undefined&&bodyStyle.MozPerspective===undefined)_.animType=false}if(bodyStyle.webkitTransform!==undefined){_.animType="webkitTransform";_.transformType="-webkit-transform";_.transitionType="webkitTransition";if(bodyStyle.perspectiveProperty===undefined&&bodyStyle.webkitPerspective===undefined)_.animType=false}if(bodyStyle.msTransform!==undefined){_.animType="msTransform";_.transformType="-ms-transform";_.transitionType="msTransition";if(bodyStyle.msTransform===undefined)_.animType=false}if(bodyStyle.transform!==undefined&&_.animType!==false){_.animType="transform";_.transformType="transform";_.transitionType="transition"}_.transformsEnabled=_.options.useTransform&&(_.animType!==null&&_.animType!==false)};Slick.prototype.setSlideClasses=function(index){var _=this,centerOffset,allSlides,indexOffset,remainder;allSlides=_.$slider.find(".slick-slide").removeClass("slick-active slick-center slick-current").attr("aria-hidden","true");_.$slides.eq(index).addClass("slick-current");if(_.options.centerMode===true){var evenCoef=_.options.slidesToShow%2===0?1:0;centerOffset=Math.floor(_.options.slidesToShow/2);if(_.options.infinite===true){if(index>=centerOffset&&index<=_.slideCount-1-centerOffset){_.$slides.slice(index-centerOffset+evenCoef,index+centerOffset+1).addClass("slick-active").attr("aria-hidden","false")}else{indexOffset=_.options.slidesToShow+index;allSlides.slice(indexOffset-centerOffset+1+evenCoef,indexOffset+centerOffset+2).addClass("slick-active").attr("aria-hidden","false")}if(index===0){allSlides.eq(allSlides.length-1-_.options.slidesToShow).addClass("slick-center")}else if(index===_.slideCount-1){allSlides.eq(_.options.slidesToShow).addClass("slick-center")}}_.$slides.eq(index).addClass("slick-center")}else{if(index>=0&&index<=_.slideCount-_.options.slidesToShow){_.$slides.slice(index,index+_.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false")}else if(allSlides.length<=_.options.slidesToShow){allSlides.addClass("slick-active").attr("aria-hidden","false")}else{remainder=_.slideCount%_.options.slidesToShow;indexOffset=_.options.infinite===true?_.options.slidesToShow+index:index;if(_.options.slidesToShow==_.options.slidesToScroll&&_.slideCount-index<_.options.slidesToShow){allSlides.slice(indexOffset-(_.options.slidesToShow-remainder),indexOffset+remainder).addClass("slick-active").attr("aria-hidden","false")}else{allSlides.slice(indexOffset,indexOffset+_.options.slidesToShow).addClass("slick-active").attr("aria-hidden","false")}}}if(_.options.lazyLoad==="ondemand"||_.options.lazyLoad==="anticipated"){_.lazyLoad()}};Slick.prototype.setupInfinite=function(){var _=this,i,slideIndex,infiniteCount;if(_.options.fade===true){_.options.centerMode=false}if(_.options.infinite===true&&_.options.fade===false){slideIndex=null;if(_.slideCount>_.options.slidesToShow){if(_.options.centerMode===true){infiniteCount=_.options.slidesToShow+1}else{infiniteCount=_.options.slidesToShow}for(i=_.slideCount;i>_.slideCount-infiniteCount;i-=1){slideIndex=i-1;$(_.$slides[slideIndex]).clone(true).attr("id","").attr("data-slick-index",slideIndex-_.slideCount).prependTo(_.$slideTrack).addClass("slick-cloned")}for(i=0;i<infiniteCount+_.slideCount;i+=1){slideIndex=i;$(_.$slides[slideIndex]).clone(true).attr("id","").attr("data-slick-index",slideIndex+_.slideCount).appendTo(_.$slideTrack).addClass("slick-cloned")}_.$slideTrack.find(".slick-cloned").find("[id]").each(function(){$(this).attr("id","")})}}};Slick.prototype.interrupt=function(toggle){var _=this;if(!toggle){_.autoPlay()}_.interrupted=toggle};Slick.prototype.selectHandler=function(event){var _=this;var targetElement=$(event.target).is(".slick-slide")?$(event.target):$(event.target).parents(".slick-slide");var index=parseInt(targetElement.attr("data-slick-index"));if(!index)index=0;if(_.slideCount<=_.options.slidesToShow){_.slideHandler(index,false,true);return}_.slideHandler(index)};Slick.prototype.slideHandler=function(index,sync,dontAnimate){var targetSlide,animSlide,oldSlide,slideLeft,targetLeft=null,_=this,navTarget;sync=sync||false;if(_.animating===true&&_.options.waitForAnimate===true){return}if(_.options.fade===true&&_.currentSlide===index){return}if(sync===false){_.asNavFor(index)}targetSlide=index;targetLeft=_.getLeft(targetSlide);slideLeft=_.getLeft(_.currentSlide);_.currentLeft=_.swipeLeft===null?slideLeft:_.swipeLeft;if(_.options.infinite===false&&_.options.centerMode===false&&(index<0||index>_.getDotCount()*_.options.slidesToScroll)){if(_.options.fade===false){targetSlide=_.currentSlide;if(dontAnimate!==true&&_.slideCount>_.options.slidesToShow){_.animateSlide(slideLeft,function(){_.postSlide(targetSlide)})}else{_.postSlide(targetSlide)}}return}else if(_.options.infinite===false&&_.options.centerMode===true&&(index<0||index>_.slideCount-_.options.slidesToScroll)){if(_.options.fade===false){targetSlide=_.currentSlide;if(dontAnimate!==true&&_.slideCount>_.options.slidesToShow){_.animateSlide(slideLeft,function(){_.postSlide(targetSlide)})}else{_.postSlide(targetSlide)}}return}if(_.options.autoplay){clearInterval(_.autoPlayTimer)}if(targetSlide<0){if(_.slideCount%_.options.slidesToScroll!==0){animSlide=_.slideCount-_.slideCount%_.options.slidesToScroll}else{animSlide=_.slideCount+targetSlide}}else if(targetSlide>=_.slideCount){if(_.slideCount%_.options.slidesToScroll!==0){animSlide=0}else{animSlide=targetSlide-_.slideCount}}else{animSlide=targetSlide}_.animating=true;_.$slider.trigger("beforeChange",[_,_.currentSlide,animSlide]);oldSlide=_.currentSlide;_.currentSlide=animSlide;_.setSlideClasses(_.currentSlide);if(_.options.asNavFor){navTarget=_.getNavTarget();navTarget=navTarget.slick("getSlick");if(navTarget.slideCount<=navTarget.options.slidesToShow){navTarget.setSlideClasses(_.currentSlide)}}_.updateDots();_.updateArrows();if(_.options.fade===true){if(dontAnimate!==true){_.fadeSlideOut(oldSlide);_.fadeSlide(animSlide,function(){_.postSlide(animSlide)})}else{_.postSlide(animSlide)}_.animateHeight();return}if(dontAnimate!==true&&_.slideCount>_.options.slidesToShow){_.animateSlide(targetLeft,function(){_.postSlide(animSlide)})}else{_.postSlide(animSlide)}};Slick.prototype.startLoad=function(){var _=this;if(_.options.arrows===true&&_.slideCount>_.options.slidesToShow){_.$prevArrow.hide();_.$nextArrow.hide()}if(_.options.dots===true&&_.slideCount>_.options.slidesToShow){_.$dots.hide()}_.$slider.addClass("slick-loading")};Slick.prototype.swipeDirection=function(){var xDist,yDist,r,swipeAngle,_=this;xDist=_.touchObject.startX-_.touchObject.curX;yDist=_.touchObject.startY-_.touchObject.curY;r=Math.atan2(yDist,xDist);swipeAngle=Math.round(r*180/Math.PI);if(swipeAngle<0){swipeAngle=360-Math.abs(swipeAngle)}if(swipeAngle<=45&&swipeAngle>=0){return _.options.rtl===false?"left":"right"}if(swipeAngle<=360&&swipeAngle>=315){return _.options.rtl===false?"left":"right"}if(swipeAngle>=135&&swipeAngle<=225){return _.options.rtl===false?"right":"left"}if(_.options.verticalSwiping===true){if(swipeAngle>=35&&swipeAngle<=135){return"down"}else{return"up"}}return"vertical"};Slick.prototype.swipeEnd=function(event){var _=this,slideCount,direction;_.dragging=false;_.swiping=false;if(_.scrolling){_.scrolling=false;return false}_.interrupted=false;_.shouldClick=_.touchObject.swipeLength>10?false:true;if(_.touchObject.curX===undefined){return false}if(_.touchObject.edgeHit===true){_.$slider.trigger("edge",[_,_.swipeDirection()])}if(_.touchObject.swipeLength>=_.touchObject.minSwipe){direction=_.swipeDirection();switch(direction){case"left":case"down":slideCount=_.options.swipeToSlide?_.checkNavigable(_.currentSlide+_.getSlideCount()):_.currentSlide+_.getSlideCount();_.currentDirection=0;break;case"right":case"up":slideCount=_.options.swipeToSlide?_.checkNavigable(_.currentSlide-_.getSlideCount()):_.currentSlide-_.getSlideCount();_.currentDirection=1;break;default:}if(direction!="vertical"){_.slideHandler(slideCount);_.touchObject={};_.$slider.trigger("swipe",[_,direction])}}else{if(_.touchObject.startX!==_.touchObject.curX){_.slideHandler(_.currentSlide);_.touchObject={}}}};Slick.prototype.swipeHandler=function(event){var _=this;if(_.options.swipe===false||"ontouchend"in document&&_.options.swipe===false){return}else if(_.options.draggable===false&&event.type.indexOf("mouse")!==-1){return}_.touchObject.fingerCount=event.originalEvent&&event.originalEvent.touches!==undefined?event.originalEvent.touches.length:1;_.touchObject.minSwipe=_.listWidth/_.options.touchThreshold;if(_.options.verticalSwiping===true){_.touchObject.minSwipe=_.listHeight/_.options.touchThreshold}switch(event.data.action){case"start":_.swipeStart(event);break;case"move":_.swipeMove(event);break;case"end":_.swipeEnd(event);break}};Slick.prototype.swipeMove=function(event){var _=this,edgeWasHit=false,curLeft,swipeDirection,swipeLength,positionOffset,touches,verticalSwipeLength;touches=event.originalEvent!==undefined?event.originalEvent.touches:null;if(!_.dragging||_.scrolling||touches&&touches.length!==1){return false}curLeft=_.getLeft(_.currentSlide);_.touchObject.curX=touches!==undefined?touches[0].pageX:event.clientX;_.touchObject.curY=touches!==undefined?touches[0].pageY:event.clientY;_.touchObject.swipeLength=Math.round(Math.sqrt(Math.pow(_.touchObject.curX-_.touchObject.startX,2)));verticalSwipeLength=Math.round(Math.sqrt(Math.pow(_.touchObject.curY-_.touchObject.startY,2)));if(!_.options.verticalSwiping&&!_.swiping&&verticalSwipeLength>4){_.scrolling=true;return false}if(_.options.verticalSwiping===true){_.touchObject.swipeLength=verticalSwipeLength}swipeDirection=_.swipeDirection();if(event.originalEvent!==undefined&&_.touchObject.swipeLength>4){_.swiping=true;event.preventDefault()}positionOffset=(_.options.rtl===false?1:-1)*(_.touchObject.curX>_.touchObject.startX?1:-1);if(_.options.verticalSwiping===true){positionOffset=_.touchObject.curY>_.touchObject.startY?1:-1}swipeLength=_.touchObject.swipeLength;_.touchObject.edgeHit=false;if(_.options.infinite===false){if(_.currentSlide===0&&swipeDirection==="right"||_.currentSlide>=_.getDotCount()&&swipeDirection==="left"){swipeLength=_.touchObject.swipeLength*_.options.edgeFriction;_.touchObject.edgeHit=true}}if(_.options.vertical===false){_.swipeLeft=curLeft+swipeLength*positionOffset}else{_.swipeLeft=curLeft+swipeLength*(_.$list.height()/_.listWidth)*positionOffset}if(_.options.verticalSwiping===true){_.swipeLeft=curLeft+swipeLength*positionOffset}if(_.options.fade===true||_.options.touchMove===false){return false}if(_.animating===true){_.swipeLeft=null;return false}_.setCSS(_.swipeLeft)};Slick.prototype.swipeStart=function(event){var _=this,touches;_.interrupted=true;if(_.touchObject.fingerCount!==1||_.slideCount<=_.options.slidesToShow){_.touchObject={};return false}if(event.originalEvent!==undefined&&event.originalEvent.touches!==undefined){touches=event.originalEvent.touches[0]}_.touchObject.startX=_.touchObject.curX=touches!==undefined?touches.pageX:event.clientX;_.touchObject.startY=_.touchObject.curY=touches!==undefined?touches.pageY:event.clientY;_.dragging=true};Slick.prototype.unfilterSlides=Slick.prototype.slickUnfilter=function(){var _=this;if(_.$slidesCache!==null){_.unload();_.$slideTrack.children(this.options.slide).detach();_.$slidesCache.appendTo(_.$slideTrack);_.reinit()}};Slick.prototype.unload=function(){var _=this;$(".slick-cloned",_.$slider).remove();if(_.$dots){_.$dots.remove()}if(_.$prevArrow&&_.htmlExpr.test(_.options.prevArrow)){_.$prevArrow.remove()}if(_.$nextArrow&&_.htmlExpr.test(_.options.nextArrow)){_.$nextArrow.remove()}_.$slides.removeClass("slick-slide slick-active slick-visible slick-current").attr("aria-hidden","true").css("width","")};Slick.prototype.unslick=function(fromBreakpoint){var _=this;_.$slider.trigger("unslick",[_,fromBreakpoint]);_.destroy()};Slick.prototype.updateArrows=function(){var _=this,centerOffset;centerOffset=Math.floor(_.options.slidesToShow/2);if(_.options.arrows===true&&_.slideCount>_.options.slidesToShow&&!_.options.infinite){_.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false");_.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false");if(_.currentSlide===0){_.$prevArrow.addClass("slick-disabled").attr("aria-disabled","true");_.$nextArrow.removeClass("slick-disabled").attr("aria-disabled","false")}else if(_.currentSlide>=_.slideCount-_.options.slidesToShow&&_.options.centerMode===false){_.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true");_.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")}else if(_.currentSlide>=_.slideCount-1&&_.options.centerMode===true){_.$nextArrow.addClass("slick-disabled").attr("aria-disabled","true");_.$prevArrow.removeClass("slick-disabled").attr("aria-disabled","false")}}};Slick.prototype.updateDots=function(){var _=this;if(_.$dots!==null){_.$dots.find("li").removeClass("slick-active").end();_.$dots.find("li").eq(Math.floor(_.currentSlide/_.options.slidesToScroll)).addClass("slick-active")}};Slick.prototype.visibility=function(){var _=this;if(_.options.autoplay){if(document[_.hidden]){_.interrupted=true}else{_.interrupted=false}}};$.fn.slick=function(){var _=this,opt=arguments[0],args=Array.prototype.slice.call(arguments,1),l=_.length,i,ret;for(i=0;i<l;i++){if(typeof opt=="object"||typeof opt=="undefined")_[i].slick=new Slick(_[i],opt);else ret=_[i].slick[opt].apply(_[i].slick,args);if(typeof ret!="undefined")return ret}return _}})},{jquery:3}]},{},[1]);
| g |
program_governance.rs | //! Program Governance Account
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use solana_program::pubkey::Pubkey;
use super::enums::GovernanceAccountType;
/// Program Governance Account
#[repr(C)]
#[derive(Clone, Debug, PartialEq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct ProgramGovernance {
/// Account type
pub account_type: GovernanceAccountType,
/// Voting threshold in % required to tip the vote
/// It's the percentage of tokens out of the entire pool of governance tokens eligible to vote
pub vote_threshold: u8,
/// Minimum % of tokens for a governance token owner to be able to create a proposal
/// It's the percentage of tokens out of the entire pool of governance tokens eligible to vote
pub token_threshold_to_create_proposal: u8,
/// Minimum waiting time in slots for an instruction to be executed after proposal is voted on
pub min_instruction_hold_up_time: u64,
/// Program ID that is governed by this Governance
pub program: Pubkey,
| pub proposal_count: u32,
} | /// Time limit in slots for proposal to be open for voting
pub max_voting_time: u64,
/// Running count of proposals |
padding_oracle.py | # coding=utf-8
from random import randint
import os
from Crypto.Cipher import AES
from base64 import b64decode
all = [
"MDAwMDAwTm93IHRoYXQgdGhlIHBhcnR5IGlzIGp1bXBpbmc=",
"MDAwMDAxV2l0aCB0aGUgYmFzcyBraWNrZWQgaW4gYW5kIHRoZSBWZWdhJ3MgYXJlIHB1bXBpbic=",
"MDAwMDAyUXVpY2sgdG8gdGhlIHBvaW50LCB0byB0aGUgcG9pbnQsIG5vIGZha2luZw==",
"MDAwMDAzQ29va2luZyBNQydzIGxpa2UgYSBwb3VuZCBvZiBiYWNvbg==",
"MDAwMDA0QnVybmluZyAnZW0sIGlmIHlvdSBhaW4ndCBxdWljayBhbmQgbmltYmxl",
"MDAwMDA1SSBnbyBjcmF6eSB3aGVuIEkgaGVhciBhIGN5bWJhbA==",
"MDAwMDA2QW5kIGEgaGlnaCBoYXQgd2l0aCBhIHNvdXBlZCB1cCB0ZW1wbw==",
"MDAwMDA3SSdtIG9uIGEgcm9sbCwgaXQncyB0aW1lIHRvIGdvIHNvbG8=",
"MDAwMDA4b2xsaW4nIGluIG15IGZpdmUgcG9pbnQgb2g=",
"MDAwMDA5aXRoIG15IHJhZy10b3AgZG93biBzbyBteSBoYWlyIGNhbiBibG93"
]
#
key = os.urandom(16)
#
pad = lambda s: s+chr(16-len(s)%16)*(16-len(s)%16)
#
unpad = lambda s: s[-ord(s[-1]):] == chr(ord(s[-1]))*ord(s[-1])
#
def oracle():
m = b64decode(all[randint(0, 9)])
iv = os.urandom(AES.block_size)
cipher = AES.new(key,AES.MODE_CBC,iv)
enc = cipher.encrypt(pad(m))
return iv+enc
#
def check_oracle(enc):
iv = enc[0:AES.block_size]
cipher = AES.new(key,AES.MODE_CBC,iv)
mess = cipher.decrypt(enc[AES.block_size:])
# res = unpad(mess)
# print res[1]
return unpad(mess)
##############################################
def xor(a,b):
return ''.join([chr(ord(i)^ord(j)) for i,j in zip(a,b)])
# 注意事项 可能有多个合法padding,需要处理,我的解决方法不太好当是也能凑合用,即记录下所有可能,找出一种合法的即可
def judge(bs,tmp,enc,pos):
if pos == bs:
return [True,''.join(tmp)]
for i in range(pos,bs):
j = 0
nxt = ''
for k in range(i, 0, -1):
nxt += chr(ord(tmp[-k]) ^ (i + 1))
record = []
while j < 256:
payload = chr(0) * (bs - i - 1) + chr(j) + nxt
if check_oracle(payload + enc):
record.append(chr(j ^ (i + 1)))
j += 1
# 非法,可能是因为之前猜测的结果错误的原因
if len(record) == 0:
return [False,'']
elif len(record) == 1:
# 只有一种可能不用调用函数
tmp[-i-1] = record[0]
else:
# 尝试所有可能性
for k in record:
tmp[-i-1] = k
res = judge(bs,tmp,enc,i+1)
# 合法的可能 直接返回,不合法的不考虑
if res[0]:
return [True, res[1]]
return [True,''.join(tmp)]
#
#
# 一块一块暴力破解
def padding_oracle_block(iv,bs,enc):
tmp = ['']*bs
res = judge(bs,tmp,enc,0)[1]
return xor(iv,res)
def padding_oracle():
enc = oracle()
bs = AES.block_size
iv = enc[0:bs]
blocks = [enc[bs*i:bs*i+bs] for i in | ])/bs)]
message = ''
for block in blocks:
try:
message += padding_oracle_block(iv,bs,block)
except:
f = open('log.txt','w+')
log = "iv == "+iv.encode('hex')+'\n'+"key == "+key.encode('hex')+'\n'+'block=='+block.encode('hex')+'\n'
f.write(log)
f.close()
return 'error please check your logs to see more details'
# print message
iv = block
return message
print padding_oracle()
| range(1,len(enc[bs: |
stream.rs | use std::io::{IoSlice, IoSliceMut};
use std::net::SocketAddr;
use std::pin::Pin;
use async_io::Async;
use crate::io::{self, Read, Write};
use crate::net::ToSocketAddrs;
use crate::sync::Arc;
use crate::task::{Context, Poll};
/// A TCP stream between a local and a remote socket.
///
/// A `TcpStream` can either be created by connecting to an endpoint, via the [`connect`] method,
/// or by [accepting] a connection from a [listener]. It can be read or written to using the
/// [`AsyncRead`], [`AsyncWrite`], and related extension traits in [`futures::io`].
///
/// The connection will be closed when the value is dropped. The reading and writing portions of
/// the connection can also be shut down individually with the [`shutdown`] method.
///
/// This type is an async version of [`std::net::TcpStream`].
///
/// [`connect`]: struct.TcpStream.html#method.connect
/// [accepting]: struct.TcpListener.html#method.accept
/// [listener]: struct.TcpListener.html
/// [`AsyncRead`]: https://docs.rs/futures/0.3/futures/io/trait.AsyncRead.html
/// [`AsyncWrite`]: https://docs.rs/futures/0.3/futures/io/trait.AsyncWrite.html
/// [`futures::io`]: https://docs.rs/futures/0.3/futures/io/index.html
/// [`shutdown`]: struct.TcpStream.html#method.shutdown
/// [`std::net::TcpStream`]: https://doc.rust-lang.org/std/net/struct.TcpStream.html
///
/// ## Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
/// use async_std::prelude::*;
///
/// let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
/// stream.write_all(b"hello world").await?;
///
/// let mut buf = vec![0u8; 1024];
/// let n = stream.read(&mut buf).await?;
/// #
/// # Ok(()) }) }
/// ```
#[derive(Debug, Clone)]
pub struct | {
pub(super) watcher: Arc<Async<std::net::TcpStream>>,
}
impl TcpStream {
/// Creates a new TCP stream connected to the specified address.
///
/// This method will create a new TCP socket and attempt to connect it to the `addr`
/// provided. The [returned future] will be resolved once the stream has successfully
/// connected, or it will return an error if one occurs.
///
/// [returned future]: struct.Connect.html
///
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:0").await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn connect<A: ToSocketAddrs>(addrs: A) -> io::Result<TcpStream> {
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
let mut last_err = None;
let addrs = addrs.to_socket_addrs().await?;
for addr in addrs {
match Async::<std::net::TcpStream>::connect(addr).await {
Ok(stream) => {
return Ok(TcpStream {
watcher: Arc::new(stream),
});
}
Err(e) => {
last_err = Some(e);
continue;
}
}
}
Err(last_err.unwrap_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"could not resolve to any addresses",
)
}))
}
/// Returns the local address that this stream is connected to.
///
/// ## Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
/// let addr = stream.local_addr()?;
/// #
/// # Ok(()) }) }
/// ```
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.watcher.get_ref().local_addr()
}
/// Returns the remote address that this stream is connected to.
///
/// ## Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
/// let peer = stream.peer_addr()?;
/// #
/// # Ok(()) }) }
/// ```
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
self.watcher.get_ref().peer_addr()
}
/// Gets the value of the `IP_TTL` option for this socket.
///
/// For more information about this option, see [`set_ttl`].
///
/// [`set_ttl`]: #method.set_ttl
///
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// stream.set_ttl(100)?;
/// assert_eq!(stream.ttl()?, 100);
/// #
/// # Ok(()) }) }
/// ```
pub fn ttl(&self) -> io::Result<u32> {
self.watcher.get_ref().ttl()
}
/// Sets the value for the `IP_TTL` option on this socket.
///
/// This value sets the time-to-live field that is used in every packet sent
/// from this socket.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// stream.set_ttl(100)?;
/// assert_eq!(stream.ttl()?, 100);
/// #
/// # Ok(()) }) }
/// ```
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
self.watcher.get_ref().set_ttl(ttl)
}
/// Receives data on the socket from the remote address to which it is connected, without
/// removing that data from the queue.
///
/// On success, returns the number of bytes peeked.
///
/// Successive calls return the same data. This is accomplished by passing `MSG_PEEK` as a flag
/// to the underlying `recv` system call.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8000").await?;
///
/// let mut buf = vec![0; 1024];
/// let n = stream.peek(&mut buf).await?;
/// #
/// # Ok(()) }) }
/// ```
pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
self.watcher.peek(buf).await
}
/// Gets the value of the `TCP_NODELAY` option on this socket.
///
/// For more information about this option, see [`set_nodelay`].
///
/// [`set_nodelay`]: #method.set_nodelay
///
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// stream.set_nodelay(true)?;
/// assert_eq!(stream.nodelay()?, true);
/// #
/// # Ok(()) }) }
/// ```
pub fn nodelay(&self) -> io::Result<bool> {
self.watcher.get_ref().nodelay()
}
/// Sets the value of the `TCP_NODELAY` option on this socket.
///
/// If set, this option disables the Nagle algorithm. This means that
/// segments are always sent as soon as possible, even if there is only a
/// small amount of data. When not set, data is buffered until there is a
/// sufficient amount to send out, thereby avoiding the frequent sending of
/// small packets.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
///
/// stream.set_nodelay(true)?;
/// assert_eq!(stream.nodelay()?, true);
/// #
/// # Ok(()) }) }
/// ```
pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
self.watcher.get_ref().set_nodelay(nodelay)
}
/// Shuts down the read, write, or both halves of this connection.
///
/// This method will cause all pending and future I/O on the specified portions to return
/// immediately with an appropriate value (see the documentation of [`Shutdown`]).
///
/// [`Shutdown`]: https://doc.rust-lang.org/std/net/enum.Shutdown.html
///
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
/// #
/// use std::net::Shutdown;
///
/// use async_std::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
/// stream.shutdown(Shutdown::Both)?;
/// #
/// # Ok(()) }) }
/// ```
pub fn shutdown(&self, how: std::net::Shutdown) -> std::io::Result<()> {
self.watcher.get_ref().shutdown(how)
}
}
impl Read for TcpStream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut &*self).poll_read(cx, buf)
}
fn poll_read_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &mut [IoSliceMut<'_>],
) -> Poll<io::Result<usize>> {
Pin::new(&mut &*self).poll_read_vectored(cx, bufs)
}
}
impl Read for &TcpStream {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut &*self.watcher).poll_read(cx, buf)
}
}
impl Write for TcpStream {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut &*self).poll_write(cx, buf)
}
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<io::Result<usize>> {
Pin::new(&mut &*self).poll_write_vectored(cx, bufs)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut &*self).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut &*self).poll_close(cx)
}
}
impl Write for &TcpStream {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
Pin::new(&mut &*self.watcher).poll_write(cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut &*self.watcher).poll_flush(cx)
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut &*self.watcher).poll_close(cx)
}
}
impl From<std::net::TcpStream> for TcpStream {
/// Converts a `std::net::TcpStream` into its asynchronous equivalent.
fn from(stream: std::net::TcpStream) -> TcpStream {
once_cell::sync::Lazy::force(&crate::rt::RUNTIME);
TcpStream {
watcher: Arc::new(Async::new(stream).expect("TcpStream is known to be good")),
}
}
}
cfg_unix! {
use crate::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
impl AsRawFd for TcpStream {
fn as_raw_fd(&self) -> RawFd {
self.watcher.get_ref().as_raw_fd()
}
}
impl FromRawFd for TcpStream {
unsafe fn from_raw_fd(fd: RawFd) -> TcpStream {
std::net::TcpStream::from_raw_fd(fd).into()
}
}
impl IntoRawFd for TcpStream {
fn into_raw_fd(self) -> RawFd {
// TODO(stjepang): This does not mean `RawFd` is now the sole owner of the file
// descriptor because it's possible that there are other clones of this `TcpStream`
// using it at the same time. We should probably document that behavior.
self.as_raw_fd()
}
}
}
cfg_windows! {
use crate::os::windows::io::{
RawSocket, AsRawSocket, FromRawSocket, IntoRawSocket
};
impl AsRawSocket for TcpStream {
fn as_raw_socket(&self) -> RawSocket {
self.watcher.get_ref().as_raw_socket()
}
}
impl FromRawSocket for TcpStream {
unsafe fn from_raw_socket(handle: RawSocket) -> TcpStream {
std::net::TcpStream::from_raw_socket(handle).into()
}
}
impl IntoRawSocket for TcpStream {
fn into_raw_socket(self) -> RawSocket {
// TODO(stjepang): This does not mean `RawFd` is now the sole owner of the file
// descriptor because it's possible that there are other clones of this `TcpStream`
// using it at the same time. We should probably document that behavior.
self.as_raw_socket()
}
}
}
| TcpStream |
api.py | class BaseHandler:
def send(self, data, p):
pass
def recv(self, data, p):
pass
def shutdown(self, p, direction=2):
pass
def close(self):
| pass |
|
k8s_config_handler.py | import base64
import re
from dataclasses import dataclass
from enum import Enum
from typing import Union, List
from kubernetes import client, config
from kubernetes.client import V1ConfigMapList, V1SecretList, CoreV1Api, V1Secret, V1ConfigMap
from nexuscasc.logger import Logger
class ResourceType(Enum):
SECRET, CONFIGMAP = range(2)
@dataclass
class WatchedResource:
name: str
version: str
type: ResourceType
class K8sConfigHandler:
v1: CoreV1Api = None
watch_list: List[WatchedResource] = list()
def __init__(self, local: bool = False):
if local:
config.load_kube_config()
else:
config.load_incluster_config()
self.v1 = client.CoreV1Api()
@staticmethod
def filter_resources(
resources: Union[V1ConfigMapList, V1SecretList],
label_value: str = None
) -> List[Union[V1ConfigMap, V1Secret]]:
matches = list()
for res in resources.items:
if label_value is None:
matches.append(res)
elif len(list(filter(lambda x: res.metadata.labels[x] == label_value, res.metadata.labels.keys()))) > 0:
matches.append(res)
return matches
def find_config_maps(self, namespace: str, label: str, label_value: str = None) -> List[V1ConfigMap]:
config_maps = self.v1.list_namespaced_config_map(namespace=namespace, label_selector=label)
return self.filter_resources(config_maps, label_value)
def | (self, namespace: str, label: str, label_value: str = None) -> List[V1Secret]:
secrets = self.v1.list_namespaced_secret(namespace=namespace, label_selector=label)
return self.filter_resources(secrets, label_value)
@staticmethod
def extract_yaml_strings_from_resources(resources: List[Union[V1ConfigMap, V1Secret]]) -> List[str]:
yaml_str = list()
for res in resources:
for k in filter(lambda key: re.search("\\.yml|\\.yaml$", key), res.data.keys()):
if type(res) == V1Secret:
Logger.debug(f"Found yaml in key '{k}' for secret '{res.metadata.name}'")
yaml_str.append(base64.b64decode(res.data[k]).decode())
else:
Logger.debug(f"Found yaml in key '{k}' for configmap '{res.metadata.name}'")
yaml_str.append(res.data[k])
return yaml_str
def any_resource_has_changed(self, resources: List[Union[V1ConfigMap, V1Secret]]) -> bool:
has_changed = False
if len(self.watch_list) == 0:
has_changed = True
for res in resources:
self.watch_resource(res)
else:
for res in resources:
r_name = res.metadata.name
r_type = ResourceType.SECRET if type(res) == V1Secret else ResourceType.CONFIGMAP
watched_resource = next(filter(lambda r: r_name == r.name and r_type == r.type, self.watch_list), None)
if watched_resource is None:
self.watch_resource(res)
has_changed = True
break
elif watched_resource.version != res.metadata.resource_version:
watched_resource.version = res.metadata.resource_version
has_changed = True
break
return has_changed
def watch_resource(self, resource: Union[V1ConfigMap, V1Secret]):
self.watch_list.append(
WatchedResource(
name=resource.metadata.name,
version=resource.metadata.resource_version,
type=ResourceType.SECRET if type(resource) == V1Secret else ResourceType.CONFIGMAP
))
| find_secrets |
36-ui-cancel-combinator-4-ok.rs | use futures::channel::mpsc::{unbounded, UnboundedSender};
use futures::stream::{Stream, StreamExt};
use futures::{future, join};
use lazy_static::lazy_static;
use rand::distributions::{Distribution, Uniform};
use std::ops::Range;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use tokio::spawn;
use tokio::time::{sleep, Instant};
lazy_static! {
static ref START_TIME: Instant = Instant::now();
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Cancel 25 queries, buffered by 3");
cancel_queries_buffered(5, 3).await?;
Ok(())
}
async fn cancel_queries_buffered(
n: usize,
buf_factor: usize,
) -> Result<(), Box<dyn std::error::Error>> {
let (tx, rx) = unbounded();
let (valid_writer, valid_reader) = ValidRange::new();
let counter = Arc::new(ValidCounter::new());
let send = spawn(async move {
send_task_tracking_validity(tx, n, valid_writer).await;
});
let counter_writer = counter.clone();
let receive = spawn(async move {
receive_task_buffered(
cancel(rx, &valid_reader),
buf_factor,
&valid_reader,
&counter_writer,
)
.await;
});
let (send_res, receive_res) = join!(send, receive);
send_res?;
receive_res?;
counter.print();
Ok(())
}
fn cancel<'a, S: Stream<Item = usize> + 'a>(
stream: S,
valid_range: &'a ValidRange,
) -> impl Stream<Item = usize> + 'a {
stream.filter(move |i| {
let is_valid = valid_range.is_valid(*i);
println!("## filter({}) = {}", i, is_valid);
future::ready(is_valid)
})
}
async fn send_task_tracking_validity(
tx: UnboundedSender<usize>,
n: usize,
valid_writer: ValidRange,
) {
for i in 0..n {
let range = 10 * i..10 * i + 5;
valid_writer.set(range.clone());
for j in range {
println!("## unbounded_send({})", j);
tx.unbounded_send(j).unwrap();
}
let millis = Uniform::from(0..10).sample(&mut rand::thread_rng());
println!("## sleep({}) for {} ms", i, millis);
let duration = Duration::from_millis(millis);
sleep(duration).await;
println!("## sleep({}) completed", i);
}
}
async fn receive_task_buffered(
rx: impl Stream<Item = usize>,
buf_factor: usize,
valid_reader: &ValidRange,
counter_writer: &Arc<ValidCounter>,
) {
rx.map(|i| get_data(i))
.buffered(buf_factor)
.for_each(|data| async move {
let is_valid = valid_reader.is_valid(data.0);
counter_writer.increment(is_valid);
println!(
"## data = {:?} ({})",
data,
if is_valid { "valid" } else { "expired" }
);
})
.await;
}
#[derive(Clone)]
struct ValidRange {
range: Arc<RwLock<Range<usize>>>,
}
impl ValidRange {
fn new() -> (ValidRange, ValidRange) {
let writer = Arc::new(RwLock::new(0..0));
let reader = writer.clone();
(ValidRange { range: writer }, ValidRange { range: reader })
}
fn set(&self, range: Range<usize>) {
*self.range.write().unwrap() = range;
}
fn is_valid(&self, x: usize) -> bool {
self.range.read().unwrap().contains(&x)
}
}
struct ValidCounter {
valid: AtomicUsize,
expired: AtomicUsize,
}
impl ValidCounter {
fn new() -> ValidCounter {
ValidCounter {
valid: AtomicUsize::new(0),
expired: AtomicUsize::new(0),
}
}
fn increment(&self, is_valid: bool) |
fn print(&self) {
let valid = self.valid.load(Ordering::SeqCst);
let expired = self.expired.load(Ordering::SeqCst);
println!(
"Made {} queries, {} results were still valid, {} expired",
valid + expired,
valid,
expired
);
}
}
#[derive(Clone, Copy)]
struct Data(usize);
impl std::fmt::Debug for Data {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!("d:{}", self.0))
}
}
async fn get_data(i: usize) -> Data {
let millis = Uniform::from(0..10).sample(&mut rand::thread_rng());
println!(
"[{}] ## get_data({}) will complete in {} ms",
START_TIME.elapsed().as_millis(),
i,
millis
);
sleep(Duration::from_millis(millis)).await;
println!(
"[{}] ## get_data({}) completed",
START_TIME.elapsed().as_millis(),
i
);
Data(i)
}
| {
if is_valid {
self.valid.fetch_add(1, Ordering::SeqCst);
} else {
self.expired.fetch_add(1, Ordering::SeqCst);
}
} |
links.go | package customerinsights
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"net/http"
)
// LinksClient is the the Azure Customer Insights management API provides a RESTful set of web services that interact
// with Azure Customer Insights service to manage your resources. The API has entities that capture the relationship
// between an end user and the Azure Customer Insights service.
type LinksClient struct {
BaseClient
}
// NewLinksClient creates an instance of the LinksClient client.
func NewLinksClient(subscriptionID string) LinksClient {
return NewLinksClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewLinksClientWithBaseURI creates an instance of the LinksClient client.
func | (baseURI string, subscriptionID string) LinksClient {
return LinksClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// CreateOrUpdate creates a link or updates an existing link in the hub.
// Parameters:
// resourceGroupName - the name of the resource group.
// hubName - the name of the hub.
// linkName - the name of the link.
// parameters - parameters supplied to the CreateOrUpdate Link operation.
func (client LinksClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, hubName string, linkName string, parameters LinkResourceFormat) (result LinksCreateOrUpdateFuture, err error) {
if err := validation.Validate([]validation.Validation{
{TargetValue: linkName,
Constraints: []validation.Constraint{{Target: "linkName", Name: validation.MaxLength, Rule: 512, Chain: nil},
{Target: "linkName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "linkName", Name: validation.Pattern, Rule: `^[a-zA-Z][a-zA-Z0-9_]+$`, Chain: nil}}},
{TargetValue: parameters,
Constraints: []validation.Constraint{{Target: "parameters.LinkDefinition", Name: validation.Null, Rule: false,
Chain: []validation.Constraint{{Target: "parameters.LinkDefinition.SourceEntityTypeName", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.LinkDefinition.TargetEntityTypeName", Name: validation.Null, Rule: true, Chain: nil},
{Target: "parameters.LinkDefinition.ParticipantPropertyReferences", Name: validation.Null, Rule: true, Chain: nil},
}}}}}); err != nil {
return result, validation.NewError("customerinsights.LinksClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, hubName, linkName, parameters)
if err != nil {
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
result, err = client.CreateOrUpdateSender(req)
if err != nil {
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "CreateOrUpdate", result.Response(), "Failure sending request")
return
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client LinksClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, hubName string, linkName string, parameters LinkResourceFormat) (*http.Request, error) {
pathParameters := map[string]interface{}{
"hubName": autorest.Encode("path", hubName),
"linkName": autorest.Encode("path", linkName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-26"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/links/{linkName}", pathParameters),
autorest.WithJSON(parameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client LinksClient) CreateOrUpdateSender(req *http.Request) (future LinksCreateOrUpdateFuture, err error) {
sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client))
future.Future = azure.NewFuture(req)
future.req = req
_, err = future.Done(sender)
if err != nil {
return
}
err = autorest.Respond(future.Response(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted))
return
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client LinksClient) CreateOrUpdateResponder(resp *http.Response) (result LinkResourceFormat, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete deletes a link in the hub.
// Parameters:
// resourceGroupName - the name of the resource group.
// hubName - the name of the hub.
// linkName - the name of the link.
func (client LinksClient) Delete(ctx context.Context, resourceGroupName string, hubName string, linkName string) (result autorest.Response, err error) {
req, err := client.DeletePreparer(ctx, resourceGroupName, hubName, linkName)
if err != nil {
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client LinksClient) DeletePreparer(ctx context.Context, resourceGroupName string, hubName string, linkName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"hubName": autorest.Encode("path", hubName),
"linkName": autorest.Encode("path", linkName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-26"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/links/{linkName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client LinksClient) DeleteSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client LinksClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted),
autorest.ByClosing())
result.Response = resp
return
}
// Get gets a link in the hub.
// Parameters:
// resourceGroupName - the name of the resource group.
// hubName - the name of the hub.
// linkName - the name of the link.
func (client LinksClient) Get(ctx context.Context, resourceGroupName string, hubName string, linkName string) (result LinkResourceFormat, err error) {
req, err := client.GetPreparer(ctx, resourceGroupName, hubName, linkName)
if err != nil {
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client LinksClient) GetPreparer(ctx context.Context, resourceGroupName string, hubName string, linkName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"hubName": autorest.Encode("path", hubName),
"linkName": autorest.Encode("path", linkName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-26"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/links/{linkName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client LinksClient) GetSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client LinksClient) GetResponder(resp *http.Response) (result LinkResourceFormat, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByHub gets all the links in the specified hub.
// Parameters:
// resourceGroupName - the name of the resource group.
// hubName - the name of the hub.
func (client LinksClient) ListByHub(ctx context.Context, resourceGroupName string, hubName string) (result LinkListResultPage, err error) {
result.fn = client.listByHubNextResults
req, err := client.ListByHubPreparer(ctx, resourceGroupName, hubName)
if err != nil {
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "ListByHub", nil, "Failure preparing request")
return
}
resp, err := client.ListByHubSender(req)
if err != nil {
result.llr.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "ListByHub", resp, "Failure sending request")
return
}
result.llr, err = client.ListByHubResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "ListByHub", resp, "Failure responding to request")
}
return
}
// ListByHubPreparer prepares the ListByHub request.
func (client LinksClient) ListByHubPreparer(ctx context.Context, resourceGroupName string, hubName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"hubName": autorest.Encode("path", hubName),
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-26"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/links", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByHubSender sends the ListByHub request. The method will close the
// http.Response Body if it receives an error.
func (client LinksClient) ListByHubSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByHubResponder handles the response to the ListByHub request. The method always
// closes the http.Response Body.
func (client LinksClient) ListByHubResponder(resp *http.Response) (result LinkListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByHubNextResults retrieves the next set of results, if any.
func (client LinksClient) listByHubNextResults(lastResults LinkListResult) (result LinkListResult, err error) {
req, err := lastResults.linkListResultPreparer()
if err != nil {
return result, autorest.NewErrorWithError(err, "customerinsights.LinksClient", "listByHubNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByHubSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "customerinsights.LinksClient", "listByHubNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByHubResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "customerinsights.LinksClient", "listByHubNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByHubComplete enumerates all values, automatically crossing page boundaries as required.
func (client LinksClient) ListByHubComplete(ctx context.Context, resourceGroupName string, hubName string) (result LinkListResultIterator, err error) {
result.page, err = client.ListByHub(ctx, resourceGroupName, hubName)
return
}
| NewLinksClientWithBaseURI |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.