file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
partition.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This module defines the partition data structure used for tracking equality among nonces.
use crate::nonce::Nonce;
use mirai_annotations::checked_verify;
use std::{
collections::{BTreeMap, BTreeSet},
usize::MAX,
};
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Partition {
nonce_to_id: BTreeMap<Nonce, usize>,
id_to_nonce_set: BTreeMap<usize, BTreeSet<Nonce>>,
}
impl Partition {
// adds a nonce to the partition; new_nonce must be a fresh nonce
pub fn add_nonce(&mut self, new_nonce: Nonce) {
let nonce_const = new_nonce.inner();
self.nonce_to_id.insert(new_nonce.clone(), nonce_const);
let mut singleton_set = BTreeSet::new();
singleton_set.insert(new_nonce);
self.id_to_nonce_set.insert(nonce_const, singleton_set);
}
// removes a nonce that already exists in the partition
pub fn remove_nonce(&mut self, nonce: Nonce) {
let id = self.nonce_to_id.remove(&nonce).unwrap();
self.id_to_nonce_set.entry(id).and_modify(|x| {
x.remove(&nonce);
});
if self.id_to_nonce_set[&id].is_empty() {
self.id_to_nonce_set.remove(&id).unwrap();
}
}
// adds an equality between nonce1 and nonce2
pub fn add_equality(&mut self, nonce1: Nonce, nonce2: Nonce) {
let id1 = self.nonce_to_id[&nonce1];
let id2 = self.nonce_to_id[&nonce2];
if id1 == id2 {
return;
}
let mut nonce_set2 = self.id_to_nonce_set.remove(&id2).unwrap();
for nonce in &nonce_set2 {
self.nonce_to_id
.entry(nonce.clone())
.and_modify(|x| *x = id1);
}
self.id_to_nonce_set.entry(id1).and_modify(|x| {
x.append(&mut nonce_set2);
});
}
// checks if nonce1 and nonce2 are known to be equal
pub fn is_equal(&self, nonce1: Nonce, nonce2: Nonce) -> bool {
self.nonce_to_id[&nonce1] == self.nonce_to_id[&nonce2]
}
// returns a canonical version of self in which an id of a set is determined
// to be the least element of the set.
// the choice of returned id is arbitrary but it must be a function on nonce sets.
pub fn construct_canonical_partition(self, nonce_map: &BTreeMap<Nonce, Nonce>) -> Self {
let mut id_to_nonce_set = BTreeMap::new();
for nonce_set in self.id_to_nonce_set.values() {
let canonical_nonce_set: BTreeSet<Nonce> = nonce_set
.iter()
.map(|nonce| nonce_map[nonce].clone())
.collect();
let canonical_id = Self::canonical_id(&canonical_nonce_set);
id_to_nonce_set.insert(canonical_id, canonical_nonce_set);
}
let nonce_to_id = Self::compute_nonce_to_id(&id_to_nonce_set);
Self {
nonce_to_id,
id_to_nonce_set,
}
}
pub fn nonces(&self) -> BTreeSet<Nonce> {
self.nonce_to_id.keys().cloned().collect()
}
// both self and partition must be canonical and over the same set of nonces
pub fn join(&self, partition: &Partition) -> Self {
checked_verify!(self.nonces() == partition.nonces());
// The join algorithm exploits the property that both self and partition are partitions over
// the same set of nonces. The algorithm does partition refinement by constructing
// for each nonce the intersection of the two sets containing it in self and partition.
// In the resulting partition, the nonce is mapped to this intersection set.
let mut nonce_to_id_pair = BTreeMap::new();
let mut id_pair_to_nonce_set = BTreeMap::new();
for (nonce, id) in self.nonce_to_id.iter() {
let id_pair = (id, partition.nonce_to_id[nonce]);
nonce_to_id_pair.insert(nonce.clone(), id_pair);
id_pair_to_nonce_set.entry(id_pair).or_insert({
let nonce_set_for_id_pair: BTreeSet<Nonce> = self.id_to_nonce_set[&id_pair.0]
.intersection(&partition.id_to_nonce_set[&id_pair.1])
.cloned()
.collect();
nonce_set_for_id_pair
});
}
let id_to_nonce_set: BTreeMap<usize, BTreeSet<Nonce>> = id_pair_to_nonce_set
.into_iter()
.map(|(_, nonce_set)| (Self::canonical_id(&nonce_set), nonce_set))
.collect();
let nonce_to_id = Self::compute_nonce_to_id(&id_to_nonce_set);
Self {
nonce_to_id,
id_to_nonce_set,
}
}
fn canonical_id(nonce_set: &BTreeSet<Nonce>) -> usize {
let mut minimum_id = MAX;
for nonce in nonce_set {
let id = nonce.inner();
if minimum_id > id {
minimum_id = id;
}
}
minimum_id
}
fn compute_nonce_to_id(
id_to_nonce_set: &BTreeMap<usize, BTreeSet<Nonce>>,
) -> BTreeMap<Nonce, usize> |
}
| {
let mut nonce_to_id = BTreeMap::new();
for (id, nonce_set) in id_to_nonce_set.iter() {
for nonce in nonce_set {
nonce_to_id.insert(nonce.clone(), id.clone());
}
}
nonce_to_id
} |
shm_streams.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Provides an implementation of the audio_streams::shm_streams::ShmStream trait using the VioS
//! client.
//! Given that the VioS server doesn't emit an event when the next buffer is expected, this
//! implementation uses thread::sleep to drive the frame timings.
use super::shm_vios::{VioSClient, VioSStreamParams};
use crate::virtio::snd::constants::*;
use audio_streams::shm_streams::{BufferSet, ServerRequest, ShmStream, ShmStreamSource};
use audio_streams::{BoxError, SampleFormat, StreamDirection, StreamEffect};
use base::{error, SharedMemory, SharedMemoryUnix};
use std::fs::File;
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use std::path::Path;
use std::sync::Arc;
use std::time::{Duration, Instant};
use sys_util::{Error as SysError, SharedMemory as SysSharedMemory};
use super::shm_vios::{Error, Result};
// This is the error type used in audio_streams::shm_streams. Unfortunately, it's not declared
// public there so it needs to be re-declared here. It also prevents the usage of anyhow::Error.
type GenericResult<T> = std::result::Result<T, BoxError>;
/// Adapter that provides the ShmStreamSource trait around the VioS backend.
pub struct VioSShmStreamSource {
vios_client: Arc<VioSClient>,
}
impl VioSShmStreamSource {
/// Creates a new stream source given the path to the audio server's socket.
pub fn new<P: AsRef<Path>>(server: P) -> Result<VioSShmStreamSource> {
Ok(Self {
vios_client: Arc::new(VioSClient::try_new(server)?),
})
}
}
fn from_sample_format(format: SampleFormat) -> u8 {
match format {
SampleFormat::U8 => VIRTIO_SND_PCM_FMT_U8,
SampleFormat::S16LE => VIRTIO_SND_PCM_FMT_U16,
SampleFormat::S24LE => VIRTIO_SND_PCM_FMT_U24,
SampleFormat::S32LE => VIRTIO_SND_PCM_FMT_U32,
}
}
fn virtio_frame_rate(frame_rate: u32) -> GenericResult<u8> {
Ok(match frame_rate {
5512u32 => VIRTIO_SND_PCM_RATE_5512,
8000u32 => VIRTIO_SND_PCM_RATE_8000,
11025u32 => VIRTIO_SND_PCM_RATE_11025,
16000u32 => VIRTIO_SND_PCM_RATE_16000,
22050u32 => VIRTIO_SND_PCM_RATE_22050,
32000u32 => VIRTIO_SND_PCM_RATE_32000,
44100u32 => VIRTIO_SND_PCM_RATE_44100,
48000u32 => VIRTIO_SND_PCM_RATE_48000,
64000u32 => VIRTIO_SND_PCM_RATE_64000,
88200u32 => VIRTIO_SND_PCM_RATE_88200,
96000u32 => VIRTIO_SND_PCM_RATE_96000,
176400u32 => VIRTIO_SND_PCM_RATE_176400,
192000u32 => VIRTIO_SND_PCM_RATE_192000,
384000u32 => VIRTIO_SND_PCM_RATE_384000,
_ => {
return Err(Box::new(Error::UnsupportedFrameRate(frame_rate)));
}
})
}
impl VioSShmStreamSource {
fn new_stream_inner(
&mut self,
stream_id: u32,
direction: StreamDirection,
num_channels: usize,
format: SampleFormat,
frame_rate: u32,
buffer_size: usize,
_effects: &[StreamEffect],
client_shm: &SysSharedMemory,
_buffer_offsets: [u64; 2],
) -> GenericResult<Box<dyn ShmStream>> {
let frame_size = num_channels * format.sample_bytes();
let period_bytes = (frame_size * buffer_size) as u32;
self.vios_client.prepare_stream(stream_id)?;
let params = VioSStreamParams {
buffer_bytes: 2 * period_bytes,
period_bytes,
features: 0u32,
channels: num_channels as u8,
format: from_sample_format(format),
rate: virtio_frame_rate(frame_rate)?,
};
self.vios_client.set_stream_parameters(stream_id, params)?;
self.vios_client.start_stream(stream_id)?;
VioSndShmStream::new(
buffer_size,
num_channels,
format,
frame_rate,
stream_id,
direction,
self.vios_client.clone(),
client_shm,
)
}
}
impl ShmStreamSource for VioSShmStreamSource {
/// Creates a new stream
#[allow(clippy::too_many_arguments)]
fn new_stream(
&mut self,
direction: StreamDirection,
num_channels: usize,
format: SampleFormat,
frame_rate: u32,
buffer_size: usize,
effects: &[StreamEffect],
client_shm: &SysSharedMemory,
buffer_offsets: [u64; 2],
) -> GenericResult<Box<dyn ShmStream>> {
self.vios_client.ensure_bg_thread_started()?;
let virtio_dir = match direction {
StreamDirection::Playback => VIRTIO_SND_D_OUTPUT,
StreamDirection::Capture => VIRTIO_SND_D_INPUT,
};
let stream_id = self
.vios_client
.get_unused_stream_id(virtio_dir)
.ok_or(Box::new(Error::NoStreamsAvailable))?;
self.new_stream_inner(
stream_id,
direction,
num_channels,
format,
frame_rate,
buffer_size,
effects,
client_shm,
buffer_offsets,
)
.map_err(|e| {
// Attempt to release the stream so that it can be used later. This is a best effort
// attempt, so we ignore any error it may return.
let _ = self.vios_client.release_stream(stream_id);
e
})
}
/// Get a list of file descriptors used by the implementation.
///
/// Returns any open file descriptors needed by the implementation.
/// This list helps users of the ShmStreamSource enter Linux jails without
/// closing needed file descriptors.
fn keep_fds(&self) -> Vec<RawFd> {
self.vios_client.keep_fds()
}
}
/// Adapter around a VioS stream that implements the ShmStream trait.
pub struct VioSndShmStream {
num_channels: usize,
frame_rate: u32,
buffer_size: usize,
frame_size: usize,
interval: Duration,
next_frame: Duration,
start_time: Instant,
stream_id: u32,
direction: StreamDirection,
vios_client: Arc<VioSClient>,
client_shm: SharedMemory,
}
impl VioSndShmStream {
/// Creates a new shm stream.
fn | (
buffer_size: usize,
num_channels: usize,
format: SampleFormat,
frame_rate: u32,
stream_id: u32,
direction: StreamDirection,
vios_client: Arc<VioSClient>,
client_shm: &SysSharedMemory,
) -> GenericResult<Box<dyn ShmStream>> {
let interval = Duration::from_millis(buffer_size as u64 * 1000 / frame_rate as u64);
let dup_fd = unsafe {
// Safe because fcntl doesn't affect memory and client_shm should wrap a known valid
// file descriptor.
libc::fcntl(client_shm.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 0)
};
if dup_fd < 0 {
return Err(Box::new(Error::DupError(SysError::last())));
}
let file = unsafe {
// safe because we checked the result of libc::fcntl()
File::from_raw_fd(dup_fd)
};
let client_shm_clone = SharedMemory::from_file(file).map_err(Error::BaseMmapError)?;
Ok(Box::new(Self {
num_channels,
frame_rate,
buffer_size,
frame_size: format.sample_bytes() * num_channels,
interval,
next_frame: interval,
start_time: Instant::now(),
stream_id,
direction,
vios_client,
client_shm: client_shm_clone,
}))
}
}
impl ShmStream for VioSndShmStream {
fn frame_size(&self) -> usize {
self.frame_size
}
fn num_channels(&self) -> usize {
self.num_channels
}
fn frame_rate(&self) -> u32 {
self.frame_rate
}
/// Waits until the next time a frame should be sent to the server. The server may release the
/// previous buffer much sooner than it needs the next one, so this function may sleep to wait
/// for the right time.
fn wait_for_next_action_with_timeout(
&mut self,
timeout: Duration,
) -> GenericResult<Option<ServerRequest>> {
let elapsed = self.start_time.elapsed();
if elapsed < self.next_frame {
if timeout < self.next_frame - elapsed {
std::thread::sleep(timeout);
return Ok(None);
} else {
std::thread::sleep(self.next_frame - elapsed);
}
}
self.next_frame += self.interval;
Ok(Some(ServerRequest::new(self.buffer_size, self)))
}
}
impl BufferSet for VioSndShmStream {
fn callback(&mut self, offset: usize, frames: usize) -> GenericResult<()> {
match self.direction {
StreamDirection::Playback => {
self.vios_client.inject_audio_data(
self.stream_id,
&mut self.client_shm,
offset,
frames * self.frame_size,
)?;
}
StreamDirection::Capture => {
self.vios_client.request_audio_data(
self.stream_id,
&mut self.client_shm,
offset,
frames * self.frame_size,
)?;
}
}
Ok(())
}
fn ignore(&mut self) -> GenericResult<()> {
Ok(())
}
}
impl Drop for VioSndShmStream {
fn drop(&mut self) {
let stream_id = self.stream_id;
if let Err(e) = self
.vios_client
.stop_stream(stream_id)
.and_then(|_| self.vios_client.release_stream(stream_id))
{
error!("Failed to stop and release stream {}: {}", stream_id, e);
}
}
}
| new |
volume_language_attributes.py | from netapp.netapp_object import NetAppObject
class VolumeLanguageAttributes(NetAppObject):
"""
Information about the volume language settings.
"""
_language_code = None
@property
def language_code(self):
"""
The volume's language code (e.g. 'en_US').
<p>
Volume language can be specified using 'language-code'
parameter.
<p>
Attributes: optional-for-create, non-modifiable
"""
return self._language_code
@language_code.setter
def language_code(self, val):
if val != None:
self.validate('language_code', val)
self._language_code = val
_nfs_character_set = None
@property
def nfs_character_set(self):
"""
The NFS language mapping character set that is currently
in effect for the volume.
<p>
This field is of the following format:
<ul>
<li>
'<nfs-character-set>|<display-name>|<asctime>'
</ul>
Note that '|' is not an OR syntax.
<p>
<asctime> is the timestamp in the language
configuration file header and its format is based on the
standard: 'A la ISO/IEC 9945-1, ANSI/IEEE Std 1003.1,
Second Edition, 1996-07-12.'
<p>
It uses the C Programming Language Printf format:
<p>
<ul>
<li> '%.3s %.3s%3d %02d:%02d:%02d %s %d'
</ul>
<p>
This format takes the following parameters in order:
<ul>
<li> <weekday name>,
<li> <month name>,
<li> <month day>,
<li> <hour>,
<li> <minute>,
<li> <second>
<li> <timezone> OR <''>,
<li> <year>
</ul>
<p>
E.g., If the volume language code is set to 'en_US,' the
default NFS character set is as follows:
<ul>
<li> 'iso-8859-1|iso-8859-1|Thu Oct 1 15:00:53 PDT
1998'
</ul>
<p>
Attributes: non-creatable, non-modifiable
"""
return self._nfs_character_set
@nfs_character_set.setter
def nfs_character_set(self, val):
if val != None:
self.validate('nfs_character_set', val)
self._nfs_character_set = val
_language = None
@property
def | (self):
"""
The volume's fully-qualified language mapping, in the
form: 'LanguageCode (Full Name).'
<p>
Example: 'en_US (English (US)).'
<p>
Attributes: non-creatable, non-modifiable
"""
return self._language
@language.setter
def language(self, val):
if val != None:
self.validate('language', val)
self._language = val
_is_convert_ucode_enabled = None
@property
def is_convert_ucode_enabled(self):
"""
This field controls whether all directories in this
volume are forcibly converted to UNICODE format when
accessed from both NFS and CIFS. The default value for
7-Mode volumes is false, in which case access from CIFS
causes conversion of pre-4.0 and 4.0-format directories,
and access from NFS causes conversion to 4.0-format
directories. The default value for Cluster-Mode volumes
is true.
<p>
Note that this field can be set to false if and only if
the volume is a 7-Mode volume, or a Cluster-Mode volume
that was transitioned from 7-Mode.
<p>
Attributes: non-creatable, modifiable
"""
return self._is_convert_ucode_enabled
@is_convert_ucode_enabled.setter
def is_convert_ucode_enabled(self, val):
if val != None:
self.validate('is_convert_ucode_enabled', val)
self._is_convert_ucode_enabled = val
_oem_character_set = None
@property
def oem_character_set(self):
"""
The OEM language mapping character set that is currently
in effect for the volume.
<p>
This field is of the following format:
<ul>
<li>
'<oem-code-page>|<display-name>|<asctime>'
</ul>
Note that '|' is not an OR syntax.
<p>
<asctime> is the timestamp in the language
configuration file header and its format is based on the
standard: 'A la ISO/IEC 9945-1, ANSI/IEEE Std 1003.1,
Second Edition, 1996-07-12.'
<p>
It uses the C Programming Language Printf format:
<ul>
<li> '%.3s %.3s%3d %02d:%02d:%02d %s %d'
</ul>
<p>
This format takes the following parameters in order:
<ul>
<li> <weekday name>,
<li> <month name>,
<li> <month day>,
<li> <hour>,
<li> <minute>,
<li> <second>,
<li> <timezone> OR <''>,
<li> <year>
</ul>
<p>
E.g., If the volume language code is set to 'en_US,' the
default OEM character set is as follows:
<ul>
<li> 'cp437|cp437|Thu Oct 1 15:00:53 PDT 1998'
</ul>
<p>
Attributes: non-creatable, non-modifiable
"""
return self._oem_character_set
@oem_character_set.setter
def oem_character_set(self, val):
if val != None:
self.validate('oem_character_set', val)
self._oem_character_set = val
_is_create_ucode_enabled = None
@property
def is_create_ucode_enabled(self):
"""
This field controls whether all directories in this
volume are forced to use the UNICODE format when they are
created, both from NFS and CIFS. The default value is
false for 7-Mode volumes, in which case all directories
are created in pre-4.0 format and only converted to
UNICODE format upon the first CIFS access. The default
value is true for Cluster-Mode volumes.
<p>
Note that this field can be set to false if and only if
the volume is a 7-Mode volume.
<p>
Attributes: non-creatable, non-modifiable
"""
return self._is_create_ucode_enabled
@is_create_ucode_enabled.setter
def is_create_ucode_enabled(self, val):
if val != None:
self.validate('is_create_ucode_enabled', val)
self._is_create_ucode_enabled = val
@staticmethod
def get_api_name():
return "volume-language-attributes"
@staticmethod
def get_desired_attrs():
return [
'language-code',
'nfs-character-set',
'language',
'is-convert-ucode-enabled',
'oem-character-set',
'is-create-ucode-enabled',
]
def describe_properties(self):
return {
'language_code': { 'class': basestring, 'is_list': False, 'required': 'optional' },
'nfs_character_set': { 'class': basestring, 'is_list': False, 'required': 'optional' },
'language': { 'class': basestring, 'is_list': False, 'required': 'optional' },
'is_convert_ucode_enabled': { 'class': bool, 'is_list': False, 'required': 'optional' },
'oem_character_set': { 'class': basestring, 'is_list': False, 'required': 'optional' },
'is_create_ucode_enabled': { 'class': bool, 'is_list': False, 'required': 'optional' },
}
| language |
replica_proposal_quota.go | // Copyright 2019 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package storage
import (
"bytes"
"context"
"time"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/quotapool"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"go.etcd.io/etcd/raft"
"go.etcd.io/etcd/raft/tracker"
)
// MaxQuotaReplicaLivenessDuration is the maximum duration that a replica
// can remain inactive while still being counting against the range's
// available proposal quota.
const MaxQuotaReplicaLivenessDuration = 10 * time.Second
func (r *Replica) maybeAcquireProposalQuota(
ctx context.Context, quota uint64,
) (*quotapool.IntAlloc, error) {
r.mu.RLock()
quotaPool := r.mu.proposalQuota
desc := *r.mu.state.Desc
r.mu.RUnlock()
// Quota acquisition only takes place on the leader replica,
// r.mu.proposalQuota is set to nil if a node is a follower (see
// updateProposalQuotaRaftMuLocked). For the cases where the range lease
// holder is not the same as the range leader, i.e. the lease holder is a
// follower, r.mu.proposalQuota == nil. This means all quota acquisitions
// go through without any throttling whatsoever but given how short lived
// these scenarios are we don't try to remedy any further.
//
// NB: It is necessary to allow proposals with a nil quota pool to go
// through, for otherwise a follower could never request the lease.
if quotaPool == nil {
return nil, nil
}
if !quotaPoolEnabledForRange(desc) {
return nil, nil
}
// Trace if we're running low on available proposal quota; it might explain
// why we're taking so long.
if log.HasSpanOrEvent(ctx) {
if q := quotaPool.ApproximateQuota(); q < quotaPool.Capacity()/10 {
log.Eventf(ctx, "quota running low, currently available ~%d", q)
}
}
alloc, err := quotaPool.Acquire(ctx, quota)
// Let quotapool errors due to being closed pass through.
if _, isClosed := err.(*quotapool.ErrClosed); isClosed {
err = nil
}
return alloc, err
}
func | (desc roachpb.RangeDescriptor) bool {
// The NodeLiveness range does not use a quota pool. We don't want to
// throttle updates to the NodeLiveness range even if a follower is falling
// behind because this could result in cascading failures.
return !bytes.HasPrefix(desc.StartKey, keys.NodeLivenessPrefix)
}
func (r *Replica) updateProposalQuotaRaftMuLocked(
ctx context.Context, lastLeaderID roachpb.ReplicaID,
) {
r.mu.Lock()
defer r.mu.Unlock()
if r.mu.replicaID == 0 {
// The replica was created from preemptive snapshot and has not been
// added to the Raft group.
return
}
// We need to check if the replica is being destroyed and if so, unblock
// all ongoing and subsequent quota acquisition goroutines (if any).
//
// TODO(irfansharif): There is still a potential problem here that leaves
// clients hanging if the replica gets destroyed but this code path is
// never taken. Moving quota pool draining to every point where a
// replica can get destroyed is an option, alternatively we can clear
// our leader status and close the proposalQuota whenever the replica is
// destroyed.
if r.mu.destroyStatus.Removed() {
if r.mu.proposalQuota != nil {
r.mu.proposalQuota.Close("destroyed")
}
r.mu.proposalQuota = nil
r.mu.lastUpdateTimes = nil
r.mu.quotaReleaseQueue = nil
return
}
status := r.mu.internalRaftGroup.BasicStatus()
if r.mu.leaderID != lastLeaderID {
if r.mu.replicaID == r.mu.leaderID {
// We're becoming the leader.
// Initialize the proposalQuotaBaseIndex at the applied index.
// After the proposal quota is enabled all entries applied by this replica
// will be appended to the quotaReleaseQueue. The proposalQuotaBaseIndex
// and the quotaReleaseQueue together track status.Applied exactly.
r.mu.proposalQuotaBaseIndex = status.Applied
if r.mu.proposalQuota != nil {
log.Fatal(ctx, "proposalQuota was not nil before becoming the leader")
}
if releaseQueueLen := len(r.mu.quotaReleaseQueue); releaseQueueLen != 0 {
log.Fatalf(ctx, "len(r.mu.quotaReleaseQueue) = %d, expected 0", releaseQueueLen)
}
// Raft may propose commands itself (specifically the empty
// commands when leadership changes), and these commands don't go
// through the code paths where we acquire quota from the pool. To
// offset this we reset the quota pool whenever leadership changes
// hands.
r.mu.proposalQuota = quotapool.NewIntPool(r.rangeStr.String(), uint64(r.store.cfg.RaftProposalQuota))
r.mu.lastUpdateTimes = make(map[roachpb.ReplicaID]time.Time)
r.mu.lastUpdateTimes.updateOnBecomeLeader(r.mu.state.Desc.Replicas().All(), timeutil.Now())
} else if r.mu.proposalQuota != nil {
// We're becoming a follower.
// We unblock all ongoing and subsequent quota acquisition goroutines
// (if any) and release the quotaReleaseQueue so its allocs are pooled.
r.mu.proposalQuota.Close("leader change")
r.mu.proposalQuota.Release(r.mu.quotaReleaseQueue...)
r.mu.quotaReleaseQueue = nil
r.mu.proposalQuota = nil
r.mu.lastUpdateTimes = nil
}
return
} else if r.mu.proposalQuota == nil {
if r.mu.replicaID == r.mu.leaderID {
log.Fatal(ctx, "leader has uninitialized proposalQuota pool")
}
// We're a follower.
return
}
// We're still the leader.
// Find the minimum index that active followers have acknowledged.
now := timeutil.Now()
// commitIndex is used to determine whether a newly added replica has fully
// caught up.
commitIndex := status.Commit
// Initialize minIndex to the currently applied index. The below progress
// checks will only decrease the minIndex. Given that the quotaReleaseQueue
// cannot correspond to values beyond the applied index there's no reason
// to consider progress beyond it as meaningful.
minIndex := status.Applied
r.mu.internalRaftGroup.WithProgress(func(id uint64, _ raft.ProgressType, progress tracker.Progress) {
rep, ok := r.mu.state.Desc.GetReplicaDescriptorByID(roachpb.ReplicaID(id))
if !ok {
return
}
// Only consider followers that are active.
if !r.mu.lastUpdateTimes.isFollowerActive(ctx, rep.ReplicaID, now) {
return
}
// Only consider followers that that have "healthy" RPC connections.
if err := r.store.cfg.NodeDialer.ConnHealth(rep.NodeID); err != nil {
return
}
// Note that the Match field has different semantics depending on
// the State.
//
// In state ProgressStateReplicate, the Match index is optimistically
// updated whenever a message is *sent* (not received). Due to Raft
// flow control, only a reasonably small amount of data can be en
// route to a given follower at any point in time.
//
// In state ProgressStateProbe, the Match index equals Next-1, and
// it tells us the leader's optimistic best guess for the right log
// index (and will try once per heartbeat interval to update its
// estimate). In the usual case, the follower responds with a hint
// when it rejects the first probe and the leader replicates or
// sends a snapshot. In the case in which the follower does not
// respond, the leader reduces Match by one each heartbeat interval.
// But if the follower does not respond, we've already filtered it
// out above. We use the Match index as is, even though the follower
// likely isn't there yet because that index won't go up unless the
// follower is actually catching up, so it won't cause it to fall
// behind arbitrarily.
//
// Another interesting tidbit about this state is that the Paused
// field is usually true as it is used to limit the number of probes
// (i.e. appends) sent to this follower to one per heartbeat
// interval.
//
// In state ProgressStateSnapshot, the Match index is the last known
// (possibly optimistic, depending on previous state) index before
// the snapshot went out. Once the snapshot applies, the follower
// will enter ProgressStateReplicate again. So here the Match index
// works as advertised too.
// Only consider followers who are in advance of the quota base
// index. This prevents a follower from coming back online and
// preventing throughput to the range until it has caught up.
if progress.Match < r.mu.proposalQuotaBaseIndex {
return
}
if progress.Match > 0 && progress.Match < minIndex {
minIndex = progress.Match
}
// If this is the most recently added replica and it has caught up, clear
// our state that was tracking it. This is unrelated to managing proposal
// quota, but this is a convenient place to do so.
if rep.ReplicaID == r.mu.lastReplicaAdded && progress.Match >= commitIndex {
r.mu.lastReplicaAdded = 0
r.mu.lastReplicaAddedTime = time.Time{}
}
})
if r.mu.proposalQuotaBaseIndex < minIndex {
// We've persisted at least minIndex-r.mu.proposalQuotaBaseIndex entries
// to the raft log on all 'active' replicas and applied at least minIndex
// entries locally since last we checked, so we are able to release the
// difference back to the quota pool.
numReleases := minIndex - r.mu.proposalQuotaBaseIndex
// NB: Release deals with cases where allocs being released do not originate
// from this incarnation of quotaReleaseQueue, which can happen if a
// proposal acquires quota while this replica is the raft leader in some
// term and then commits while at a different term.
r.mu.proposalQuota.Release(r.mu.quotaReleaseQueue[:numReleases]...)
r.mu.quotaReleaseQueue = r.mu.quotaReleaseQueue[numReleases:]
r.mu.proposalQuotaBaseIndex += numReleases
}
// Assert the sanity of the base index and the queue. Queue entries should
// correspond to applied entries. It should not be possible for the base
// index and the not yet released applied entries to not equal the applied
// index.
releasableIndex := r.mu.proposalQuotaBaseIndex + uint64(len(r.mu.quotaReleaseQueue))
if releasableIndex != status.Applied {
log.Fatalf(ctx, "proposalQuotaBaseIndex (%d) + quotaReleaseQueueLen (%d) = %d"+
" must equal the applied index (%d)",
r.mu.proposalQuotaBaseIndex, len(r.mu.quotaReleaseQueue), releasableIndex,
status.Applied)
}
}
| quotaPoolEnabledForRange |
byted-grinning-face-with-squinting-eyes.ts | /**
* @format
* @file BytedGrinningFaceWithSquintingEyes byted-grinning-face-with-squinting-eyes
* @author 由 fe6 自动生成
*/
import { IIconProps, IconWrapper } from '../runtime';
// 获取 SVG 的 HTML 字符串
export const getIconBytedGrinningFaceWithSquintingEyesSvgHtml = (
props: IIconProps,
) => | `<?xml version="1.0" encoding="UTF-8"?>
<svg width="${props.size}" height="${props.size}" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="48" height="48" fill="white" fill-opacity="0.01"/>
<path d="M24 44C35.0457 44 44 35.0457 44 24C44 12.9543 35.0457 4 24 4C12.9543 4 4 12.9543 4 24C4 35.0457 12.9543 44 24 44Z" fill="${props.colors?.[1]}" stroke="${props.colors?.[0]}" stroke-width="${props.strokeWidth}" stroke-linejoin="${props.strokeLinejoin}"/>
<path d="M24 35C29 35 31 31 31 31H17C17 31 19 35 24 35Z" stroke="${props.colors?.[2]}" stroke-width="${props.strokeWidth}" stroke-linecap="${props.strokeLinecap}" stroke-linejoin="${props.strokeLinejoin}"/>
<path d="M21 21C21 21 20 17 17 17C14 17 13 21 13 21" stroke="${props.colors?.[2]}" stroke-width="${props.strokeWidth}" stroke-linecap="${props.strokeLinecap}" stroke-linejoin="${props.strokeLinejoin}"/>
<path d="M35 21C35 21 34 17 31 17C28 17 27 21 27 21" stroke="${props.colors?.[2]}" stroke-width="${props.strokeWidth}" stroke-linecap="${props.strokeLinecap}" stroke-linejoin="${props.strokeLinejoin}"/>
</svg>`;
// 默认导出组件
export default IconWrapper(
'byted-grinning-face-with-squinting-eyes',
false,
getIconBytedGrinningFaceWithSquintingEyesSvgHtml,
); | |
kirin.go | package kirin
import (
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"time"
"github.com/coreos/etcd/clientv3"
"github.com/lightninglabs/kirin/auth"
"github.com/lightninglabs/kirin/mint"
"github.com/lightninglabs/kirin/proxy"
"github.com/lightningnetwork/lnd/build"
"github.com/lightningnetwork/lnd/cert"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/tor"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/net/http2"
"golang.org/x/net/http2/h2c"
"gopkg.in/yaml.v2"
)
const (
// topLevelKey is the top level key for an etcd cluster where we'll
// store all LSAT proxy related data.
topLevelKey = "lsat/proxy"
// etcdKeyDelimeter is the delimeter we'll use for all etcd keys to
// represent a path-like structure.
etcdKeyDelimeter = "/"
)
// Main is the true entrypoint of Kirin.
func Main() {
// TODO: Prevent from running twice.
err := start()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
// start sets up the proxy server and runs it. This function blocks until a
// shutdown signal is received.
func start() error {
// First, parse configuration file and set up logging.
configFile := filepath.Join(kirinDataDir, defaultConfigFilename)
cfg, err := getConfig(configFile)
if err != nil {
return fmt.Errorf("unable to parse config file: %v", err)
}
err = setupLogging(cfg)
if err != nil {
return fmt.Errorf("unable to set up logging: %v", err)
}
// Initialize our etcd client.
etcdClient, err := clientv3.New(clientv3.Config{
Endpoints: []string{cfg.Etcd.Host},
DialTimeout: 5 * time.Second,
Username: cfg.Etcd.User,
Password: cfg.Etcd.Password,
})
if err != nil {
return fmt.Errorf("unable to connect to etcd: %v", err)
}
// Create the proxy and connect it to lnd.
genInvoiceReq := func() (*lnrpc.Invoice, error) {
return &lnrpc.Invoice{
Memo: "LSAT",
Value: 1,
}, nil
}
servicesProxy, err := createProxy(cfg, genInvoiceReq, etcdClient)
if err != nil {
return err
}
handler := http.HandlerFunc(servicesProxy.ServeHTTP)
httpsServer := &http.Server{
Addr: cfg.ListenAddr,
Handler: handler,
}
// Create TLS certificates.
var tlsKeyFile, tlsCertFile string
switch {
// When using autocert, we set a TLSConfig on the server so the key and
// cert file we pass in are ignored and don't need to exist.
case cfg.AutoCert:
serverName := cfg.ServerName
if serverName == "" {
return fmt.Errorf("servername option is required for " +
"secure operation")
}
certDir := filepath.Join(kirinDataDir, "autocert")
log.Infof("Configuring autocert for server %v with cache dir "+
"%v", serverName, certDir)
manager := autocert.Manager{
Cache: autocert.DirCache(certDir),
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(serverName),
}
go func() {
err := http.ListenAndServe(
":http", manager.HTTPHandler(nil),
)
if err != nil {
log.Errorf("autocert http: %v", err)
}
}()
httpsServer.TLSConfig = &tls.Config{
GetCertificate: manager.GetCertificate,
}
// If we're not using autocert, we want to create self-signed TLS certs
// and save them at the specified location (if they don't already
// exist).
default:
tlsKeyFile = filepath.Join(kirinDataDir, defaultTLSKeyFilename)
tlsCertFile = filepath.Join(kirinDataDir, defaultTLSCertFilename)
if !fileExists(tlsCertFile) && !fileExists(tlsKeyFile) {
log.Infof("Generating TLS certificates...")
err := cert.GenCertPair(
"kirin autogenerated cert", tlsCertFile,
tlsKeyFile, nil, nil,
cert.DefaultAutogenValidity,
)
if err != nil {
return err
}
log.Infof("Done generating TLS certificates")
}
}
// The ListenAndServeTLS below will block until shut down or an error
// occurs. So we can just defer a cleanup function here that will close
// everything on shutdown.
defer cleanup(etcdClient, httpsServer)
// Finally start the server.
log.Infof("Starting the server, listening on %s.", cfg.ListenAddr)
errChan := make(chan error)
go func() {
errChan <- httpsServer.ListenAndServeTLS(tlsCertFile, tlsKeyFile)
}()
// If we need to listen over Tor as well, we'll set up the onion
// services now. We're not able to use TLS for onion services since they
// can't be verified, so we'll spin up an additional HTTP/2 server
// _without_ TLS that is not exposed to the outside world. This server
// will only be reached through the onion services, which already
// provide encryption, so running this additional HTTP server should be
// relatively safe.
if cfg.Tor.V2 || cfg.Tor.V3 {
torController, err := initTorListener(cfg, etcdClient)
if err != nil {
return err
}
defer func() {
_ = torController.Stop()
}()
httpServer := &http.Server{
Addr: fmt.Sprintf("localhost:%d", cfg.Tor.ListenPort),
Handler: h2c.NewHandler(handler, &http2.Server{}),
}
go func() {
errChan <- httpServer.ListenAndServe()
}()
defer httpServer.Close()
}
return <-errChan
}
// fileExists reports whether the named file or directory exists.
// This function is taken from https://github.com/btcsuite/btcd
func fileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
// getConfig loads and parses the configuration file then checks it for valid
// content.
func | (configFile string) (*config, error) {
cfg := &config{}
b, err := ioutil.ReadFile(configFile)
if err != nil {
return nil, err
}
err = yaml.Unmarshal(b, cfg)
if err != nil {
return nil, err
}
// Then check the configuration that we got from the config file, all
// required values need to be set at this point.
if cfg.ListenAddr == "" {
return nil, fmt.Errorf("missing listen address for server")
}
return cfg, nil
}
// setupLogging parses the debug level and initializes the log file rotator.
func setupLogging(cfg *config) error {
if cfg.DebugLevel == "" {
cfg.DebugLevel = defaultLogLevel
}
// Now initialize the logger and set the log level.
logFile := filepath.Join(kirinDataDir, defaultLogFilename)
err := logWriter.InitLogRotator(
logFile, defaultMaxLogFileSize, defaultMaxLogFiles,
)
if err != nil {
return err
}
return build.ParseAndSetDebugLevels(cfg.DebugLevel, logWriter)
}
// initTorListener initiates a Tor controller instance with the Tor server
// specified in the config. Onion services will be created over which the proxy
// can be reached at.
func initTorListener(cfg *config, etcd *clientv3.Client) (*tor.Controller, error) {
// Establish a controller connection with the backing Tor server and
// proceed to create the requested onion services.
onionCfg := tor.AddOnionConfig{
VirtualPort: int(cfg.Tor.VirtualPort),
TargetPorts: []int{int(cfg.Tor.ListenPort)},
Store: newOnionStore(etcd),
}
torController := tor.NewController(cfg.Tor.Control, "", "")
if err := torController.Start(); err != nil {
return nil, err
}
if cfg.Tor.V2 {
onionCfg.Type = tor.V2
addr, err := torController.AddOnion(onionCfg)
if err != nil {
return nil, err
}
log.Infof("Listening over Tor on %v", addr)
}
if cfg.Tor.V3 {
onionCfg.Type = tor.V3
addr, err := torController.AddOnion(onionCfg)
if err != nil {
return nil, err
}
log.Infof("Listening over Tor on %v", addr)
}
return torController, nil
}
// createProxy creates the proxy with all the services it needs.
func createProxy(cfg *config, genInvoiceReq InvoiceRequestGenerator,
etcdClient *clientv3.Client) (*proxy.Proxy, error) {
challenger, err := NewLndChallenger(cfg.Authenticator, genInvoiceReq)
if err != nil {
return nil, err
}
minter := mint.New(&mint.Config{
Challenger: challenger,
Secrets: newSecretStore(etcdClient),
ServiceLimiter: newStaticServiceLimiter(cfg.Services),
})
authenticator := auth.NewLsatAuthenticator(minter)
return proxy.New(authenticator, cfg.Services, cfg.StaticRoot)
}
// cleanup closes the given server and shuts down the log rotator.
func cleanup(etcdClient io.Closer, server io.Closer) {
if err := etcdClient.Close(); err != nil {
log.Errorf("Error terminating etcd client: %v", err)
}
err := server.Close()
if err != nil {
log.Errorf("Error closing server: %v", err)
}
log.Info("Shutdown complete")
err = logWriter.Close()
if err != nil {
log.Errorf("Could not close log rotator: %v", err)
}
}
| getConfig |
ReScript.tsx | import React from "react"
import { Badge } from "../badge"
import type { BadgeProps } from "../badge" | const ReScript = (props: BadgeProps) => <Badge name="ReScript" {...props} backgroundColor="#E6484F" />
export default ReScript | |
main.go | // Copyright 2020 IBM Corp.
// SPDX-License-Identifier: Apache-2.0
package main
import (
"flag"
"os"
kapps "k8s.io/api/apps/v1"
kbatch "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/fields"
kruntime "k8s.io/apimachinery/pkg/runtime"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
motionv1 "fybrik.io/data-movement-controller/manager/apis/motion/v1alpha1"
"fybrik.io/data-movement-controller/manager/controllers"
"fybrik.io/data-movement-controller/manager/controllers/motion"
"fybrik.io/data-movement-controller/manager/controllers/utils"
"fybrik.io/data-movement-controller/pkg/environment"
)
const (
managerPort = 9443
listeningPort = 8085
)
var (
scheme = kruntime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
func init() {
_ = motionv1.AddToScheme(scheme)
_ = corev1.AddToScheme(scheme)
_ = kbatch.AddToScheme(scheme)
_ = kapps.AddToScheme(scheme)
}
func run(namespace, metricsAddr string, enableLeaderElection bool) int {
setupLog.Info("creating manager")
blueprintNamespace := utils.GetBlueprintNamespace()
systemNamespaceSelector := fields.SelectorFromSet(fields.Set{"metadata.namespace": utils.GetSystemNamespace()})
workerNamespaceSelector := fields.SelectorFromSet(fields.Set{"metadata.namespace": blueprintNamespace})
setupLog.Info("Watching BatchTransfers and StreamTransfers", "namespace", workerNamespaceSelector)
selectorsByObject := cache.SelectorsByObject{
&corev1.ConfigMap{}: {Field: systemNamespaceSelector},
&motionv1.BatchTransfer{}: {Field: workerNamespaceSelector},
&motionv1.StreamTransfer{}: {Field: workerNamespaceSelector},
&kbatch.Job{}: {Field: workerNamespaceSelector},
&kbatch.CronJob{}: {Field: workerNamespaceSelector},
&corev1.Secret{}: {Field: workerNamespaceSelector},
&corev1.Pod{}: {Field: workerNamespaceSelector},
&kapps.Deployment{}: {Field: workerNamespaceSelector},
&corev1.PersistentVolumeClaim{}: {Field: workerNamespaceSelector},
}
client := ctrl.GetConfigOrDie()
client.QPS = environment.GetEnvAsFloat32(controllers.KubernetesClientQPSConfiguration, controllers.DefaultKubernetesClientQPS)
client.Burst = environment.GetEnvAsInt(controllers.KubernetesClientBurstConfiguration, controllers.DefaultKubernetesClientBurst)
setupLog.Info("Manager client rate limits:", "qps", client.QPS, "burst", client.Burst)
mgr, err := ctrl.NewManager(client, ctrl.Options{
Scheme: scheme,
Namespace: namespace,
MetricsBindAddress: metricsAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "data-movement-operator-leader-election",
Port: managerPort,
NewCache: cache.BuilderWithOptions(cache.Options{SelectorsByObject: selectorsByObject}),
})
if err != nil {
setupLog.Error(err, "unable to start manager")
return 1
}
setupLog.Info("creating motion controllers")
if err := motion.SetupMotionControllers(mgr); err != nil {
setupLog.Error(err, "unable to setup motion controllers")
return 1
}
setupLog.Info("starting manager")
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil |
return 0
}
// Main entry point starts manager and controllers
func main() {
var namespace string
var metricsAddr string
var enableLeaderElection bool
address := utils.ListeningAddress(listeningPort)
flag.StringVar(&metricsAddr, "metrics-bind-addr", address, "The address the metric endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.")
flag.StringVar(&namespace, "namespace", "", "The namespace to which this controller manager is limited.")
flag.Parse()
ctrl.SetLogger(zap.New(zap.UseDevMode(true)))
os.Exit(run(namespace, metricsAddr, enableLeaderElection))
}
| {
setupLog.Error(err, "problem running manager")
return 1
} |
rand_test.go | // Copyright 2016 asana Author. 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.
package utils
import "testing"
func | (t *testing.T) {
bs0 := RandomCreateBytes(16)
bs1 := RandomCreateBytes(16)
t.Log(string(bs0), string(bs1))
if string(bs0) == string(bs1) {
t.FailNow()
}
bs0 = RandomCreateBytes(4, []byte(`a`)...)
if string(bs0) != "aaaa" {
t.FailNow()
}
}
| TestRand_01 |
list_key_detail_request.py | # coding: utf-8
import pprint
import re
import six
class ListKeyDetailRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'version_id': 'str',
'body': 'OperateKeyRequestBody'
}
attribute_map = {
'version_id': 'version_id',
'body': 'body'
}
def __init__(self, version_id=None, body=None):
"""ListKeyDetailRequest - a model defined in huaweicloud sdk"""
self._version_id = None
self._body = None
self.discriminator = None
self.version_id = version_id
if body is not None:
self.body = body
@property
def version_id(self):
"""Gets the version_id of this ListKeyDetailRequest.
:return: The version_id of this ListKeyDetailRequest.
:rtype: str
"""
return self._version_id
@version_id.setter
def version_id(self, version_id):
"""Sets the version_id of this ListKeyDetailRequest.
:param version_id: The version_id of this ListKeyDetailRequest.
:type: str
"""
self._version_id = version_id
@property
def body(self):
"""Gets the body of this ListKeyDetailRequest.
:return: The body of this ListKeyDetailRequest.
:rtype: OperateKeyRequestBody
"""
return self._body
@body.setter
def body(self, body):
"""Sets the body of this ListKeyDetailRequest.
:param body: The body of this ListKeyDetailRequest.
:type: OperateKeyRequestBody
"""
self._body = body
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str() |
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ListKeyDetailRequest):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | |
mod.rs | use serde::{Deserialize, Serialize};
mod loader;
mod publication_store;
mod waking_state;
pub use loader::MessageLoader; | /// Keys used in persistence.
/// Ordered by offset
#[derive(Hash, Eq, Ord, PartialOrd, PartialEq, Clone, Debug, Deserialize, Serialize, Copy)]
pub struct Key {
offset: u64,
}
#[derive(Debug, thiserror::Error)]
pub enum PersistError {
#[error("Attempted to remove entry which does not exist")]
RemovalForMissing,
} | pub use publication_store::PublicationStore;
pub use waking_state::{memory::WakingMemoryStore, StreamWakeableState};
|
f.py | """(Non-central) F distribution."""
import numpy
from scipy import special
from ..baseclass import Dist
from ..operators.addition import Add
class f(Dist):
"""F distribution."""
def __init__(self, dfn, dfd, nc):
Dist.__init__(self, dfn=dfn, dfd=dfd, nc=nc)
def _pdf(self, x, dfn, dfd, nc):
n1, n2 = dfn, dfd
term = -nc/2.+nc*n1*x/(2*(n2+n1*x)) + special.gammaln(n1/2.)+special.gammaln(1+n2/2.)
term -= special.gammaln((n1+n2)/2.)
Px = numpy.exp(term)
Px *= n1**(n1/2.) * n2**(n2/2.) * x**(n1/2.-1)
Px *= (n2+n1*x)**(-(n1+n2)/2.)
Px *= special.assoc_laguerre(-nc*n1*x/(2.*(n2+n1*x)), n2/2., n1/2.-1)
Px /= special.beta(n1/2., n2/2.)
return Px
def _cdf(self, x, dfn, dfd, nc):
return special.ncfdtr(dfn, dfd, nc, x)
def _ppf(self, q, dfn, dfd, nc):
return special.ncfdtri(dfn, dfd, nc, q)
def _bnd(self, x, dfn, dfd, nc):
return 0.0, self._ppf(1-1e-10, dfn, dfd, nc)
class F(Add):
"""
(Non-central) F or Fisher-Snedecor distribution.
Args:
n (float, Dist) : Degres of freedom for numerator
m (float, Dist) : Degres of freedom for denominator
scale (float, Dist) : Scaling parameter
shift (float, Dist) : Location parameter
nc (float, Dist) : Non-centrality parameter
Examples:
>>> distribution = chaospy.F(3, 3, 2, 1, 1)
>>> print(distribution)
F(m=3, n=3, nc=1, scale=2, shift=1)
>>> q = numpy.linspace(0, 1, 6)[1:-1] | >>> print(numpy.around(distribution.fwd(distribution.inv(q)), 4))
[0.2 0.4 0.6 0.8]
>>> print(numpy.around(distribution.pdf(distribution.inv(q)), 4))
[0.2277 0.1572 0.0837 0.027 ]
>>> print(numpy.around(distribution.sample(4), 4))
[ 5.4212 1.5739 25.7656 3.5586]
>>> print(distribution.mom(1) > 10**8) # undefined
True
"""
def __init__(self, n=1, m=1, scale=1, shift=0, nc=0):
self._repr = {"n": n, "m": m, "scale": scale, "shift": shift, "nc": nc}
Add.__init__(self, left=f(n, m, nc)*scale, right=shift) | >>> print(numpy.around(distribution.inv(q), 4))
[1.9336 2.9751 4.7028 8.8521] |
standard_information.rs | // Copyright 2021-2022 Colin Finck <[email protected]>
// SPDX-License-Identifier: MIT OR Apache-2.0
use binread::io::{Cursor, Read, Seek};
use binread::{BinRead, BinReaderExt};
use crate::attribute::NtfsAttributeType;
use crate::attribute_value::{NtfsAttributeValue, NtfsResidentAttributeValue};
use crate::error::{NtfsError, Result};
use crate::structured_values::{
NtfsFileAttributeFlags, NtfsStructuredValue, NtfsStructuredValueFromResidentAttributeValue,
};
use crate::time::NtfsTime;
use crate::types::NtfsPosition;
/// Size of all [`StandardInformationData`] fields plus some reserved bytes.
const STANDARD_INFORMATION_SIZE_NTFS1: usize = 48;
/// Size of all [`StandardInformationData`] plus [`StandardInformationDataNtfs3`] fields.
const STANDARD_INFORMATION_SIZE_NTFS3: usize = 72;
#[derive(BinRead, Clone, Debug)]
struct StandardInformationDataNtfs1 {
creation_time: NtfsTime,
modification_time: NtfsTime,
mft_record_modification_time: NtfsTime,
access_time: NtfsTime,
file_attributes: u32,
}
#[derive(BinRead, Clone, Debug)]
struct StandardInformationDataNtfs3 {
maximum_versions: u32,
version: u32,
class_id: u32,
owner_id: u32,
security_id: u32,
quota_charged: u64,
usn: u64,
}
/// Structure of a $STANDARD_INFORMATION attribute.
///
/// Among other things, this is the place where the file times and "File Attributes"
/// (Read-Only, Hidden, System, Archive, etc.) are stored.
///
/// A $STANDARD_INFORMATION attribute is always resident.
///
/// Reference: <https://flatcap.github.io/linux-ntfs/ntfs/attributes/standard_information.html>
#[derive(Clone, Debug)]
pub struct NtfsStandardInformation {
ntfs1_data: StandardInformationDataNtfs1,
ntfs3_data: Option<StandardInformationDataNtfs3>,
}
impl NtfsStandardInformation {
fn new<T>(r: &mut T, position: NtfsPosition, value_length: u64) -> Result<Self>
where
T: Read + Seek,
{
if value_length < STANDARD_INFORMATION_SIZE_NTFS1 as u64 {
return Err(NtfsError::InvalidStructuredValueSize {
position,
ty: NtfsAttributeType::StandardInformation,
expected: STANDARD_INFORMATION_SIZE_NTFS1 as u64,
actual: value_length,
});
}
let ntfs1_data = r.read_le::<StandardInformationDataNtfs1>()?;
let mut ntfs3_data = None;
if value_length >= STANDARD_INFORMATION_SIZE_NTFS3 as u64 {
ntfs3_data = Some(r.read_le::<StandardInformationDataNtfs3>()?);
}
Ok(Self {
ntfs1_data,
ntfs3_data,
})
}
/// Returns the time this file was last accessed.
pub fn access_time(&self) -> NtfsTime { | self.ntfs1_data.access_time
}
/// Returns the Class ID of the file, if stored via NTFS 3.x file information.
pub fn class_id(&self) -> Option<u32> {
self.ntfs3_data.as_ref().map(|x| x.class_id)
}
/// Returns the time this file was created.
pub fn creation_time(&self) -> NtfsTime {
self.ntfs1_data.creation_time
}
/// Returns flags that a user can set for a file (Read-Only, Hidden, System, Archive, etc.).
/// Commonly called "File Attributes" in Windows Explorer.
pub fn file_attributes(&self) -> NtfsFileAttributeFlags {
NtfsFileAttributeFlags::from_bits_truncate(self.ntfs1_data.file_attributes)
}
/// Returns the maximum allowed versions for this file, if stored via NTFS 3.x file information.
///
/// A value of zero means that versioning is disabled for this file.
pub fn maximum_versions(&self) -> Option<u32> {
self.ntfs3_data.as_ref().map(|x| x.maximum_versions)
}
/// Returns the time the MFT record of this file was last modified.
pub fn mft_record_modification_time(&self) -> NtfsTime {
self.ntfs1_data.mft_record_modification_time
}
/// Returns the time this file was last modified.
pub fn modification_time(&self) -> NtfsTime {
self.ntfs1_data.modification_time
}
/// Returns the Owner ID of the file, if stored via NTFS 3.x file information.
pub fn owner_id(&self) -> Option<u32> {
self.ntfs3_data.as_ref().map(|x| x.owner_id)
}
/// Returns the quota charged by this file, if stored via NTFS 3.x file information.
pub fn quota_charged(&self) -> Option<u64> {
self.ntfs3_data.as_ref().map(|x| x.quota_charged)
}
/// Returns the Security ID of the file, if stored via NTFS 3.x file information.
pub fn security_id(&self) -> Option<u32> {
self.ntfs3_data.as_ref().map(|x| x.security_id)
}
/// Returns the Update Sequence Number (USN) of the file, if stored via NTFS 3.x file information.
pub fn usn(&self) -> Option<u64> {
self.ntfs3_data.as_ref().map(|x| x.usn)
}
/// Returns the version of the file, if stored via NTFS 3.x file information.
///
/// This will be zero if versioning is disabled for this file.
pub fn version(&self) -> Option<u32> {
self.ntfs3_data.as_ref().map(|x| x.version)
}
}
impl<'n, 'f> NtfsStructuredValue<'n, 'f> for NtfsStandardInformation {
const TY: NtfsAttributeType = NtfsAttributeType::StandardInformation;
fn from_attribute_value<T>(fs: &mut T, value: NtfsAttributeValue<'n, 'f>) -> Result<Self>
where
T: Read + Seek,
{
let position = value.data_position();
let value_length = value.len();
let mut value_attached = value.attach(fs);
Self::new(&mut value_attached, position, value_length)
}
}
impl<'n, 'f> NtfsStructuredValueFromResidentAttributeValue<'n, 'f> for NtfsStandardInformation {
fn from_resident_attribute_value(value: NtfsResidentAttributeValue<'f>) -> Result<Self> {
let position = value.data_position();
let value_length = value.len();
let mut cursor = Cursor::new(value.data());
Self::new(&mut cursor, position, value_length)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::file::KnownNtfsFileRecordNumber;
use crate::ntfs::Ntfs;
#[test]
fn test_standard_information() {
let mut testfs1 = crate::helpers::tests::testfs1();
let ntfs = Ntfs::new(&mut testfs1).unwrap();
let mft = ntfs
.file(&mut testfs1, KnownNtfsFileRecordNumber::MFT as u64)
.unwrap();
let mut mft_attributes = mft.attributes_raw();
// Check the StandardInformation attribute of the MFT.
let attribute = mft_attributes.nth(0).unwrap();
assert_eq!(
attribute.ty().unwrap(),
NtfsAttributeType::StandardInformation,
);
assert_eq!(attribute.attribute_length(), 96);
assert!(attribute.is_resident());
assert_eq!(attribute.name_length(), 0);
assert_eq!(attribute.value_length(), 72);
// Try to read the actual information.
let _standard_info = attribute
.resident_structured_value::<NtfsStandardInformation>()
.unwrap();
// There are no reliable values to check here, so that's it.
}
} | |
privado.go | package constants
import (
"net"
"github.com/rxtreme8/gluetun/internal/models"
)
//nolint:lll
const (
PrivadoCertificate = "MIIFKDCCAxCgAwIBAgIJAMtrmqZxIV/OMA0GCSqGSIb3DQEBDQUAMBIxEDAOBgNVBAMMB1ByaXZhZG8wHhcNMjAwMTA4MjEyODQ1WhcNMzUwMTA5MjEyODQ1WjASMRAwDgYDVQQDDAdQcml2YWRvMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAxPwOgiwNJzZTnKIXwAB0TSu/Lu2qt2U2I8obtQjwhi/7OrfmbmYykSdro70al2XPhnwAGGdCxW6LDnp0UN/IOhD11mgBPo14f5CLkBQjSJ6VN5miPbvK746LsNZl9H8rQGvDuPo4CG9BfPZMiDRGlsMxij/jztzgT1gmuxQ7WHfFRcNzBas1dHa9hV/d3TU6/t47x4SE/ljdcCtJiu7Zn6ODKQoys3mB7Luz2ngqUJWvkqsg+E4+3eJ0M8Hlbn5TPaRJBID7DAdYo6Vs6xGCYr981ThFcmoIQ10js10yANrrfGAzd03b3TnLAgko0uQMHjliMZL6L8sWOPHxyxJI0us88SFh4UgcFyRHKHPKux7w24SxAlZUYoUcTHp9VjG5XvDKYxzgV2RdM4ulBGbQRQ3y3/CyddsyQYMvA55Ets0LfPaBvDIcct70iXijGsdvlX1du3ArGpG7Vaje/RU4nbbGT6HYRdt5YyZfof288ukMOSj20nVcmS+c/4tqsxSerRb1aq5LOi1IemSkTMeC5gCbexk+L1vl7NT/58sxjGmu5bXwnvev/lIItfi2AlITrfUSEv19iDMKkeshwn/+sFJBMWYyluP+yJ56yR+MWoXvLlSWphLDTqq19yx3BZn0P1tgbXoR0g8PTdJFcz8z3RIb7myVLYulV1oGG/3rka0CAwEAAaOBgDB+MB0GA1UdDgQWBBTFtJkZCVDuDAD6k5bJzefjJdO3DTBCBgNVHSMEOzA5gBTFtJkZCVDuDAD6k5bJzefjJdO3DaEWpBQwEjEQMA4GA1UEAwwHUHJpdmFkb4IJAMtrmqZxIV/OMAwGA1UdEwQFMAMBAf8wCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBDQUAA4ICAQB7MUSXMeBb9wlSv4sUaT1JHEwE26nlBw+TKmezfuPU5pBlY0LYr6qQZY95DHqsRJ7ByUzGUrGo17dNGXlcuNc6TAaQQEDRPo6y+LVh2TWMk15TUMI+MkqryJtCret7xGvDigKYMJgBy58HN3RAVr1B7cL9youwzLgc2Y/NcFKvnQJKeiIYAJ7g0CcnJiQvgZTS7xdwkEBXfsngmUCIG320DLPEL+Ze0HiUrxwWljMRya6i40AeH3Zu2i532xX1wV5+cjA4RJWIKg6ri/Q54iFGtZrA9/nc6y9uoQHkmz8cGyVUmJxFzMrrIICVqUtVRxLhkTMe4UzwRWTBeGgtW4tS0yq1QonAKfOyjgRw/CeY55D2UGvnAFZdTadtYXS4Alu2P9zdwoEk3fzHiVmDjqfJVr5wz9383aABUFrPI3nz6ed/Z6LZflKh1k+DUDEp8NxU4klUULWsSOKoa5zGX51G8cdHxwQLImXvtGuN5eSR8jCTgxFZhdps/xes4KkyfIz9FMYG748M+uOTgKITf4zdJ9BAyiQaOufVQZ8WjhWzWk9YHec9VqPkzpWNGkVjiRI5ewuXwZzZ164tMv2hikBXSuUCnFz37/ZNwGlDi0oBdDszCk2GxccdFHHaCSmpjU5MrdJ+5IhtTKGeTx+US2hTIVHQFIO99DmacxSYvLNcSQ=="
)
func PrivadoCountryChoices() (choices []string) {
servers := PrivadoServers()
choices = make([]string, len(servers))
for i := range servers {
choices[i] = servers[i].Country
}
return makeUnique(choices)
}
func PrivadoRegionChoices() (choices []string) {
servers := PrivadoServers()
choices = make([]string, len(servers))
for i := range servers {
choices[i] = servers[i].Region
}
return makeUnique(choices)
}
func PrivadoCityChoices() (choices []string) {
servers := PrivadoServers()
choices = make([]string, len(servers))
for i := range servers {
choices[i] = servers[i].City
}
return makeUnique(choices)
}
func PrivadoHostnameChoices() (choices []string) {
servers := PrivadoServers()
choices = make([]string, len(servers))
for i := range servers {
choices[i] = servers[i].Hostname
}
return makeUnique(choices)
}
//nolint:lll
// PrivadoServers returns a slice of all the Privado servers.
func PrivadoServers() []models.PrivadoServer {
return []models.PrivadoServer{
{Country: "Argentina", Region: "Buenos Aires F.D.", City: "Buenos Aires", Hostname: "eze-001.vpn.privado.io", IP: net.IP{168, 205, 93, 211}},
{Country: "Australia", Region: "New South Wales", City: "Sydney", Hostname: "syd-001.vpn.privado.io", IP: net.IP{93, 115, 35, 35}},
{Country: "Australia", Region: "New South Wales", City: "Sydney", Hostname: "syd-002.vpn.privado.io", IP: net.IP{93, 115, 35, 42}},
{Country: "Australia", Region: "New South Wales", City: "Sydney", Hostname: "syd-003.vpn.privado.io", IP: net.IP{93, 115, 35, 49}},
{Country: "Australia", Region: "New South Wales", City: "Sydney", Hostname: "syd-004.vpn.privado.io", IP: net.IP{93, 115, 35, 56}},
{Country: "Austria", Region: "Vienna", City: "Vienna", Hostname: "vie-001.vpn.privado.io", IP: net.IP{5, 253, 207, 227}},
{Country: "Austria", Region: "Vienna", City: "Vienna", Hostname: "vie-002.vpn.privado.io", IP: net.IP{5, 253, 207, 234}},
{Country: "Austria", Region: "Vienna", City: "Vienna", Hostname: "vie-003.vpn.privado.io", IP: net.IP{5, 253, 207, 241}},
{Country: "Austria", Region: "Vienna", City: "Vienna", Hostname: "vie-004.vpn.privado.io", IP: net.IP{5, 253, 207, 248}},
{Country: "Belgium", Region: "Flanders", City: "Zaventem", Hostname: "bru-001.vpn.privado.io", IP: net.IP{217, 138, 211, 163}},
{Country: "Belgium", Region: "Flanders", City: "Zaventem", Hostname: "bru-002.vpn.privado.io", IP: net.IP{217, 138, 211, 170}},
{Country: "Belgium", Region: "Flanders", City: "Zaventem", Hostname: "bru-003.vpn.privado.io", IP: net.IP{217, 138, 211, 177}},
{Country: "Belgium", Region: "Flanders", City: "Zaventem", Hostname: "bru-004.vpn.privado.io", IP: net.IP{217, 138, 211, 184}},
{Country: "Brazil", Region: "São Paulo", City: "São Paulo", Hostname: "gru-001.vpn.privado.io", IP: net.IP{177, 54, 145, 193}},
{Country: "Brazil", Region: "São Paulo", City: "São Paulo", Hostname: "gru-002.vpn.privado.io", IP: net.IP{177, 54, 145, 197}},
{Country: "Bulgaria", Region: "Sofia-Capital", City: "Sofia", Hostname: "sof-001.vpn.privado.io", IP: net.IP{217, 138, 221, 163}},
{Country: "Bulgaria", Region: "Sofia-Capital", City: "Sofia", Hostname: "sof-002.vpn.privado.io", IP: net.IP{217, 138, 221, 169}},
{Country: "Canada", Region: "British Columbia", City: "Vancouver", Hostname: "yvr-001.vpn.privado.io", IP: net.IP{71, 19, 248, 57}},
{Country: "Canada", Region: "British Columbia", City: "Vancouver", Hostname: "yvr-002.vpn.privado.io", IP: net.IP{71, 19, 248, 113}},
{Country: "Canada", Region: "Ontario", City: "Toronto", Hostname: "yyz-003.vpn.privado.io", IP: net.IP{199, 189, 27, 19}},
{Country: "Canada", Region: "Quebec", City: "Montréal", Hostname: "yul-001.vpn.privado.io", IP: net.IP{217, 138, 213, 67}},
{Country: "Canada", Region: "Quebec", City: "Montréal", Hostname: "yul-002.vpn.privado.io", IP: net.IP{217, 138, 213, 72}},
{Country: "Canada", Region: "Quebec", City: "Montréal", Hostname: "yul-004.vpn.privado.io", IP: net.IP{217, 138, 213, 82}},
{Country: "Czech Republic", Region: "Hlavní město Praha", City: "Prague", Hostname: "prg-002.vpn.privado.io", IP: net.IP{185, 216, 35, 105}},
{Country: "Denmark", Region: "Capital Region", City: "Copenhagen", Hostname: "cph-001.vpn.privado.io", IP: net.IP{2, 58, 46, 35}},
{Country: "Denmark", Region: "Capital Region", City: "Copenhagen", Hostname: "cph-002.vpn.privado.io", IP: net.IP{2, 58, 46, 42}},
{Country: "Denmark", Region: "Capital Region", City: "Copenhagen", Hostname: "cph-003.vpn.privado.io", IP: net.IP{2, 58, 46, 49}},
{Country: "Denmark", Region: "Capital Region", City: "Copenhagen", Hostname: "cph-004.vpn.privado.io", IP: net.IP{2, 58, 46, 56}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-005.vpn.privado.io", IP: net.IP{146, 59, 31, 2}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-006.vpn.privado.io", IP: net.IP{146, 59, 31, 4}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-007.vpn.privado.io", IP: net.IP{146, 59, 31, 6}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-008.vpn.privado.io", IP: net.IP{146, 59, 31, 8}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-009.vpn.privado.io", IP: net.IP{146, 59, 31, 10}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-010.vpn.privado.io", IP: net.IP{146, 59, 31, 12}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-013.vpn.privado.io", IP: net.IP{146, 59, 31, 18}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-015.vpn.privado.io", IP: net.IP{146, 59, 31, 22}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-016.vpn.privado.io", IP: net.IP{146, 59, 31, 24}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-017.vpn.privado.io", IP: net.IP{146, 59, 31, 26}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-018.vpn.privado.io", IP: net.IP{146, 59, 31, 28}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-020.vpn.privado.io", IP: net.IP{146, 59, 31, 32}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-023.vpn.privado.io", IP: net.IP{146, 59, 31, 38}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-025.vpn.privado.io", IP: net.IP{146, 59, 31, 42}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-026.vpn.privado.io", IP: net.IP{146, 59, 31, 44}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-027.vpn.privado.io", IP: net.IP{146, 59, 31, 46}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-028.vpn.privado.io", IP: net.IP{146, 59, 31, 48}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-029.vpn.privado.io", IP: net.IP{146, 59, 31, 50}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-030.vpn.privado.io", IP: net.IP{146, 59, 31, 52}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-031.vpn.privado.io", IP: net.IP{146, 59, 31, 54}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-032.vpn.privado.io", IP: net.IP{146, 59, 31, 56}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-033.vpn.privado.io", IP: net.IP{146, 59, 31, 58}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-034.vpn.privado.io", IP: net.IP{146, 59, 31, 60}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-035.vpn.privado.io", IP: net.IP{146, 59, 31, 62}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-037.vpn.privado.io", IP: net.IP{146, 59, 31, 66}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-039.vpn.privado.io", IP: net.IP{146, 59, 31, 70}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-041.vpn.privado.io", IP: net.IP{146, 59, 31, 74}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-042.vpn.privado.io", IP: net.IP{146, 59, 31, 76}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-043.vpn.privado.io", IP: net.IP{146, 59, 31, 78}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-044.vpn.privado.io", IP: net.IP{146, 59, 31, 80}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-046.vpn.privado.io", IP: net.IP{146, 59, 31, 84}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-047.vpn.privado.io", IP: net.IP{146, 59, 31, 86}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-048.vpn.privado.io", IP: net.IP{146, 59, 31, 88}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-049.vpn.privado.io", IP: net.IP{146, 59, 31, 90}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-051.vpn.privado.io", IP: net.IP{146, 59, 31, 94}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-053.vpn.privado.io", IP: net.IP{146, 59, 31, 98}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-054.vpn.privado.io", IP: net.IP{146, 59, 31, 100}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-056.vpn.privado.io", IP: net.IP{146, 59, 31, 104}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-057.vpn.privado.io", IP: net.IP{146, 59, 31, 106}},
{Country: "France", Region: "Hauts-de-France", City: "Roubaix", Hostname: "waw-058.vpn.privado.io", IP: net.IP{146, 59, 31, 109}},
{Country: "France", Region: "Île-de-France", City: "Paris", Hostname: "cdg-001.vpn.privado.io", IP: net.IP{89, 40, 183, 99}},
{Country: "France", Region: "Île-de-France", City: "Paris", Hostname: "cdg-002.vpn.privado.io", IP: net.IP{89, 40, 183, 104}},
{Country: "France", Region: "Île-de-France", City: "Paris", Hostname: "cdg-003.vpn.privado.io", IP: net.IP{89, 40, 183, 109}},
{Country: "France", Region: "Île-de-France", City: "Paris", Hostname: "cdg-004.vpn.privado.io", IP: net.IP{89, 40, 183, 114}},
{Country: "Germany", Region: "Hesse", City: "Frankfurt am Main", Hostname: "ber-001.vpn.privado.io", IP: net.IP{89, 36, 76, 35}},
{Country: "Germany", Region: "Hesse", City: "Frankfurt am Main", Hostname: "fra-001.vpn.privado.io", IP: net.IP{91, 148, 232, 10}},
{Country: "Germany", Region: "Hesse", City: "Frankfurt am Main", Hostname: "fra-002.vpn.privado.io", IP: net.IP{91, 148, 232, 20}},
{Country: "Germany", Region: "Hesse", City: "Frankfurt am Main", Hostname: "fra-003.vpn.privado.io", IP: net.IP{91, 148, 232, 30}},
{Country: "Germany", Region: "Hesse", City: "Frankfurt am Main", Hostname: "fra-004.vpn.privado.io", IP: net.IP{91, 148, 232, 40}},
{Country: "Germany", Region: "Hesse", City: "Frankfurt am Main", Hostname: "fra-005.vpn.privado.io", IP: net.IP{91, 148, 233, 7}},
{Country: "Germany", Region: "Hesse", City: "Frankfurt am Main", Hostname: "fra-006.vpn.privado.io", IP: net.IP{91, 148, 233, 8}},
{Country: "Germany", Region: "Hesse", City: "Frankfurt am Main", Hostname: "fra-007.vpn.privado.io", IP: net.IP{91, 148, 233, 9}},
{Country: "Germany", Region: "Hesse", City: "Frankfurt am Main", Hostname: "fra-008.vpn.privado.io", IP: net.IP{91, 148, 233, 10}},
{Country: "Greece", Region: "Attica", City: "Athens", Hostname: "ath-001.vpn.privado.io", IP: net.IP{188, 123, 126, 61}},
{Country: "Greece", Region: "Attica", City: "Athens", Hostname: "ath-002.vpn.privado.io", IP: net.IP{188, 123, 126, 64}},
{Country: "Greece", Region: "Attica", City: "Athens", Hostname: "ath-003.vpn.privado.io", IP: net.IP{188, 123, 126, 68}},
{Country: "Greece", Region: "Attica", City: "Athens", Hostname: "ath-004.vpn.privado.io", IP: net.IP{188, 123, 126, 72}},
{Country: "Hong Kong", Region: "Central and Western", City: "Hong Kong", Hostname: "hkg-001.vpn.privado.io", IP: net.IP{209, 58, 185, 88}},
{Country: "Hong Kong", Region: "Central and Western", City: "Hong Kong", Hostname: "hkg-003.vpn.privado.io", IP: net.IP{209, 58, 185, 108}},
{Country: "Hong Kong", Region: "Central and Western", City: "Hong Kong", Hostname: "hkg-004.vpn.privado.io", IP: net.IP{209, 58, 185, 120}},
{Country: "Hungary", Region: "Budapest", City: "Budapest", Hostname: "bud-001.vpn.privado.io", IP: net.IP{185, 128, 26, 194}},
{Country: "Hungary", Region: "Budapest", City: "Budapest", Hostname: "bud-002.vpn.privado.io", IP: net.IP{185, 128, 26, 200}},
{Country: "Iceland", Region: "Capital Region", City: "Reykjavík", Hostname: "rkv-001.vpn.privado.io", IP: net.IP{82, 221, 131, 78}},
{Country: "Iceland", Region: "Capital Region", City: "Reykjavík", Hostname: "rkv-002.vpn.privado.io", IP: net.IP{82, 221, 131, 127}},
{Country: "India", Region: "Maharashtra", City: "Mumbai", Hostname: "bom-001.vpn.privado.io", IP: net.IP{103, 26, 204, 61}},
{Country: "India", Region: "Maharashtra", City: "Mumbai", Hostname: "bom-002.vpn.privado.io", IP: net.IP{103, 26, 204, 70}},
{Country: "Ireland", Region: "Leinster", City: "Dublin", Hostname: "dub-001.vpn.privado.io", IP: net.IP{84, 247, 48, 227}},
{Country: "Ireland", Region: "Leinster", City: "Dublin", Hostname: "dub-002.vpn.privado.io", IP: net.IP{84, 247, 48, 234}},
{Country: "Ireland", Region: "Leinster", City: "Dublin", Hostname: "dub-003.vpn.privado.io", IP: net.IP{84, 247, 48, 241}},
{Country: "Ireland", Region: "Leinster", City: "Dublin", Hostname: "dub-004.vpn.privado.io", IP: net.IP{84, 247, 48, 248}},
{Country: "Israel", Region: "Tel Aviv", City: "Tel Aviv", Hostname: "jrs-001.vpn.privado.io", IP: net.IP{31, 168, 251, 131}},
{Country: "Israel", Region: "Tel Aviv", City: "Tel Aviv", Hostname: "jrs-002.vpn.privado.io", IP: net.IP{31, 168, 251, 137}},
{Country: "Italy", Region: "Lombardy", City: "Figino", Hostname: "mxp-001.vpn.privado.io", IP: net.IP{89, 40, 182, 195}},
{Country: "Italy", Region: "Lombardy", City: "Figino", Hostname: "mxp-002.vpn.privado.io", IP: net.IP{89, 40, 182, 201}},
{Country: "Japan", Region: "Tokyo", City: "Tokyo", Hostname: "nrt-001.vpn.privado.io", IP: net.IP{217, 138, 252, 3}},
{Country: "Japan", Region: "Tokyo", City: "Tokyo", Hostname: "nrt-002.vpn.privado.io", IP: net.IP{217, 138, 252, 10}},
{Country: "Japan", Region: "Tokyo", City: "Tokyo", Hostname: "nrt-003.vpn.privado.io", IP: net.IP{217, 138, 252, 17}},
{Country: "Korea", Region: "Seoul", City: "Seoul", Hostname: "icn-001.vpn.privado.io", IP: net.IP{169, 56, 73, 146}},
{Country: "Korea", Region: "Seoul", City: "Seoul", Hostname: "icn-002.vpn.privado.io", IP: net.IP{169, 56, 73, 153}},
{Country: "Latvia", Region: "Riga", City: "Riga", Hostname: "rix-001.vpn.privado.io", IP: net.IP{109, 248, 149, 35}},
{Country: "Latvia", Region: "Riga", City: "Riga", Hostname: "rix-002.vpn.privado.io", IP: net.IP{109, 248, 149, 40}},
{Country: "Lithuania", Region: "Marijampolė County", City: "Marijampolė", Hostname: "vno-001.vpn.privado.io", IP: net.IP{185, 64, 104, 176}},
{Country: "Lithuania", Region: "Vilnius", City: "Vilnius", Hostname: "vno-002.vpn.privado.io", IP: net.IP{185, 64, 104, 180}},
{Country: "Netherlands", Region: "North Holland", City: "Amsterdam", Hostname: "ams-009.vpn.privado.io", IP: net.IP{91, 148, 228, 10}},
{Country: "Netherlands", Region: "North Holland", City: "Amsterdam", Hostname: "ams-010.vpn.privado.io", IP: net.IP{91, 148, 228, 20}},
{Country: "Netherlands", Region: "North Holland", City: "Amsterdam", Hostname: "ams-011.vpn.privado.io", IP: net.IP{91, 148, 228, 30}},
{Country: "Netherlands", Region: "North Holland", City: "Amsterdam", Hostname: "ams-012.vpn.privado.io", IP: net.IP{91, 148, 228, 40}},
{Country: "Netherlands", Region: "North Holland", City: "Amsterdam", Hostname: "ams-013.vpn.privado.io", IP: net.IP{91, 148, 228, 50}},
{Country: "Netherlands", Region: "North Holland", City: "Amsterdam", Hostname: "ams-014.vpn.privado.io", IP: net.IP{91, 148, 228, 60}},
{Country: "Netherlands", Region: "North Holland", City: "Amsterdam", Hostname: "ams-015.vpn.privado.io", IP: net.IP{91, 148, 228, 70}},
{Country: "Netherlands", Region: "North Holland", City: "Amsterdam", Hostname: "ams-016.vpn.privado.io", IP: net.IP{91, 148, 228, 80}},
{Country: "New Zealand", Region: "Auckland", City: "Auckland", Hostname: "akl-004.vpn.privado.io", IP: net.IP{103, 76, 164, 99}},
{Country: "New Zealand", Region: "Auckland", City: "Auckland", Hostname: "akl-005.vpn.privado.io", IP: net.IP{103, 76, 164, 105}},
{Country: "Norway", Region: "Oslo", City: "Oslo", Hostname: "osl-001.vpn.privado.io", IP: net.IP{84, 247, 50, 115}},
{Country: "Norway", Region: "Oslo", City: "Oslo", Hostname: "osl-002.vpn.privado.io", IP: net.IP{84, 247, 50, 119}},
{Country: "Poland", Region: "Mazovia", City: "Warsaw", Hostname: "waw-001.vpn.privado.io", IP: net.IP{217, 138, 209, 163}},
{Country: "Poland", Region: "Mazovia", City: "Warsaw", Hostname: "waw-002.vpn.privado.io", IP: net.IP{217, 138, 209, 164}},
{Country: "Poland", Region: "Mazovia", City: "Warsaw", Hostname: "waw-003.vpn.privado.io", IP: net.IP{217, 138, 209, 165}},
{Country: "Poland", Region: "Mazovia", City: "Warsaw", Hostname: "waw-004.vpn.privado.io", IP: net.IP{217, 138, 209, 166}},
{Country: "Portugal", Region: "Lisbon", City: "Lisbon", Hostname: "lis-001.vpn.privado.io", IP: net.IP{89, 26, 243, 153}},
{Country: "Portugal", Region: "Lisbon", City: "Lisbon", Hostname: "lis-002.vpn.privado.io", IP: net.IP{89, 26, 243, 154}},
{Country: "Romania", Region: "Bucureşti", City: "Bucharest", Hostname: "otp-001.vpn.privado.io", IP: net.IP{89, 46, 102, 179}},
{Country: "Romania", Region: "Bucureşti", City: "Bucharest", Hostname: "otp-002.vpn.privado.io", IP: net.IP{89, 46, 102, 185}},
{Country: "Serbia", Region: "Central Serbia", City: "Belgrade", Hostname: "beg-001.vpn.privado.io", IP: net.IP{89, 38, 224, 19}},
{Country: "Serbia", Region: "Central Serbia", City: "Belgrade", Hostname: "beg-002.vpn.privado.io", IP: net.IP{89, 38, 224, 25}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "kul-002.vpn.privado.io", IP: net.IP{103, 246, 112, 231}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "kul-003.vpn.privado.io", IP: net.IP{103, 246, 112, 233}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "kul-004.vpn.privado.io", IP: net.IP{103, 246, 112, 235}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "kul-005.vpn.privado.io", IP: net.IP{103, 246, 112, 237}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "kul-006.vpn.privado.io", IP: net.IP{103, 246, 112, 239}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "kul-007.vpn.privado.io", IP: net.IP{103, 246, 112, 241}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "kul-009.vpn.privado.io", IP: net.IP{103, 246, 112, 245}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "kul-010.vpn.privado.io", IP: net.IP{103, 246, 112, 247}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "kul-012.vpn.privado.io", IP: net.IP{103, 246, 112, 251}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "kul-013.vpn.privado.io", IP: net.IP{103, 246, 112, 253}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "sin-001.vpn.privado.io", IP: net.IP{92, 119, 178, 131}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "sin-002.vpn.privado.io", IP: net.IP{92, 119, 178, 138}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "sin-003.vpn.privado.io", IP: net.IP{92, 119, 178, 145}},
{Country: "Singapore", Region: "Singapore", City: "Singapore", Hostname: "sin-004.vpn.privado.io", IP: net.IP{92, 119, 178, 152}},
{Country: "Slovakia", Region: "Bratislavský Kraj", City: "Bratislava", Hostname: "bts-001.vpn.privado.io", IP: net.IP{37, 120, 221, 227}},
{Country: "South Africa", Region: "Gauteng", City: "Johannesburg", Hostname: "jnb-001.vpn.privado.io", IP: net.IP{172, 107, 93, 131}},
{Country: "South Africa", Region: "Gauteng", City: "Johannesburg", Hostname: "jnb-002.vpn.privado.io", IP: net.IP{172, 107, 93, 137}},
{Country: "Spain", Region: "Madrid", City: "Madrid", Hostname: "mad-001.vpn.privado.io", IP: net.IP{217, 138, 218, 131}},
{Country: "Spain", Region: "Madrid", City: "Madrid", Hostname: "mad-002.vpn.privado.io", IP: net.IP{217, 138, 218, 138}},
{Country: "Spain", Region: "Madrid", City: "Madrid", Hostname: "mad-003.vpn.privado.io", IP: net.IP{217, 138, 218, 145}},
{Country: "Spain", Region: "Madrid", City: "Madrid", Hostname: "mad-004.vpn.privado.io", IP: net.IP{217, 138, 218, 152}},
{Country: "Sweden", Region: "Stockholm", City: "Stockholm", Hostname: "arn-001.vpn.privado.io", IP: net.IP{86, 106, 103, 67}},
{Country: "Sweden", Region: "Stockholm", City: "Stockholm", Hostname: "arn-002.vpn.privado.io", IP: net.IP{86, 106, 103, 74}},
{Country: "Sweden", Region: "Stockholm", City: "Stockholm", Hostname: "arn-003.vpn.privado.io", IP: net.IP{86, 106, 103, 81}},
{Country: "Sweden", Region: "Stockholm", City: "Stockholm", Hostname: "arn-004.vpn.privado.io", IP: net.IP{86, 106, 103, 88}},
{Country: "Switzerland", Region: "Zurich", City: "Zürich", Hostname: "zrh-002.vpn.privado.io", IP: net.IP{185, 156, 175, 202}},
{Country: "Switzerland", Region: "Zurich", City: "Zürich", Hostname: "zrh-003.vpn.privado.io", IP: net.IP{185, 156, 175, 209}},
{Country: "Switzerland", Region: "Zurich", City: "Zürich", Hostname: "zrh-004.vpn.privado.io", IP: net.IP{185, 156, 175, 216}},
{Country: "Thailand", Region: "Bangkok", City: "Bangkok", Hostname: "bkk-001.vpn.privado.io", IP: net.IP{119, 59, 111, 3}},
{Country: "Thailand", Region: "Bangkok", City: "Bangkok", Hostname: "bkk-002.vpn.privado.io", IP: net.IP{119, 59, 111, 11}},
{Country: "Turkey", Region: "Istanbul", City: "Istanbul", Hostname: "ist-001.vpn.privado.io", IP: net.IP{185, 84, 183, 3}},
{Country: "Turkey", Region: "Istanbul", City: "Istanbul", Hostname: "ist-002.vpn.privado.io", IP: net.IP{185, 84, 183, 4}},
{Country: "Ukraine", Region: "Kyiv City", City: "Kyiv", Hostname: "iev-001.vpn.privado.io", IP: net.IP{176, 103, 52, 40}},
{Country: "Ukraine", Region: "Kyiv City", City: "Kyiv", Hostname: "iev-002.vpn.privado.io", IP: net.IP{176, 103, 53, 40}},
{Country: "United Kingdom", Region: "England", City: "London", Hostname: "lhr-001.vpn.privado.io", IP: net.IP{217, 138, 195, 163}},
{Country: "United Kingdom", Region: "England", City: "London", Hostname: "lhr-002.vpn.privado.io", IP: net.IP{217, 138, 195, 168}},
{Country: "United Kingdom", Region: "England", City: "London", Hostname: "lhr-003.vpn.privado.io", IP: net.IP{217, 138, 195, 173}},
{Country: "United Kingdom", Region: "England", City: "London", Hostname: "lhr-004.vpn.privado.io", IP: net.IP{217, 138, 195, 178}},
{Country: "United Kingdom", Region: "England", City: "Manchester", Hostname: "man-001.vpn.privado.io", IP: net.IP{217, 138, 196, 131}},
{Country: "United Kingdom", Region: "England", City: "Manchester", Hostname: "man-002.vpn.privado.io", IP: net.IP{217, 138, 196, 138}},
{Country: "United Kingdom", Region: "England", City: "Manchester", Hostname: "man-003.vpn.privado.io", IP: net.IP{217, 138, 196, 145}},
{Country: "United Kingdom", Region: "England", City: "Manchester", Hostname: "man-004.vpn.privado.io", IP: net.IP{217, 138, 196, 152}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "lax-001.vpn.privado.io", IP: net.IP{81, 171, 62, 3}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "lax-002.vpn.privado.io", IP: net.IP{81, 171, 62, 13}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "lax-003.vpn.privado.io", IP: net.IP{81, 171, 62, 24}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "lax-004.vpn.privado.io", IP: net.IP{81, 171, 62, 34}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "lax-005.vpn.privado.io", IP: net.IP{81, 171, 62, 70}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "lax-006.vpn.privado.io", IP: net.IP{81, 171, 62, 80}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "lax-007.vpn.privado.io", IP: net.IP{81, 171, 62, 90}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "lax-008.vpn.privado.io", IP: net.IP{81, 171, 62, 100}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "lax-010.vpn.privado.io", IP: net.IP{45, 152, 182, 234}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "mex-003.vpn.privado.io", IP: net.IP{81, 171, 63, 3}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "mex-004.vpn.privado.io", IP: net.IP{81, 171, 63, 13}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "mex-005.vpn.privado.io", IP: net.IP{81, 171, 63, 23}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "mex-006.vpn.privado.io", IP: net.IP{81, 171, 63, 33}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "mex-007.vpn.privado.io", IP: net.IP{81, 171, 63, 44}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "mex-008.vpn.privado.io", IP: net.IP{81, 171, 63, 54}},
{Country: "United States", Region: "California", City: "Los Angeles", Hostname: "mex-009.vpn.privado.io", IP: net.IP{81, 171, 63, 64}},
{Country: "United States", Region: "California", City: "Santa Clara", Hostname: "mex-001.vpn.privado.io", IP: net.IP{169, 57, 96, 52}},
{Country: "United States", Region: "California", City: "Santa Clara", Hostname: "mex-002.vpn.privado.io", IP: net.IP{169, 57, 96, 57}},
{Country: "United States", Region: "Florida", City: "Miami", Hostname: "mia-002.vpn.privado.io", IP: net.IP{86, 106, 87, 136}},
{Country: "United States", Region: "Florida", City: "Miami", Hostname: "mia-003.vpn.privado.io", IP: net.IP{86, 106, 87, 141}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-007.vpn.privado.io", IP: net.IP{23, 108, 95, 203}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-011.vpn.privado.io", IP: net.IP{23, 108, 95, 228}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-012.vpn.privado.io", IP: net.IP{23, 108, 95, 230}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-014.vpn.privado.io", IP: net.IP{23, 108, 95, 234}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-015.vpn.privado.io", IP: net.IP{23, 108, 95, 236}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-016.vpn.privado.io", IP: net.IP{23, 108, 95, 238}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-017.vpn.privado.io", IP: net.IP{23, 108, 95, 240}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-018.vpn.privado.io", IP: net.IP{23, 108, 95, 242}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-019.vpn.privado.io", IP: net.IP{23, 108, 95, 244}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-020.vpn.privado.io", IP: net.IP{23, 108, 95, 246}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-021.vpn.privado.io", IP: net.IP{108, 62, 107, 153}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-022.vpn.privado.io", IP: net.IP{108, 62, 107, 156}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-024.vpn.privado.io", IP: net.IP{108, 62, 107, 160}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-025.vpn.privado.io", IP: net.IP{108, 62, 107, 162}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-026.vpn.privado.io", IP: net.IP{108, 62, 107, 164}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-027.vpn.privado.io", IP: net.IP{108, 62, 107, 166}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-028.vpn.privado.io", IP: net.IP{108, 62, 107, 168}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-029.vpn.privado.io", IP: net.IP{108, 62, 107, 170}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-030.vpn.privado.io", IP: net.IP{108, 62, 107, 172}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-031.vpn.privado.io", IP: net.IP{108, 62, 107, 174}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-032.vpn.privado.io", IP: net.IP{108, 62, 107, 176}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-033.vpn.privado.io", IP: net.IP{108, 62, 107, 178}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-034.vpn.privado.io", IP: net.IP{108, 62, 107, 180}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-046.vpn.privado.io", IP: net.IP{23, 82, 107, 87}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-048.vpn.privado.io", IP: net.IP{23, 82, 107, 91}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-049.vpn.privado.io", IP: net.IP{23, 82, 107, 93}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-050.vpn.privado.io", IP: net.IP{23, 82, 107, 95}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-052.vpn.privado.io", IP: net.IP{23, 82, 107, 99}},
{Country: "United States", Region: "Illinois", City: "Chicago", Hostname: "ord-055.vpn.privado.io", IP: net.IP{23, 82, 107, 105}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-008.vpn.privado.io", IP: net.IP{23, 108, 95, 222}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-035.vpn.privado.io", IP: net.IP{23, 82, 107, 65}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-036.vpn.privado.io", IP: net.IP{23, 82, 107, 67}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-039.vpn.privado.io", IP: net.IP{23, 82, 107, 73}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-040.vpn.privado.io", IP: net.IP{23, 82, 107, 75}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-047.vpn.privado.io", IP: net.IP{23, 82, 107, 89}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-051.vpn.privado.io", IP: net.IP{23, 82, 107, 97}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-053.vpn.privado.io", IP: net.IP{23, 82, 107, 101}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-054.vpn.privado.io", IP: net.IP{23, 82, 107, 103}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-056.vpn.privado.io", IP: net.IP{23, 82, 107, 107}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-059.vpn.privado.io", IP: net.IP{23, 82, 107, 113}},
{Country: "United States", Region: "Minnesota", City: "Minnetonka", Hostname: "ord-061.vpn.privado.io", IP: net.IP{23, 82, 107, 117}},
{Country: "United States", Region: "Missouri", City: "St. Louis", Hostname: "stl-001.vpn.privado.io", IP: net.IP{148, 72, 170, 145}},
{Country: "United States", Region: "Missouri", City: "St. Louis", Hostname: "stl-002.vpn.privado.io", IP: net.IP{148, 72, 172, 82}},
{Country: "United States", Region: "New York", City: "Buffalo", Hostname: "ord-003.vpn.privado.io", IP: net.IP{23, 254, 112, 130}},
{Country: "United States", Region: "New York", City: "Buffalo", Hostname: "ord-004.vpn.privado.io", IP: net.IP{23, 254, 112, 138}},
{Country: "United States", Region: "New York", City: "Buffalo", Hostname: "ord-005.vpn.privado.io", IP: net.IP{23, 254, 112, 145}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-002.vpn.privado.io", IP: net.IP{217, 138, 208, 106}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-003.vpn.privado.io", IP: net.IP{217, 138, 208, 113}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-005.vpn.privado.io", IP: net.IP{37, 120, 244, 3}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-007.vpn.privado.io", IP: net.IP{37, 120, 244, 17}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-008.vpn.privado.io", IP: net.IP{37, 120, 244, 24}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-009.vpn.privado.io", IP: net.IP{23, 19, 225, 65}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-010.vpn.privado.io", IP: net.IP{23, 19, 225, 67}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-011.vpn.privado.io", IP: net.IP{23, 19, 225, 69}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-012.vpn.privado.io", IP: net.IP{23, 19, 225, 71}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-014.vpn.privado.io", IP: net.IP{23, 19, 225, 75}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-015.vpn.privado.io", IP: net.IP{23, 19, 225, 77}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-016.vpn.privado.io", IP: net.IP{23, 19, 225, 79}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-017.vpn.privado.io", IP: net.IP{23, 19, 225, 81}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-018.vpn.privado.io", IP: net.IP{23, 19, 225, 83}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-019.vpn.privado.io", IP: net.IP{23, 19, 225, 85}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-020.vpn.privado.io", IP: net.IP{23, 19, 225, 87}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-021.vpn.privado.io", IP: net.IP{23, 19, 225, 89}}, | {Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-023.vpn.privado.io", IP: net.IP{23, 19, 225, 93}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-024.vpn.privado.io", IP: net.IP{23, 19, 225, 95}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-025.vpn.privado.io", IP: net.IP{23, 19, 225, 97}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-026.vpn.privado.io", IP: net.IP{23, 19, 225, 99}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-027.vpn.privado.io", IP: net.IP{23, 19, 225, 101}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-028.vpn.privado.io", IP: net.IP{23, 19, 225, 103}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-029.vpn.privado.io", IP: net.IP{23, 19, 225, 105}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-030.vpn.privado.io", IP: net.IP{23, 19, 225, 107}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-032.vpn.privado.io", IP: net.IP{23, 19, 225, 111}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-034.vpn.privado.io", IP: net.IP{23, 19, 225, 115}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-035.vpn.privado.io", IP: net.IP{23, 19, 225, 117}},
{Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-036.vpn.privado.io", IP: net.IP{23, 19, 225, 119}},
{Country: "United States", Region: "North Carolina", City: "Beaufort", Hostname: "ord-038.vpn.privado.io", IP: net.IP{23, 82, 107, 71}},
{Country: "United States", Region: "North Carolina", City: "Beaufort", Hostname: "ord-041.vpn.privado.io", IP: net.IP{23, 82, 107, 77}},
{Country: "United States", Region: "North Carolina", City: "Beaufort", Hostname: "ord-042.vpn.privado.io", IP: net.IP{23, 82, 107, 79}},
{Country: "United States", Region: "North Carolina", City: "Beaufort", Hostname: "ord-044.vpn.privado.io", IP: net.IP{23, 82, 107, 83}},
{Country: "United States", Region: "North Carolina", City: "Beaufort", Hostname: "ord-057.vpn.privado.io", IP: net.IP{23, 82, 107, 109}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-001.vpn.privado.io", IP: net.IP{104, 255, 228, 131}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-002.vpn.privado.io", IP: net.IP{104, 255, 228, 135}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-003.vpn.privado.io", IP: net.IP{104, 255, 228, 139}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-004.vpn.privado.io", IP: net.IP{104, 255, 228, 143}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-006.vpn.privado.io", IP: net.IP{104, 255, 228, 151}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-007.vpn.privado.io", IP: net.IP{104, 255, 228, 155}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-008.vpn.privado.io", IP: net.IP{104, 255, 228, 159}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-009.vpn.privado.io", IP: net.IP{104, 255, 228, 163}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-010.vpn.privado.io", IP: net.IP{104, 255, 228, 167}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-011.vpn.privado.io", IP: net.IP{104, 255, 228, 171}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-012.vpn.privado.io", IP: net.IP{104, 255, 228, 175}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-013.vpn.privado.io", IP: net.IP{104, 255, 228, 179}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-014.vpn.privado.io", IP: net.IP{104, 255, 228, 183}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-015.vpn.privado.io", IP: net.IP{104, 255, 228, 187}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-016.vpn.privado.io", IP: net.IP{104, 255, 228, 195}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-017.vpn.privado.io", IP: net.IP{104, 255, 228, 199}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-018.vpn.privado.io", IP: net.IP{104, 255, 228, 203}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-019.vpn.privado.io", IP: net.IP{104, 255, 228, 207}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-020.vpn.privado.io", IP: net.IP{104, 255, 228, 211}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-021.vpn.privado.io", IP: net.IP{104, 255, 228, 215}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-022.vpn.privado.io", IP: net.IP{104, 255, 228, 219}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-023.vpn.privado.io", IP: net.IP{104, 255, 228, 223}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-024.vpn.privado.io", IP: net.IP{104, 255, 228, 227}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-025.vpn.privado.io", IP: net.IP{104, 255, 228, 231}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-026.vpn.privado.io", IP: net.IP{104, 255, 228, 235}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-027.vpn.privado.io", IP: net.IP{104, 255, 228, 239}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-028.vpn.privado.io", IP: net.IP{104, 255, 228, 243}},
{Country: "United States", Region: "Oregon", City: "Portland", Hostname: "pdx-030.vpn.privado.io", IP: net.IP{104, 255, 228, 251}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-001.vpn.privado.io", IP: net.IP{23, 105, 32, 243}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-002.vpn.privado.io", IP: net.IP{23, 105, 32, 244}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-003.vpn.privado.io", IP: net.IP{172, 241, 25, 157}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-006.vpn.privado.io", IP: net.IP{172, 241, 25, 163}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-007.vpn.privado.io", IP: net.IP{172, 241, 25, 165}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-008.vpn.privado.io", IP: net.IP{172, 241, 25, 167}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-009.vpn.privado.io", IP: net.IP{172, 241, 25, 169}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-010.vpn.privado.io", IP: net.IP{172, 241, 25, 171}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-011.vpn.privado.io", IP: net.IP{172, 241, 25, 173}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-012.vpn.privado.io", IP: net.IP{172, 241, 25, 175}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-013.vpn.privado.io", IP: net.IP{172, 241, 25, 177}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-014.vpn.privado.io", IP: net.IP{172, 241, 25, 179}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-015.vpn.privado.io", IP: net.IP{172, 241, 25, 181}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-016.vpn.privado.io", IP: net.IP{172, 241, 25, 183}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-017.vpn.privado.io", IP: net.IP{172, 241, 25, 185}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-018.vpn.privado.io", IP: net.IP{172, 241, 30, 65}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-020.vpn.privado.io", IP: net.IP{172, 241, 30, 69}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-021.vpn.privado.io", IP: net.IP{172, 241, 30, 71}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-022.vpn.privado.io", IP: net.IP{172, 241, 30, 73}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-023.vpn.privado.io", IP: net.IP{172, 241, 30, 75}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-024.vpn.privado.io", IP: net.IP{172, 241, 30, 77}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-025.vpn.privado.io", IP: net.IP{172, 241, 30, 79}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-026.vpn.privado.io", IP: net.IP{172, 241, 30, 81}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-028.vpn.privado.io", IP: net.IP{172, 241, 30, 85}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-029.vpn.privado.io", IP: net.IP{172, 241, 30, 87}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-030.vpn.privado.io", IP: net.IP{172, 241, 30, 89}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-032.vpn.privado.io", IP: net.IP{172, 241, 30, 93}},
{Country: "United States", Region: "Texas", City: "Dallas", Hostname: "dfw-033.vpn.privado.io", IP: net.IP{172, 241, 30, 95}},
{Country: "United States", Region: "Virginia", City: "Ashburn", Hostname: "dca-003.vpn.privado.io", IP: net.IP{85, 12, 61, 30}},
{Country: "United States", Region: "Virginia", City: "Ashburn", Hostname: "dca-004.vpn.privado.io", IP: net.IP{85, 12, 61, 40}},
{Country: "United States", Region: "Virginia", City: "Ashburn", Hostname: "dca-005.vpn.privado.io", IP: net.IP{85, 12, 61, 50}},
{Country: "United States", Region: "Virginia", City: "Ashburn", Hostname: "dca-006.vpn.privado.io", IP: net.IP{85, 12, 61, 60}},
{Country: "United States", Region: "Virginia", City: "Ashburn", Hostname: "dca-007.vpn.privado.io", IP: net.IP{85, 12, 61, 70}},
{Country: "United States", Region: "Virginia", City: "Ashburn", Hostname: "dca-008.vpn.privado.io", IP: net.IP{85, 12, 61, 80}},
{Country: "United States", Region: "Virginia", City: "Ashburn", Hostname: "dca-009.vpn.privado.io", IP: net.IP{85, 12, 61, 90}},
{Country: "United States", Region: "Virginia", City: "Ashburn", Hostname: "dca-011.vpn.privado.io", IP: net.IP{85, 12, 61, 110}},
{Country: "United States", Region: "Virginia", City: "Ashburn", Hostname: "dca-012.vpn.privado.io", IP: net.IP{85, 12, 61, 120}},
{Country: "United States", Region: "Washington", City: "Mirrormont", Hostname: "sea-003.vpn.privado.io", IP: net.IP{23, 19, 87, 109}},
{Country: "United States", Region: "Washington", City: "Mirrormont", Hostname: "sea-004.vpn.privado.io", IP: net.IP{23, 19, 87, 116}},
{Country: "United States", Region: "Washington", City: "Seattle", Hostname: "sea-001.vpn.privado.io", IP: net.IP{23, 81, 208, 96}},
{Country: "United States", Region: "Washington", City: "Seattle", Hostname: "sea-002.vpn.privado.io", IP: net.IP{23, 81, 208, 104}},
{Country: "United States", Region: "Washington, D.C.", City: "Washington", Hostname: "dca-013.vpn.privado.io", IP: net.IP{185, 247, 68, 3}},
{Country: "United States", Region: "Washington, D.C.", City: "Washington", Hostname: "dca-014.vpn.privado.io", IP: net.IP{185, 247, 68, 14}},
}
} | {Country: "United States", Region: "New York", City: "New York City", Hostname: "jfk-022.vpn.privado.io", IP: net.IP{23, 19, 225, 91}}, |
404.js | import React, { useState, useLayoutEffect } from "react";
// Components
import Layout from "../components/layout";
import SEO from "../components/seo";
// Images
import Astronaut from '../images/404/Astronaut-big.png'
import BalloonLost from '../images/404/Balloon Lost-big.png'
import BrokenClock from '../images/404/Broken Clock-big.png'
import Ostrich from '../images/404/Ostrich-big.png'
import CautionTape from '../images/404/Caution Tape-big.png'
import BrokenMug from '../images/404/Broken Mug-big.png'
import BurntToast from '../images/404/Burnt Toast-big.png'
import DogAte from '../images/404/Dog Ate-big.png'
import SpilledMilk from '../images/404/Spilled Milk-big.png'
import ShoesTied from '../images/404/Shoes Tied-big.png'
import KidsToy from '../images/404/Kid_s Toy-big.png'
import LostTourist from '../images/404/Lost Tourist-big.png'
import BoatLeak from '../images/404/Boat Leak-big.png'
import Ghost from '../images/404/Ghost-big.png'
import PizzaBox from '../images/404/Pizza Box-big.png'
import LostKeys from '../images/404/Lost Keys-big.png'
import Trash from '../images/404/Trash-big.png'
import LochNess from '../images/404/Loch Ness-big.png'
import IceCreamSpill from '../images/404/Ice Cream Spill-big.png'
const fourOhFourHeadingText = [
"This Page is Lost in Space",
"This Page is Lost in the Wind",
"This Page is Burried in the Sand",
"This Page is Broken",
"Caution! This Page is Cordoned Off",
"This Page is Broken",
"This Page is Burnt to a Crisp",
"A Dog Ate this Page",
"Don't Cry Over Spilled Page",
"Oh No! We Tripped Up!",
"This Page is Wrong",
"This Page is Not on the Map",
"There's a Leak in the Website",
"This Page is a Ghost",
"This Page Contains Nothing but Scraps",
"This Page is Lost",
"This Page is in the Garbage",
"This Page is Not Real",
"This Page is Melted in the Sun"
]
const fourOhFourParagraphText = [
"You thought this mission to the moon would be a quick six month thing. Your neighbor offered to look after your dog. Your high school math teacher was impressed. He once said you wouldn't amount to anything. You sure showed him. But now here you are, fifty feet from your spaceship with no way to get back. Your dog will be so sad. Your math teacher will be so smug. Pretty devastating.",
"The child had looked so excited when the clown had presented a large red balloon. You had seen this, but in the throes of your morning commute you didn't register it until it was too late. Who asked the government to support a fair in the middle of Main Street during a week day anyway? Your bike barrelled right between the child and the clown and sent the balloon on its merry way. You didn't turn back to see the damage you had done. Later you saw the balloon floating outside your office window.",
"You have never seen an ostrich head. Whenever you're around it seems ostriches are avoiding your gaze. You came on this trip specifically to see an ostrich head, but here is this ostrich right in front of you, head invisible. You may never see an ostrich head.",
"A broken clock is right twice a day. But if you just have one clock, it's impossible to tell exactly when the clock is right. So it could be right at any moment. And that brings you to the crux of the conceptualization. What is time? Nothing but an abyss. Clocks are just false attempts to harness its power. It's a cruel reality.",
"The earthquake was not good to the bike lane on your way to work. A large gap in the pavement (too big to be called a pothole) had swallowed three oblivious bikers whole. So the city had put up two pylons and yellow caution tape. Pretty frustrating for you given your propensity to do 360 jumps over the gap.",
"This mug was a family heirloom. Of your neighbor. Your neighbor always loved the color, shape, and quantity of coffee held by this mug. But your neighbor moved out and left it on their porch, no explanation, no repair materials, no nothing. So now you have this broken mug.",
"Toast takes so long to make. You stare at the toaster tapping your feet. Your laundry is in the dryer and it just dingerd. Maybe you'll take it out. After all, you have time. You take out your laundry. You fold your underwear. You think about folding your socks. You remember your toast! It's too late. It's burnt to a crisp. The process repeats itself. You should probably figure out your toasting settings.",
"Your dog is cute but honestly a menace. Where are my shoes? Where is my graduation certificate? Where is the chocolate cake I baked for my Aunt's birthday? And why did you take your dog to the vet on that same Thursday?!",
"Gulp. You hold back tears as the white liquid spreads across the floor from your sad looking carton. You should have bought the chocolate milk. It was clearly the better choice. And then maybe you wouldn't have so carelessly smacked it across the room when you emphatically pointed at a bird outside. Too late now. You wipe the single tear from your eye and go fetch the mop.",
"You had been told you should always check your shoes before getting up from the bleachers. Freshman were known to walk under them and tie peoples’ shoes together.",
"You have been trying for ten minutes. It’s pretty late at night and pretty dark in your room. You reach over and flick on a lamp. You feel oh so stupid. The gap in the toy is a triangle and you only have the cylinder and cube pieces. In dismay you toss the toy aside. Curse your five year old’s inability to keep track of the triangle!",
"You told your friends you weren’t bringing your phone, to try and experience what travel was like back in the day. You bought a map and a bottle of water and carried your camera for the money shot. But the map was from 2005 and the landscape had changed. So here you are, in the middle of a large field, that the map continues to claim is a local grocer.",
"The boat had looked good to the naked eye. But you wear a very strong prescription and should have been wearing glasses. As you cling on to the bouey the coast guard had thrown at you, you watch the water rush into you beloved dingy. The leak sprays water higher and higher. Then the boat was swallowed and sunk into the abyss.",
"Once alive and now dead, this ghost appears to have some unfinished business. Could it be with you? Or the treasure hidden under the floorboards of the old mansion in the hills that may never reach its rightful owner, a compassionate school teacher in Brooklyn.",
"A perfectly enticing pizza box sitting on a table. You open it filled with anticipation. And find… nothing but scraps. Perhaps a half eaten crust. And a lot of grease. The anticipation turns to deep disappointment and despair. There’s nothing left!",
"You bought a little bracelet for the express purpose of not losing your keys. You put a hook on your door specifically meant for keeping your keys. You briefly attempted to attach your keys to your phone. But here they are. In the dirt. In the park across the street from that bar you used to like but decided the last time you went that you probably wouldn’t go again. You’ll never find them.",
"When the king of racoons approached you during the fall of 2005, you were taken aback by the generosity of the offer he made and also his ability to talk. You’ve been living in harmony ever since. They pay 50% of your rent and you “forget” to take out the garbage every other week.",
"The imposing figure with the trenchcoat shows you the two polaroids. One appears to show the Loch Ness monster herself in the middle of a stretch of dark water. The other shows a sasquatch picking it’s way through a dark forest. You look closer. The animal shapes are drawn on with ink. “This isn’t real!” You scream and throw the polaroids to the floor, sobbing.",
"People questioned your desire to get strawberry. “That’s the worst flavor,” they said. But you are strong and independent so you got it anyway. And honestly, it wasn’t great. Luckily, two licks in a bike whizzed past you and knocked the cone out of your hand. “Oh no!” you yelled as the creamy pink became a mess in the dirt. But really you were happy."
]
const fourOhFourImgSrc = [
Astronaut,
BalloonLost,
Ostrich,
BrokenClock,
CautionTape,
BrokenMug,
BurntToast,
DogAte,
SpilledMilk,
ShoesTied,
KidsToy,
LostTourist,
BoatLeak,
Ghost,
PizzaBox,
LostKeys,
Trash,
LochNess,
IceCreamSpill
]
export default () => {
const [ pick, updatePick ] = useState(0)
useLayoutEffect(() => {
const newPick = Math.floor(Math.random()*fourOhFourHeadingText.length)
updatePick(newPick)
})
return (
<Layout>
<SEO title="404: Not found" />
<div>
<img
src={fourOhFourImgSrc[pick]}
className="block mx-auto w-1/2"
alt="Ghost getting abducted by aliens"
/>
<h2 className="bg-yellow-400 text-2xl font-bold inline-block my-8 p-3"> | {fourOhFourParagraphText[pick]}
</p>
</div>
</Layout>
);
} | {fourOhFourHeadingText[pick]}
</h2>
<p className="font-sans text-lg subpixel-antialiased font-thin"> |
cat.count.js | /*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict'
/* eslint camelcase: 0 */
/* eslint no-unused-vars: 0 */
function | (opts) {
// eslint-disable-next-line no-unused-vars
const { makeRequest, ConfigurationError, handleError, snakeCaseKeys } = opts
const acceptedQuerystring = [
'format',
'h',
'help',
's',
'v',
'pretty',
'human',
'error_trace',
'source',
'filter_path'
]
const snakeCase = {
errorTrace: 'error_trace',
filterPath: 'filter_path'
}
/**
* Perform a cat.count request
* Provides quick access to the document count of the entire cluster, or individual indices.
* https://www.elastic.co/guide/en/elasticsearch/reference/master/cat-count.html
*/
return function catCount (params, options, callback) {
options = options || {}
if (typeof options === 'function') {
callback = options
options = {}
}
if (typeof params === 'function' || params == null) {
callback = params
params = {}
options = {}
}
// validate headers object
if (options.headers != null && typeof options.headers !== 'object') {
const err = new ConfigurationError(`Headers should be an object, instead got: ${typeof options.headers}`)
return handleError(err, callback)
}
var warnings = []
var { method, body, index, ...querystring } = params
querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring, warnings)
var ignore = options.ignore
if (typeof ignore === 'number') {
options.ignore = [ignore]
}
var path = ''
if ((index) != null) {
if (method == null) method = 'GET'
path = '/' + '_cat' + '/' + 'count' + '/' + encodeURIComponent(index) + '/'
} else {
if (method == null) method = 'GET'
path = '/' + '_cat' + '/' + 'count' + '/'
}
// build request object
const request = {
method,
path,
body: null,
querystring
}
options.warnings = warnings.length === 0 ? null : warnings
return makeRequest(request, options, callback)
}
}
module.exports = buildCatCount
| buildCatCount |
consumer_close.handler.rs | use crate::room::dto::consumer_close_request::ConsumerCloseRequest;
use crate::room::dto::consumer_close_response::ConsumerCloseResponse;
use crate::room::Room;
use actix::prelude::*;
///
/// This handler is used to serve user's request to close consumer stream.
///
impl Handler<ConsumerCloseRequest> for Room {
type Result = ();
fn handle(&mut self, msg: ConsumerCloseRequest, _ctx: &mut Context<Self>) {
if let Some(my_user) = self.users.get(&msg.user_id) {
let user_lock = my_user.clone();
actix::spawn(async move {
let mut user = user_lock.as_ref().write().await;
user.remove_consumer(msg.id);
user.ws_actor_addr.do_send(ConsumerCloseResponse { | id: msg.id,
});
});
}
}
} | user_id: msg.producer_user_id, |
testutil.py | # 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.
"""Utilities for writing tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import tempfile
import tensorflow as tf
from tensorflow_model_analysis.types_compat import Dict, Iterable, Union, Sequence, Tuple
from tensorflow.core.example import example_pb2
class TensorflowModelAnalysisTest(tf.test.TestCase):
"""Test class that extends tf.test.TestCase with extra functionality."""
def setUp(self):
self.longMessage = True # pylint: disable=invalid-name
def _getTempDir(self):
return tempfile.mkdtemp()
def _makeExample(self, **kwargs):
"""Make a TensorFlow Example with the given fields.
The arguments can be singleton values, or a list of values, e.g.
_makeExample(age=3.0, fruits=['apples', 'pears', 'oranges']).
Empty lists are not allowed, since we won't be able to deduce the type.
Args:
**kwargs: Each key=value pair defines a field in the example to be
constructed. The name of the field will be key, and the value will be
value. The type will be deduced from the type of the value.
Returns:
TensorFlow.Example with the corresponding fields set to the corresponding
values.
Raises:
ValueError: One of the arguments was an empty list.
TypeError: One of the elements (or one of the elements in a list) had an
unsupported type.
"""
result = example_pb2.Example()
for key, value in kwargs.items():
if isinstance(value, float) or isinstance(value, int):
result.features.feature[key].float_list.value[:] = [value]
elif isinstance(value, str):
result.features.feature[key].bytes_list.value[:] = [value]
elif isinstance(value, list):
if len(value) == 0: # pylint: disable=g-explicit-length-test
raise ValueError('empty lists not allowed, but field %s was an empty '
'list' % key)
if isinstance(value[0], float) or isinstance(value[0], int):
result.features.feature[key].float_list.value[:] = value
elif isinstance(value[0], str):
result.features.feature[key].bytes_list.value[:] = value
else: | else:
raise TypeError('unrecognised type for field %s: type %s' %
(key, type(value)))
return result
def assertHasKeyWithValueAlmostEqual(self,
d,
key,
value,
places = 5):
self.assertIn(key, d)
self.assertAlmostEqual(d[key], value, places=places, msg='key %s' % key)
def assertDictElementsAlmostEqual(self,
got_values_dict,
expected_values_dict,
places = 5):
for key, expected_value in expected_values_dict.items():
self.assertHasKeyWithValueAlmostEqual(got_values_dict, key,
expected_value, places)
def assertDictMatrixRowsAlmostEqual(
self,
got_values_dict,
expected_values_dict,
places = 5):
"""Fails if got_values_dict does not match values in expected_values_dict.
For each entry, expected_values_dict provides the row index and the values
of that row to be compared to the bucketing result in got_values_dict. For
example:
got_values_dict={'key', [[1,2,3],[4,5,6],[7,8,9]]}
you can check the first and last row of got_values_dict[key] by setting
expected_values_dict={'key', [(0,[1,2,3]), (2,[7,8,9])]}
Args:
got_values_dict: The dict got, where each value represents a full
bucketing result.
expected_values_dict: The expected dict. It may contain a subset of keys
in got_values_dict. The value is of type "Iterable[Tuple[int,
Iterable[scalar]]]", where each Tuple contains the index of a row to be
checked and the expected values of that row.
places: The number of decimal places to compare.
"""
for key, expected_value in expected_values_dict.items():
self.assertIn(key, got_values_dict)
for (row, values) in expected_value:
self.assertSequenceAlmostEqual(
got_values_dict[key][row],
values,
places=places,
msg_prefix='for key %s, row %d: ' % (key, row))
def assertSequenceAlmostEqual(self,
got_seq,
expected_seq,
places = 5,
msg_prefix=''):
got = list(got_seq)
expected = list(expected_seq)
self.assertEqual(
len(got), len(expected), msg=msg_prefix + 'lengths do not match')
for index, (a, b) in enumerate(zip(got, expected)):
msg = msg_prefix + 'at index %d. sequences were: %s and %s' % (index, got,
expected),
if math.isnan(a) or math.isnan(b):
self.assertEqual(math.isnan(a), math.isnan(b), msg=msg)
else:
self.assertAlmostEqual(a, b, msg=msg, places=places) | raise TypeError('field %s was a list, but the first element had '
'unknown type %s' % key, type(value[0])) |
telemetryHelper.ts | import * as vscode from 'vscode';
import * as telemetryConnect from './telemetryConnect';
let telemetryconnect: telemetryConnect.telemetryConnect = require('../telemetryConnect.json');
// extension telemetry
import TelemetryReporter from 'vscode-extension-telemetry';
const extensionId = 'drewsk.demo-mode';
const extension = vscode.extensions.getExtension(extensionId);
const extensionVersion = extension.packageJSON.version;
const key = telemetryconnect.token;
export class | {
public reporter: TelemetryReporter;
constructor(context:vscode.ExtensionContext) {
this.reporter = new TelemetryReporter(extensionId, extensionVersion, key);
context.subscriptions.push(this.reporter);
}
public sendTelemetry(eventName:string, stringObj:any, numericObj:any) {
var theSettings = vscode.workspace.getConfiguration();
if ( theSettings.get('demomode.telemetry') && theSettings.get('telemetry.enableTelemetry') ) {
this.reporter.sendTelemetryEvent(eventName, stringObj, numericObj);
}
}
} | telemetryHelper |
test_models.py | import pytest
from google_auth.users.models import User
pytestmark = pytest.mark.django_db
def test_user_get_absolute_url(user: User):
| assert user.get_absolute_url() == f"/users/{user.username}/" |
|
index.d.ts | declare module 'input-event'; |
||
certificates.py | # Copyright 2018 VMware, Inc. 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 vmware_nsx.shell.admin.plugins.common import constants
from vmware_nsx.shell.admin.plugins.common import utils as admin_utils
from vmware_nsx.shell.admin.plugins.common import v3_common_cert
from vmware_nsx.shell import resources as shell
from neutron_lib.callbacks import registry
from oslo_config import cfg
@admin_utils.output_header
def generate_cert(resource, event, trigger, **kwargs):
"""Generate self signed client certificate and private key
"""
return v3_common_cert.generate_cert(cfg.CONF.nsx_p, **kwargs)
@admin_utils.output_header
def | (resource, event, trigger, **kwargs):
"""Delete client certificate and private key """
return v3_common_cert.delete_cert(cfg.CONF.nsx_p, **kwargs)
@admin_utils.output_header
def show_cert(resource, event, trigger, **kwargs):
"""Show client certificate details """
return v3_common_cert.show_cert(cfg.CONF.nsx_p, **kwargs)
@admin_utils.output_header
def import_cert(resource, event, trigger, **kwargs):
"""Import client certificate that was generated externally"""
return v3_common_cert.import_cert(cfg.CONF.nsx_p, **kwargs)
@admin_utils.output_header
def show_nsx_certs(resource, event, trigger, **kwargs):
"""Show client certificates associated with openstack identity in NSX"""
return v3_common_cert.show_nsx_certs(cfg.CONF.nsx_p, **kwargs)
registry.subscribe(generate_cert,
constants.CERTIFICATE,
shell.Operations.GENERATE.value)
registry.subscribe(show_cert,
constants.CERTIFICATE,
shell.Operations.SHOW.value)
registry.subscribe(delete_cert,
constants.CERTIFICATE,
shell.Operations.CLEAN.value)
registry.subscribe(import_cert,
constants.CERTIFICATE,
shell.Operations.IMPORT.value)
registry.subscribe(show_nsx_certs,
constants.CERTIFICATE,
shell.Operations.NSX_LIST.value)
| delete_cert |
lib.rs | // This file is part of Bit.Country.
// Copyright (C) 2020-2021 Bit.Country.
// SPDX-License-Identifier: Apache-2.0
// 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.
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::unused_unit)]
use codec::{Decode, Encode};
use frame_support::{dispatch::DispatchResult, ensure, traits::Get, PalletId};
use frame_system::{self as system, ensure_root, ensure_signed};
use primitives::{continuum::Continuum, Balance, CurrencyId, ItemId, MetaverseId, SpotId};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};
use sp_runtime::{
traits::{AccountIdConversion, CheckedAdd, CheckedDiv, One, Zero},
DispatchError, FixedPointNumber, RuntimeDebug,
};
use sp_std::vec;
use sp_std::vec::Vec;
use auction_manager::{Auction, AuctionType, CheckAuctionItemHandler, ListingLevel};
use bc_primitives::{MetaverseInfo, MetaverseTrait};
use frame_support::traits::{Currency, LockableCurrency, ReservableCurrency};
use sp_arithmetic::Perbill;
// use crate::pallet::{Config, Pallet, ActiveAuctionSlots};
#[cfg(feature = "std")]
use frame_support::traits::GenesisBuild;
mod types;
mod vote;
pub use types::*;
pub use vote::*;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
pub use pallet::*;
#[derive(Encode, Decode, Copy, Clone, PartialEq, Eq, RuntimeDebug)]
pub enum ContinuumAuctionSlotStatus {
/// Accept participation
AcceptParticipates,
/// Progressing at Good Neighborhood Protocol
GNPStarted,
/// Auction confirmed
GNPConfirmed,
}
/// Information of EOI on Continuum spot
#[cfg_attr(feature = "std", derive(PartialEq, Eq))]
#[derive(Encode, Decode, Clone, RuntimeDebug)]
pub struct SpotEOI<AccountId> {
spot_id: SpotId,
participants: Vec<AccountId>,
}
/// Information of an active auction slot
#[cfg_attr(feature = "std", derive(PartialEq, Eq))]
#[derive(Encode, Decode, Clone, RuntimeDebug)]
pub struct AuctionSlot<BlockNumber, AccountId> {
spot_id: SpotId,
participants: Vec<AccountId>,
active_session_index: BlockNumber,
status: ContinuumAuctionSlotStatus,
}
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::traits::ExistenceRequirement;
use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*};
use frame_system::pallet_prelude::OriginFor;
pub(crate) type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
/// Configure the pallet by specifying the parameters and types on which it depends.
#[pallet::config]
pub trait Config: frame_system::Config {
/// Because this pallet emits events, it depends on the runtime's definition of an event.
type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;
/// New Slot Duration
/// How long the new auction slot will be released. If set to zero, no new auctions are
/// generated
type SessionDuration: Get<Self::BlockNumber>;
/// Auction Slot Chilling Duration
/// How long the participates in the New Auction Slots will get confirmed by neighbours
type SpotAuctionChillingDuration: Get<Self::BlockNumber>;
/// Emergency shutdown origin which allow cancellation in an emergency
type EmergencyOrigin: EnsureOrigin<Self::Origin>;
/// Auction Handler
type AuctionHandler: Auction<Self::AccountId, Self::BlockNumber> + CheckAuctionItemHandler;
/// Auction duration
type AuctionDuration: Get<Self::BlockNumber>;
/// Continuum Treasury
type ContinuumTreasury: Get<PalletId>;
/// Currency
type Currency: ReservableCurrency<Self::AccountId>
+ LockableCurrency<Self::AccountId, Moment = Self::BlockNumber>;
/// Source of Metaverse Network Info
type MetaverseInfoSource: MetaverseTrait<Self::AccountId>;
}
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub initial_active_session: T::BlockNumber,
pub initial_auction_rate: u8,
pub initial_max_bound: (i32, i32),
pub spot_price: BalanceOf<T>,
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
GenesisConfig {
initial_active_session: Default::default(),
initial_auction_rate: Default::default(),
initial_max_bound: Default::default(),
spot_price: Default::default(),
}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
CurrentIndex::<T>::set(self.initial_active_session);
MaxDesiredAuctionSlot::<T>::set(self.initial_auction_rate);
let eoi_slots: Vec<SpotEOI<T::AccountId>> = vec![];
let gnp_slots: Vec<AuctionSlot<T::BlockNumber, T::AccountId>> = vec![];
let active_auction_slots: Vec<AuctionSlot<T::BlockNumber, T::AccountId>> = vec![];
EOISlots::<T>::insert(self.initial_active_session, eoi_slots);
GNPSlots::<T>::insert(self.initial_active_session, gnp_slots);
ActiveAuctionSlots::<T>::insert(self.initial_active_session, active_auction_slots);
MaxBound::<T>::set(self.initial_max_bound);
SpotPrice::<T>::set(self.spot_price);
}
}
#[pallet::pallet]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::hooks]
impl<T: Config> Hooks<T::BlockNumber> for Pallet<T> {
/// Initialization
fn on_initialize(now: T::BlockNumber) -> Weight {
let auction_duration: T::BlockNumber = T::SessionDuration::get();
if !auction_duration.is_zero() && (now % auction_duration).is_zero() {
Self::rotate_auction_slots(now);
T::BlockWeights::get().max_block
} else {
0
}
}
}
/// Get current active session
#[pallet::storage]
#[pallet::getter(fn current_session)]
pub type CurrentIndex<T: Config> = StorageValue<_, T::BlockNumber, ValueQuery>;
/// Continuum Spot
#[pallet::storage]
#[pallet::getter(fn get_continuum_spot)]
pub type ContinuumSpots<T: Config> = StorageMap<_, Twox64Concat, SpotId, ContinuumSpot, OptionQuery>;
/// Continuum Spot Position
#[pallet::storage]
#[pallet::getter(fn get_continuum_position)]
pub type ContinuumCoordinates<T: Config> = StorageMap<_, Twox64Concat, (i32, i32), SpotId, OptionQuery>;
/// Active Auction Slots of current session index that accepting participants
#[pallet::storage]
#[pallet::getter(fn get_active_auction_slots)]
pub type ActiveAuctionSlots<T: Config> =
StorageMap<_, Twox64Concat, T::BlockNumber, Vec<AuctionSlot<T::BlockNumber, T::AccountId>>, OptionQuery>;
/// Active Auction Slots that is currently conducting GN Protocol
#[pallet::storage]
#[pallet::getter(fn get_active_gnp_slots)]
pub type GNPSlots<T: Config> =
StorageMap<_, Twox64Concat, T::BlockNumber, Vec<AuctionSlot<T::BlockNumber, T::AccountId>>, OptionQuery>;
/// Active set of EOI on Continuum Spot
#[pallet::storage]
#[pallet::getter(fn get_eoi_set)]
pub type EOISlots<T: Config> = StorageMap<_, Twox64Concat, T::BlockNumber, Vec<SpotEOI<T::AccountId>>, ValueQuery>;
/// Information of Continuum Spot Referendum
#[pallet::storage]
#[pallet::getter(fn get_continuum_referendum)]
pub type ReferendumInfoOf<T: Config> =
StorageMap<_, Twox64Concat, SpotId, ReferendumInfo<T::AccountId, T::BlockNumber>, OptionQuery>;
/// All votes of a particular voter
#[pallet::storage]
#[pallet::getter(fn get_voting_info)]
pub type VotingOf<T: Config> = StorageMap<_, Twox64Concat, T::AccountId, Voting<T::AccountId>, ValueQuery>;
/// Get max bound
#[pallet::storage]
#[pallet::getter(fn get_max_bound)]
pub type MaxBound<T: Config> = StorageValue<_, (i32, i32), ValueQuery>;
/// Record of all spot ids voting that in an emergency shut down
#[pallet::storage]
#[pallet::getter(fn get_cancellations)]
pub type Cancellations<T: Config> = StorageMap<_, Twox64Concat, SpotId, bool, ValueQuery>;
/// Maximum desired auction slots available per term
#[pallet::storage]
#[pallet::getter(fn get_max_desired_slot)]
pub type MaxDesiredAuctionSlot<T: Config> = StorageValue<_, u8, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn next_spot_id)]
pub type NextContinuumSpotId<T: Config> = StorageValue<_, SpotId, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn allow_buy_now)]
pub type AllowBuyNow<T: Config> = StorageValue<_, bool, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn initial_spot_price)]
pub type SpotPrice<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;
#[pallet::event]
#[pallet::generate_deposit(pub (crate) fn deposit_event)]
pub enum Event<T: Config> {
/// New express of interest
NewExpressOfInterestAdded(T::AccountId, SpotId),
}
#[pallet::error]
pub enum Error<T> {
/// No Active Auction Slot
NoActiveAuctionSlot,
/// No Active GNP List
NoActiveGNP,
/// Can't add EOI to Slot
FailedEOIToSlot,
/// Only send EOI once
EOIAlreadyExists,
/// No Active Session
NoActiveSession,
/// No Active Referendum
NoActiveReferendum,
/// Referendum is invalid
ReferendumIsInValid,
/// Tally Overflow
TallyOverflow,
/// Already shutdown
AlreadyShutdown,
/// Spot Not Found
SpotNotFound,
/// No permission
NoPermission,
/// Spot Owned
SpotIsNotAvailable,
/// Spot is out of bound
SpotIsOutOfBound,
/// Continuum Spot is not found
ContinuumSpotNotFound,
/// Insufficient fund to buy
InsufficientFund,
/// Continuum Buynow is disable
ContinuumBuyNowIsDisabled,
/// Continuum Spot is in auction
SpotIsInAuction,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
pub fn buy_continuum_spot(
origin: OriginFor<T>,
coordinate: (i32, i32),
metaverse_id: MetaverseId,
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
ensure!(
T::MetaverseInfoSource::check_ownership(&sender, &metaverse_id),
Error::<T>::NoPermission
);
ensure!(AllowBuyNow::<T>::get() == true, Error::<T>::ContinuumBuyNowIsDisabled);
let spot_from_coordinates = ContinuumCoordinates::<T>::get(coordinate);
let spot_id = Self::check_spot_ownership(spot_from_coordinates, coordinate)?;
let continuum_price_spot = SpotPrice::<T>::get();
let continuum_treasury = Self::account_id();
//Define how many NUUM for continuum spot - default 1 NUUM - need to change to variable
ensure!(
T::Currency::free_balance(&sender) > continuum_price_spot,
Error::<T>::InsufficientFund
);
T::Currency::transfer(
&sender,
&continuum_treasury,
continuum_price_spot,
ExistenceRequirement::KeepAlive,
)?;
Self::do_transfer_spot(spot_id, &continuum_treasury, &(sender, metaverse_id))?;
Ok(().into())
}
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
pub fn set_allow_buy_now(origin: OriginFor<T>, enable: bool) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
AllowBuyNow::<T>::set(enable);
Ok(().into())
}
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
pub fn register_interest(
origin: OriginFor<T>,
metaverse_id: MetaverseId,
coordinate: (i32, i32),
) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
ensure!(
T::MetaverseInfoSource::check_ownership(&sender, &metaverse_id),
Error::<T>::NoPermission
);
let spot_from_coordinates = ContinuumCoordinates::<T>::get(coordinate);
let spot_id = Self::check_spot_ownership(spot_from_coordinates, coordinate)?;
/// Get current active session
let current_active_session_id = CurrentIndex::<T>::get();
if EOISlots::<T>::contains_key(current_active_session_id) {
/// Mutate current active EOI Slot session
EOISlots::<T>::try_mutate(current_active_session_id, |spot_eoi| -> DispatchResult {
/// Check if the interested Spot exists
let interested_spot_index: Option<usize> = spot_eoi.iter().position(|x| x.spot_id == spot_id);
match interested_spot_index {
/// Already got participants
Some(index) => {
/// Works on existing eoi index
let interested_spot = spot_eoi.get_mut(index).ok_or("No Spot EOI exist")?;
interested_spot.participants.push(sender.clone());
}
/// No participants - add one
None => {
/// No spot found - first one in EOI
let mut new_list: Vec<T::AccountId> = Vec::new();
new_list.push(sender.clone());
let _spot_eoi = SpotEOI {
spot_id,
participants: new_list,
};
spot_eoi.push(_spot_eoi);
}
}
Ok(())
})?;
} else {
/// Never get to this logic but it's safe to handle it nicely.
let mut eoi_slots: Vec<SpotEOI<T::AccountId>> = Vec::new();
eoi_slots.push(SpotEOI {
spot_id,
participants: vec![sender.clone()],
});
EOISlots::<T>::insert(current_active_session_id, eoi_slots);
}
Self::deposit_event(Event::NewExpressOfInterestAdded(sender, spot_id));
Ok(().into())
}
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
pub fn enable_bidder_rejection_voting(origin: OriginFor<T>, spot_id: SpotId) -> DispatchResultWithPostInfo {
let root = ensure_root(origin);
//TODO Check if neighborhood
//Enable democracy pallet
//Propose bidder removal action on democracy
Ok(().into())
}
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
pub fn set_max_bounds(origin: OriginFor<T>, new_bound: (i32, i32)) -> DispatchResultWithPostInfo {
/// Only execute by governance
ensure_root(origin)?;
MaxBound::<T>::set(new_bound);
//TODO Emit event
Ok(().into())
}
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
pub fn set_new_auction_rate(origin: OriginFor<T>, new_rate: u8) -> DispatchResultWithPostInfo {
ensure_root(origin)?;
MaxDesiredAuctionSlot::<T>::set(new_rate);
//TODO Emit event
Ok(().into())
}
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
pub fn vote(origin: OriginFor<T>, id: SpotId, reject: AccountVote<T::AccountId>) -> DispatchResultWithPostInfo {
let sender = ensure_signed(origin)?;
Self::try_vote(&sender, id, reject)?;
Ok(().into())
}
#[pallet::weight(10_000 + T::DbWeight::get().writes(1))]
pub fn emergency_shutdown(origin: OriginFor<T>, spot_id: SpotId) -> DispatchResultWithPostInfo {
// Only some origins can execute this function
T::EmergencyOrigin::ensure_origin(origin)?;
ensure!(!Cancellations::<T>::contains_key(spot_id), Error::<T>::AlreadyShutdown);
Cancellations::<T>::insert(spot_id, true);
ReferendumInfoOf::<T>::remove(spot_id);
Ok(().into())
}
}
}
impl<T: Config> Pallet<T> {
fn account_id() -> T::AccountId {
T::ContinuumTreasury::get().into_account()
}
//noinspection ALL
fn rotate_auction_slots(now: T::BlockNumber) -> DispatchResult {
// Get current active session
let current_active_session_id = CurrentIndex::<T>::get();
// Change status of all current active auction slots
// Move EOI to Auction Slots
Self::eoi_to_auction_slots(current_active_session_id, now)?;
// Finalise due vote
Self::finalize_vote(now);
let mut active_auction_slots = <ActiveAuctionSlots<T>>::get(¤t_active_session_id);
match active_auction_slots {
Some(s) => {
// Move current auctions slot to start GN Protocol
if s.len() > 0 {
let started_gnp_auction_slots: Vec<_> = s
.iter()
.map(|x| {
let mut t = x.clone();
t.status = ContinuumAuctionSlotStatus::GNPStarted;
t
})
.collect();
// Move active auction slots to GNP
GNPSlots::<T>::insert(now, started_gnp_auction_slots.clone());
// Start referedum
Self::start_gnp_protocol(started_gnp_auction_slots, now)?;
}
// TODO Emit event Auction slot start GNP
}
None => {}
}
// Remove the old active auction slots
ActiveAuctionSlots::<T>::remove(¤t_active_session_id);
CurrentIndex::<T>::set(now);
// TODO Emit event
Ok(().into())
}
fn finalize_vote(now: T::BlockNumber) -> DispatchResult {
let recent_slots = GNPSlots::<T>::get(now).ok_or(Error::<T>::NoActiveReferendum)?;
for mut recent_slot in recent_slots.into_iter() {
let referendum_info: ReferendumStatus<T::AccountId, T::BlockNumber> =
Self::referendum_status(recent_slot.spot_id)?;
if referendum_info.end == now {
// let tallies = referendum_info.tallies;
let banned_list: Vec<T::AccountId> = referendum_info
.tallies
.into_iter()
.filter(|mut t| Self::check_approved(t) == true)
.map(|tally| tally.who)
.collect();
for banned_account in banned_list {
let account_index = recent_slot
.participants
.iter()
.position(|x| *x == banned_account)
.unwrap();
recent_slot.participants.remove(account_index);
recent_slot.status = ContinuumAuctionSlotStatus::GNPConfirmed;
}
let treasury = Self::account_id();
// From treasury spot
T::AuctionHandler::create_auction(
AuctionType::Auction,
ItemId::Spot(recent_slot.spot_id, Default::default()),
Some(now + T::AuctionDuration::get()),
treasury,
Default::default(),
now,
ListingLevel::Global,
);
// TODO Emit event
}
}
Ok(())
}
fn start_gnp_protocol(
slots: Vec<AuctionSlot<T::BlockNumber, T::AccountId>>,
end: T::BlockNumber,
) -> DispatchResult {
for slot in slots {
let end = end + T::SessionDuration::get();
Self::start_referendum(end, slot.spot_id)?;
// TODO Emit event
}
Ok(())
}
fn start_referendum(end: T::BlockNumber, spot_id: SpotId) -> Result<SpotId, DispatchError> {
let spot = ContinuumSpots::<T>::get(spot_id).ok_or(Error::<T>::SpotNotFound)?;
let neighbors = spot.find_neighbour();
let mut available_neighbors: u8 = 0;
for (x, y) in neighbors {
match ContinuumCoordinates::<T>::get((x, y)) {
Some(i) => {
available_neighbors = available_neighbors.checked_add(One::one()).ok_or("Overflow")?;
}
_ => (),
}
}
let mut status: ReferendumStatus<T::AccountId, T::BlockNumber> = ReferendumStatus {
end,
spot_id,
tallies: Default::default(),
};
for _i in 0..available_neighbors {
let initial_tally: ContinuumSpotTally<T::AccountId> = ContinuumSpotTally {
nays: One::one(),
who: Default::default(),
turnout: available_neighbors,
};
status.tallies.push(initial_tally);
}
let item: ReferendumInfo<T::AccountId, T::BlockNumber> = ReferendumInfo::Ongoing(status);
ReferendumInfoOf::<T>::insert(spot_id, item);
// TODO Emit event
Ok(spot_id)
}
fn eoi_to_auction_slots(active_session: T::BlockNumber, now: T::BlockNumber) -> DispatchResult {
// Get maximum desired slots
let desired_slots = MaxDesiredAuctionSlot::<T>::get();
let session_duration = T::SessionDuration::get();
// Get active EOI and add the top N to new Auction Slots
let mut current_eoi_slots: Vec<SpotEOI<T::AccountId>> = EOISlots::<T>::get(active_session);
current_eoi_slots.sort_by_key(|eoi_slot| eoi_slot.participants.len());
// Get highest ranked slot
let mut new_valid_auction_slot: Vec<AuctionSlot<T::BlockNumber, T::AccountId>> = Vec::new();
let highest_ranked_sorted: Vec<SpotEOI<T::AccountId>> = current_eoi_slots
.iter()
.map(|x| x.clone())
.take(desired_slots as usize)
.collect::<Vec<SpotEOI<T::AccountId>>>();
// Add highest ranked EOI to New Active Auction slot
for (x, item) in highest_ranked_sorted.iter().enumerate() {
let auction_slot = AuctionSlot {
spot_id: item.spot_id,
participants: item.participants.clone(),
active_session_index: now + session_duration,
status: ContinuumAuctionSlotStatus::AcceptParticipates,
};
new_valid_auction_slot.push(auction_slot);
}
ActiveAuctionSlots::<T>::insert(now, new_valid_auction_slot);
// Remove EOISlot
EOISlots::<T>::remove(active_session);
let empty_eoi_spots: Vec<SpotEOI<T::AccountId>> = Vec::new();
// Add new EOISlot for current session - ensure active session has entry
EOISlots::<T>::insert(now, empty_eoi_spots);
// TODO Emit event
Ok(())
}
fn try_vote(who: &T::AccountId, spot_id: SpotId, vote: AccountVote<T::AccountId>) -> DispatchResult {
// TODO ensure is actual neighbor once metaverse trait is completed
let mut status = Self::referendum_status(spot_id)?;
VotingOf::<T>::try_mutate(who, |mut voting| -> DispatchResult {
let mut votes = &mut voting.votes;
match votes.binary_search_by_key(&spot_id, |i| i.0) {
// Already voted
Ok(i) => {}
Err(i) => {
// Haven't vote for this spot id
// Add votes under user
let new_vote: AccountVote<T::AccountId> = vote.clone();
let who = new_vote.vote_who();
votes.insert(i, (spot_id, vote.clone()));
let mut tallies = status.tallies.clone();
// Find existing tally of bidder
for mut tally in status.tallies {
// Existing vote
if tally.who == who.who {
tally.add(vote.clone()).ok_or(Error::<T>::TallyOverflow)?
} else {
//Create new vote
}
}
}
}
Ok(())
})
}
fn referendum_status(spot_id: SpotId) -> Result<ReferendumStatus<T::AccountId, T::BlockNumber>, DispatchError> {
let info = ReferendumInfoOf::<T>::get(spot_id).ok_or(Error::<T>::ReferendumIsInValid)?;
Self::ensure_ongoing(info.into())
}
fn referendum_info(spot_id: SpotId) -> Result<ReferendumInfo<T::AccountId, T::BlockNumber>, DispatchError> {
let info = ReferendumInfoOf::<T>::get(spot_id).ok_or(Error::<T>::ReferendumIsInValid.into());
info
}
/// Ok if the given referendum is active, Err otherwise
fn ensure_ongoing(
r: ReferendumInfo<T::AccountId, T::BlockNumber>,
) -> Result<ReferendumStatus<T::AccountId, T::BlockNumber>, DispatchError> {
match r {
ReferendumInfo::Ongoing(s) => Ok(s),
_ => Err(Error::<T>::ReferendumIsInValid.into()),
}
}
fn do_register(who: &T::AccountId, spot_id: &SpotId) -> SpotId {
return 5;
}
fn get_spot(spot_id: SpotId) -> Result<ContinuumSpot, DispatchError> |
fn do_transfer_spot(
spot_id: SpotId,
from: &T::AccountId,
to: &(T::AccountId, MetaverseId),
) -> Result<SpotId, DispatchError> {
Self::transfer_spot(spot_id, from, to)
}
fn check_approved(tally: &ContinuumSpotTally<T::AccountId>) -> bool {
let nay_ratio = tally.turnout.checked_div(tally.nays).unwrap_or(0);
let nay_percent = nay_ratio.checked_mul(100).unwrap_or(0);
nay_percent > 51
}
fn check_spot_ownership(spot_id: Option<SpotId>, coordinate: (i32, i32)) -> Result<SpotId, DispatchError> {
match spot_id {
None => {
// Insert continuum spot as it's empty
let max_bound = MaxBound::<T>::get();
ensure!(
(coordinate.0 >= max_bound.0 && max_bound.1 >= coordinate.0)
&& (coordinate.1 >= max_bound.0 && max_bound.1 >= coordinate.1),
Error::<T>::SpotIsOutOfBound
);
let spot = ContinuumSpot {
x: coordinate.0,
y: coordinate.1,
country: 0,
};
let next_spot_id = NextContinuumSpotId::<T>::try_mutate(|id| -> Result<SpotId, DispatchError> {
let current_id = *id;
*id = id.checked_add(One::one()).ok_or(Error::<T>::SpotIsNotAvailable)?;
Ok(current_id)
})?;
ContinuumSpots::<T>::insert(next_spot_id, spot);
ContinuumCoordinates::<T>::insert(coordinate, next_spot_id);
Ok(next_spot_id)
}
Some(spot_id) => {
let spot = ContinuumSpots::<T>::get(spot_id).ok_or(Error::<T>::SpotNotFound)?;
ensure!(spot.country == 0, Error::<T>::SpotIsNotAvailable);
Ok(spot_id)
}
}
}
}
impl<T: Config> Continuum<T::AccountId> for Pallet<T> {
fn transfer_spot(
spot_id: SpotId,
from: &T::AccountId,
to: &(T::AccountId, MetaverseId),
) -> Result<SpotId, DispatchError> {
ensure!(
!T::AuctionHandler::check_item_in_auction(ItemId::Spot(spot_id, to.1.clone())),
Error::<T>::SpotIsInAuction
);
ContinuumSpots::<T>::try_mutate(spot_id, |maybe_spot| -> Result<SpotId, DispatchError> {
let treasury = Self::account_id();
if *from != treasury {
// TODO Check account Id own country spot.country
}
let mut spot = maybe_spot.take().ok_or(Error::<T>::SpotNotFound)?;
spot.country = to.1;
Ok(spot_id)
})
}
}
| {
ContinuumSpots::<T>::get(spot_id).ok_or(Error::<T>::SpotNotFound.into())
} |
suite.ts | /* tslint:disable */
/* eslint-disable */
/**
* Qase.io API
* Qase API Specification.
*
* The version of the OpenAPI document: 1.0.0
* Contact: [email protected]
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/ | *
* @export
* @interface Suite
*/
export interface Suite {
/**
*
* @type {number}
* @memberof Suite
*/
'id'?: number;
/**
*
* @type {string}
* @memberof Suite
*/
'title'?: string;
/**
*
* @type {string}
* @memberof Suite
*/
'description'?: string;
/**
*
* @type {string}
* @memberof Suite
*/
'preconditions'?: string;
/**
*
* @type {number}
* @memberof Suite
*/
'position'?: number;
/**
*
* @type {number}
* @memberof Suite
*/
'cases_count'?: number;
/**
*
* @type {number}
* @memberof Suite
*/
'parent_id'?: number | null;
/**
*
* @type {string}
* @memberof Suite
*/
'created'?: string;
/**
*
* @type {string}
* @memberof Suite
*/
'updated'?: string | null;
} |
/** |
idsextractor_jwt.go | // Copyright (c) 2018 Palantir Technologies. 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.
package extractor
import (
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/satori/go.uuid"
)
const (
UIDKey = "uid"
SIDKey = "sid"
TokenIDKey = "tokenId"
)
// newIDsFromJWTExtractor creates an extractor that sets the UIDKey, SIDKey and TokenIDKey keys to have the values
// parsed from the JWT used as the bearer token in the "Authorization" header of the request. The JWT's "sub" field is
// used as the UID, the "sid" field is used as the SID and the "jti" field is used as the tokenID.
func newIDsFromJWTExtractor() IDsFromRequest {
return &jwtRequestIDsExtractor{}
}
type jwtRequestIDsExtractor struct{}
func (e *jwtRequestIDsExtractor) ExtractIDs(req *http.Request) map[string]string {
const bearerTokenPrefix = "Bearer "
var uid, sid, tokenID string
authContent := req.Header.Get("Authorization")
if strings.HasPrefix(authContent, bearerTokenPrefix) {
uid, sid, tokenID, _ = idsFromJWT(authContent[len(bearerTokenPrefix):])
}
return map[string]string{
UIDKey: uid,
SIDKey: sid,
TokenIDKey: tokenID,
}
}
// idsFromJWT returns the uid, sid and tokenID in the provided JWT. Note that signature verification is not performed on
// the JWT, so the returned values should not be considered secure or used for security purposes. However, the values
// are considered acceptable for use in logging.
func idsFromJWT(jwtContent string) (uid string, sid string, tokenID string, err error) {
parts := strings.Split(jwtContent, ".")
if len(parts) != 3 |
bytes, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return "", "", "", fmt.Errorf("failed to decode JWT content %q as Base64 URL-encoded string: %v", parts[1], err)
}
var jsonMap map[string]interface{}
if err := json.Unmarshal(bytes, &jsonMap); err != nil {
return "", "", "", fmt.Errorf("failed to decode JWT content %s as JSON: %v", string(bytes), err)
}
// "sub" = "subject" field, which is used as the UID
uid = getMapUUIDStringVal(jsonMap, "sub")
// "sid" is used to store the session ID
sid = getMapUUIDStringVal(jsonMap, "sid")
// "jti" is used to store the token ID
tokenID = getMapUUIDStringVal(jsonMap, "jti")
return uid, sid, tokenID, nil
}
func getMapUUIDStringVal(m map[string]interface{}, key string) string {
val, ok := m[key]
if !ok {
return ""
}
str, ok := val.(string)
if !ok {
return ""
}
rawBytes, err := base64.StdEncoding.DecodeString(str)
if err != nil {
// if string was not Base64-encoded, return original raw string
return str
}
id, err := uuid.FromBytes(rawBytes)
if err != nil {
// if Base64-decoded bytes did not represent a UUID, return original raw string
return str
}
// success: return string representation of UUID
return id.String()
}
| {
return "", "", "", fmt.Errorf("JWT must have 3 '.'-separated parts, but had %d: %q", len(parts), jwtContent)
} |
inkscape_control.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import paste
import subprocess
from multiprocessing import Process
from pathlib import Path
import tkinter.messagebox as messagebox
from shutil import copy
from appdirs import user_config_dir
import logging as log
from globe import Globe as globe
from util import StrUtil as strutil
import workspace
SYSTEM = globe.SYSTEM
if SYSTEM == "Darwin":
from pynput import keyboard
elif SYSTEM == "Windows":
import keyboard
import mouse as w_mouse
user_dir = Path(user_config_dir("project", "ww"))
if not user_dir.is_dir():
user_dir.mkdir(parents=True)
roots_file = user_dir / 'roots'
template = user_dir / 'template.svg'
config = user_dir / 'config.py'
if not template.is_file():
source = str(Path(__file__).parent / 'template.svg')
destination = str(template)
copy(source, destination)
def inkscape(path):
log.info("Inkscape function started")
#
# def for_canonical(f):
# log.info("for_canonical")
# return lambda k: f(l.canonical(k))
# hotkey = keyboard.HotKey(
# keyboard.HotKey.parse('<cmd>+u'),
# on_activate)
if SYSTEM == "Darwin":
processOpen = subprocess.Popen(['/Applications/Inkscape.app/Contents/MacOS/inkscape', str(path)])
log.info("Opening file")
elif SYSTEM == "Windows":
processOpen = subprocess.Popen(['inkscape', str(path)])
log.info("Opening file")
# with keyboard.GlobalHotKeys({'<cmd>+i': paste.open_vim}) as hotkey:
# hotkey.join()
# l = keyboard.Listener(
# on_press=for_canonical(hotkey.press),
# on_release=for_canonical(hotkey.release),
# # suppress=True
# )
# l.start()
processOpen.wait()
log.info("Inkscape terminated")
if SYSTEM == "Darwin":
version = os.popen('/Applications/Inkscape.app/Contents/MacOS/inkscape --version').readlines()
if '4035a4f' not in str(version):
messagebox.showinfo('警告!', 'inkscape版本可能不兼容!导致并没有生成latex能识别的文件,请检查是否为1.0 (4035a4f, 2020-05-01)')
inkscape_name = '/Applications/Inkscape.app/Contents/MacOS/inkscape'
subprocess.Popen([inkscape_name, str(path), '-o', str(path.with_suffix(".pdf")), '--export-latex'])
#else:
#os.system('/Applications/Inkscape.app/Contents/MacOS/inkscape '+ str(path)+ ' --export-file='+str(path.with_suffix(".pdf"))+' --export-latex')
elif SYSTEM == "Windows":
subprocess.Popen(['inkscape', str(path), '-o', str(path.with_suffix(".pdf")), '--export-latex'])
log.info("Export to pdf_tex process and InkscapeProcess terminated")
def create(factor):
# """
# Creates a figure.
# First | ent is the title of the figure
# Second argument is the figure directory.
# """
# title = title.strip()
# file_name = title.replace(' ', '-').lower() + '.svg'
# figures = root + os.path.sep + 'figures'+os.path.sep
# figure_path = figures + file_name
# # If a file with this name already exists, append a '2'.
# if Path(figure_path).exists():
# title = title + '-2'
# create(title,root)
# else:
# figure_path = Path(figure_path).absolute()
# inkscape(figure_path)
"""
Creates a figure.
First argument is the title of the figure
Second argument is the figure directory.
"""
workspace.sub('figures')
log.debug("File name without extension " + factor['fileName'])
file_fullname = factor['fileName'] + '.svg'
log.debug("File name " + file_fullname)
figures_dir = Path(globe.workspace['sub']['figures'])
figure_path = figures_dir / file_fullname
# If a file with this name already exists, quit
#TODO: 查重工作应该放在paste中完成,也许可以将功能封装,放在util里
if figure_path.exists():
log.warning("{} already exists. Edit but not create.".format(str(figure_path)))
else:
copy(str(template), str(figure_path))
log.info("Template copied")
log.info("Starting Inkscape")
process_inkscape = Process(target=inkscape, args=(figure_path,))
process_inkscape.start()
return
| argum |
compression.rs | use cratesfyi::storage::{compress, decompress, CompressionAlgorithm};
use criterion::{black_box, criterion_group, criterion_main, Criterion};
const ALGORITHM: CompressionAlgorithm = CompressionAlgorithm::Zstd;
pub fn criterion_benchmark(c: &mut Criterion) |
criterion_group!(compression, criterion_benchmark);
criterion_main!(compression);
| {
// this isn't a great benchmark because it only tests on one file
// ideally we would build a whole crate and compress each file, taking the average
let html = std::fs::read_to_string("benches/struct.CaptureMatches.html").unwrap();
let html_slice = html.as_bytes();
c.bench_function("compress regex html", |b| {
b.iter(|| compress(black_box(html_slice, ALGORITHM)))
});
let compressed = compress(html_slice, ALGORITHM).unwrap();
c.bench_function("decompress regex html", |b| {
b.iter(|| decompress(black_box(compressed.as_slice()), ALGORITHM))
});
} |
volunteercontrol.go | package volunteercontrol
import (
"math"
"fmt"
"github.com/DCNT-developer/dcnt/electionsCore/messages"
. "github.com/DCNT-developer/dcnt/electionsCore/primitives"
)
var _ = fmt.Println
// VolunteerControl will keep a record of all votes
// for a given volunteer and produce the best vote
// possible.
type VolunteerControl struct {
AuthSet
Self Identity
Volunteer *messages.VolunteerMessage
Votes map[Identity]messages.LeaderLevelMessage
}
func NewVolunteerControl(self Identity, authset AuthSet) *VolunteerControl {
v := new(VolunteerControl)
v.Votes = make(map[Identity]messages.LeaderLevelMessage)
v.Self = self
v.AuthSet = authset
return v
}
// addVote just adds the vote to the vote map, and will not act upon it
func (v *VolunteerControl) AddVote(msg messages.LeaderLevelMessage) bool {
if v.Volunteer == nil {
v.Volunteer = &msg.VolunteerMessage
}
// If we already have a vote from that leader for this audit, then we only replace ours if this is better
if cur, ok := v.Votes[msg.Signer]; ok {
if cur.Level == msg.Level {
// Same level, same message (we have no malicious actors)
return false
}
if msg.Rank > cur.Rank {
// Greater rank is always better. Replace their current with the new
msg.Justification = nil
v.Votes[msg.Signer] = msg
return true
} else {
return false
}
}
v.Votes[msg.Signer] = msg
// New Vote, if we have more than a majority, delete the lowest vote
// to keep the majority the best majority possible
if len(v.Votes) > v.Majority() {
// Delete the lowest one, we don't need it
lowest := math.MaxInt32
var lowestvote messages.LeaderLevelMessage
lowestvote.Rank = math.MaxInt32
remove := NewIdentityFromInt(-1)
for k, v := range v.Votes {
if v.Level < lowest || (v.Level == lowest && !v.Less(&lowestvote)) {
// If level is lower OR equal and less
lowest = v.Level
remove = k
lowestvote = v
}
}
delete(v.Votes, remove)
}
return true
}
// checkVoteCount will check to see if we have enough votes to issue a ranked message. We will not add
// that message to our votemap, as we may have not chosen to actually send that vote. If we decide to send that
// vote, we will get it sent back to us
// Returns a LeaderLevelMessage with the level set, however it may need adjusting! (Can only adjust it up)
func (v *VolunteerControl) CheckVoteCount() *messages.LeaderLevelMessage {
// No majority, no bueno.
if len(v.Votes) < v.Majority() {
return nil
}
var justification []messages.LeaderLevelMessage
// Majority votes exist, we need to find the lowest level, and use it for our rank.
rank := math.MaxInt32
highestlevel := 0
for _, vote := range v.Votes {
// If vote level is less than current rank, bring down our rank
if vote.Level < rank {
rank = vote.Level
}
if vote.Level > highestlevel {
highestlevel = vote.Level
}
justification = append(justification, vote)
}
// Now we have the lowest level, any message at that level can no longer help us.
// We can only reuse votes at higher levels
for k, vote := range v.Votes {
if vote.Level <= rank {
delete(v.Votes, k)
}
}
llmsg := messages.NewLeaderLevelMessage(v.Self, rank, highestlevel, *v.Volunteer)
llmsg.Justification = justification
return &llmsg | }
func (a *VolunteerControl) Copy() *VolunteerControl {
b := NewVolunteerControl(a.Self, a.AuthSet.Copy())
if a.Volunteer != nil {
v := *a.Volunteer
b.Volunteer = &v
}
for k, v := range a.Votes {
b.Votes[k] = *v.Copy()
}
return b
} | |
stats.py | """
Training Statics Tools
A class for loading statistics related to a particular rutraiining session.
"""
import numpy as np
#from scipy import stats
import pandas as pd
import os
def | (s, start, end):
return (s.split(start))[1].split(end)[0]
def is_stat_file_version(file_name, version):
return file_name.startswith("stats_{}_gen".format(version)) and file_name.endswith(".h5")
class TrainingStates:
def __init__(self, versions, directory, verbose=True):
self.stats_files = self.get_stat_files(versions, directory)
if verbose:
print("Loading files:")
for f in self.stats_files:
print(directory + f)
self.generation_stats = self.load_stats('generation_stats')
self.game_stats = self.load_stats('game_stats')
self.move_stats = self.load_stats('self_play_stats')
def get_stat_files(self, versions, directory):
stat_files = []
for version in reversed(versions):
files = [directory + f for f in os.listdir(directory) if is_stat_file_version(f, version)]
stat_files += list(sorted(files))
return stat_files
def load_stats(self, key_name):
df_list = []
for f in self.stats_files:
path = f
generation = str_between(f, "_gen", ".h5")
df = pd.read_hdf(path, key=key_name)
df['_generation'] = int(generation)
df_list.append(df)
if df_list:
stats = pd.concat(df_list, ignore_index=True)
else:
return pd.DataFrame()
return stats
def first_move_stats(self):
"""
Note: There is an indexing issue (the index of first_play_stats is the orginal index
while the index of game_stats is the game number). The easiest fix is to just use
the values (an array) of the series and not the series itself.
"""
return self.move_stats[self.move_stats['_step_id'] == 0]
def found_target_on_first_move(self):
return (self.first_move_stats()['shortest_path'] >= 0).values
def lost_but_found_target_on_first_move(self):
return self.found_target_on_first_move() & ~self.game_stats['win']
def win_but_did_not_find_target_on_first_move(self):
return ~self.found_target_on_first_move() & self.game_stats['win']
if __name__ == '__main__':
from pprint import pprint
versions = ['v0.9.3']
save_dir = '../save/stats_v0.9.3/'
#VERSIONS = ['v0.9.2.1', 'v0.9.2']
#SAVE_DIR = '../save/stats_archive/'
cube_stats = TrainingStates(versions, save_dir)
pprint(cube_stats.generation_stats)
pprint(np.mean(cube_stats.lost_but_found_target_on_first_move()))
pprint(np.mean(cube_stats.win_but_did_not_find_target_on_first_move()))
| str_between |
crypto.ts | import * as crypto from 'crypto'; | }
}
export default new Crypto(); |
class Crypto {
hash(value: string) {
return crypto.createHash('sha256').update(value).digest('hex'); |
index.js | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.signature = signature;
exports.functionNameMetadata = functionNameMetadata;
exports.localNameMetadata = localNameMetadata;
exports.moduleMetadata = moduleMetadata;
exports.identifier = identifier;
exports.valtype = valtype;
exports.stringLiteral = stringLiteral;
exports.program = program;
exports.module = _module;
exports.sectionMetadata = sectionMetadata;
exports.binaryModule = binaryModule;
exports.quoteModule = quoteModule;
exports.moduleExport = moduleExport;
exports.functionSignature = functionSignature;
exports.func = func;
exports.funcWithTypeRef = funcWithTypeRef;
exports.objectInstruction = objectInstruction;
exports.instruction = instruction;
exports.loopInstruction = loopInstruction;
exports.blockInstruction = blockInstruction;
exports.numberLiteral = numberLiteral;
exports.getUniqueNameGenerator = getUniqueNameGenerator;
exports.callInstruction = callInstruction;
exports.ifInstruction = ifInstruction;
exports.withLoc = withLoc;
exports.withRaw = withRaw;
exports.moduleImport = moduleImport;
exports.globalImportDescr = globalImportDescr;
exports.funcParam = funcParam;
exports.funcImportDescr = funcImportDescr;
exports.table = table;
exports.limits = limits;
exports.memory = memory;
exports.data = data;
exports.global = global;
exports.globalType = globalType;
exports.byteArray = byteArray;
exports.leadingComment = leadingComment;
exports.blockComment = blockComment;
exports.indexLiteral = indexLiteral;
exports.memIndexLiteral = memIndexLiteral;
exports.typeInstructionFunc = typeInstructionFunc;
exports.callIndirectInstruction = callIndirectInstruction;
exports.callIndirectInstructionWithTypeRef = callIndirectInstructionWithTypeRef;
exports.start = start;
exports.elem = elem;
exports.indexInFuncSection = indexInFuncSection;
exports.isAnonymous = isAnonymous;
Object.defineProperty(exports, "traverse", {
enumerable: true,
get: function () {
return _traverse.traverse;
}
});
Object.defineProperty(exports, "traverseWithHooks", {
enumerable: true,
get: function () {
return _traverse.traverseWithHooks;
}
});
Object.defineProperty(exports, "signatures", {
enumerable: true,
get: function () {
return _signatures.signatures;
}
});
Object.defineProperty(exports, "getSectionMetadata", {
enumerable: true,
get: function () {
return _utils.getSectionMetadata;
}
});
Object.defineProperty(exports, "sortSectionMetadata", {
enumerable: true,
get: function () {
return _utils.sortSectionMetadata;
}
});
Object.defineProperty(exports, "cloneNode", {
enumerable: true,
get: function () {
return _clone.cloneNode;
}
});
var _traverse = require("./traverse");
var _signatures = require("./signatures");
var _utils = require("./utils");
var _clone = require("./clone");
function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
var _require = require("@webassemblyjs/wast-parser/lib/number-literals"),
parse32F = _require.parse32F,
parse64F = _require.parse64F,
parse32I = _require.parse32I,
parse64I = _require.parse64I,
parseU32 = _require.parseU32,
isNanLiteral = _require.isNanLiteral,
isInfLiteral = _require.isInfLiteral;
var _require2 = require("./signatures"),
signatures = _require2.signatures;
function assert(cond) {
if (!cond) {
throw new Error("assertion error");
}
}
function signature(object, name) {
var opcodeName = name;
if (object !== undefined && object !== "") {
opcodeName = object + "." + name; |
if (sign == undefined) {
// TODO: Uncomment this when br_table and others has been done
//throw new Error("Invalid opcode: "+opcodeName);
return [object, object];
}
return sign[0];
}
function functionNameMetadata(value, index) {
return {
type: "FunctionNameMetadata",
value: value,
index: index
};
}
function localNameMetadata(value, localIndex, functionIndex) {
return {
type: "LocalNameMetadata",
value: value,
localIndex: localIndex,
functionIndex: functionIndex
};
}
function moduleMetadata(sections, functionNames, localNames) {
var n = {
type: "ModuleMetadata",
sections: sections
};
if (functionNames.length) {
n.functionNames = functionNames;
}
if (localNames.length) {
n.localNames = localNames;
}
return n;
}
function identifier(value) {
return {
type: "Identifier",
value: value
};
}
function valtype(name) {
return {
type: "ValtypeLiteral",
name: name
};
}
function stringLiteral(value) {
return {
type: "StringLiteral",
value: value
};
}
function program(body) {
return {
type: "Program",
body: body
};
}
function _module(id, fields, metadata) {
if (id != null) {
assert(typeof id === "string");
}
assert(_typeof(fields) === "object" && typeof fields.length !== "undefined");
var n = {
type: "Module",
id: id,
fields: fields
};
if (typeof metadata !== "undefined") {
n.metadata = metadata;
}
return n;
}
function sectionMetadata(section, startOffset, size) {
var vectorOfSize = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : numberLiteral(-1);
assert(size.type === "NumberLiteral");
assert(vectorOfSize.type === "NumberLiteral");
return {
type: "SectionMetadata",
section: section,
startOffset: startOffset,
size: size,
vectorOfSize: vectorOfSize
};
}
function binaryModule(id, blob) {
return {
type: "BinaryModule",
blob: blob,
id: id,
fields: []
};
}
function quoteModule(id, string) {
return {
type: "QuoteModule",
string: string,
id: id,
fields: []
};
}
function moduleExport(name, type, id) {
return {
type: "ModuleExport",
name: name,
descr: {
type: type,
id: id
}
};
}
function functionSignature(params, results) {
return {
type: "Signature",
params: params,
results: results
};
}
function func(name, params, results, body) {
assert(_typeof(params) === "object" && typeof params.length !== "undefined");
assert(_typeof(results) === "object" && typeof results.length !== "undefined");
assert(_typeof(body) === "object" && typeof body.length !== "undefined");
assert(typeof name !== "string");
return {
type: "Func",
name: name,
signature: functionSignature(params, results),
body: body
};
}
function funcWithTypeRef(name, typeRef, body) {
assert(_typeof(body) === "object" && typeof body.length !== "undefined");
assert(typeof name !== "string");
return {
type: "Func",
name: name,
signature: typeRef,
body: body
};
}
function objectInstruction(id, object) {
var args = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
var namedArgs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
assert(_typeof(args) === "object" && typeof args.length !== "undefined");
assert(typeof object === "string");
var n = {
type: "Instr",
id: id,
object: object,
args: args
};
if (Object.keys(namedArgs).length !== 0) {
n.namedArgs = namedArgs;
}
return n;
}
function instruction(id) {
var args = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var namedArgs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
assert(_typeof(args) === "object" && typeof args.length !== "undefined");
assert(id !== "block");
assert(id !== "if");
assert(id !== "loop");
var n = {
type: "Instr",
id: id,
args: args
};
if (Object.keys(namedArgs).length !== 0) {
n.namedArgs = namedArgs;
}
return n;
}
function loopInstruction(label, resulttype, instr) {
assert(label !== null);
assert(_typeof(instr) === "object" && typeof instr.length !== "undefined");
return {
type: "LoopInstruction",
id: "loop",
label: label,
resulttype: resulttype,
instr: instr
};
}
function blockInstruction(label, instr, result) {
assert(typeof label !== "undefined");
assert(typeof label.type === "string");
assert(_typeof(instr) === "object" && typeof instr.length !== "undefined");
return {
type: "BlockInstruction",
id: "block",
label: label,
instr: instr,
result: result
};
}
function numberLiteral(rawValue) {
var instructionType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "i32";
var value;
var nan = false;
var inf = false;
var type = "NumberLiteral";
var original = rawValue; // Remove numeric separators _
if (typeof rawValue === "string") {
rawValue = rawValue.replace(/_/g, "");
}
if (typeof rawValue === "number") {
value = rawValue;
} else {
switch (instructionType) {
case "i32":
{
value = parse32I(rawValue);
break;
}
case "u32":
{
value = parseU32(rawValue);
break;
}
case "i64":
{
type = "LongNumberLiteral";
value = parse64I(rawValue);
break;
}
case "f32":
{
type = "FloatLiteral";
value = parse32F(rawValue);
nan = isNanLiteral(rawValue);
inf = isInfLiteral(rawValue);
break;
}
// f64
default:
{
type = "FloatLiteral";
value = parse64F(rawValue);
nan = isNanLiteral(rawValue);
inf = isInfLiteral(rawValue);
break;
}
}
} // This is a hack to avoid rewriting all tests to have a "isnan: false" field
// $FlowIgnore: this is correct, but flow doesn't like mutations like this
var x = {
type: type,
value: value
};
if (nan === true) {
// $FlowIgnore
x.nan = true;
}
if (inf === true) {
// $FlowIgnore
x.inf = true;
}
x.raw = String(original);
return x;
}
function getUniqueNameGenerator() {
var inc = {};
return function () {
var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "temp";
if (!(prefix in inc)) {
inc[prefix] = 0;
} else {
inc[prefix] = inc[prefix] + 1;
}
return prefix + "_" + inc[prefix];
};
}
function callInstruction(index, instrArgs) {
assert(typeof index.type === "string");
var n = {
type: "CallInstruction",
id: "call",
index: index
};
if (_typeof(instrArgs) === "object") {
n.instrArgs = instrArgs;
}
return n;
}
function ifInstruction(testLabel, result, test, consequent, alternate) {
assert(typeof testLabel.type === "string");
return {
type: "IfInstruction",
id: "if",
testLabel: testLabel,
test: test,
result: result,
consequent: consequent,
alternate: alternate
};
}
/**
* Decorators
*/
function withLoc(n, end, start) {
var loc = {
start: start,
end: end
};
n.loc = loc;
return n;
}
function withRaw(n, raw) {
// $FlowIgnore
n.raw = raw;
return n;
}
/**
* Import
*/
function moduleImport(module, name, descr) {
return {
type: "ModuleImport",
module: module,
name: name,
descr: descr
};
}
function globalImportDescr(valtype, mutability) {
return {
type: "GlobalType",
valtype: valtype,
mutability: mutability
};
}
function funcParam(valtype, id) {
return {
id: id,
valtype: valtype
};
}
function funcImportDescr(id) {
var params = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var results = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
assert(_typeof(params) === "object" && typeof params.length !== "undefined");
assert(_typeof(results) === "object" && typeof results.length !== "undefined");
return {
type: "FuncImportDescr",
id: id,
signature: functionSignature(params, results)
};
}
function table(elementType, limits, name, elements) {
var n = {
type: "Table",
elementType: elementType,
limits: limits,
name: name
};
if (_typeof(elements) === "object") {
n.elements = elements;
}
return n;
}
function limits(min, max) {
assert(typeof min === "number");
if (typeof max !== "undefined") {
assert(typeof max === "number");
}
return {
type: "Limit",
min: min,
max: max
};
}
function memory(limits, id) {
return {
type: "Memory",
limits: limits,
id: id
};
}
function data(memoryIndex, offset, init) {
return {
type: "Data",
memoryIndex: memoryIndex,
offset: offset,
init: init
};
}
function global(globalType, init, name) {
return {
type: "Global",
globalType: globalType,
init: init,
name: name
};
}
function globalType(valtype, mutability) {
return {
type: "GlobalType",
valtype: valtype,
mutability: mutability
};
}
function byteArray(values) {
return {
type: "Bytes",
values: values
};
}
function leadingComment(value) {
return {
type: "LeadingComment",
value: value
};
}
function blockComment(value) {
return {
type: "BlockComment",
value: value
};
}
function indexLiteral(value) {
// $FlowIgnore
var x = numberLiteral(value, "u32");
return x;
}
function memIndexLiteral(value) {
// $FlowIgnore
var x = numberLiteral(value, "u32");
return x;
}
function typeInstructionFunc() {
var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
var results = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
var id = arguments.length > 2 ? arguments[2] : undefined;
return {
type: "TypeInstruction",
id: id,
functype: functionSignature(params, results)
};
}
function callIndirectInstruction(params, results, intrs) {
return {
type: "CallIndirectInstruction",
signature: functionSignature(params, results),
intrs: intrs
};
}
function callIndirectInstructionWithTypeRef(typeRef, intrs) {
return {
type: "CallIndirectInstruction",
signature: typeRef,
intrs: intrs
};
}
function start(index) {
return {
type: "Start",
index: index
};
}
function elem() {
var table = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : indexLiteral(0);
var offset = arguments.length > 1 ? arguments[1] : undefined;
var funcs = arguments.length > 2 ? arguments[2] : undefined;
return {
type: "Elem",
table: table,
offset: offset,
funcs: funcs
};
}
function indexInFuncSection(index) {
return {
type: "IndexInFuncSection",
index: index
};
}
function isAnonymous(ident) {
return ident.raw === "";
} | }
var sign = signatures[opcodeName]; |
attachment.go | // Copyright 2022 Google LLC. 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.
package beta
import (
"context"
"fmt"
"time"
"google.golang.org/api/googleapi"
"github.com/GoogleCloudPlatform/declarative-resource-client-library/dcl"
)
type Attachment struct {
Name *string `json:"name"`
Environment *string `json:"environment"`
CreatedAt *int64 `json:"createdAt"`
Envgroup *string `json:"envgroup"`
}
func (r *Attachment) String() string {
return dcl.SprintResource(r)
}
// Describe returns a simple description of this resource to ensure that automated tools
// can identify it.
func (r *Attachment) Describe() dcl.ServiceTypeVersion {
return dcl.ServiceTypeVersion{
Service: "apigee",
Type: "Attachment",
Version: "beta",
}
}
func (r *Attachment) ID() (string, error) {
if err := extractAttachmentFields(r); err != nil {
return "", err
}
nr := r.urlNormalized()
params := map[string]interface{}{
"name": dcl.ValueOrEmptyString(nr.Name),
"environment": dcl.ValueOrEmptyString(nr.Environment),
"createdAt": dcl.ValueOrEmptyString(nr.CreatedAt),
"envgroup": dcl.ValueOrEmptyString(nr.Envgroup),
}
return dcl.Nprintf("{{envgroup}}/attachments/{{name}}", params), nil
}
const AttachmentMaxPage = -1
type AttachmentList struct {
Items []*Attachment
nextToken string
pageSize int32
resource *Attachment
}
func (l *AttachmentList) HasNext() bool {
return l.nextToken != ""
}
func (l *AttachmentList) Next(ctx context.Context, c *Client) error {
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
if !l.HasNext() {
return fmt.Errorf("no next page")
}
items, token, err := c.listAttachment(ctx, l.resource, l.nextToken, l.pageSize)
if err != nil {
return err
}
l.Items = items
l.nextToken = token
return err
}
func (c *Client) ListAttachment(ctx context.Context, envgroup string) (*AttachmentList, error) {
ctx = dcl.ContextWithRequestID(ctx)
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
return c.ListAttachmentWithMaxResults(ctx, envgroup, AttachmentMaxPage)
}
func (c *Client) ListAttachmentWithMaxResults(ctx context.Context, envgroup string, pageSize int32) (*AttachmentList, error) {
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
// Create a resource object so that we can use proper url normalization methods.
r := &Attachment{
Envgroup: &envgroup,
}
items, token, err := c.listAttachment(ctx, r, "", pageSize)
if err != nil {
return nil, err
}
return &AttachmentList{
Items: items,
nextToken: token,
pageSize: pageSize,
resource: r,
}, nil
}
func (c *Client) GetAttachment(ctx context.Context, r *Attachment) (*Attachment, error) {
ctx = dcl.ContextWithRequestID(ctx)
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
// This is *purposefully* supressing errors.
// This function is used with url-normalized values + not URL normalized values.
// URL Normalized values will throw unintentional errors, since those values are not of the proper parent form.
extractAttachmentFields(r)
b, err := c.getAttachmentRaw(ctx, r)
if err != nil {
if dcl.IsNotFound(err) {
return nil, &googleapi.Error{
Code: 404,
Message: err.Error(),
}
}
return nil, err
}
result, err := unmarshalAttachment(b, c, r)
if err != nil {
return nil, err
}
result.Envgroup = r.Envgroup
result.Name = r.Name
c.Config.Logger.InfoWithContextf(ctx, "Retrieved raw result state: %v", result)
c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with specified state: %v", r)
result, err = canonicalizeAttachmentNewState(c, result, r)
if err != nil {
return nil, err
}
if err := postReadExtractAttachmentFields(result); err != nil {
return result, err
}
c.Config.Logger.InfoWithContextf(ctx, "Created result state: %v", result)
return result, nil
}
func (c *Client) DeleteAttachment(ctx context.Context, r *Attachment) error {
ctx = dcl.ContextWithRequestID(ctx)
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
if r == nil {
return fmt.Errorf("Attachment resource is nil")
}
c.Config.Logger.InfoWithContext(ctx, "Deleting Attachment...")
deleteOp := deleteAttachmentOperation{}
return deleteOp.do(ctx, r, c)
}
// DeleteAllAttachment deletes all resources that the filter functions returns true on.
func (c *Client) DeleteAllAttachment(ctx context.Context, envgroup string, filter func(*Attachment) bool) error {
listObj, err := c.ListAttachment(ctx, envgroup)
if err != nil {
return err
}
err = c.deleteAllAttachment(ctx, filter, listObj.Items)
if err != nil {
return err
}
for listObj.HasNext() {
err = listObj.Next(ctx, c)
if err != nil {
return nil
}
err = c.deleteAllAttachment(ctx, filter, listObj.Items)
if err != nil {
return err
}
}
return nil
}
func (c *Client) ApplyAttachment(ctx context.Context, rawDesired *Attachment, opts ...dcl.ApplyOption) (*Attachment, error) {
ctx, cancel := context.WithTimeout(ctx, c.Config.TimeoutOr(0*time.Second))
defer cancel()
ctx = dcl.ContextWithRequestID(ctx)
var resultNewState *Attachment
err := dcl.Do(ctx, func(ctx context.Context) (*dcl.RetryDetails, error) {
newState, err := applyAttachmentHelper(c, ctx, rawDesired, opts...)
resultNewState = newState
if err != nil {
// If the error is 409, there is conflict in resource update.
// Here we want to apply changes based on latest state.
if dcl.IsConflictError(err) {
return &dcl.RetryDetails{}, dcl.OperationNotDone{Err: err}
}
return nil, err
}
return nil, nil
}, c.Config.RetryProvider)
return resultNewState, err
}
func applyAttachmentHelper(c *Client, ctx context.Context, rawDesired *Attachment, opts ...dcl.ApplyOption) (*Attachment, error) {
c.Config.Logger.InfoWithContext(ctx, "Beginning ApplyAttachment...")
c.Config.Logger.InfoWithContextf(ctx, "User specified desired state: %v", rawDesired)
// 1.1: Validation of user-specified fields in desired state.
if err := rawDesired.validate(); err != nil {
return nil, err
}
if err := extractAttachmentFields(rawDesired); err != nil {
return nil, err
}
initial, desired, fieldDiffs, err := c.attachmentDiffsForRawDesired(ctx, rawDesired, opts...)
if err != nil {
return nil, fmt.Errorf("failed to create a diff: %w", err)
}
diffs, err := convertFieldDiffsToAttachmentDiffs(c.Config, fieldDiffs, opts)
if err != nil {
return nil, err
}
// TODO(magic-modules-eng): 2.2 Feasibility check (all updates are feasible so far).
// 2.3: Lifecycle Directive Check
var create bool
lp := dcl.FetchLifecycleParams(opts)
if initial == nil {
if dcl.HasLifecycleParam(lp, dcl.BlockCreation) {
return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Creation blocked by lifecycle params: %#v.", desired)}
}
create = true
} else if dcl.HasLifecycleParam(lp, dcl.BlockAcquire) {
return nil, dcl.ApplyInfeasibleError{
Message: fmt.Sprintf("Resource already exists - apply blocked by lifecycle params: %#v.", initial),
}
} else {
for _, d := range diffs {
if d.RequiresRecreate {
return nil, dcl.ApplyInfeasibleError{
Message: fmt.Sprintf("infeasible update: (%v) would require recreation", d),
}
}
if dcl.HasLifecycleParam(lp, dcl.BlockModification) {
return nil, dcl.ApplyInfeasibleError{Message: fmt.Sprintf("Modification blocked, diff (%v) unresolvable.", d)} | // 2.4 Imperative Request Planning
var ops []attachmentApiOperation
if create {
ops = append(ops, &createAttachmentOperation{})
} else {
for _, d := range diffs {
ops = append(ops, d.UpdateOp)
}
}
c.Config.Logger.InfoWithContextf(ctx, "Created plan: %#v", ops)
// 2.5 Request Actuation
for _, op := range ops {
c.Config.Logger.InfoWithContextf(ctx, "Performing operation %T %+v", op, op)
if err := op.do(ctx, desired, c); err != nil {
c.Config.Logger.InfoWithContextf(ctx, "Failed operation %T %+v: %v", op, op, err)
return nil, err
}
c.Config.Logger.InfoWithContextf(ctx, "Finished operation %T %+v", op, op)
}
return applyAttachmentDiff(c, ctx, desired, rawDesired, ops, opts...)
}
func applyAttachmentDiff(c *Client, ctx context.Context, desired *Attachment, rawDesired *Attachment, ops []attachmentApiOperation, opts ...dcl.ApplyOption) (*Attachment, error) {
// 3.1, 3.2a Retrieval of raw new state & canonicalization with desired state
c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state...")
rawNew, err := c.GetAttachment(ctx, desired.urlNormalized())
if err != nil {
return nil, err
}
// Get additional values from the first response.
// These values should be merged into the newState above.
if len(ops) > 0 {
lastOp := ops[len(ops)-1]
if o, ok := lastOp.(*createAttachmentOperation); ok {
if r, hasR := o.FirstResponse(); hasR {
c.Config.Logger.InfoWithContext(ctx, "Retrieving raw new state from operation...")
fullResp, err := unmarshalMapAttachment(r, c, rawDesired)
if err != nil {
return nil, err
}
rawNew, err = canonicalizeAttachmentNewState(c, rawNew, fullResp)
if err != nil {
return nil, err
}
}
}
}
c.Config.Logger.InfoWithContextf(ctx, "Canonicalizing with raw desired state: %v", rawDesired)
// 3.2b Canonicalization of raw new state using raw desired state
newState, err := canonicalizeAttachmentNewState(c, rawNew, rawDesired)
if err != nil {
return rawNew, err
}
c.Config.Logger.InfoWithContextf(ctx, "Created canonical new state: %v", newState)
// 3.3 Comparison of the new state and raw desired state.
// TODO(magic-modules-eng): EVENTUALLY_CONSISTENT_UPDATE
newDesired, err := canonicalizeAttachmentDesiredState(rawDesired, newState)
if err != nil {
return newState, err
}
if err := postReadExtractAttachmentFields(newState); err != nil {
return newState, err
}
// Need to ensure any transformations made here match acceptably in differ.
if err := postReadExtractAttachmentFields(newDesired); err != nil {
return newState, err
}
c.Config.Logger.InfoWithContextf(ctx, "Diffing using canonicalized desired state: %v", newDesired)
newDiffs, err := diffAttachment(c, newDesired, newState)
if err != nil {
return newState, err
}
if len(newDiffs) == 0 {
c.Config.Logger.InfoWithContext(ctx, "No diffs found. Apply was successful.")
} else {
c.Config.Logger.InfoWithContextf(ctx, "Found diffs: %v", newDiffs)
diffMessages := make([]string, len(newDiffs))
for i, d := range newDiffs {
diffMessages[i] = fmt.Sprintf("%v", d)
}
return newState, dcl.DiffAfterApplyError{Diffs: diffMessages}
}
c.Config.Logger.InfoWithContext(ctx, "Done Apply.")
return newState, nil
} | }
}
}
|
repl_writer.rs | use crate::style::TextStyling;
use crate::{impl_colored_methods, ColorWriter};
use crossterm::cursor::MoveLeft;
use crossterm::execute;
use crossterm::style::Color;
use crossterm::terminal::{Clear, ClearType};
use std::fmt::Display;
pub struct ReplWriter {
writer: ColorWriter,
prompt_prefix: Option<String>
}
#[allow(unused)]
impl ReplWriter {
pub fn new() -> Self {
let writer = ColorWriter::new();
ReplWriter {
writer,
prompt_prefix: None,
}
}
pub fn with_prompt_prefix<S: Into<String>>(prefix: S) -> Self {
let writer = ColorWriter::new();
ReplWriter {
writer,
prompt_prefix: Some(prefix.into()),
}
}
pub fn fg(&mut self, color: Option<Color>) -> &mut Self {
self.writer.fg(color);
self
}
pub fn bg(&mut self, color: Option<Color>) -> &mut Self {
self.writer.bg(color);
self
}
pub fn styled(&mut self, styling: TextStyling) -> &mut Self {
self.writer.styled(styling);
self
}
pub fn flush(&self) {
self.writer.flush();
}
pub fn write_prompt_prefix(&mut self) {
if let Some(prefix) = self.prompt_prefix.clone() {
self.cyan().write(prefix);
}
}
pub fn write<D: Display>(&mut self, data: D) {
self.writer.write(data);
}
pub fn writeln<D: Display>(&mut self, data: D) {
self.writer.writeln(data);
self.write_prompt_prefix();
}
pub fn write_err<D: Display>(&mut self, data: D) {
self.writer.write_err(data);
}
pub fn writeln_err<D: Display>(&mut self, data: D) {
self.writer.writeln_err(data);
self.write_prompt_prefix();
}
pub fn rewrite<D: Display>(&mut self, data: D) {
let fg = self.writer.fg.clone();
let bg = self.writer.bg.clone();
execute!(
std::io::stdout(),
Clear(ClearType::CurrentLine),
MoveLeft(u16::MAX)
)
.unwrap();
self.write_prompt_prefix();
self.fg(fg).bg(bg).write(data);
}
pub fn rewrite_err<D: Display>(&mut self, data: D) { |
execute!(
std::io::stderr(),
Clear(ClearType::CurrentLine),
MoveLeft(u16::MAX)
)
.unwrap();
self.write_prompt_prefix();
self.fg(fg).bg(bg).write(data);
}
impl_colored_methods! {
// Foreground Colors
fg red Red,
fg green Green,
fg yellow Yellow,
fg blue Blue,
fg magenta Magenta,
fg cyan Cyan,
fg white White,
fg gray Grey,
fg black Black,
fg dark_red DarkRed,
fg dark_green DarkGreen,
fg dark_yellow DarkYellow,
fg dark_blue DarkBlue,
fg dark_magenta DarkMagenta,
fg dark_cyan DarkCyan,
fg dark_gray DarkGrey,
// Foreground Colors
bg on_red Red,
bg on_green Green,
bg on_yellow Yellow,
bg on_blue Blue,
bg on_magenta Magenta,
bg on_cyan Cyan,
bg on_white White,
bg on_gray Grey,
bg on_black Black,
bg on_dark_red DarkRed,
bg on_dark_green DarkGreen,
bg on_dark_yellow DarkYellow,
bg on_dark_blue DarkBlue,
bg on_dark_magenta DarkMagenta,
bg on_dark_cyan DarkCyan,
bg on_dark_gray DarkGrey,
}
} | let fg = self.writer.fg.clone();
let bg = self.writer.bg.clone(); |
_field_common.py | import six
import sys
from pyrsistent._checked_types import (
CheckedPMap,
CheckedPSet,
CheckedPVector,
CheckedType,
InvariantException,
_restore_pickle,
get_type,
maybe_parse_user_type,
maybe_parse_many_user_types,
)
from pyrsistent._checked_types import optional as optional_type
from pyrsistent._checked_types import wrap_invariant
import inspect
PY2 = sys.version_info[0] < 3
def set_fields(dct, bases, name):
dct[name] = dict(sum([list(b.__dict__.get(name, {}).items()) for b in bases], []))
for k, v in list(dct.items()):
if isinstance(v, _PField):
dct[name][k] = v
del dct[k]
def check_global_invariants(subject, invariants):
error_codes = tuple(error_code for is_ok, error_code in
(invariant(subject) for invariant in invariants) if not is_ok)
if error_codes:
raise InvariantException(error_codes, (), 'Global invariant failed')
def serialize(serializer, format, value):
if isinstance(value, CheckedType) and serializer is PFIELD_NO_SERIALIZER:
return value.serialize(format)
return serializer(format, value)
def check_type(destination_cls, field, name, value):
if field.type and not any(isinstance(value, get_type(t)) for t in field.type):
actual_type = type(value)
message = "Invalid type for field {0}.{1}, was {2}".format(destination_cls.__name__, name, actual_type.__name__)
raise PTypeError(destination_cls, name, field.type, actual_type, message)
def is_type_cls(type_cls, field_type):
if type(field_type) is set:
return True
types = tuple(field_type)
if len(types) == 0:
return False
return issubclass(get_type(types[0]), type_cls)
def is_field_ignore_extra_complaint(type_cls, field, ignore_extra):
# ignore_extra param has default False value, for speed purpose no need to propagate False
if not ignore_extra:
return False
if not is_type_cls(type_cls, field.type):
return False
if PY2:
return 'ignore_extra' in inspect.getargspec(field.factory).args
else:
return 'ignore_extra' in inspect.signature(field.factory).parameters
class _PField(object):
__slots__ = ('type', 'invariant', 'initial', 'mandatory', '_factory', 'serializer')
def __init__(self, type, invariant, initial, mandatory, factory, serializer):
self.type = type
self.invariant = invariant
self.initial = initial
self.mandatory = mandatory
self._factory = factory
self.serializer = serializer
@property
def factory(self):
# If no factory is specified and the type is another CheckedType use the factory method of that CheckedType
if self._factory is PFIELD_NO_FACTORY and len(self.type) == 1:
typ = get_type(tuple(self.type)[0])
if issubclass(typ, CheckedType):
return typ.create
return self._factory
PFIELD_NO_TYPE = ()
PFIELD_NO_INVARIANT = lambda _: (True, None)
PFIELD_NO_FACTORY = lambda x: x
PFIELD_NO_INITIAL = object()
PFIELD_NO_SERIALIZER = lambda _, value: value
def field(type=PFIELD_NO_TYPE, invariant=PFIELD_NO_INVARIANT, initial=PFIELD_NO_INITIAL,
mandatory=False, factory=PFIELD_NO_FACTORY, serializer=PFIELD_NO_SERIALIZER):
"""
Field specification factory for :py:class:`PRecord`.
:param type: a type or iterable with types that are allowed for this field
:param invariant: a function specifying an invariant that must hold for the field
:param initial: value of field if not specified when instantiating the record
:param mandatory: boolean specifying if the field is mandatory or not
:param factory: function called when field is set.
:param serializer: function that returns a serialized version of the field
"""
# NB: We have to check this predicate separately from the predicates in
# `maybe_parse_user_type` et al. because this one is related to supporting
# the argspec for `field`, while those are related to supporting the valid
# ways to specify types.
# Multiple types must be passed in one of the following containers. Note
# that a type that is a subclass of one of these containers, like a
| # `collections.namedtuple`, will work as expected, since we check
# `isinstance` and not `issubclass`.
if isinstance(type, (list, set, tuple)):
types = set(maybe_parse_many_user_types(type))
else:
types = set(maybe_parse_user_type(type))
invariant_function = wrap_invariant(invariant) if invariant != PFIELD_NO_INVARIANT and callable(invariant) else invariant
field = _PField(type=types, invariant=invariant_function, initial=initial,
mandatory=mandatory, factory=factory, serializer=serializer)
_check_field_parameters(field)
return field
def _check_field_parameters(field):
for t in field.type:
if not isinstance(t, type) and not isinstance(t, six.string_types):
raise TypeError('Type parameter expected, not {0}'.format(type(t)))
if field.initial is not PFIELD_NO_INITIAL and \
not callable(field.initial) and \
field.type and not any(isinstance(field.initial, t) for t in field.type):
raise TypeError('Initial has invalid type {0}'.format(type(field.initial)))
if not callable(field.invariant):
raise TypeError('Invariant must be callable')
if not callable(field.factory):
raise TypeError('Factory must be callable')
if not callable(field.serializer):
raise TypeError('Serializer must be callable')
class PTypeError(TypeError):
"""
Raised when trying to assign a value with a type that doesn't match the declared type.
Attributes:
source_class -- The class of the record
field -- Field name
expected_types -- Types allowed for the field
actual_type -- The non matching type
"""
def __init__(self, source_class, field, expected_types, actual_type, *args, **kwargs):
super(PTypeError, self).__init__(*args, **kwargs)
self.source_class = source_class
self.field = field
self.expected_types = expected_types
self.actual_type = actual_type
SEQ_FIELD_TYPE_SUFFIXES = {
CheckedPVector: "PVector",
CheckedPSet: "PSet",
}
# Global dictionary to hold auto-generated field types: used for unpickling
_seq_field_types = {}
def _restore_seq_field_pickle(checked_class, item_type, data):
"""Unpickling function for auto-generated PVec/PSet field types."""
type_ = _seq_field_types[checked_class, item_type]
return _restore_pickle(type_, data)
def _types_to_names(types):
"""Convert a tuple of types to a human-readable string."""
return "".join(get_type(typ).__name__.capitalize() for typ in types)
def _make_seq_field_type(checked_class, item_type):
"""Create a subclass of the given checked class with the given item type."""
type_ = _seq_field_types.get((checked_class, item_type))
if type_ is not None:
return type_
class TheType(checked_class):
__type__ = item_type
def __reduce__(self):
return (_restore_seq_field_pickle,
(checked_class, item_type, list(self)))
suffix = SEQ_FIELD_TYPE_SUFFIXES[checked_class]
TheType.__name__ = _types_to_names(TheType._checked_types) + suffix
_seq_field_types[checked_class, item_type] = TheType
return TheType
def _sequence_field(checked_class, item_type, optional, initial):
"""
Create checked field for either ``PSet`` or ``PVector``.
:param checked_class: ``CheckedPSet`` or ``CheckedPVector``.
:param item_type: The required type for the items in the set.
:param optional: If true, ``None`` can be used as a value for
this field.
:param initial: Initial value to pass to factory.
:return: A ``field`` containing a checked class.
"""
TheType = _make_seq_field_type(checked_class, item_type)
if optional:
def factory(argument, _factory_fields=None, ignore_extra=False):
if argument is None:
return None
else:
return TheType.create(argument, _factory_fields=_factory_fields, ignore_extra=ignore_extra)
else:
factory = TheType.create
return field(type=optional_type(TheType) if optional else TheType,
factory=factory, mandatory=True,
initial=factory(initial))
def pset_field(item_type, optional=False, initial=()):
"""
Create checked ``PSet`` field.
:param item_type: The required type for the items in the set.
:param optional: If true, ``None`` can be used as a value for
this field.
:param initial: Initial value to pass to factory if no value is given
for the field.
:return: A ``field`` containing a ``CheckedPSet`` of the given type.
"""
return _sequence_field(CheckedPSet, item_type, optional,
initial)
def pvector_field(item_type, optional=False, initial=()):
"""
Create checked ``PVector`` field.
:param item_type: The required type for the items in the vector.
:param optional: If true, ``None`` can be used as a value for
this field.
:param initial: Initial value to pass to factory if no value is given
for the field.
:return: A ``field`` containing a ``CheckedPVector`` of the given type.
"""
return _sequence_field(CheckedPVector, item_type, optional,
initial)
_valid = lambda item: (True, "")
# Global dictionary to hold auto-generated field types: used for unpickling
_pmap_field_types = {}
def _restore_pmap_field_pickle(key_type, value_type, data):
"""Unpickling function for auto-generated PMap field types."""
type_ = _pmap_field_types[key_type, value_type]
return _restore_pickle(type_, data)
def _make_pmap_field_type(key_type, value_type):
"""Create a subclass of CheckedPMap with the given key and value types."""
type_ = _pmap_field_types.get((key_type, value_type))
if type_ is not None:
return type_
class TheMap(CheckedPMap):
__key_type__ = key_type
__value_type__ = value_type
def __reduce__(self):
return (_restore_pmap_field_pickle,
(self.__key_type__, self.__value_type__, dict(self)))
TheMap.__name__ = "{0}To{1}PMap".format(
_types_to_names(TheMap._checked_key_types),
_types_to_names(TheMap._checked_value_types))
_pmap_field_types[key_type, value_type] = TheMap
return TheMap
def pmap_field(key_type, value_type, optional=False, invariant=PFIELD_NO_INVARIANT):
"""
Create a checked ``PMap`` field.
:param key: The required type for the keys of the map.
:param value: The required type for the values of the map.
:param optional: If true, ``None`` can be used as a value for
this field.
:param invariant: Pass-through to ``field``.
:return: A ``field`` containing a ``CheckedPMap``.
"""
TheMap = _make_pmap_field_type(key_type, value_type)
if optional:
def factory(argument):
if argument is None:
return None
else:
return TheMap.create(argument)
else:
factory = TheMap.create
return field(mandatory=True, initial=TheMap(),
type=optional_type(TheMap) if optional else TheMap,
factory=factory, invariant=invariant) | |
rpc.go | // Copyright 2019 Yunion
//
// 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 handler
import (
"context"
"fmt"
"net/http"
"reflect"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
"yunion.io/x/pkg/utils"
"yunion.io/x/onecloud/pkg/appctx"
"yunion.io/x/onecloud/pkg/appsrv"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient/auth"
"yunion.io/x/onecloud/pkg/mcclient/modulebase"
"yunion.io/x/onecloud/pkg/util/httputils"
)
type RPCHandlers struct {
*SHandlers
}
func | (prefix string) *RPCHandlers {
return &RPCHandlers{NewHandlers(prefix)}
}
func (h *RPCHandlers) AddGet(mf appsrv.MiddlewareFunc) *RPCHandlers {
h.AddByMethod(GET, mf, NewHP(rpcHandler, APIVer, "rpc"))
return h
}
func (h *RPCHandlers) AddPost(mf appsrv.MiddlewareFunc) *RPCHandlers {
h.AddByMethod(POST, mf, NewHP(rpcHandler, APIVer, "rpc"))
return h
}
func rpcHandler(ctx context.Context, w http.ResponseWriter, req *http.Request) {
curpath := appctx.AppContextCurrentPath(ctx)
var resType string
var resId string
var callName string
resType = curpath[0]
if len(curpath) == 2 {
callName = curpath[1]
} else {
resId = curpath[1]
callName = curpath[2]
}
var e error
var verb string
var params jsonutils.JSONObject = nil
switch req.Method {
case "GET":
verb = "Get"
params, e = jsonutils.ParseQueryString(req.URL.RawQuery)
if e != nil {
log.Errorf("Error parse query string: %s", e)
}
case "POST":
verb = "Do"
params, e = appsrv.FetchJSON(req)
if e != nil {
log.Errorf("Error get JSON body: %s", e)
}
default:
httperrors.InvalidInputError(w, fmt.Sprintf("Unsupported RPC method %s", req.Method))
return
}
token := AppContextToken(ctx)
pathParams := appctx.AppContextParams(ctx)
s := auth.GetSession(ctx, token, FetchRegion(req), pathParams["<apiver>"])
funcname := verb + utils.Kebab2Camel(callName, "-")
mod, e := modulebase.GetModule(s, resType)
if e != nil || mod == nil {
if e != nil {
log.Debugf("module %s not found %s", resType, e)
}
httperrors.NotFoundError(w, fmt.Sprintf("resource %s not exists", resType))
return
}
modvalue := reflect.ValueOf(mod)
funcvalue := modvalue.MethodByName(funcname)
if !funcvalue.IsValid() || funcvalue.IsNil() {
httperrors.NotFoundError(w, fmt.Sprintf("RPC method %s not found", funcname))
return
}
callParams := make([]reflect.Value, 0)
callParams = append(callParams, reflect.ValueOf(s))
if len(resId) > 0 {
callParams = append(callParams, reflect.ValueOf(resId))
}
if params == nil {
params = jsonutils.NewDict()
}
callParams = append(callParams, reflect.ValueOf(params))
log.Debugf("%s", callParams)
retValue := funcvalue.Call(callParams)
retobj := retValue[0]
reterr := retValue[1]
if reterr.IsNil() {
v, ok := retobj.Interface().(jsonutils.JSONObject)
if ok {
appsrv.SendJSON(w, v)
} else {
httperrors.BadGatewayError(w, "recv invalid data")
}
} else {
v, ok := reterr.Interface().(*httputils.JSONClientError)
if ok {
httperrors.JsonClientError(w, v)
} else {
httperrors.BadGatewayError(w, fmt.Sprintf("%s", reterr.Interface()))
}
}
}
| NewRPCHandlers |
test_regkey_controller.py | import json
import pytest
from sqlalchemy.sql import text as sa_text
from sqlalchemy.orm.session import sessionmaker
from opencdms.models.climsoft import v4_1_1_core as climsoft_models
from apps.climsoft.db.engine import db_engine
from apps.climsoft.schemas import regkey_schema
from datagen.climsoft import regkey as climsoft_regkey
from faker import Faker
from fastapi.testclient import TestClient
from apps.auth.db.engine import db_engine as auth_db_engine
from apps.auth.db.models import user_model
from passlib.hash import django_pbkdf2_sha256 as handler
fake = Faker()
def setup_module(module):
with auth_db_engine.connect().execution_options(autocommit=True) as connection:
with connection.begin():
auth_db_engine.execute(sa_text(f'''
TRUNCATE TABLE {user_model.AuthUser.__tablename__} RESTART IDENTITY CASCADE
''').execution_options(autocommit=True))
with db_engine.connect().execution_options(autocommit=True) as connection:
with connection.begin():
db_engine.execute(sa_text(f"""
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE {climsoft_models.Regkey.__tablename__};
SET FOREIGN_KEY_CHECKS = 1;
"""))
Session = sessionmaker(bind=db_engine)
db_session = Session()
for i in range(1, 11):
db_session.add(climsoft_models.Regkey(
**climsoft_regkey.get_valid_reg_key_input().dict()
))
db_session.commit()
db_session.close()
AuthSession = sessionmaker(bind=auth_db_engine)
auth_session = AuthSession()
user = user_model.AuthUser(
username="testuser",
password=handler.hash("password"),
first_name=fake.first_name(),
last_name=fake.last_name(),
email=fake.email()
)
auth_session.add(user)
auth_session.commit()
auth_session.close()
def teardown_module(module):
with auth_db_engine.connect().execution_options(autocommit=True) as connection:
with connection.begin():
auth_db_engine.execute(sa_text(f'''
TRUNCATE TABLE {user_model.AuthUser.__tablename__} RESTART IDENTITY CASCADE
''').execution_options(autocommit=True))
with db_engine.connect().execution_options(autocommit=True) as connection:
with connection.begin():
db_engine.execute(sa_text(f"""
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE {climsoft_models.Regkey.__tablename__};
SET FOREIGN_KEY_CHECKS = 1;
"""))
@pytest.fixture
def get_access_token(user_access_token: str) -> str:
return user_access_token
@pytest.fixture
def get_reg_key():
Session = sessionmaker(bind=db_engine)
session = Session()
reg_key = climsoft_models.Regkey(**climsoft_regkey.get_valid_reg_key_input().dict())
session.add(reg_key)
session.commit()
yield reg_key
session.close()
def test_should_return_first_five_reg_keys(client: TestClient, get_access_token: str):
|
def test_should_return_single_reg_key(client: TestClient, get_reg_key: climsoft_models.Regkey, get_access_token: str):
response = client.get(f"/climsoft/v1/reg-keys/{get_reg_key.keyName}", headers={
"Authorization": f"Bearer {get_access_token}"
})
assert response.status_code == 200
response_data = response.json()
assert len(response_data["result"]) == 1
def test_should_create_a_reg_key(client: TestClient, get_access_token: str):
reg_key_data = climsoft_regkey.get_valid_reg_key_input().dict(by_alias=True)
response = client.post("/climsoft/v1/reg-keys", data=json.dumps(reg_key_data, default=str), headers={
"Authorization": f"Bearer {get_access_token}"
})
assert response.status_code == 200
response_data = response.json()
assert len(response_data["result"]) == 1
def test_should_raise_validation_error(client: TestClient, get_access_token: str):
reg_key_data = {"aaa": "bbbbbbb"}
response = client.post("/climsoft/v1/reg-keys", data=json.dumps(reg_key_data, default=str), headers={
"Authorization": f"Bearer {get_access_token}"
})
assert response.status_code == 422
def test_should_update_reg_key(client: TestClient, get_reg_key, get_access_token: str):
reg_key_data = regkey_schema.RegKey.from_orm(get_reg_key).dict(by_alias=True)
key_name = reg_key_data.pop("key_name")
updates = {**reg_key_data, "key_description": "updated name"}
response = client.put(f"/climsoft/v1/reg-keys/{key_name}", data=json.dumps(updates, default=str), headers={
"Authorization": f"Bearer {get_access_token}"
})
response_data = response.json()
assert response.status_code == 200
assert response_data["result"][0]["key_description"] == updates["key_description"]
def test_should_delete_reg_key(client: TestClient, get_reg_key, get_access_token: str):
reg_key_data = regkey_schema.RegKey.from_orm(get_reg_key).dict(by_alias=True)
key_name = reg_key_data.pop("key_name")
response = client.delete(f"/climsoft/v1/reg-keys/{key_name}", headers={
"Authorization": f"Bearer {get_access_token}"
})
assert response.status_code == 200
response = client.get(f"/climsoft/v1/reg-keys/{key_name}", headers={
"Authorization": f"Bearer {get_access_token}"
})
assert response.status_code == 404
| response = client.get("/climsoft/v1/reg-keys", params={"limit": 5}, headers={
"Authorization": f"Bearer {get_access_token}"
})
assert response.status_code == 200
response_data = response.json()
assert len(response_data["result"]) == 5 |
dataset_factory.py | #
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: EPL-2.0
#
# Copyright 2016 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.
# ==============================================================================
"""A factory-pattern class which returns classification image/label pairs."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import imagenet
datasets_map = {
'imagenet': imagenet,
}
def | (name, split_name, dataset_dir, file_pattern=None, reader=None):
"""Given a dataset name and a split_name returns a Dataset.
Args:
name: String, the name of the dataset.
split_name: A train/test split name.
dataset_dir: The directory where the dataset files are stored.
file_pattern: The file pattern to use for matching the dataset source files.
reader: The subclass of tf.ReaderBase. If left as `None`, then the default
reader defined by each dataset is used.
Returns:
A `Dataset` class.
Raises:
ValueError: If the dataset `name` is unknown.
"""
if name not in datasets_map:
raise ValueError('Name of dataset unknown %s' % name)
return datasets_map[name].get_split(
split_name,
dataset_dir,
file_pattern,
reader)
| get_dataset |
root.go | package cmd
import (
"os"
template "github.com/timmypotts/gk/templates"
"github.com/kujtimiihoxha/gk/fs"
"github.com/sirupsen/logrus"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "gk",
Short: "A generator for go-kit that helps you create/update boilerplate code",
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() |
func init() {
cobra.OnInitialize(initConfig)
RootCmd.PersistentFlags().Bool("testing", false, "If testing the generator.")
RootCmd.PersistentFlags().BoolP("debug", "d", false, "If you want to se the debug logs.")
RootCmd.PersistentFlags().BoolP("force", "f", false, "Force overide existing files without asking.")
RootCmd.PersistentFlags().String("folder", "", "If you want to specify the base folder of the project.")
viper.BindPFlag("gk_testing", RootCmd.PersistentFlags().Lookup("testing"))
viper.BindPFlag("gk_folder", RootCmd.PersistentFlags().Lookup("folder"))
viper.BindPFlag("gk_force", RootCmd.PersistentFlags().Lookup("force"))
viper.BindPFlag("gk_debug", RootCmd.PersistentFlags().Lookup("debug"))
}
func initConfig() {
initViperDefaults()
viper.SetFs(fs.NewDefaultFs("").Fs)
viper.SetConfigFile("gk.json")
if viper.GetBool("gk_debug") {
logrus.SetLevel(logrus.DebugLevel)
} else {
logrus.SetLevel(logrus.InfoLevel)
}
if err := viper.ReadInConfig(); err == nil {
logrus.Debug("Using config file:", viper.ConfigFileUsed())
} else {
logrus.Info("No config file found initializing the project with the default config file.")
te := template.NewEngine()
st, err := te.Execute("gk.json", nil)
if err != nil {
logrus.Panic(err)
}
err = fs.Get().WriteFile("gk.json", st, false)
if err != nil {
logrus.Panic(err)
}
initConfig()
}
}
func initViperDefaults() {
viper.SetDefault("service.path", "{{toSnakeCase .ServiceName}}"+afero.FilePathSeparator+"pkg"+afero.FilePathSeparator+"service")
viper.SetDefault("service.file_name", "service.go")
viper.SetDefault("service.interface_name", "{{toUpperFirstCamelCase .ServiceName}}Service")
viper.SetDefault("service.struct_name", "stub{{toCamelCase .ServiceName}}Service")
viper.SetDefault("middleware.file_name", "middleware.go")
viper.SetDefault("endpoints.path", "{{toSnakeCase .ServiceName}}"+afero.FilePathSeparator+"pkg"+afero.FilePathSeparator+"endpoints")
viper.SetDefault("endpoints.file_name", "endpoints.go")
viper.SetDefault("transport.path", "{{toSnakeCase .ServiceName}}"+afero.FilePathSeparator+"pkg"+afero.FilePathSeparator+"{{.TransportType}}")
viper.SetDefault("transport.file_name", "handler.go")
viper.SetDefault("default_transport", "http")
}
| {
if err := RootCmd.Execute(); err != nil {
logrus.Error(err)
os.Exit(-1)
}
} |
models.py | def breast_cancer(x_train, y_train, x_val, y_val, params):
from keras.models import Sequential
from keras.layers import Dropout, Dense
from talos.model import lr_normalizer, early_stopper, hidden_layers
from talos.metrics.keras_metrics import matthews, precision, recall, f1score
model = Sequential()
model.add(Dense(params['first_neuron'],
input_dim=x_train.shape[1],
activation='relu'))
model.add(Dropout(params['dropout']))
hidden_layers(model, params, 1)
model.add(Dense(1, activation=params['last_activation']))
model.compile(optimizer=params['optimizer']
(lr=lr_normalizer(params['lr'],
params['optimizer'])),
loss=params['losses'],
metrics=['acc',
f1score,
recall,
precision,
matthews])
results = model.fit(x_train, y_train,
batch_size=params['batch_size'],
epochs=params['epochs'],
verbose=0,
validation_data=[x_val, y_val],
callbacks=[early_stopper(params['epochs'],
mode='moderate',
monitor='val_f1score')])
return results, model
def cervical_cancer(x_train, y_train, x_val, y_val, params):
from keras.models import Sequential
from keras.layers import Dropout, Dense
from talos.model import lr_normalizer, early_stopper, hidden_layers
from talos.metrics.keras_metrics import matthews, precision, recall, f1score
model = Sequential()
model.add(Dense(params['first_neuron'],
input_dim=x_train.shape[1],
activation='relu'))
model.add(Dropout(params['dropout']))
hidden_layers(model, params, 1)
model.add(Dense(1, activation=params['last_activation']))
model.compile(optimizer=params['optimizer']
(lr=lr_normalizer(params['lr'],
params['optimizer'])),
loss=params['losses'],
metrics=['acc',
f1score,
recall,
precision,
matthews])
results = model.fit(x_train, y_train,
batch_size=params['batch_size'],
epochs=params['epochs'],
verbose=0,
validation_data=[x_val, y_val],
callbacks=[early_stopper(params['epochs'],
mode='moderate',
monitor='val_f1score')])
return results, model
def titanic(x_train, y_train, x_val, y_val, params):
from keras.models import Sequential
from keras.layers import Dropout, Dense
# note how instead of passing the value, we pass a dictionary entry
model = Sequential()
model.add(Dense(params['first_neuron'],
input_dim=x_train.shape[1],
activation='relu'))
# same here, just passing a dictionary entry
model.add(Dropout(params['dropout']))
# again, instead of the activation name, we have a dictionary entry
model.add(Dense(1, activation=params['last_activation']))
# here are using a learning rate boundary
model.compile(optimizer=params['optimizer'],
loss=params['losses'],
metrics=['acc'])
# here we are also using the early_stopper function for a callback
out = model.fit(x_train, y_train,
batch_size=params['batch_size'],
epochs=2,
verbose=0,
validation_data=[x_val, y_val])
return out, model
def | (x_train, y_train, x_val, y_val, params):
from keras.models import Sequential
from keras.layers import Dropout, Dense
from talos.model import lr_normalizer, early_stopper, hidden_layers
# note how instead of passing the value, we pass a dictionary entry
model = Sequential()
model.add(Dense(params['first_neuron'],
input_dim=x_train.shape[1],
activation='relu'))
# same here, just passing a dictionary entry
model.add(Dropout(params['dropout']))
# with this call we can create any number of hidden layers
hidden_layers(model, params, y_train.shape[1])
# again, instead of the activation name, we have a dictionary entry
model.add(Dense(y_train.shape[1],
activation=params['last_activation']))
# here are using a learning rate boundary
model.compile(optimizer=params['optimizer']
(lr=lr_normalizer(params['lr'],
params['optimizer'])),
loss=params['losses'],
metrics=['acc'])
# here we are also using the early_stopper function for a callback
out = model.fit(x_train, y_train,
batch_size=params['batch_size'],
epochs=params['epochs'],
verbose=0,
validation_data=[x_val, y_val],
callbacks=[early_stopper(params['epochs'], mode=[1, 1])])
return out, model
| iris |
lib.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
use anyhow::{bail, Context, Result};
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use teaclave_binder::proto::{ECallCommand, StartServiceInput, StartServiceOutput};
use teaclave_binder::TeeBinder;
use teaclave_config::RuntimeConfig;
use teaclave_types::{TeeServiceError, TeeServiceResult};
extern "C" {
fn _exit(status: i32) -> !;
}
struct TeaclaveServiceLauncher {
tee: TeeBinder,
config: RuntimeConfig,
}
impl TeaclaveServiceLauncher {
pub fn new<P: AsRef<Path>>(package_name: &str, config_path: P) -> Result<Self> {
let config = RuntimeConfig::from_toml(config_path.as_ref())
.context("Failed to load config file.")?;
let tee = TeeBinder::new(package_name).context("Failed to new the enclave.")?;
Ok(Self { tee, config })
}
pub fn start(&self) -> Result<String> {
let input = StartServiceInput::new(self.config.clone());
let command = ECallCommand::StartService;
match self
.tee
.invoke::<StartServiceInput, TeeServiceResult<StartServiceOutput>>(command, input)
{
Err(e) => bail!("TEE invocation error: {:?}", e),
Ok(Err(TeeServiceError::EnclaveForceTermination)) => {
log::info!("Exit");
if cfg!(sgx_sim) {
// use _exit to force exit in simulation mode to avoid SIGSEG
unsafe {
_exit(1);
}
} else {
std::process::exit(1);
}
}
Ok(Err(e)) => bail!("Service exit with error: {:?}", e),
_ => Ok(String::from("Service successfully exit")),
}
}
pub fn finalize(&self) {
self.tee.finalize();
}
/// # Safety
/// Force to destroy current enclave.
pub unsafe fn destroy(&self) {
self.tee.destroy();
}
}
pub fn launch_teaclave_service(host_package_name: &str) -> Result<()> {
env_logger::init_from_env(
env_logger::Env::new()
.filter_or("TEACLAVE_LOG", "RUST_LOG")
.write_style_or("TEACLAVE_LOG_STYLE", "RUST_LOG_STYLE"),
);
let launcher = Arc::new(TeaclaveServiceLauncher::new(
host_package_name,
"runtime.config.toml",
)?);
let launcher_ref = launcher.clone();
thread::spawn(move || {
let _ = launcher_ref.start();
unsafe { libc::raise(signal_hook::SIGTERM) }
});
let term = Arc::new(AtomicBool::new(false));
register_signals(term.clone()).context("Failed to register signal handler")?;
while !term.load(Ordering::Relaxed) {
thread::park();
}
launcher.finalize();
unsafe {
launcher.destroy(); // force to destroy the enclave
}
Ok(())
}
fn register_signals(term: Arc<AtomicBool>) -> Result<()> {
for signal in &[
signal_hook::SIGTERM,
signal_hook::SIGINT,
signal_hook::SIGHUP,
] {
let term_ref = term.clone();
let thread = std::thread::current();
unsafe {
signal_hook::register(*signal, move || {
term_ref.store(true, Ordering::Relaxed);
thread.unpark();
})?;
}
} | Ok(())
} | |
logger.rs | use crate::{
rpc::{rpc_log, streaming_message::Content, RpcLog, StreamingMessage},
worker::Sender,
};
use log::{Level, Log, Metadata, Record};
pub struct Logger {
level: Level,
sender: Sender,
}
impl Logger {
pub fn new(level: Level, sender: Sender) -> Logger {
Logger { level, sender }
}
}
impl Log for Logger {
fn enabled(&self, metadata: &Metadata) -> bool |
fn log(&self, record: &Record) {
if !self.enabled(record.metadata()) {
return;
}
let mut event = RpcLog {
level: match record.level() {
Level::Trace => rpc_log::Level::Trace,
Level::Debug => rpc_log::Level::Debug,
Level::Info => rpc_log::Level::Information,
Level::Warn => rpc_log::Level::Warning,
Level::Error => rpc_log::Level::Error,
} as i32,
message: record.args().to_string(),
..Default::default()
};
event.invocation_id = crate::context::CURRENT.with(|c| c.borrow().invocation_id.clone());
self.sender
.unbounded_send(StreamingMessage {
content: Some(Content::RpcLog(event)),
..Default::default()
})
.unwrap_or(());
}
fn flush(&self) {}
}
| {
metadata.level() <= self.level
} |
main.py | # %% [markdown]
# [](https://colab.research.google.com/github/jun-hyeok/SUP5001-41_Deep-Neural-Networks_2022Spring/blob/main/DNN_HW5/main.ipynb)
# %% [markdown]
# # DNN HW5 : #9
#
# 2022.03.23
# 박준혁
# %%
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# %% [markdown]
# Create XOR dataset with torch.FloatTensor
# %%
# xor dataset
x = torch.FloatTensor([[0, 0], [0, 1], [1, 0], [1, 1]])
y = torch.FloatTensor([[0], [1], [1], [0]])
# %% [markdown]
# 1. NN model - 10 hidden layer with 4 nodes each
# %%
# neural network 10 hidden layers with 4 nodes each
class NN10(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(2, 4, bias=True)
self.fc2 = nn.Linear(4, 4)
self.fc3 = nn.Linear(4, 4)
self.fc4 = nn.Linear(4, 4)
self.fc5 = nn.Linear(4, 4)
self.fc6 = nn.Linear(4, 4)
self.fc7 = nn.Linear(4, 4)
self.fc8 = nn.Linear(4, 4)
self.fc9 = nn.Linear(4, 4)
self.fc10 = nn.Linear(4, 1)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x)) | x = F.relu(self.fc5(x))
x = F.relu(self.fc6(x))
x = F.relu(self.fc7(x))
x = F.relu(self.fc8(x))
x = F.relu(self.fc9(x))
x = F.sigmoid(self.fc10(x))
return x
# %%
nn10 = NN10()
optimizer10 = optim.SGD(nn10.parameters(), lr=0.1)
epochs = 10000
for epoch in range(epochs):
optimizer10.zero_grad()
y_pred10 = nn10(x)
ce10 = F.binary_cross_entropy(y_pred10, y)
ce10.backward()
optimizer10.step()
if epoch % 1000 == 0:
print("Epoch: {:4d}/{}".format(epoch, epochs), end=" ")
print("Cost: {:.6f}".format(ce10.item()))
# %% [markdown]
# 2. NN model - 2 hidden layer with 4 nodes each
# %%
# neural network 2 hidden layers with 4 nodes each
class NN02(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(2, 4, bias=True)
self.fc2 = nn.Linear(4, 4)
self.fc3 = nn.Linear(4, 1)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.sigmoid(self.fc3(x))
return x
# %%
nn02 = NN02()
optimizer02 = optim.SGD(nn02.parameters(), lr=0.1)
epochs = 10000
for epoch in range(epochs):
optimizer02.zero_grad()
y_pred02 = nn02(x)
ce02 = F.binary_cross_entropy(y_pred02, y)
ce02.backward()
optimizer02.step()
if epoch % 1000 == 0:
print("Epoch: {:4d}/{}".format(epoch, epochs), end=" ")
print("Cost: {:.6f}".format(ce02.item())) | x = F.relu(self.fc3(x))
x = F.relu(self.fc4(x)) |
JobBrowserBFF_JSONRPCServer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import json
import sys
import traceback
from getopt import getopt, GetoptError
from multiprocessing import Process
from wsgiref.simple_server import make_server
from JobBrowserBFF.jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError, \
JSONRPCError, InvalidRequestError
from JobBrowserBFF.jsonrpcbase import ServerError as JSONServerError
from biokbase import log
from JobBrowserBFF.authclient import KBaseAuth as _KBaseAuth
from JobBrowserBFF.Config import Config
from JobBrowserBFF.JobBrowserBFFImpl import JobBrowserBFF # noqa @IgnorePep8
from JobBrowserBFF.constants import AUTH
config = Config()
impl_JobBrowserBFF = JobBrowserBFF(config.get_config())
class JSONObjectEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, set):
return list(obj)
if isinstance(obj, frozenset):
return list(obj)
if hasattr(obj, 'toJSONable'):
return obj.toJSONable()
return json.JSONEncoder.default(self, obj)
class JSONRPCServiceCustom(JSONRPCService):
def call(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in a JSON
string or None if there is none.
Arguments:
jsondata -- remote method call in jsonrpc format
"""
result = self.call_py(ctx, jsondata)
if result is not None:
return json.dumps(result, cls=JSONObjectEncoder)
return None
def _call_method(self, ctx, request):
"""Calls given method with given params and returns it value."""
method = self.method_data[request['method']]['method']
params = request.get('params', None)
result = None
try:
if isinstance(params, list):
# Does it have enough arguments?
if len(params) < self._man_args(method) - 1:
raise InvalidParamsError(data={'issue': 'not enough arguments'})
# Does it have too many arguments?
if(not self._vargs(method) and len(params) >
self._max_args(method) - 1):
raise InvalidParamsError(data={'issue': 'too many arguments'})
result = method(ctx, *params)
elif isinstance(params, dict):
# Do not accept keyword arguments if the jsonrpc version is
# not >=2.0
if request['jsonrpc'] < 20:
raise KeywordError
result = method(ctx, params)
else: # No params
result = method(ctx)
except JSONRPCError:
raise
except Exception as e:
# log.exception('method %s threw an exception' % request['method'])
# Exception was raised inside the method.
newerr = JSONServerError()
newerr.trace = traceback.format_exc()
if len(e.args) == 1:
newerr.data = repr(e.args[0])
else:
newerr.data = repr(e.args)
raise newerr
return result
def call_py(self, ctx, jsondata):
"""
Calls jsonrpc service's method and returns its return value in python
object format or None if there is none.
This method is same as call() except the return value is a python
object instead of JSON string. This method is mainly only useful for
debugging purposes.
"""
rdata = jsondata
# we already deserialize the json string earlier in the server code, no
# need to do it again
# try:
# rdata = json.loads(jsondata)
# except ValueError:
# raise ParseError
# set some default values for error handling
request = self._get_default_vals()
if isinstance(rdata, dict) and rdata:
# It's a single request.
self._fill_request(request, rdata)
respond = self._handle_request(ctx, request)
# Don't respond to notifications
if respond is None:
return None
return respond
elif isinstance(rdata, list) and rdata:
# It's a batch.
requests = []
responds = []
for rdata_ in rdata:
# set some default values for error handling
request_ = self._get_default_vals()
self._fill_request(request_, rdata_)
requests.append(request_)
for request_ in requests:
respond = self._handle_request(ctx, request_)
# Don't respond to notifications
if respond is not None:
responds.append(respond)
if responds:
return responds
# Nothing to respond.
return None
else:
# empty dict, list or wrong type
raise InvalidRequestError
def _handle_request(self, ctx, request):
"""Handles given request and returns its response."""
if 'types' in self.method_data[request['method']]:
self._validate_params_types(request['method'], request['params'])
result = self._call_method(ctx, request)
# Do not respond to notifications.
if request['id'] is None:
return None
respond = {}
self._fill_ver(request['jsonrpc'], respond)
respond['result'] = result
respond['id'] = request['id']
return respond
class MethodContext(dict):
def __init__(self, logger):
self['client_ip'] = None
self['user_id'] = None
self['authenticated'] = None
self['token'] = None
self['module'] = None
self['method'] = None
self['call_id'] = None
self['rpc_context'] = None
self._debug_levels = set([7, 8, 9, 'DEBUG', 'DEBUG2', 'DEBUG3'])
self._logger = logger
def log_err(self, message):
self._log(log.ERR, message)
def log_info(self, message):
self._log(log.INFO, message)
def log_debug(self, message, level=1):
if level in self._debug_levels:
pass
else:
level = int(level)
if level < 1 or level > 3:
raise ValueError("Illegal log level: " + str(level))
level = level + 6
self._log(level, message)
def set_log_level(self, level):
self._logger.set_log_level(level)
def get_log_level(self):
return self._logger.get_log_level()
def clear_log_level(self):
self._logger.clear_user_log_level()
def _log(self, level, message):
self._logger.log_message(level, message, self['client_ip'],
self['user_id'], self['module'],
self['method'], self['call_id'])
class ServerError(Exception):
'''
The call returned an error. Fields:
name - the name of the error.
code - the error code.
message - a human readable error message.
data - the server side stacktrace.
'''
def __init__(self, name, code, message, data=None, error=None):
super(Exception, self).__init__(message)
self.name = name
self.code = code
self.message = message if message else ''
if data:
self.data = data
elif error:
self.data = {
'error': error
}
def __str__(self):
return self.name + ': ' + str(self.code) + '. ' + self.message + \
'\n' + self.data
def getIPAddress(environ):
xFF = environ.get('HTTP_X_FORWARDED_FOR')
realIP = environ.get('HTTP_X_REAL_IP')
trustXHeaders = config.test('dont_trust_x_ip_headers', 'true', True)
trustXHeaders = config is None or \
config.get('dont_trust_x_ip_headers') != 'true'
if (trustXHeaders):
if (xFF):
return xFF.split(',')[0].strip()
if (realIP):
return realIP.strip()
return environ.get('REMOTE_ADDR')
class Application(object):
# Wrap the wsgi handler in a class definition so that we can
# do some initialization and avoid regenerating stuff over
# and over
def logcallback(self):
self.serverlog.set_log_file(self.userlog.get_log_file())
def log(self, level, context, message):
self.serverlog.log_message(level, message, context['client_ip'],
context['user_id'], context['module'],
context['method'], context['call_id'])
def __init__(self):
submod = config.get_service_name() or 'JobBrowserBFF'
self.userlog = log.log(
submod, ip_address=True, authuser=True, module=True, method=True,
call_id=True, changecallback=self.logcallback,
config=config.get_config_file())
self.serverlog = log.log(
submod, ip_address=True, authuser=True, module=True, method=True,
call_id=True, logfile=self.userlog.get_log_file())
self.serverlog.set_log_level(6)
self.rpc_service = JSONRPCServiceCustom()
self.method_authentication = dict()
self.rpc_service.add(impl_JobBrowserBFF.get_jobs,
name='JobBrowserBFF.get_jobs')
self.method_authentication['JobBrowserBFF.get_jobs'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.query_jobs,
name='JobBrowserBFF.query_jobs')
self.method_authentication['JobBrowserBFF.query_jobs'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.get_job_log,
name='JobBrowserBFF.get_job_log')
self.method_authentication['JobBrowserBFF.get_job_log'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.cancel_job,
name='JobBrowserBFF.cancel_job')
self.method_authentication['JobBrowserBFF.cancel_job'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.get_job_types,
name='JobBrowserBFF.get_job_types')
self.method_authentication['JobBrowserBFF.get_job_types'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.get_job_states,
name='JobBrowserBFF.get_job_states')
self.method_authentication['JobBrowserBFF.get_job_states'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.get_client_groups,
name='JobBrowserBFF.get_client_groups')
self.method_authentication['JobBrowserBFF.get_client_groups'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.get_searchable_job_fields,
name='JobBrowserBFF.get_searchable_job_fields')
self.method_authentication['JobBrowserBFF.get_searchable_job_fields'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.get_sort_specs,
name='JobBrowserBFF.get_sort_specs')
self.method_authentication['JobBrowserBFF.get_sort_specs'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.get_log_levels,
name='JobBrowserBFF.get_log_levels')
self.method_authentication['JobBrowserBFF.get_log_levels'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.is_admin,
name='JobBrowserBFF.is_admin')
self.method_authentication['JobBrowserBFF.is_admin'] = 'required' # noqa
self.rpc_service.add(impl_JobBrowserBFF.status,
name='JobBrowserBFF.status')
authurl = config.get(AUTH) if config else None
self.auth_client = _KBaseAuth(authurl)
def handle_call(self, environ, ctx):
try:
body_size = int(environ.get('CONTENT_LENGTH', 0))
except ValueError:
body_size = 0
if environ['REQUEST_METHOD'] == 'OPTIONS':
return '', None
if body_size == 0:
return None, self.process_error({
'error': {
'code': -32700,
'message': "Parse error - no request data",
}
}, ctx)
try:
request_body = environ['wsgi.input'].read(body_size)
except Exception as e:
return None, self.process_error({
'error': {
'code': -32603,
'message': 'Internal error',
'data': {
'exception': str(e)
}
}
}, ctx)
try:
request = json.loads(request_body)
except ValueError as ve:
return None, self.process_error({
'error': {
'code': -32700,
'message': "Parse error - parsing the request as json",
'data': {
'exception': str(ve)
}
}
}, ctx)
ctx['module'], ctx['method'] = request['method'].split('.')
ctx['call_id'] = request['id']
ctx['rpc_context'] = {
'call_stack': [{
'time': self.now_in_utc(),
'method': request['method']
}]
}
# Provenance not used in jsonrpc calls as far as I can tell.
# Perhaps propagated to any local methods called? But I don't think any
# pure sdk dynamic services use local methods, so...
# TODO: ensure that prov_action cannot be used, before removing entirely.
# prov_action = {
# 'service': ctx['module'],
# 'method': ctx['method'],
# 'method_params': request['params']
# }
try:
token = environ.get('HTTP_AUTHORIZATION')
# Enforce authentication requirement.
method_name = request['method']
auth_req = self.method_authentication.get(method_name, 'none')
if auth_req != 'none':
if token is None and auth_req == 'required':
# TODO: replace with actual error return
err = JSONServerError()
err.data = (
'Authentication required for ' +
'JobBrowserBFF ' +
'but no authentication header was passed')
raise err
elif token is None and auth_req == 'optional':
pass
else:
try:
user = self.auth_client.get_user(token)
ctx['user_id'] = user
ctx['authenticated'] = 1
ctx['token'] = token
except Exception as e:
if auth_req == 'required':
err = JSONServerError()
err.data = \
"Token validation failed: %s" % e
raise err
if (environ.get('HTTP_X_FORWARDED_FOR')):
self.log(log.INFO, ctx, 'X-Forwarded-For: ' + environ.get('HTTP_X_FORWARDED_FOR'))
self.log(log.INFO, ctx, 'start method')
rpc_result = self.rpc_service.call(ctx, request)
self.log(log.INFO, ctx, 'end method')
if not rpc_result:
return None, self.process_error({
'error': {
'code': -32001,
'message': 'Empty response from method'
}
}, ctx, request)
# TADA!
return rpc_result, None
except JSONRPCError as jre:
response = {
'error': {
'code': jre.code,
'message': jre.message,
'data': jre.data
}
}
trace = jre.trace if hasattr(jre, 'trace') else None
return None, self.process_error(response, ctx, request, trace)
except Exception as ex:
trace = ex.trace if hasattr(ex, 'trace') else None
response = {
'error': {
'code': -32000,
'message': 'Unexpected Server Error'
}
}
return None, self.process_error(response, ctx, request, trace)
def __call__(self, environ, start_response):
ctx = MethodContext(self.userlog)
ctx['client_ip'] = getIPAddress(environ)
result, error = self.handle_call(environ, ctx)
if result is not None:
response_body = result
status = '200 OK'
else:
response_body = error
status = '200 OK'
# TODO: CORS should not be handled here! That should be an administrative
# decision at the proxy level.
response_headers = [
('Access-Control-Allow-Origin', '*'),
('Access-Control-Allow-Headers', environ.get(
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS', 'authorization')),
('content-type', 'application/json'),
('content-length', str(len(response_body)))]
start_response(status, response_headers)
return [response_body.encode('utf8')]
def process_error(self, response, context, request=None, trace=None):
response['jsonrpc'] = '2.0'
# If trace provided, log it.
if trace:
trace = trace.split('\n')[0:-1]
self.log(log.ERR, context, trace)
# TODO: trace down how 'data' is getting corrupted as a string...
if 'data' not in response['error']:
response['error']['data'] = {}
elif not isinstance(response['error']['data'], dict):
response['error']['data'] = {
'message': response['error']['data']
}
response['error']['data']['trace'] = trace
# Errors early in the processing phase before a valid request is
# available will not have a jsonrpc request available.
if request is None:
response['id'] = None
else:
response['id'] = request['id']
return json.dumps(response)
def now_in_utc(self):
# noqa Taken from http://stackoverflow.com/questions/3401428/how-to-get-an-isoformat-datetime-string-including-the-default-timezone @IgnorePep8
dtnow = datetime.datetime.now()
dtutcnow = datetime.datetime.utcnow()
delta = dtnow - dtutcnow
hh, mm = divmod((delta.days * 24 * 60 * 60 + delta.seconds + 30) // 60,
60)
return "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
application = Application()
# This is the uwsgi application dictionary. On startup uwsgi will look
# for this dict and pull its configuration from here.
# This simply lists where to "mount" the application in the URL path
#
# This uwsgi module "magically" appears when running the app within
# uwsgi and is not available otherwise, so wrap an exception handler
# around it
#
# To run this server in uwsgi with 4 workers listening on port 9999 use:
# uwsgi -M -p 4 --http :9999 --wsgi-file _this_file_
# To run a using the single threaded python BaseHTTP service
# listening on port 9999 by default execute this file
#
try:
import uwsgi
# Before we do anything with the application, see if the
# configs specify patching all std routines to be asynch
# *ONLY* use this if you are going to wrap the service in
# a wsgi container that has enabled gevent, such as
# uwsgi with the --gevent option
if config is not None and config.get('gevent_monkeypatch_all', False):
print("Monkeypatching std libraries for async")
from gevent import monkey
monkey.patch_all()
uwsgi.applications = {'': application}
except ImportError:
# Not available outside of wsgi, ignore
pass
_proc = None
def start_server(host='localhost', port=0, newprocess=False):
'''
By default, will start the server on localhost on a system assigned port
in the main thread. Execution of the main thread will stay in the server
main loop until interrupted. To run the server in a separate process, and
thus allow the stop_server method to be called, set newprocess = True. This
will also allow returning of the port number.'''
global _proc
if _proc:
raise RuntimeError('server is already running')
httpd = make_server(host, port, application) | _proc = Process(target=httpd.serve_forever)
_proc.daemon = True
_proc.start()
else:
httpd.serve_forever()
return port
def stop_server():
global _proc
_proc.terminate()
_proc = None
if __name__ == "__main__":
try:
opts, args = getopt(sys.argv[1:], "", ["port=", "host="])
except GetoptError as err:
# print help information and exit:
print(str(err)) # will print something like "option -a not recognized"
sys.exit(2)
port = 9999
host = 'localhost'
for o, a in opts:
if o == '--port':
port = int(a)
elif o == '--host':
host = a
print("Host set to %s" % host)
else:
assert False, "unhandled option"
start_server(host=host, port=port) | port = httpd.server_address[1]
print("Listening on port %s" % port)
if newprocess: |
main.go | package p003
import (
"strconv"
"github.com/JustinKuli/project-euler/pkg/prime"
)
// Solve this problem:
// What is the largest prime factor of the number 600851475143?
func Solve() string | {
factors, err := prime.FactorsOf(uint64(600_851_475_143))
if err != nil {
return "Error"
}
return strconv.Itoa(int(factors[len(factors)-1]))
} |
|
login.component.ts | import { ChangeDetectorRef, Component, Inject, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NbAuthService, NbLoginComponent, NB_AUTH_OPTIONS } from '@nebular/auth';
import { environment } from './../../../environments/environment';
@Component({
selector: 'ngx-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class NgxLoginComponent extends NbLoginComponent implements OnInit {
environment = environment;
constructor(
public readonly nbAuthService: NbAuthService,
public readonly cdr: ChangeDetectorRef,
public readonly router: Router,
@Inject(NB_AUTH_OPTIONS) options
) {
super(nbAuthService, options, cdr, router);
}
ngOnInit() {
if (this.environment.DEMO) {
this.user.email = '[email protected]';
this.user.password = 'admin';
}
}
} | ||
artifact-extract-task.ts | import * as yauzl from 'yauzl';
import { join } from 'path';
import mkdirp from 'mkdirp';
import { createWriteStream, existsSync } from 'fs';
import { IArtifact } from '../../artifact';
import { ArtifactTask } from '../artifact-task';
import { exists } from '../../../util';
export interface IArtifactExtractTaskProgress {
total: number;
completed: number;
}
export const enum ArtifactExtractTaskEvent {
PROGRESS = 'progress',
EXCLUDE = 'exclude',
FINISH = 'finish',
ENTRY = 'entry',
ERROR = 'error',
}
export interface IArtifactExtractTaskEntry {
fileName: string;
uncompressedSize: number;
compressedSize: number;
}
export class ArtifactExtractTask extends ArtifactTask {
constructor(
artifact: Partial<IArtifact>,
public readonly artifactRoot: string,
public readonly extractionRoot: string,
public exclude: string[] = ['META-INF/'],
) {
super(artifact);
}
async start(): Promise<this> {
const extractionRootExist = await exists(this.extractionRoot);
if (!extractionRootExist) {
await mkdirp(this.extractionRoot);
}
return new Promise<this>((resolve, reject) => {
const fileOptions: yauzl.Options = { autoClose: true, lazyEntries: true };
const filePath = join(this.artifactRoot, this.artifact.path);
yauzl.open(filePath, fileOptions, (err, file) => {
if (err) {
return reject(err);
}
if (!file) {
return reject(new Error('cannot open zip file'));
}
const progress: IArtifactExtractTaskProgress = {
total: file.entryCount,
completed: 0,
};
const nextEntry = () => {
progress.completed++;
this.emit(ArtifactExtractTaskEvent.PROGRESS, progress);
file.readEntry();
};
file
.on('entry', (entry: yauzl.Entry) => {
const {
fileName,
uncompressedSize,
compressedSize,
} = entry;
const _entry: IArtifactExtractTaskEntry = {
fileName,
uncompressedSize,
compressedSize,
};
this.emit(ArtifactExtractTaskEvent.ENTRY, _entry);
const exclude: boolean = this.exclude
.map(e => entry.fileName.startsWith(e))
.includes(true);
if (exclude) {
this.emit(ArtifactExtractTaskEvent.EXCLUDE, fileName);
return nextEntry();
} |
file.openReadStream(entry, (err, readStream) => {
if (err) {
return reject(err);
}
if (!readStream) {
return reject(new Error('cannot open read stream from zip file'));
}
const filePath = join(this.extractionRoot, fileName);
if (fileName.endsWith('/')) {
try {
mkdirp.sync(filePath);
} catch (err) {
this.emit(ArtifactExtractTaskEvent.ERROR, err);
}
return nextEntry();
}
if (existsSync(filePath)) {
return nextEntry();
}
const writeStream = createWriteStream(filePath);
writeStream
.on('finish', () => {
nextEntry();
})
.on('error', (err) => {
this.emit(ArtifactExtractTaskEvent.ERROR, err);
});
readStream.pipe(writeStream);
});
})
.on('end', () => {
this.emit(ArtifactExtractTaskEvent.FINISH);
resolve(this);
});
file.readEntry(); // start read entries
});
});
}
} | |
main.go | package main
import (
"fmt"
"os"
"os/user"
"github.com/ujuc/monkey/internal/repl"
)
func main() | {
user, err := user.Current()
if err != nil {
panic(err)
}
fmt.Printf("Hello %s! This is the Monkey programming language!\n", user.Username)
fmt.Printf("Feel free to type in commands\n")
repl.Start(os.Stdin, os.Stdout)
} |
|
output.rs | //! # Convert from SCSS AST to CSS
use std::{io::Write, mem};
use codemap::CodeMap;
use crate::{
atrule::{
keyframes::{Keyframes, KeyframesRuleSet, KeyframesSelector},
media::MediaRule,
SupportsRule, UnknownAtRule,
},
error::SassResult,
parse::Stmt,
selector::{ComplexSelector, ComplexSelectorComponent, Selector},
style::Style,
OutputStyle,
};
#[derive(Debug, Clone)]
struct ToplevelUnknownAtRule {
name: String,
params: String,
body: Vec<Stmt>,
}
#[derive(Debug, Clone)]
enum Toplevel {
RuleSet(Selector, Vec<BlockEntry>),
MultilineComment(String),
UnknownAtRule(Box<ToplevelUnknownAtRule>),
Keyframes(Box<Keyframes>),
KeyframesRuleSet(Vec<KeyframesSelector>, Vec<BlockEntry>),
Media { query: String, body: Vec<Stmt> },
Supports { params: String, body: Vec<Stmt> },
Newline,
// todo: do we actually need a toplevel style variant?
Style(Style),
Import(String),
}
#[derive(Debug, Clone)]
enum BlockEntry {
Style(Style),
MultilineComment(String),
}
impl BlockEntry {
pub fn to_string(&self) -> SassResult<String> {
match self {
BlockEntry::Style(s) => s.to_string(),
BlockEntry::MultilineComment(s) => Ok(format!("/*{}*/", s)),
}
}
}
impl Toplevel {
const fn new_rule(selector: Selector) -> Self {
Toplevel::RuleSet(selector, Vec::new())
}
fn new_keyframes_rule(selector: Vec<KeyframesSelector>) -> Self {
Toplevel::KeyframesRuleSet(selector, Vec::new())
}
fn push_style(&mut self, s: Style) {
if s.value.is_null() {
return;
}
if let Toplevel::RuleSet(_, entries) | Toplevel::KeyframesRuleSet(_, entries) = self {
entries.push(BlockEntry::Style(s));
} else {
panic!();
}
}
fn push_comment(&mut self, s: String) {
if let Toplevel::RuleSet(_, entries) | Toplevel::KeyframesRuleSet(_, entries) = self {
entries.push(BlockEntry::MultilineComment(s));
} else {
panic!();
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct Css {
blocks: Vec<Toplevel>,
in_at_rule: bool,
allows_charset: bool,
plain_imports: Vec<Toplevel>,
}
impl Css {
pub const fn new(in_at_rule: bool, allows_charset: bool) -> Self {
Css {
blocks: Vec::new(),
in_at_rule,
allows_charset,
plain_imports: Vec::new(),
}
}
pub(crate) fn from_stmts(
s: Vec<Stmt>,
in_at_rule: bool,
allows_charset: bool,
) -> SassResult<Self> {
Css::new(in_at_rule, allows_charset).parse_stylesheet(s)
}
fn parse_stmt(&mut self, stmt: Stmt) -> SassResult<Vec<Toplevel>> {
Ok(match stmt {
Stmt::RuleSet { selector, body } => {
if body.is_empty() {
return Ok(Vec::new());
}
let selector = selector.into_selector().remove_placeholders();
if selector.is_empty() {
return Ok(Vec::new());
}
let mut vals = vec![Toplevel::new_rule(selector)];
for rule in body {
match rule {
Stmt::RuleSet { .. } => vals.extend(self.parse_stmt(rule)?),
Stmt::Style(s) => vals.first_mut().unwrap().push_style(s),
Stmt::Comment(s) => vals.first_mut().unwrap().push_comment(s),
Stmt::Media(m) => {
let MediaRule { query, body, .. } = *m;
vals.push(Toplevel::Media { query, body });
}
Stmt::Supports(s) => {
let SupportsRule { params, body } = *s;
vals.push(Toplevel::Supports { params, body });
}
Stmt::UnknownAtRule(u) => {
let UnknownAtRule {
params, body, name, ..
} = *u;
vals.push(Toplevel::UnknownAtRule(Box::new(ToplevelUnknownAtRule {
name,
params,
body,
})));
}
Stmt::Return(..) => unreachable!(),
Stmt::AtRoot { body } => {
body.into_iter().try_for_each(|r| -> SassResult<()> {
vals.append(&mut self.parse_stmt(r)?);
Ok(())
})?;
}
Stmt::Keyframes(k) => {
let Keyframes { rule, name, body } = *k;
vals.push(Toplevel::Keyframes(Box::new(Keyframes {
rule,
name,
body,
})));
}
k @ Stmt::KeyframesRuleSet(..) => {
unreachable!("@keyframes ruleset {:?}", k);
}
Stmt::Import(s) => self.plain_imports.push(Toplevel::Import(s)),
};
}
vals
}
Stmt::Comment(s) => vec![Toplevel::MultilineComment(s)],
Stmt::Import(s) => {
self.plain_imports.push(Toplevel::Import(s));
Vec::new()
}
Stmt::Style(s) => vec![Toplevel::Style(s)],
Stmt::Media(m) => {
let MediaRule { query, body, .. } = *m;
vec![Toplevel::Media { query, body }]
}
Stmt::Supports(s) => {
let SupportsRule { params, body } = *s;
vec![Toplevel::Supports { params, body }]
}
Stmt::UnknownAtRule(u) => {
let UnknownAtRule {
params, body, name, ..
} = *u;
vec![Toplevel::UnknownAtRule(Box::new(ToplevelUnknownAtRule {
name,
params,
body,
}))]
}
Stmt::Return(..) => unreachable!("@return: {:?}", stmt),
Stmt::AtRoot { .. } => unreachable!("@at-root: {:?}", stmt),
Stmt::Keyframes(k) => vec![Toplevel::Keyframes(k)],
Stmt::KeyframesRuleSet(k) => {
let KeyframesRuleSet { body, selector } = *k;
if body.is_empty() {
return Ok(Vec::new());
}
let mut vals = vec![Toplevel::new_keyframes_rule(selector)];
for rule in body {
match rule {
Stmt::Style(s) => vals.first_mut().unwrap().push_style(s),
Stmt::KeyframesRuleSet(..) => vals.extend(self.parse_stmt(rule)?),
_ => todo!(),
}
}
vals
}
})
}
fn parse_stylesheet(mut self, stmts: Vec<Stmt>) -> SassResult<Css> {
let mut is_first = true;
for stmt in stmts {
let v = self.parse_stmt(stmt)?;
// this is how we print newlines between unrelated styles
// it could probably be refactored
if !v.is_empty() {
if let Some(Toplevel::MultilineComment(..)) = v.first() {
} else if is_first {
is_first = false;
} else {
self.blocks.push(Toplevel::Newline);
}
self.blocks.extend(v);
}
}
// move plain imports to top of file
self.plain_imports.append(&mut self.blocks);
mem::swap(&mut self.plain_imports, &mut self.blocks);
Ok(self)
}
pub fn pretty_print(self, map: &CodeMap, style: OutputStyle) -> SassResult<String> {
let mut buf = Vec::new();
let allows_charset = self.allows_charset;
match style {
OutputStyle::Compressed => {
CompressedFormatter::default().write_css(&mut buf, self, map)?;
}
OutputStyle::Expanded => ExpandedFormatter::default().write_css(&mut buf, self, map)?,
}
// TODO: check for this before writing
let show_charset = allows_charset && buf.iter().any(|s| !s.is_ascii());
let out = unsafe { String::from_utf8_unchecked(buf) };
Ok(if show_charset {
match style {
OutputStyle::Compressed => format!("\u{FEFF}{}", out),
OutputStyle::Expanded => format!("@charset \"UTF-8\";\n{}", out),
}
} else {
out
})
}
}
trait Formatter {
fn write_css(&mut self, buf: &mut Vec<u8>, css: Css, map: &CodeMap) -> SassResult<()>;
}
#[derive(Debug, Default)]
struct CompressedFormatter {}
impl Formatter for CompressedFormatter {
fn write_css(&mut self, buf: &mut Vec<u8>, mut css: Css, map: &CodeMap) -> SassResult<()> {
for block in mem::take(&mut css.blocks) {
match block {
Toplevel::RuleSet(selector, styles) => {
if styles.is_empty() {
continue;
}
let mut complexes = selector.0.components.iter().filter(|c| !c.is_invisible());
if let Some(complex) = complexes.next() {
self.write_complex(buf, complex)?;
}
for complex in complexes {
write!(buf, ",")?;
self.write_complex(buf, complex)?;
}
write!(buf, "{{")?;
self.write_block_entry(buf, &styles)?;
write!(buf, "}}")?;
}
Toplevel::KeyframesRuleSet(selectors, styles) => {
if styles.is_empty() {
continue;
}
let mut selectors = selectors.iter();
if let Some(selector) = selectors.next() {
match selector {
KeyframesSelector::To => write!(buf, "to")?,
KeyframesSelector::From => write!(buf, "from")?,
KeyframesSelector::Percent(p) => write!(buf, "{}%", p)?,
}
}
for selector in selectors {
match selector {
KeyframesSelector::To => write!(buf, ",to")?,
KeyframesSelector::From => write!(buf, ",from")?,
KeyframesSelector::Percent(p) => write!(buf, ",{}%", p)?,
}
}
write!(buf, "{{")?;
self.write_block_entry(buf, &styles)?;
write!(buf, "}}")?;
}
Toplevel::MultilineComment(..) => continue,
Toplevel::Import(s) => {
write!(buf, "@import {};", s)?;
}
Toplevel::UnknownAtRule(u) => {
let ToplevelUnknownAtRule { params, name, body } = *u;
if params.is_empty() {
write!(buf, "@{}", name)?;
} else {
write!(buf, "@{} {}", name, params)?;
}
if body.is_empty() {
write!(buf, ";")?;
continue;
}
write!(buf, "{{")?;
let css = Css::from_stmts(body, true, css.allows_charset)?;
self.write_css(buf, css, map)?;
write!(buf, "}}")?;
}
Toplevel::Keyframes(k) => {
let Keyframes { rule, name, body } = *k;
write!(buf, "@{}", rule)?;
if !name.is_empty() {
write!(buf, " {}", name)?;
}
if body.is_empty() {
write!(buf, "{{}}")?;
continue;
}
write!(buf, "{{")?;
let css = Css::from_stmts(body, true, css.allows_charset)?;
self.write_css(buf, css, map)?;
write!(buf, "}}")?;
}
Toplevel::Supports { params, body } => {
if params.is_empty() {
write!(buf, "@supports")?;
} else {
write!(buf, "@supports {}", params)?;
}
if body.is_empty() {
write!(buf, ";")?;
continue;
}
write!(buf, "{{")?;
let css = Css::from_stmts(body, true, css.allows_charset)?;
self.write_css(buf, css, map)?;
write!(buf, "}}")?;
}
Toplevel::Media { query, body } => {
if body.is_empty() {
continue;
}
write!(buf, "@media {}{{", query)?;
let css = Css::from_stmts(body, true, css.allows_charset)?;
self.write_css(buf, css, map)?;
write!(buf, "}}")?;
}
Toplevel::Style(style) => {
let value = style.value.node.to_css_string(style.value.span)?;
write!(buf, "{}:{};", style.property, value)?;
}
Toplevel::Newline => {}
}
}
Ok(())
}
}
// this could be a trait implemented on value itself
#[allow(clippy::unused_self)]
impl CompressedFormatter {
fn write_complex(&self, buf: &mut Vec<u8>, complex: &ComplexSelector) -> SassResult<()> {
let mut was_compound = false;
for component in &complex.components {
match component {
ComplexSelectorComponent::Compound(c) if was_compound => write!(buf, " {}", c)?,
ComplexSelectorComponent::Compound(c) => write!(buf, "{}", c)?,
ComplexSelectorComponent::Combinator(c) => write!(buf, "{}", c)?,
}
was_compound = matches!(component, ComplexSelectorComponent::Compound(_));
}
Ok(())
}
fn write_block_entry(&self, buf: &mut Vec<u8>, styles: &[BlockEntry]) -> SassResult<()> {
let mut styles = styles.iter();
while let Some(style) = styles.next() {
match style {
BlockEntry::Style(s) => {
let value = s.value.node.to_css_string(s.value.span)?;
write!(buf, "{}:{}", s.property, value)?;
break;
}
BlockEntry::MultilineComment(..) => continue,
}
}
for style in styles {
match style {
BlockEntry::Style(s) => {
let value = s.value.node.to_css_string(s.value.span)?;
write!(buf, ";{}:{}", s.property, value)?;
}
BlockEntry::MultilineComment(..) => continue,
}
}
Ok(())
}
}
#[derive(Debug, Default)]
struct ExpandedFormatter {
nesting: usize,
}
impl Formatter for ExpandedFormatter {
fn write_css(&mut self, buf: &mut Vec<u8>, mut css: Css, map: &CodeMap) -> SassResult<()> {
let mut has_written = false;
let padding = " ".repeat(self.nesting);
let mut should_emit_newline = false;
self.nesting += 1;
for block in mem::take(&mut css.blocks) {
match block {
Toplevel::RuleSet(selector, styles) => {
if styles.is_empty() {
continue;
}
has_written = true;
if should_emit_newline && !css.in_at_rule {
should_emit_newline = false;
writeln!(buf)?;
}
writeln!(buf, "{}{} {{", padding, selector)?;
for style in styles {
writeln!(buf, "{} {}", padding, style.to_string()?)?;
}
writeln!(buf, "{}}}", padding)?;
}
Toplevel::KeyframesRuleSet(selector, body) => {
if body.is_empty() {
continue;
}
has_written = true;
writeln!(
buf,
"{}{} {{",
padding,
selector
.into_iter()
.map(|s| s.to_string())
.collect::<Vec<String>>()
.join(", ")
)?;
for style in body {
writeln!(buf, "{} {}", padding, style.to_string()?)?;
}
writeln!(buf, "{}}}", padding)?;
}
Toplevel::MultilineComment(s) => {
has_written = true;
writeln!(buf, "{}/*{}*/", padding, s)?;
}
Toplevel::Import(s) => {
has_written = true;
writeln!(buf, "{}@import {};", padding, s)?;
}
Toplevel::UnknownAtRule(u) => {
let ToplevelUnknownAtRule { params, name, body } = *u;
if should_emit_newline {
should_emit_newline = false;
writeln!(buf)?;
}
if params.is_empty() {
write!(buf, "{}@{}", padding, name)?; |
if body.is_empty() {
writeln!(buf, ";")?;
continue;
}
writeln!(buf, " {{")?;
let css = Css::from_stmts(body, true, css.allows_charset)?;
self.write_css(buf, css, map)?;
writeln!(buf, "{}}}", padding)?;
}
Toplevel::Keyframes(k) => {
let Keyframes { rule, name, body } = *k;
if should_emit_newline {
should_emit_newline = false;
writeln!(buf)?;
}
write!(buf, "{}@{}", padding, rule)?;
if !name.is_empty() {
write!(buf, " {}", name)?;
}
if body.is_empty() {
writeln!(buf, " {{}}")?;
continue;
}
writeln!(buf, " {{")?;
let css = Css::from_stmts(body, true, css.allows_charset)?;
self.write_css(buf, css, map)?;
writeln!(buf, "{}}}", padding)?;
}
Toplevel::Supports { params, body } => {
if should_emit_newline {
should_emit_newline = false;
writeln!(buf)?;
}
if params.is_empty() {
write!(buf, "{}@supports", padding)?;
} else {
write!(buf, "{}@supports {}", padding, params)?;
}
if body.is_empty() {
writeln!(buf, ";")?;
continue;
}
writeln!(buf, " {{")?;
let css = Css::from_stmts(body, true, css.allows_charset)?;
self.write_css(buf, css, map)?;
writeln!(buf, "{}}}", padding)?;
}
Toplevel::Media { query, body } => {
if body.is_empty() {
continue;
}
writeln!(buf, "{}@media {} {{", padding, query)?;
let css = Css::from_stmts(body, true, css.allows_charset)?;
self.write_css(buf, css, map)?;
writeln!(buf, "{}}}", padding)?;
}
Toplevel::Style(s) => {
writeln!(buf, "{}{}", padding, s.to_string()?)?;
}
Toplevel::Newline => {
if has_written {
should_emit_newline = true;
}
continue;
}
}
}
self.nesting -= 1;
Ok(())
}
} | } else {
write!(buf, "{}@{} {}", padding, name, params)?;
} |
confidant.py | # -*- coding: utf-8 -*-
'''
An SDB module for getting credentials from confidant.
Configuring the Confidant module
================================
The module can be configured via sdb in the minion config:
.. code-block:: yaml
confidant:
driver: confidant
# The URL of the confidant web service
url: 'https://confidant-production.example.com'
# The context to use for KMS authentication
auth_context:
from: example-production-iad
to: confidant-production-iad
user_type: service
# The KMS master key to use for authentication
auth_key: "alias/authnz"
# Cache file for KMS auth token
token_cache_file: /run/confidant/confidant_token
# The duration of the validity of a token, in minutes
token_duration: 60
# key, keyid and region can be defined in the profile, but it's generally
# best to use IAM roles or environment variables for AWS auth.
keyid: 98nh9h9h908h09kjjk
key: jhf908gyeghehe0he0g8h9u0j0n0n09hj09h0
region: us-east-1
:depends: confidant-common, confidant-client
Module Documentation
====================
'''
from __future__ import absolute_import
# Import python libs
import logging
import copy
# Import third party libs
try:
import confidant.client
import confidant.formatter
HAS_LIBS = True
except ImportError:
HAS_LIBS = False
# Set up logging
log = logging.getLogger(__name__)
__virtualname__ = 'confidant'
def __virtual__():
'''
Only return if requests and boto are installed.
'''
if HAS_LIBS:
return __virtualname__
else:
return False
def | (key, profile=None):
'''
Read pillar data from Confidant via its API.
CLI Example:
salt myminion sdb.get 'sdb://confidant/credentials'
Valid keys are: credentials, credentials_metadata, result. credentials
returns a dict of joined credential_pairs, credentials_metadata returns a
dict of metadata relevant to the credentials mapped to the confidant
service, and result returns a bool that can be used to determine if the sdb
call succeded or failed to fetch credentials from confidant (or from local
cache). If result is false, the data in credentials or credentials_metadata
can't be trusted.
'''
# default to returning failure
ret = {'result': False, 'credentials': None, 'credentials_metadata': None}
profile_data = copy.deepcopy(profile)
if profile_data.get('disabled', False):
ret['result'] = True
return ret.get(key)
token_version = profile_data.get('token_version', 1)
try:
url = profile_data['url']
auth_key = profile_data['auth_key']
auth_context = profile_data['auth_context']
role = auth_context['from']
except (KeyError, TypeError):
msg = ('profile has undefined url, auth_key or auth_context')
log.debug(msg)
return ret.get(key)
region = profile_data.get('region', 'us-east-1')
token_duration = profile_data.get('token_duration', 60)
retries = profile_data.get('retries', 5)
token_cache_file = profile_data.get('token_cache_file')
backoff = profile_data.get('backoff', 1)
client = confidant.client.ConfidantClient(
url,
auth_key,
auth_context,
token_lifetime=token_duration,
token_version=token_version,
token_cache_file=token_cache_file,
region=region,
retries=retries,
backoff=backoff
)
try:
data = client.get_service(
role,
decrypt_blind=True
)
except confidant.client.TokenCreationError:
return ret.get(key)
if not data['result']:
return ret.get(key)
ret = confidant.formatter.combined_credential_pair_format(data)
ret['result'] = True
return ret.get(key)
| get |
Staff.js | import axios from 'axios';
import React, { Component } from "react";
class Staff extends Component {
constructor(props) {
super(props)
this.state = {
gallery: [],
};
}
componentDidMount() {
axios.get('http://localhost:8000/api/gallery/')
.then(res => {
this.setState({
gallery: res.data
});
})
.catch((error) => {
console.log(error);
}) | render(){
return(
this.state.gallery.map((ga, i) => {
return(
<OwlCarousel className="owl-carousel staff-carousel" items={4} margin={8} autoplay ={true}>
<div className="member" data-aos-delay={100}>
<div className="pic"><img src="assets/img/team/team-1.jpg" className="img-fluid" alt="" /></div>
<div className="member-info">
<h4>Walter White</h4>
<span>Chief Executive Officer</span>
<div className="social">
<a href><i className="icofont-twitter" /></a>
<a href><i className="icofont-facebook" /></a>
<a href><i className="icofont-instagram" /></a>
<a href><i className="icofont-linkedin" /></a>
</div>
</div>
</div> </OwlCarousel>
)})
)}}
export default Staff; | }
|
logoHeader.tsx | import * as React from 'react';
import classNames from './logoHeader.classNames';
export enum LogoColors {
white = 'white',
gray = 'gray'
}
export interface LogoProps extends React.Props<any> {
logoColor?: LogoColors;
}
export const LogoHeader = (props: LogoProps) => (
<header className={classNames().root}>
<img
className={classNames().logo}
alt='Microsoft' | src={`https://assets.onestore.ms/cdnfiles/external/uhf/long/9a49a7e9d8e881327e81b9eb43dabc01de70a9bb/images/microsoft-${props.logoColor || LogoColors.white}.png`}
/>
{props.children}
</header>); | |
eventos.js | /*var eventos = [
{ "idevento": 3,
"idlocal": 3,
"idesporte":2,
"idcategoria": 2,
"idmodalidade": -1,
"descricao": "Jogo de fulano vs etc",
"horario": "00:50",
"local": "maracanã",
"data": "22/05/2016"
},
{
"idevento": 2,
"idlocal": 3,
"idesporte":2,
"idcategoria": 2,
"idmodalidade": -1,
"descricao": "Jogo de fulano vs etc",
"horario": "00:50",
"local": "maracanã",
"data": "22/05/2016"
},
{
"idevento": 1,
"idlocal": 3,
"idesporte":1,
"idcategoria": 1,
"idmodalidade": -1,
"descricao": "Jogo de fulano vs ciclano",
"horario": "00:50",
"local": "maracanã",
"data": "22/05/2016"
}
];*/
var eventosTotal = [
{"data":"2016-08-03",
"conteudo": [{"idevento": 1,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-03 19:00:00","nome": "Minerao","idlocal": 18}, {"idevento": 2,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-03 13:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 6,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-03 15:00:00","nome": "Arena Corinthians","idlocal": 35}]
},
{"data":"2016-08-04",
"conteudo": [{"idevento": 7,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-04 18:00:00","nome": "Arena da Amazonia","idlocal": 1}, {"idevento": 8,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-04 17:00:00","nome": "Arena Fonte Nova","idlocal": 11}, {"idevento": 9,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-04 13:00:00","nome": "Estadio Mane Garrincha","idlocal": 17}, {"idevento": 10,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-04 15:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}]
},
{"data":"2016-08-05",
"conteudo": [{"idevento": 16,"idesporte": 28,"idmodalidade": -1,"idcategoria": 273,"data": "2016-08-05 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 17,"idesporte": 28,"idmodalidade": -1,"idcategoria": 273,"data": "2016-08-05 14:00:00","nome": "Sambodromo","idlocal": 34}] | },
{"data":"2016-08-07",
"conteudo": [{"idevento": 66,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-07 18:00:00","nome": "Arena da Amazonia","idlocal": 1}, {"idevento": 67,"idesporte": 24,"idmodalidade": -1,"idcategoria": 251,"data": "2016-08-07 16:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 68,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-07 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 68,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-07 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 69,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-07 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 69,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-07 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 70,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-07 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 70,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-07 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 71,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-07 14:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 72,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-07 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 73,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-07 22:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 74,"idesporte": 14,"idmodalidade": -1,"idcategoria": 152,"data": "2016-08-07 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 74,"idesporte": 14,"idmodalidade": -1,"idcategoria": 145,"data": "2016-08-07 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 75,"idesporte": 14,"idmodalidade": -1,"idcategoria": 152,"data": "2016-08-07 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 75,"idesporte": 14,"idmodalidade": -1,"idcategoria": 145,"data": "2016-08-07 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 76,"idesporte": 7,"idmodalidade": 14,"idcategoria": 106,"data": "2016-08-07 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 76,"idesporte": 7,"idmodalidade": 14,"idcategoria": 106,"data": "2016-08-07 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 76,"idesporte": 7,"idmodalidade": 14,"idcategoria": 106,"data": "2016-08-07 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 76,"idesporte": 7,"idmodalidade": 14,"idcategoria": 106,"data": "2016-08-07 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 77,"idesporte": 7,"idmodalidade": 14,"idcategoria": 106,"data": "2016-08-07 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 77,"idesporte": 7,"idmodalidade": 14,"idcategoria": 106,"data": "2016-08-07 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 77,"idesporte": 7,"idmodalidade": 14,"idcategoria": 106,"data": "2016-08-07 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 77,"idesporte": 7,"idmodalidade": 14,"idcategoria": 106,"data": "2016-08-07 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 78,"idesporte": 23,"idmodalidade": -1,"idcategoria": 246,"data": "2016-08-07 11:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 79,"idesporte": 23,"idmodalidade": -1,"idcategoria": 246,"data": "2016-08-07 16:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 80,"idesporte": 12,"idmodalidade": 20,"idcategoria": 138,"data": "2016-08-07 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 80,"idesporte": 12,"idmodalidade": 20,"idcategoria": 139,"data": "2016-08-07 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 81,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-07 13:00:00","nome": "Arena Fonte Nova","idlocal": 11}, {"idevento": 82,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-07 09:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 83,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-07 14:40:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 84,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-07 19:50:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 85,"idesporte": 6,"idmodalidade": 10,"idcategoria": 89,"data": "2016-08-07 12:15:00","nome": "Forte de Copacabana","idlocal": 13}, {"idevento": 86,"idesporte": 22,"idmodalidade": -1,"idcategoria": 242,"data": "2016-08-07 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 86,"idesporte": 22,"idmodalidade": -1,"idcategoria": 234,"data": "2016-08-07 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 86,"idesporte": 22,"idmodalidade": -1,"idcategoria": 232,"data": "2016-08-07 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 86,"idesporte": 22,"idmodalidade": -1,"idcategoria": 231,"data": "2016-08-07 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 86,"idesporte": 22,"idmodalidade": -1,"idcategoria": 241,"data": "2016-08-07 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 86,"idesporte": 22,"idmodalidade": -1,"idcategoria": 233,"data": "2016-08-07 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 86,"idesporte": 22,"idmodalidade": -1,"idcategoria": 239,"data": "2016-08-07 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 86,"idesporte": 22,"idmodalidade": -1,"idcategoria": 236,"data": "2016-08-07 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 86,"idesporte": 22,"idmodalidade": -1,"idcategoria": 235,"data": "2016-08-07 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 86,"idesporte": 22,"idmodalidade": -1,"idcategoria": 240,"data": "2016-08-07 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 87,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-07 19:00:00","nome": "Estadio Mane Garrincha","idlocal": 17}, {"idevento": 88,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-07 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 89,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-07 15:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 90,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-07 20:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 91,"idesporte": 19,"idmodalidade": 24,"idcategoria": 204,"data": "2016-08-07 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 91,"idesporte": 19,"idmodalidade": 25,"idcategoria": 211,"data": "2016-08-07 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 91,"idesporte": 19,"idmodalidade": 24,"idcategoria": 205,"data": "2016-08-07 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 91,"idesporte": 19,"idmodalidade": 24,"idcategoria": 200,"data": "2016-08-07 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 91,"idesporte": 19,"idmodalidade": 24,"idcategoria": 205,"data": "2016-08-07 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 91,"idesporte": 19,"idmodalidade": 25,"idcategoria": 209,"data": "2016-08-07 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 24,"idcategoria": 200,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 24,"idcategoria": 197,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 25,"idcategoria": 209,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 27,"idcategoria": 219,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 26,"idcategoria": 215,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 26,"idcategoria": 213,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 27,"idcategoria": 219,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 24,"idcategoria": 200,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 26,"idcategoria": 213,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 25,"idcategoria": 211,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 92,"idesporte": 19,"idmodalidade": 24,"idcategoria": 205,"data": "2016-08-07 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 93,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-07 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 94,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-07 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 95,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 96,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-07 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 97,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-07 15:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 98,"idesporte": 29,"idmodalidade": -1,"idcategoria": 288,"data": "2016-08-07 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 99,"idesporte": 29,"idmodalidade": -1,"idcategoria": 289,"data": "2016-08-07 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 100,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-07 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 100,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-07 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 100,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-07 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 100,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-07 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 101,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-07 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 101,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-07 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 101,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-07 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 101,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-07 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 102,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 102,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 102,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 102,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 103,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 103,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 103,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 103,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 104,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 104,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 104,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 104,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-07 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 105,"idesporte": 15,"idmodalidade": -1,"idcategoria": 167,"data": "2016-08-07 10:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 105,"idesporte": 15,"idmodalidade": -1,"idcategoria": 158,"data": "2016-08-07 10:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 106,"idesporte": 15,"idmodalidade": -1,"idcategoria": 167,"data": "2016-08-07 15:30:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 107,"idesporte": 15,"idmodalidade": -1,"idcategoria": 158,"data": "2016-08-07 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 108,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-07 09:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 108,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-07 09:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 109,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-07 13:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 109,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-07 13:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 110,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-07 18:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 110,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-07 18:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 111,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-07 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 111,"idesporte": 4,"idmodalidade": -1,"idcategoria": 55,"data": "2016-08-07 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 111,"idesporte": 4,"idmodalidade": -1,"idcategoria": 63,"data": "2016-08-07 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 112,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-07 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 112,"idesporte": 4,"idmodalidade": -1,"idcategoria": 55,"data": "2016-08-07 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 112,"idesporte": 4,"idmodalidade": -1,"idcategoria": 63,"data": "2016-08-07 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 113,"idesporte": 9,"idmodalidade": 16,"idcategoria": 125,"data": "2016-08-07 09:45:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 113,"idesporte": 9,"idmodalidade": 16,"idcategoria": 126,"data": "2016-08-07 09:45:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 113,"idesporte": 9,"idmodalidade": 16,"idcategoria": 127,"data": "2016-08-07 09:45:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 113,"idesporte": 9,"idmodalidade": 16,"idcategoria": 124,"data": "2016-08-07 09:45:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 113,"idesporte": 9,"idmodalidade": 16,"idcategoria": 125,"data": "2016-08-07 09:45:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 113,"idesporte": 9,"idmodalidade": 16,"idcategoria": 126,"data": "2016-08-07 09:45:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 113,"idesporte": 9,"idmodalidade": 16,"idcategoria": 127,"data": "2016-08-07 09:45:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 113,"idesporte": 9,"idmodalidade": 16,"idcategoria": 124,"data": "2016-08-07 09:45:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 114,"idesporte": 9,"idmodalidade": 16,"idcategoria": 127,"data": "2016-08-07 14:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 114,"idesporte": 9,"idmodalidade": 16,"idcategoria": 124,"data": "2016-08-07 14:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 114,"idesporte": 9,"idmodalidade": 16,"idcategoria": 126,"data": "2016-08-07 14:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 114,"idesporte": 9,"idmodalidade": 16,"idcategoria": 125,"data": "2016-08-07 14:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 115,"idesporte": 9,"idmodalidade": 16,"idcategoria": 126,"data": "2016-08-07 17:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 115,"idesporte": 9,"idmodalidade": 16,"idcategoria": 125,"data": "2016-08-07 17:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 115,"idesporte": 9,"idmodalidade": 16,"idcategoria": 127,"data": "2016-08-07 17:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 115,"idesporte": 9,"idmodalidade": 16,"idcategoria": 124,"data": "2016-08-07 17:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 116,"idesporte": 9,"idmodalidade": 16,"idcategoria": 125,"data": "2016-08-07 20:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 116,"idesporte": 9,"idmodalidade": 16,"idcategoria": 127,"data": "2016-08-07 20:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 116,"idesporte": 9,"idmodalidade": 16,"idcategoria": 124,"data": "2016-08-07 20:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 116,"idesporte": 9,"idmodalidade": 16,"idcategoria": 126,"data": "2016-08-07 20:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 117,"idesporte": 28,"idmodalidade": -1,"idcategoria": 275,"data": "2016-08-07 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 118,"idesporte": 28,"idmodalidade": -1,"idcategoria": 275,"data": "2016-08-07 14:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 119,"idesporte": 5,"idmodalidade": 7,"idcategoria": 70,"data": "2016-08-07 12:30:00","nome": "Estadio de Canoagem Slalom","idlocal": 36}, {"idevento": 119,"idesporte": 5,"idmodalidade": 7,"idcategoria": 70,"data": "2016-08-07 12:30:00","nome": "Estadio de Canoagem Slalom","idlocal": 36}, {"idevento": 119,"idesporte": 5,"idmodalidade": 7,"idcategoria": 68,"data": "2016-08-07 12:30:00","nome": "Estadio de Canoagem Slalom","idlocal": 36}, {"idevento": 119,"idesporte": 5,"idmodalidade": 7,"idcategoria": 68,"data": "2016-08-07 12:30:00","nome": "Estadio de Canoagem Slalom","idlocal": 36}, {"idevento": 120,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-07 12:00:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 120,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-07 12:00:00","nome": "Arena da Juventude","idlocal": 37}]
},
{"data":"2016-08-08",
"conteudo": [{"idevento": 122,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-08 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 123,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-08 19:30:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 124,"idesporte": 24,"idmodalidade": -1,"idcategoria": 250,"data": "2016-08-08 16:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 125,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-08 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 125,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-08 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 126,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-08 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 126,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-08 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 127,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-08 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 127,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-08 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 128,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-08 14:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 129,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-08 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 130,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-08 22:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 131,"idesporte": 14,"idmodalidade": -1,"idcategoria": 153,"data": "2016-08-08 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 131,"idesporte": 14,"idmodalidade": -1,"idcategoria": 146,"data": "2016-08-08 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 132,"idesporte": 14,"idmodalidade": -1,"idcategoria": 153,"data": "2016-08-08 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 132,"idesporte": 14,"idmodalidade": -1,"idcategoria": 146,"data": "2016-08-08 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 133,"idesporte": 7,"idmodalidade": 15,"idcategoria": 110,"data": "2016-08-08 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 133,"idesporte": 7,"idmodalidade": 15,"idcategoria": 110,"data": "2016-08-08 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 133,"idesporte": 7,"idmodalidade": 15,"idcategoria": 110,"data": "2016-08-08 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 133,"idesporte": 7,"idmodalidade": 15,"idcategoria": 110,"data": "2016-08-08 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 134,"idesporte": 7,"idmodalidade": 15,"idcategoria": 110,"data": "2016-08-08 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 134,"idesporte": 7,"idmodalidade": 15,"idcategoria": 110,"data": "2016-08-08 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 134,"idesporte": 7,"idmodalidade": 15,"idcategoria": 110,"data": "2016-08-08 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 134,"idesporte": 7,"idmodalidade": 15,"idcategoria": 110,"data": "2016-08-08 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 135,"idesporte": 23,"idmodalidade": -1,"idcategoria": 246,"data": "2016-08-08 12:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 136,"idesporte": 23,"idmodalidade": -1,"idcategoria": 246,"data": "2016-08-08 17:30:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 137,"idesporte": 12,"idmodalidade": 20,"idcategoria": 139,"data": "2016-08-08 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 137,"idesporte": 12,"idmodalidade": 20,"idcategoria": 138,"data": "2016-08-08 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 138,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-08 09:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 139,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-08 14:40:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 140,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-08 19:50:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 142,"idesporte": 31,"idmodalidade": -1,"idcategoria": 298,"data": "2016-08-08 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 142,"idesporte": 19,"idmodalidade": 27,"idcategoria": 218,"data": "2016-08-08 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 142,"idesporte": 31,"idmodalidade": -1,"idcategoria": 299,"data": "2016-08-08 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 142,"idesporte": 31,"idmodalidade": -1,"idcategoria": 293,"data": "2016-08-08 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 142,"idesporte": 19,"idmodalidade": 24,"idcategoria": 204,"data": "2016-08-08 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 142,"idesporte": 19,"idmodalidade": 26,"idcategoria": 214,"data": "2016-08-08 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 142,"idesporte": 31,"idmodalidade": -1,"idcategoria": 294,"data": "2016-08-08 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 142,"idesporte": 19,"idmodalidade": 28,"idcategoria": 224,"data": "2016-08-08 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 143,"idesporte": 22,"idmodalidade": -1,"idcategoria": 238,"data": "2016-08-08 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 143,"idesporte": 22,"idmodalidade": -1,"idcategoria": 237,"data": "2016-08-08 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 143,"idesporte": 22,"idmodalidade": -1,"idcategoria": 231,"data": "2016-08-08 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 143,"idesporte": 22,"idmodalidade": -1,"idcategoria": 239,"data": "2016-08-08 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 143,"idesporte": 22,"idmodalidade": -1,"idcategoria": 244,"data": "2016-08-08 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 143,"idesporte": 22,"idmodalidade": -1,"idcategoria": 243,"data": "2016-08-08 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 143,"idesporte": 22,"idmodalidade": -1,"idcategoria": 235,"data": "2016-08-08 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 143,"idesporte": 22,"idmodalidade": -1,"idcategoria": 240,"data": "2016-08-08 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 143,"idesporte": 22,"idmodalidade": -1,"idcategoria": 242,"data": "2016-08-08 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 143,"idesporte": 22,"idmodalidade": -1,"idcategoria": 234,"data": "2016-08-08 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 144,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-08 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 145,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-08 15:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 146,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-08 20:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 148,"idesporte": 19,"idmodalidade": 24,"idcategoria": 204,"data": "2016-08-08 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 148,"idesporte": 19,"idmodalidade": 27,"idcategoria": 218,"data": "2016-08-08 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 148,"idesporte": 19,"idmodalidade": 26,"idcategoria": 215,"data": "2016-08-08 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 148,"idesporte": 19,"idmodalidade": 28,"idcategoria": 224,"data": "2016-08-08 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 148,"idesporte": 19,"idmodalidade": 24,"idcategoria": 197,"data": "2016-08-08 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 148,"idesporte": 19,"idmodalidade": 25,"idcategoria": 211,"data": "2016-08-08 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 148,"idesporte": 19,"idmodalidade": 25,"idcategoria": 209,"data": "2016-08-08 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 148,"idesporte": 19,"idmodalidade": 26,"idcategoria": 215,"data": "2016-08-08 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 148,"idesporte": 19,"idmodalidade": 24,"idcategoria": 197,"data": "2016-08-08 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 148,"idesporte": 19,"idmodalidade": 25,"idcategoria": 209,"data": "2016-08-08 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 149,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-08 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 150,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-08 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 150,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-08 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 151,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 152,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-08 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 153,"idesporte": 29,"idmodalidade": -1,"idcategoria": 282,"data": "2016-08-08 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 154,"idesporte": 29,"idmodalidade": -1,"idcategoria": 278,"data": "2016-08-08 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 155,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-08 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 155,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-08 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 155,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-08 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 155,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-08 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 156,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-08 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 156,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-08 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 156,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-08 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 156,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-08 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 157,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 157,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 157,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 157,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 158,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 158,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 158,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 158,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 159,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 159,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 159,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 159,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-08 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 160,"idesporte": 15,"idmodalidade": -1,"idcategoria": 159,"data": "2016-08-08 10:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 160,"idesporte": 15,"idmodalidade": -1,"idcategoria": 168,"data": "2016-08-08 10:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 161,"idesporte": 15,"idmodalidade": -1,"idcategoria": 168,"data": "2016-08-08 15:30:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 162,"idesporte": 15,"idmodalidade": -1,"idcategoria": 159,"data": "2016-08-08 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 163,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-08 10:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 163,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-08 10:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 164,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-08 16:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 164,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-08 16:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 165,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-08 20:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 165,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-08 20:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 166,"idesporte": 4,"idmodalidade": -1,"idcategoria": 60,"data": "2016-08-08 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 166,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-08 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 167,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-08 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 167,"idesporte": 4,"idmodalidade": -1,"idcategoria": 60,"data": "2016-08-08 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 168,"idesporte": 9,"idmodalidade": 16,"idcategoria": 114,"data": "2016-08-08 16:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}]
},
{"data":"2016-08-09",
"conteudo": [{"idevento": 169,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-09 18:00:00","nome": "Arena da Amazonia","idlocal": 1}, {"idevento": 170,"idesporte": 21,"idmodalidade": -1,"idcategoria": 230,"data": "2016-08-09 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 171,"idesporte": 24,"idmodalidade": -1,"idcategoria": 254,"data": "2016-08-09 16:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 172,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-09 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 172,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-09 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 173,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-09 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 173,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-09 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 177,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-09 16:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 178,"idesporte": 14,"idmodalidade": -1,"idcategoria": 154,"data": "2016-08-09 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 178,"idesporte": 14,"idmodalidade": -1,"idcategoria": 147,"data": "2016-08-09 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 179,"idesporte": 14,"idmodalidade": -1,"idcategoria": 154,"data": "2016-08-09 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 179,"idesporte": 14,"idmodalidade": -1,"idcategoria": 147,"data": "2016-08-09 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 180,"idesporte": 7,"idmodalidade": 13,"idcategoria": 102,"data": "2016-08-09 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 180,"idesporte": 7,"idmodalidade": 13,"idcategoria": 102,"data": "2016-08-09 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 180,"idesporte": 7,"idmodalidade": 13,"idcategoria": 102,"data": "2016-08-09 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 180,"idesporte": 7,"idmodalidade": 13,"idcategoria": 102,"data": "2016-08-09 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 181,"idesporte": 7,"idmodalidade": 13,"idcategoria": 102,"data": "2016-08-09 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 181,"idesporte": 7,"idmodalidade": 13,"idcategoria": 102,"data": "2016-08-09 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 181,"idesporte": 7,"idmodalidade": 13,"idcategoria": 102,"data": "2016-08-09 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 181,"idesporte": 7,"idmodalidade": 13,"idcategoria": 102,"data": "2016-08-09 16:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 182,"idesporte": 4,"idmodalidade": -1,"idcategoria": 64,"data": "2016-08-09 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 182,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-09 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 182,"idesporte": 4,"idmodalidade": -1,"idcategoria": 58,"data": "2016-08-09 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 183,"idesporte": 23,"idmodalidade": -1,"idcategoria": 245,"data": "2016-08-09 16:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 184,"idesporte": 12,"idmodalidade": 20,"idcategoria": 138,"data": "2016-08-09 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 184,"idesporte": 12,"idmodalidade": 20,"idcategoria": 139,"data": "2016-08-09 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 185,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-09 16:00:00","nome": "Arena Fonte Nova","idlocal": 11}, {"idevento": 186,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-09 09:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 187,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-09 14:40:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 188,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-09 19:50:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 189,"idesporte": 31,"idmodalidade": -1,"idcategoria": 299,"data": "2016-08-09 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 189,"idesporte": 31,"idmodalidade": -1,"idcategoria": 293,"data": "2016-08-09 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 189,"idesporte": 31,"idmodalidade": -1,"idcategoria": 294,"data": "2016-08-09 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 189,"idesporte": 31,"idmodalidade": -1,"idcategoria": 295,"data": "2016-08-09 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 189,"idesporte": 31,"idmodalidade": -1,"idcategoria": 298,"data": "2016-08-09 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 190,"idesporte": 22,"idmodalidade": -1,"idcategoria": 239,"data": "2016-08-09 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 190,"idesporte": 22,"idmodalidade": -1,"idcategoria": 232,"data": "2016-08-09 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 190,"idesporte": 22,"idmodalidade": -1,"idcategoria": 241,"data": "2016-08-09 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 190,"idesporte": 22,"idmodalidade": -1,"idcategoria": 233,"data": "2016-08-09 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 190,"idesporte": 22,"idmodalidade": -1,"idcategoria": 236,"data": "2016-08-09 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 190,"idesporte": 22,"idmodalidade": -1,"idcategoria": 242,"data": "2016-08-09 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 190,"idesporte": 22,"idmodalidade": -1,"idcategoria": 234,"data": "2016-08-09 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 190,"idesporte": 22,"idmodalidade": -1,"idcategoria": 231,"data": "2016-08-09 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 191,"idesporte": 9,"idmodalidade": 16,"idcategoria": 122,"data": "2016-08-09 16:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 192,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-09 22:00:00","nome": "Estadio Mane Garrincha","idlocal": 17}, {"idevento": 193,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-09 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 194,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-09 15:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 195,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-09 20:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 196,"idesporte": 19,"idmodalidade": 26,"idcategoria": 215,"data": "2016-08-09 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 196,"idesporte": 19,"idmodalidade": 24,"idcategoria": 196,"data": "2016-08-09 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 196,"idesporte": 19,"idmodalidade": 24,"idcategoria": 201,"data": "2016-08-09 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 196,"idesporte": 19,"idmodalidade": 27,"idcategoria": 220,"data": "2016-08-09 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 197,"idesporte": 19,"idmodalidade": 24,"idcategoria": 201,"data": "2016-08-09 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 197,"idesporte": 19,"idmodalidade": 24,"idcategoria": 204,"data": "2016-08-09 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 197,"idesporte": 19,"idmodalidade": 26,"idcategoria": 214,"data": "2016-08-09 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 197,"idesporte": 19,"idmodalidade": 28,"idcategoria": 224,"data": "2016-08-09 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 197,"idesporte": 19,"idmodalidade": 27,"idcategoria": 220,"data": "2016-08-09 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 197,"idesporte": 19,"idmodalidade": 24,"idcategoria": 204,"data": "2016-08-09 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 197,"idesporte": 19,"idmodalidade": 27,"idcategoria": 218,"data": "2016-08-09 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 197,"idesporte": 19,"idmodalidade": 24,"idcategoria": 201,"data": "2016-08-09 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 197,"idesporte": 19,"idmodalidade": 24,"idcategoria": 196,"data": "2016-08-09 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 197,"idesporte": 19,"idmodalidade": 28,"idcategoria": 224,"data": "2016-08-09 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 198,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-09 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 199,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-09 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 200,"idesporte": 23,"idmodalidade": -1,"idcategoria": 245,"data": "2016-08-09 11:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 201,"idesporte": 29,"idmodalidade": -1,"idcategoria": 287,"data": "2016-08-09 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 202,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-09 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 202,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-09 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 202,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-09 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 202,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-09 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 203,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-09 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 203,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-09 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 203,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-09 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 203,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-09 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 204,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 205,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 205,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 205,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 205,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 206,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 206,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 206,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 206,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 207,"idesporte": 15,"idmodalidade": -1,"idcategoria": 160,"data": "2016-08-09 10:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 207,"idesporte": 15,"idmodalidade": -1,"idcategoria": 169,"data": "2016-08-09 10:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 208,"idesporte": 15,"idmodalidade": -1,"idcategoria": 169,"data": "2016-08-09 15:30:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 210,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-09 10:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 211,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-09 16:00:00","nome": "Estadio Mane Garrincha","idlocal": 17}, {"idevento": 212,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-09 20:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 213,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 213,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 213,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 213,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-09 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 214,"idesporte": 4,"idmodalidade": -1,"idcategoria": 64,"data": "2016-08-09 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 214,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-09 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 214,"idesporte": 4,"idmodalidade": -1,"idcategoria": 58,"data": "2016-08-09 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 216,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-09 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 216,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-09 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 216,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-09 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 216,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-09 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 217,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-09 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 217,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-09 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 217,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-09 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 217,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-09 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 218,"idesporte": 5,"idmodalidade": 7,"idcategoria": 68,"data": "2016-08-09 13:30:00","nome": "Estadio de Canoagem Slalom","idlocal": 36}, {"idevento": 218,"idesporte": 5,"idmodalidade": 7,"idcategoria": 68,"data": "2016-08-09 13:30:00","nome": "Estadio de Canoagem Slalom","idlocal": 36}, {"idevento": 219,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-09 12:15:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 220,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-09 15:30:00","nome": "Arena da Juventude","idlocal": 37}]
},
{"data":"2016-08-10",
"conteudo": [{"idevento": 221,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-10 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 222,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-10 19:30:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 223,"idesporte": 24,"idmodalidade": -1,"idcategoria": 253,"data": "2016-08-10 16:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 224,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-10 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 224,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-10 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 225,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-10 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 225,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-10 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 226,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-10 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 226,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-10 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 227,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-10 14:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 228,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-10 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 229,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-10 22:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 230,"idesporte": 14,"idmodalidade": -1,"idcategoria": 155,"data": "2016-08-10 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 230,"idesporte": 14,"idmodalidade": -1,"idcategoria": 148,"data": "2016-08-10 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 231,"idesporte": 14,"idmodalidade": -1,"idcategoria": 155,"data": "2016-08-10 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 231,"idesporte": 14,"idmodalidade": -1,"idcategoria": 148,"data": "2016-08-10 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 232,"idesporte": 7,"idmodalidade": 14,"idcategoria": 108,"data": "2016-08-10 08:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 232,"idesporte": 7,"idmodalidade": 15,"idcategoria": 109,"data": "2016-08-10 08:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 232,"idesporte": 7,"idmodalidade": 14,"idcategoria": 108,"data": "2016-08-10 08:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 232,"idesporte": 7,"idmodalidade": 15,"idcategoria": 109,"data": "2016-08-10 08:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 232,"idesporte": 7,"idmodalidade": 15,"idcategoria": 109,"data": "2016-08-10 08:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 232,"idesporte": 7,"idmodalidade": 14,"idcategoria": 108,"data": "2016-08-10 08:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 232,"idesporte": 7,"idmodalidade": 15,"idcategoria": 109,"data": "2016-08-10 08:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 232,"idesporte": 7,"idmodalidade": 14,"idcategoria": 108,"data": "2016-08-10 08:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 233,"idesporte": 7,"idmodalidade": 14,"idcategoria": 108,"data": "2016-08-10 17:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 233,"idesporte": 7,"idmodalidade": 15,"idcategoria": 109,"data": "2016-08-10 17:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 233,"idesporte": 7,"idmodalidade": 14,"idcategoria": 108,"data": "2016-08-10 17:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 233,"idesporte": 7,"idmodalidade": 15,"idcategoria": 109,"data": "2016-08-10 17:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 233,"idesporte": 7,"idmodalidade": 14,"idcategoria": 108,"data": "2016-08-10 17:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 233,"idesporte": 7,"idmodalidade": 15,"idcategoria": 109,"data": "2016-08-10 17:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 233,"idesporte": 7,"idmodalidade": 14,"idcategoria": 108,"data": "2016-08-10 17:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 233,"idesporte": 7,"idmodalidade": 15,"idcategoria": 109,"data": "2016-08-10 17:30:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 234,"idesporte": 23,"idmodalidade": -1,"idcategoria": 245,"data": "2016-08-10 11:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 235,"idesporte": 23,"idmodalidade": -1,"idcategoria": 245,"data": "2016-08-10 16:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 236,"idesporte": 12,"idmodalidade": 19,"idcategoria": 136,"data": "2016-08-10 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 237,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-10 19:00:00","nome": "Arena Fonte Nova","idlocal": 11}, {"idevento": 238,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-10 09:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 239,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-10 14:40:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 240,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-10 19:50:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 241,"idesporte": 31,"idmodalidade": -1,"idcategoria": 300,"data": "2016-08-10 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 241,"idesporte": 31,"idmodalidade": -1,"idcategoria": 299,"data": "2016-08-10 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 241,"idesporte": 31,"idmodalidade": -1,"idcategoria": 296,"data": "2016-08-10 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 241,"idesporte": 31,"idmodalidade": -1,"idcategoria": 294,"data": "2016-08-10 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 241,"idesporte": 31,"idmodalidade": -1,"idcategoria": 302,"data": "2016-08-10 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 241,"idesporte": 31,"idmodalidade": -1,"idcategoria": 295,"data": "2016-08-10 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 244,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 243,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 242,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 235,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 234,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 240,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 237,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 231,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 239,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 243,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 242,"idesporte": 22,"idmodalidade": -1,"idcategoria": 237,"data": "2016-08-10 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 243,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-10 13:00:00","nome": "Estadio Mane Garrincha","idlocal": 17}, {"idevento": 244,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-10 13:00:00","nome": "Minerao","idlocal": 18}, {"idevento": 245,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-10 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 246,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-10 15:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 247,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-10 20:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 248,"idesporte": 19,"idmodalidade": 24,"idcategoria": 208,"data": "2016-08-10 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 248,"idesporte": 19,"idmodalidade": 28,"idcategoria": 221,"data": "2016-08-10 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 248,"idesporte": 19,"idmodalidade": 24,"idcategoria": 199,"data": "2016-08-10 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 248,"idesporte": 19,"idmodalidade": 24,"idcategoria": 203,"data": "2016-08-10 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 248,"idesporte": 19,"idmodalidade": 25,"idcategoria": 210,"data": "2016-08-10 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 248,"idesporte": 19,"idmodalidade": 28,"idcategoria": 200,"data": "2016-08-10 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 248,"idesporte": 19,"idmodalidade": 24,"idcategoria": 202,"data": "2016-08-10 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 248,"idesporte": 19,"idmodalidade": 26,"idcategoria": 216,"data": "2016-08-10 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 248,"idesporte": 19,"idmodalidade": 28,"idcategoria": 207,"data": "2016-08-10 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 28,"idcategoria": 197,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 24,"idcategoria": 203,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 24,"idcategoria": 195,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 25,"idcategoria": 220,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 26,"idcategoria": 204,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 26,"idcategoria": 197,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 24,"idcategoria": 206,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 24,"idcategoria": 208,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 25,"idcategoria": 197,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 24,"idcategoria": 202,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 249,"idesporte": 19,"idmodalidade": 27,"idcategoria": 217,"data": "2016-08-10 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 250,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-10 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 251,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-10 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 252,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 252,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 253,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-10 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 253,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-10 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 254,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-10 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 254,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-10 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 254,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-10 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 254,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-10 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 255,"idesporte": 29,"idmodalidade": -1,"idcategoria": 279,"data": "2016-08-10 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 257,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 257,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 257,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 257,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 258,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 258,"idesporte": 26,"idmodalidade": -1,"idcategoria": 267,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 258,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 258,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 258,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 259,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 259,"idesporte": 26,"idmodalidade": -1,"idcategoria": 267,"data": "2016-08-10 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 260,"idesporte": 6,"idmodalidade": 10,"idcategoria": 87,"data": "2016-08-10 08:30:00","nome": "Pontal","idlocal": 27}, {"idevento": 260,"idesporte": 6,"idmodalidade": 10,"idcategoria": 86,"data": "2016-08-10 08:30:00","nome": "Pontal","idlocal": 27}, {"idevento": 262,"idesporte": 15,"idmodalidade": -1,"idcategoria": 170,"data": "2016-08-10 15:30:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 263,"idesporte": 15,"idmodalidade": -1,"idcategoria": 161,"data": "2016-08-10 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 264,"idesporte": 15,"idmodalidade": -1,"idcategoria": 170,"data": "2016-08-10 10:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 264,"idesporte": 15,"idmodalidade": -1,"idcategoria": 161,"data": "2016-08-10 10:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 265,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-10 20:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 266,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-10 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 266,"idesporte": 4,"idmodalidade": -1,"idcategoria": 63,"data": "2016-08-10 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 266,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-10 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 266,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-10 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 266,"idesporte": 4,"idmodalidade": -1,"idcategoria": 55,"data": "2016-08-10 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 267,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-10 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 267,"idesporte": 4,"idmodalidade": -1,"idcategoria": 55,"data": "2016-08-10 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 267,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-10 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 267,"idesporte": 4,"idmodalidade": -1,"idcategoria": 63,"data": "2016-08-10 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 267,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-10 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 268,"idesporte": 9,"idmodalidade": 16,"idcategoria": 115,"data": "2016-08-10 16:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 269,"idesporte": 29,"idmodalidade": -1,"idcategoria": 283,"data": "2016-08-10 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 270,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-10 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 270,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-10 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 270,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-10 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 270,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-10 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 270,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-10 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 271,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-10 19:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 273,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-10 12:15:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 274,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-10 15:30:00","nome": "Arena da Juventude","idlocal": 37}]
},
{"data":"2016-08-11",
"conteudo": [{"idevento": 275,"idesporte": 21,"idmodalidade": -1,"idcategoria": 230,"data": "2016-08-11 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 276,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-11 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 276,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-11 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 277,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-11 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 277,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-11 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 278,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-11 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 278,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-11 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 279,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-11 14:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 280,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-11 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 281,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-11 22:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 282,"idesporte": 14,"idmodalidade": -1,"idcategoria": 156,"data": "2016-08-11 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 282,"idesporte": 14,"idmodalidade": -1,"idcategoria": 149,"data": "2016-08-11 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 283,"idesporte": 14,"idmodalidade": -1,"idcategoria": 156,"data": "2016-08-11 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 283,"idesporte": 14,"idmodalidade": -1,"idcategoria": 149,"data": "2016-08-11 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 284,"idesporte": 7,"idmodalidade": 13,"idcategoria": 105,"data": "2016-08-11 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 284,"idesporte": 7,"idmodalidade": 13,"idcategoria": 105,"data": "2016-08-11 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 284,"idesporte": 7,"idmodalidade": 13,"idcategoria": 105,"data": "2016-08-11 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 284,"idesporte": 7,"idmodalidade": 13,"idcategoria": 105,"data": "2016-08-11 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 284,"idesporte": 7,"idmodalidade": 13,"idcategoria": 105,"data": "2016-08-11 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 284,"idesporte": 7,"idmodalidade": 13,"idcategoria": 105,"data": "2016-08-11 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 285,"idesporte": 7,"idmodalidade": 13,"idcategoria": 105,"data": "2016-08-11 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 285,"idesporte": 7,"idmodalidade": 13,"idcategoria": 105,"data": "2016-08-11 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 285,"idesporte": 7,"idmodalidade": 13,"idcategoria": 105,"data": "2016-08-11 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 286,"idesporte": 23,"idmodalidade": -1,"idcategoria": 245,"data": "2016-08-11 12:30:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 287,"idesporte": 23,"idmodalidade": -1,"idcategoria": 245,"data": "2016-08-11 17:30:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 288,"idesporte": 12,"idmodalidade": 19,"idcategoria": 136,"data": "2016-08-11 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 289,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-11 09:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 290,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-11 14:40:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 291,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-11 19:50:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 292,"idesporte": 31,"idmodalidade": -1,"idcategoria": 300,"data": "2016-08-11 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 292,"idesporte": 31,"idmodalidade": -1,"idcategoria": 298,"data": "2016-08-11 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 292,"idesporte": 31,"idmodalidade": -1,"idcategoria": 296,"data": "2016-08-11 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 292,"idesporte": 31,"idmodalidade": -1,"idcategoria": 293,"data": "2016-08-11 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 292,"idesporte": 31,"idmodalidade": -1,"idcategoria": 302,"data": "2016-08-11 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 292,"idesporte": 31,"idmodalidade": -1,"idcategoria": 295,"data": "2016-08-11 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 233,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 231,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 236,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 239,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 232,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 241,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 233,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 232,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 236,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 242,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 241,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 234,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 293,"idesporte": 22,"idmodalidade": -1,"idcategoria": 240,"data": "2016-08-11 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 294,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-11 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 295,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-11 15:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 296,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-11 20:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 297,"idesporte": 19,"idmodalidade": 24,"idcategoria": 206,"data": "2016-08-11 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 297,"idesporte": 19,"idmodalidade": 24,"idcategoria": 204,"data": "2016-08-11 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 297,"idesporte": 19,"idmodalidade": 24,"idcategoria": 195,"data": "2016-08-11 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 297,"idesporte": 19,"idmodalidade": 27,"idcategoria": 196,"data": "2016-08-11 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 298,"idesporte": 19,"idmodalidade": 27,"idcategoria": 196,"data": "2016-08-11 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 298,"idesporte": 19,"idmodalidade": 25,"idcategoria": 204,"data": "2016-08-11 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 298,"idesporte": 19,"idmodalidade": 25,"idcategoria": 195,"data": "2016-08-11 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 298,"idesporte": 19,"idmodalidade": 24,"idcategoria": 203,"data": "2016-08-11 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 298,"idesporte": 19,"idmodalidade": 25,"idcategoria": 197,"data": "2016-08-11 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 298,"idesporte": 19,"idmodalidade": 28,"idcategoria": 197,"data": "2016-08-11 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 298,"idesporte": 19,"idmodalidade": 26,"idcategoria": 204,"data": "2016-08-11 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 299,"idesporte": 10,"idmodalidade": -1,"idcategoria": 132,"data": "2016-08-11 08:00:00","nome": "Campo Olimpico de Golfe","idlocal": 22}, {"idevento": 300,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-11 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 301,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-11 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 302,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-11 11:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 303,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-11 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 304,"idesporte": 29,"idmodalidade": -1,"idcategoria": 285,"data": "2016-08-11 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 305,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-11 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 305,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-11 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 305,"idesporte": 26,"idmodalidade": -1,"idcategoria": 267,"data": "2016-08-11 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 305,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-11 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 306,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-11 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 306,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-11 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 306,"idesporte": 26,"idmodalidade": -1,"idcategoria": 267,"data": "2016-08-11 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 307,"idesporte": 26,"idmodalidade": -1,"idcategoria": 267,"data": "2016-08-11 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 307,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-11 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 308,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-11 10:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 309,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-11 20:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 310,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-11 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 310,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-11 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 310,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-11 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 310,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-11 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 310,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-11 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 311,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-11 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 311,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-11 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 311,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-11 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 311,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-11 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 311,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-11 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 312,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-11 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 312,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-11 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 312,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-11 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 312,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-11 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 312,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-11 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 313,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-11 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 313,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-11 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 313,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-11 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 313,"idesporte": 4,"idmodalidade": -1,"idcategoria": 60,"data": "2016-08-11 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 314,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-11 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 314,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-11 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 314,"idesporte": 4,"idmodalidade": -1,"idcategoria": 60,"data": "2016-08-11 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 314,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-11 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 315,"idesporte": 9,"idmodalidade": 16,"idcategoria": 123,"data": "2016-08-11 16:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 316,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-11 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 317,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-11 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 318,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-11 12:15:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 319,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-11 15:30:00","nome": "Arena da Juventude","idlocal": 37}]
},
{"data":"2016-08-12",
"conteudo": [{"idevento": 320,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-12 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 321,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-12 19:30:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 322,"idesporte": 24,"idmodalidade": -1,"idcategoria": 253,"data": "2016-08-12 15:30:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 323,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-12 11:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 323,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-12 11:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 324,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-12 15:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 324,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-12 15:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 325,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-12 19:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 325,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-12 19:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 326,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-12 23:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 326,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-12 23:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 327,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-12 14:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 328,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-12 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 329,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-12 22:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 330,"idesporte": 14,"idmodalidade": -1,"idcategoria": 157,"data": "2016-08-12 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 330,"idesporte": 14,"idmodalidade": -1,"idcategoria": 150,"data": "2016-08-12 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 331,"idesporte": 14,"idmodalidade": -1,"idcategoria": 150,"data": "2016-08-12 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 331,"idesporte": 14,"idmodalidade": -1,"idcategoria": 157,"data": "2016-08-12 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 332,"idesporte": 7,"idmodalidade": 14,"idcategoria": 107,"data": "2016-08-12 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 332,"idesporte": 7,"idmodalidade": 14,"idcategoria": 107,"data": "2016-08-12 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 332,"idesporte": 7,"idmodalidade": 14,"idcategoria": 107,"data": "2016-08-12 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 332,"idesporte": 7,"idmodalidade": 14,"idcategoria": 107,"data": "2016-08-12 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 332,"idesporte": 7,"idmodalidade": 14,"idcategoria": 107,"data": "2016-08-12 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 332,"idesporte": 7,"idmodalidade": 14,"idcategoria": 107,"data": "2016-08-12 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 333,"idesporte": 7,"idmodalidade": 14,"idcategoria": 107,"data": "2016-08-12 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 333,"idesporte": 7,"idmodalidade": 14,"idcategoria": 107,"data": "2016-08-12 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 333,"idesporte": 7,"idmodalidade": 14,"idcategoria": 107,"data": "2016-08-12 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 334,"idesporte": 12,"idmodalidade": 19,"idcategoria": 136,"data": "2016-08-12 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 335,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-12 16:00:00","nome": "Arena Fonte Nova","idlocal": 11}, {"idevento": 336,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-12 09:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 337,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-12 14:40:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 338,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-12 19:50:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 339,"idesporte": 31,"idmodalidade": -1,"idcategoria": 297,"data": "2016-08-12 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 339,"idesporte": 31,"idmodalidade": -1,"idcategoria": 299,"data": "2016-08-12 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 339,"idesporte": 31,"idmodalidade": -1,"idcategoria": 293,"data": "2016-08-12 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 339,"idesporte": 31,"idmodalidade": -1,"idcategoria": 300,"data": "2016-08-12 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 339,"idesporte": 31,"idmodalidade": -1,"idcategoria": 294,"data": "2016-08-12 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 339,"idesporte": 31,"idmodalidade": -1,"idcategoria": 301,"data": "2016-08-12 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 339,"idesporte": 31,"idmodalidade": -1,"idcategoria": 296,"data": "2016-08-12 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 339,"idesporte": 31,"idmodalidade": -1,"idcategoria": 298,"data": "2016-08-12 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 340,"idesporte": 22,"idmodalidade": -1,"idcategoria": 239,"data": "2016-08-12 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 340,"idesporte": 22,"idmodalidade": -1,"idcategoria": 242,"data": "2016-08-12 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 340,"idesporte": 22,"idmodalidade": -1,"idcategoria": 234,"data": "2016-08-12 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 340,"idesporte": 22,"idmodalidade": -1,"idcategoria": 240,"data": "2016-08-12 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 340,"idesporte": 22,"idmodalidade": -1,"idcategoria": 242,"data": "2016-08-12 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 340,"idesporte": 22,"idmodalidade": -1,"idcategoria": 235,"data": "2016-08-12 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 340,"idesporte": 22,"idmodalidade": -1,"idcategoria": 234,"data": "2016-08-12 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 340,"idesporte": 22,"idmodalidade": -1,"idcategoria": 240,"data": "2016-08-12 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 340,"idesporte": 22,"idmodalidade": -1,"idcategoria": 231,"data": "2016-08-12 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 340,"idesporte": 22,"idmodalidade": -1,"idcategoria": 235,"data": "2016-08-12 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 341,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-12 13:00:00","nome": "Estadio Mane Garrincha","idlocal": 17}, {"idevento": 342,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-12 22:00:00","nome": "Minerao","idlocal": 18}, {"idevento": 343,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-12 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 344,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-12 15:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 345,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-12 20:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 348,"idesporte": 10,"idmodalidade": -1,"idcategoria": 132,"data": "2016-08-12 08:00:00","nome": "Campo Olimpico de Golfe","idlocal": 22}, {"idevento": 349,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-12 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 349,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-12 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 350,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-12 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 350,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-12 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 351,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-12 11:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 352,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-12 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 353,"idesporte": 1,"idmodalidade": 1,"idcategoria": 19,"data": "2016-08-12 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 353,"idesporte": 1,"idmodalidade": 3,"idcategoria": 29,"data": "2016-08-12 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 353,"idesporte": 1,"idmodalidade": 1,"idcategoria": 13,"data": "2016-08-12 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 353,"idesporte": 1,"idmodalidade": 1,"idcategoria": 4,"data": "2016-08-12 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 353,"idesporte": 1,"idmodalidade": 3,"idcategoria": 31,"data": "2016-08-12 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 353,"idesporte": 1,"idmodalidade": 1,"idcategoria": 19,"data": "2016-08-12 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 353,"idesporte": 1,"idmodalidade": 5,"idcategoria": 40,"data": "2016-08-12 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 353,"idesporte": 1,"idmodalidade": 5,"idcategoria": 20,"data": "2016-08-12 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 353,"idesporte": 1,"idmodalidade": 3,"idcategoria": 29,"data": "2016-08-12 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 354,"idesporte": 1,"idmodalidade": 5,"idcategoria": 14,"data": "2016-08-12 20:20:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 354,"idesporte": 1,"idmodalidade": 1,"idcategoria": 3,"data": "2016-08-12 20:20:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 354,"idesporte": 1,"idmodalidade": 1,"idcategoria": 17,"data": "2016-08-12 20:20:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 354,"idesporte": 1,"idmodalidade": 1,"idcategoria": 13,"data": "2016-08-12 20:20:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 354,"idesporte": 1,"idmodalidade": 3,"idcategoria": 31,"data": "2016-08-12 20:20:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 354,"idesporte": 1,"idmodalidade": 3,"idcategoria": 34,"data": "2016-08-12 20:20:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 354,"idesporte": 1,"idmodalidade": 6,"idcategoria": 45,"data": "2016-08-12 20:20:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 354,"idesporte": 1,"idmodalidade": 3,"idcategoria": 34,"data": "2016-08-12 20:20:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 354,"idesporte": 1,"idmodalidade": 4,"idcategoria": 37,"data": "2016-08-12 20:20:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 354,"idesporte": 1,"idmodalidade": 5,"idcategoria": 31,"data": "2016-08-12 20:20:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 355,"idesporte": 29,"idmodalidade": -1,"idcategoria": 276,"data": "2016-08-12 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 355,"idesporte": 29,"idmodalidade": -1,"idcategoria": 280,"data": "2016-08-12 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 356,"idesporte": 29,"idmodalidade": -1,"idcategoria": 290,"data": "2016-08-12 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 356,"idesporte": 29,"idmodalidade": -1,"idcategoria": 284,"data": "2016-08-12 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 357,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-12 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 357,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-12 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 358,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-12 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 358,"idesporte": 26,"idmodalidade": -1,"idcategoria": 267,"data": "2016-08-12 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 360,"idesporte": 15,"idmodalidade": -1,"idcategoria": 162,"data": "2016-08-12 10:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 360,"idesporte": 15,"idmodalidade": -1,"idcategoria": 171,"data": "2016-08-12 10:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 361,"idesporte": 15,"idmodalidade": -1,"idcategoria": 171,"data": "2016-08-12 15:30:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 362,"idesporte": 15,"idmodalidade": -1,"idcategoria": 162,"data": "2016-08-12 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 363,"idesporte": 27,"idmodalidade": -1,"idcategoria": 271,"data": "2016-08-12 10:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 364,"idesporte": 27,"idmodalidade": -1,"idcategoria": 271,"data": "2016-08-12 15:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 365,"idesporte": 27,"idmodalidade": -1,"idcategoria": 269,"data": "2016-08-12 19:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 366,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-12 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 366,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-12 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 366,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-12 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 366,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-12 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 366,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-12 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 367,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-12 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 367,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-12 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 367,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-12 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 367,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-12 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 367,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-12 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 368,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-12 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 368,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-12 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 368,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-12 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 368,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-12 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 368,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-12 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 369,"idesporte": 4,"idmodalidade": -1,"idcategoria": 55,"data": "2016-08-12 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 369,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-12 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 369,"idesporte": 4,"idmodalidade": -1,"idcategoria": 66,"data": "2016-08-12 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 369,"idesporte": 4,"idmodalidade": -1,"idcategoria": 58,"data": "2016-08-12 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 369,"idesporte": 4,"idmodalidade": -1,"idcategoria": 65,"data": "2016-08-12 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 370,"idesporte": 4,"idmodalidade": -1,"idcategoria": 58,"data": "2016-08-12 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 370,"idesporte": 4,"idmodalidade": -1,"idcategoria": 66,"data": "2016-08-12 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 370,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-12 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 370,"idesporte": 4,"idmodalidade": -1,"idcategoria": 65,"data": "2016-08-12 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 372,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-12 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 373,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-12 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 374,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-12 19:00:00","nome": "Arena Corinthians","idlocal": 35}, {"idevento": 375,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-12 12:15:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 376,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-12 15:30:00","nome": "Arena da Juventude","idlocal": 37}]
},
{"data":"2016-08-13",
"conteudo": [{"idevento": 377,"idesporte": 21,"idmodalidade": -1,"idcategoria": 230,"data": "2016-08-13 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 378,"idesporte": 24,"idmodalidade": -1,"idcategoria": 253,"data": "2016-08-13 16:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 379,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-13 11:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 379,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-13 11:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 380,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-13 15:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 380,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-13 15:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 381,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-13 19:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 381,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-13 19:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 382,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-13 23:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 382,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-13 23:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 383,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-13 14:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 384,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-13 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 385,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-13 22:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 386,"idesporte": 7,"idmodalidade": 15,"idcategoria": 111,"data": "2016-08-13 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 386,"idesporte": 7,"idmodalidade": 15,"idcategoria": 111,"data": "2016-08-13 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 386,"idesporte": 7,"idmodalidade": 15,"idcategoria": 111,"data": "2016-08-13 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 386,"idesporte": 7,"idmodalidade": 15,"idcategoria": 111,"data": "2016-08-13 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 386,"idesporte": 7,"idmodalidade": 15,"idcategoria": 111,"data": "2016-08-13 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 386,"idesporte": 7,"idmodalidade": 15,"idcategoria": 111,"data": "2016-08-13 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 387,"idesporte": 7,"idmodalidade": 15,"idcategoria": 111,"data": "2016-08-13 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 387,"idesporte": 7,"idmodalidade": 15,"idcategoria": 111,"data": "2016-08-13 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 387,"idesporte": 7,"idmodalidade": 15,"idcategoria": 111,"data": "2016-08-13 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 388,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-13 16:00:00","nome": "Arena Fonte Nova","idlocal": 11}, {"idevento": 389,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-13 09:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 390,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-13 14:40:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 391,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-13 19:50:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 392,"idesporte": 31,"idmodalidade": -1,"idcategoria": 301,"data": "2016-08-13 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 392,"idesporte": 31,"idmodalidade": -1,"idcategoria": 299,"data": "2016-08-13 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 392,"idesporte": 31,"idmodalidade": -1,"idcategoria": 297,"data": "2016-08-13 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 392,"idesporte": 31,"idmodalidade": -1,"idcategoria": 294,"data": "2016-08-13 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 392,"idesporte": 31,"idmodalidade": -1,"idcategoria": 302,"data": "2016-08-13 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 392,"idesporte": 31,"idmodalidade": -1,"idcategoria": 295,"data": "2016-08-13 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 393,"idesporte": 22,"idmodalidade": -1,"idcategoria": 231,"data": "2016-08-13 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 393,"idesporte": 22,"idmodalidade": -1,"idcategoria": 239,"data": "2016-08-13 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 393,"idesporte": 22,"idmodalidade": -1,"idcategoria": 244,"data": "2016-08-13 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 393,"idesporte": 22,"idmodalidade": -1,"idcategoria": 238,"data": "2016-08-13 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 393,"idesporte": 22,"idmodalidade": -1,"idcategoria": 231,"data": "2016-08-13 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 393,"idesporte": 22,"idmodalidade": -1,"idcategoria": 239,"data": "2016-08-13 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 393,"idesporte": 22,"idmodalidade": -1,"idcategoria": 244,"data": "2016-08-13 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 393,"idesporte": 22,"idmodalidade": -1,"idcategoria": 238,"data": "2016-08-13 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 394,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-13 13:00:00","nome": "Estadio Mane Garrincha","idlocal": 17}, {"idevento": 395,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-13 19:00:00","nome": "Minerao","idlocal": 18}, {"idevento": 396,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-13 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 397,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-13 15:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 398,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-13 20:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 399,"idesporte": 19,"idmodalidade": 24,"idcategoria": 199,"data": "2016-08-13 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 399,"idesporte": 19,"idmodalidade": 28,"idcategoria": 200,"data": "2016-08-13 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 399,"idesporte": 19,"idmodalidade": 24,"idcategoria": 202,"data": "2016-08-13 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 399,"idesporte": 19,"idmodalidade": 28,"idcategoria": 207,"data": "2016-08-13 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 400,"idesporte": 10,"idmodalidade": -1,"idcategoria": 132,"data": "2016-08-13 08:00:00","nome": "Campo Olimpico de Golfe","idlocal": 22}, {"idevento": 401,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-13 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 402,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-13 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 403,"idesporte": 1,"idmodalidade": 1,"idcategoria": 1,"data": "2016-08-13 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 403,"idesporte": 1,"idmodalidade": 3,"idcategoria": 29,"data": "2016-08-13 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 403,"idesporte": 1,"idmodalidade": 1,"idcategoria": 1,"data": "2016-08-13 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 403,"idesporte": 1,"idmodalidade": 5,"idcategoria": 41,"data": "2016-08-13 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 403,"idesporte": 1,"idmodalidade": 1,"idcategoria": 22,"data": "2016-08-13 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 403,"idesporte": 1,"idmodalidade": 3,"idcategoria": 29,"data": "2016-08-13 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 403,"idesporte": 1,"idmodalidade": 1,"idcategoria": 15,"data": "2016-08-13 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 403,"idesporte": 1,"idmodalidade": 4,"idcategoria": 42,"data": "2016-08-13 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 1,"idcategoria": 4,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 4,"idcategoria": 37,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 3,"idcategoria": 31,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 1,"idcategoria": 13,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 5,"idcategoria": 32,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 1,"idcategoria": 3,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 5,"idcategoria": 32,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 4,"idcategoria": 37,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 1,"idcategoria": 7,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 1,"idcategoria": 13,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 4,"idcategoria": 35,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 404,"idesporte": 1,"idmodalidade": 5,"idcategoria": 16,"data": "2016-08-13 20:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 405,"idesporte": 29,"idmodalidade": -1,"idcategoria": 280,"data": "2016-08-13 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 406,"idesporte": 29,"idmodalidade": -1,"idcategoria": 284,"data": "2016-08-13 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 407,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-13 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 407,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-13 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 407,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-13 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 408,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-13 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 408,"idesporte": 26,"idmodalidade": -1,"idcategoria": 267,"data": "2016-08-13 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 409,"idesporte": 15,"idmodalidade": -1,"idcategoria": 163,"data": "2016-08-13 15:30:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 410,"idesporte": 15,"idmodalidade": -1,"idcategoria": 163,"data": "2016-08-13 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 411,"idesporte": 27,"idmodalidade": -1,"idcategoria": 271,"data": "2016-08-13 10:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 412,"idesporte": 27,"idmodalidade": -1,"idcategoria": 269,"data": "2016-08-13 15:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 413,"idesporte": 27,"idmodalidade": -1,"idcategoria": 271,"data": "2016-08-13 19:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 414,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-13 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 414,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-13 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 414,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-13 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 414,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-13 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 414,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-13 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 415,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-13 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 415,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-13 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 415,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-13 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 415,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-13 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 415,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-13 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 416,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-13 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 416,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-13 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 416,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-13 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 416,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-13 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 417,"idesporte": 4,"idmodalidade": -1,"idcategoria": 60,"data": "2016-08-13 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 417,"idesporte": 4,"idmodalidade": -1,"idcategoria": 64,"data": "2016-08-13 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 417,"idesporte": 4,"idmodalidade": -1,"idcategoria": 56,"data": "2016-08-13 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 417,"idesporte": 4,"idmodalidade": -1,"idcategoria": 63,"data": "2016-08-13 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 418,"idesporte": 4,"idmodalidade": -1,"idcategoria": 64,"data": "2016-08-13 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 418,"idesporte": 4,"idmodalidade": -1,"idcategoria": 56,"data": "2016-08-13 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 418,"idesporte": 4,"idmodalidade": -1,"idcategoria": 63,"data": "2016-08-13 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 418,"idesporte": 4,"idmodalidade": -1,"idcategoria": 60,"data": "2016-08-13 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 420,"idesporte": 6,"idmodalidade": 11,"idcategoria": 97,"data": "2016-08-13 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 420,"idesporte": 6,"idmodalidade": 11,"idcategoria": 98,"data": "2016-08-13 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 420,"idesporte": 6,"idmodalidade": 11,"idcategoria": 90,"data": "2016-08-13 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 421,"idesporte": 6,"idmodalidade": 11,"idcategoria": 90,"data": "2016-08-13 16:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 421,"idesporte": 6,"idmodalidade": 11,"idcategoria": 98,"data": "2016-08-13 16:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 421,"idesporte": 6,"idmodalidade": 11,"idcategoria": 97,"data": "2016-08-13 16:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 422,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-13 22:00:00","nome": "Arena Corinthians","idlocal": 35}, {"idevento": 423,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-13 12:15:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 424,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-13 15:30:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 425,"idesporte": 18,"idmodalidade": -1,"idcategoria": 193,"data": "2016-08-13 11:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 427,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-13 16:00:00","nome": "Arena de Volei de Praia","idlocal": 4}]
},
{"data":"2016-08-14",
"conteudo": [{"idevento": 428,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-14 23:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 429,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-14 14:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 430,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-14 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 431,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-14 22:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 432,"idesporte": 16,"idmodalidade": 22,"idcategoria": 173,"data": "2016-08-14 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 432,"idesporte": 16,"idmodalidade": 22,"idcategoria": 173,"data": "2016-08-14 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 433,"idesporte": 16,"idmodalidade": 22,"idcategoria": 173,"data": "2016-08-14 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 433,"idesporte": 16,"idmodalidade": 22,"idcategoria": 173,"data": "2016-08-14 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 434,"idesporte": 7,"idmodalidade": 13,"idcategoria": 103,"data": "2016-08-14 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 434,"idesporte": 7,"idmodalidade": 13,"idcategoria": 103,"data": "2016-08-14 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 434,"idesporte": 7,"idmodalidade": 13,"idcategoria": 103,"data": "2016-08-14 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 434,"idesporte": 7,"idmodalidade": 13,"idcategoria": 103,"data": "2016-08-14 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 434,"idesporte": 7,"idmodalidade": 13,"idcategoria": 103,"data": "2016-08-14 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 434,"idesporte": 7,"idmodalidade": 13,"idcategoria": 103,"data": "2016-08-14 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 435,"idesporte": 7,"idmodalidade": 13,"idcategoria": 103,"data": "2016-08-14 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 435,"idesporte": 7,"idmodalidade": 13,"idcategoria": 103,"data": "2016-08-14 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 435,"idesporte": 7,"idmodalidade": 13,"idcategoria": 103,"data": "2016-08-14 17:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 436,"idesporte": 12,"idmodalidade": 21,"idcategoria": 141,"data": "2016-08-14 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 437,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-14 09:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 438,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-14 14:40:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 439,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-14 19:50:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 440,"idesporte": 31,"idmodalidade": -1,"idcategoria": 300,"data": "2016-08-14 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 440,"idesporte": 31,"idmodalidade": -1,"idcategoria": 298,"data": "2016-08-14 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 440,"idesporte": 31,"idmodalidade": -1,"idcategoria": 296,"data": "2016-08-14 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 440,"idesporte": 31,"idmodalidade": -1,"idcategoria": 293,"data": "2016-08-14 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 440,"idesporte": 31,"idmodalidade": -1,"idcategoria": 302,"data": "2016-08-14 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 440,"idesporte": 31,"idmodalidade": -1,"idcategoria": 295,"data": "2016-08-14 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 441,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-14 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 442,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-14 15:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 443,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-14 20:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 444,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-14 12:50:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 445,"idesporte": 10,"idmodalidade": -1,"idcategoria": 132,"data": "2016-08-14 07:30:00","nome": "Campo Olimpico de Golfe","idlocal": 22}, {"idevento": 446,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-14 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 447,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-14 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 448,"idesporte": 1,"idmodalidade": 1,"idcategoria": 1,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 448,"idesporte": 1,"idmodalidade": 1,"idcategoria": 17,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 448,"idesporte": 1,"idmodalidade": 4,"idcategoria": 42,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 448,"idesporte": 1,"idmodalidade": 1,"idcategoria": 7,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 448,"idesporte": 1,"idmodalidade": 5,"idcategoria": 44,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 448,"idesporte": 1,"idmodalidade": 1,"idcategoria": 13,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 448,"idesporte": 1,"idmodalidade": 1,"idcategoria": 15,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 448,"idesporte": 1,"idmodalidade": 2,"idcategoria": 26,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 448,"idesporte": 1,"idmodalidade": 1,"idcategoria": 3,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 448,"idesporte": 1,"idmodalidade": 1,"idcategoria": 1,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 448,"idesporte": 1,"idmodalidade": 4,"idcategoria": 36,"data": "2016-08-14 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 449,"idesporte": 29,"idmodalidade": -1,"idcategoria": 277,"data": "2016-08-14 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 451,"idesporte": 15,"idmodalidade": -1,"idcategoria": 172,"data": "2016-08-14 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 452,"idesporte": 27,"idmodalidade": -1,"idcategoria": 269,"data": "2016-08-14 10:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 453,"idesporte": 27,"idmodalidade": -1,"idcategoria": 269,"data": "2016-08-14 15:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 454,"idesporte": 27,"idmodalidade": -1,"idcategoria": 271,"data": "2016-08-14 19:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 455,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-14 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 455,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-14 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 456,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-14 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 456,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-14 15:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 457,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-14 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 457,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-14 19:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 458,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-14 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 458,"idesporte": 4,"idmodalidade": -1,"idcategoria": 55,"data": "2016-08-14 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 458,"idesporte": 4,"idmodalidade": -1,"idcategoria": 58,"data": "2016-08-14 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 458,"idesporte": 4,"idmodalidade": -1,"idcategoria": 55,"data": "2016-08-14 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 458,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-14 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 458,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-14 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 458,"idesporte": 4,"idmodalidade": -1,"idcategoria": 67,"data": "2016-08-14 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 459,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-14 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 459,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-14 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 459,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-14 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 459,"idesporte": 4,"idmodalidade": -1,"idcategoria": 67,"data": "2016-08-14 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 459,"idesporte": 4,"idmodalidade": -1,"idcategoria": 58,"data": "2016-08-14 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 460,"idesporte": 9,"idmodalidade": 16,"idcategoria": 117,"data": "2016-08-14 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 460,"idesporte": 9,"idmodalidade": 16,"idcategoria": 124,"data": "2016-08-14 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 460,"idesporte": 9,"idmodalidade": 16,"idcategoria": 125,"data": "2016-08-14 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 460,"idesporte": 9,"idmodalidade": 16,"idcategoria": 116,"data": "2016-08-14 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 461,"idesporte": 1,"idmodalidade": 2,"idcategoria": 26,"data": "2016-08-14 09:30:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 461,"idesporte": 1,"idmodalidade": 2,"idcategoria": 26,"data": "2016-08-14 09:30:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 462,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-14 12:15:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 463,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-14 15:30:00","nome": "Arena da Juventude","idlocal": 37}]
},
{"data":"2016-08-15",
"conteudo": [{"idevento": 464,"idesporte": 18,"idmodalidade": -1,"idcategoria": 193,"data": "2016-08-15 11:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 465,"idesporte": 24,"idmodalidade": -1,"idcategoria": 247,"data": "2016-08-15 15:15:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 466,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-15 16:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 467,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-15 23:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 468,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-15 14:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 469,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-15 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 470,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-15 22:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 471,"idesporte": 16,"idmodalidade": 22,"idcategoria": 175,"data": "2016-08-15 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 471,"idesporte": 16,"idmodalidade": 22,"idcategoria": 175,"data": "2016-08-15 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 472,"idesporte": 16,"idmodalidade": 22,"idcategoria": 175,"data": "2016-08-15 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 472,"idesporte": 16,"idmodalidade": 22,"idcategoria": 175,"data": "2016-08-15 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 473,"idesporte": 12,"idmodalidade": 19,"idcategoria": 137,"data": "2016-08-15 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 474,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-15 09:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 475,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-15 14:40:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 476,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-15 19:50:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 477,"idesporte": 17,"idmodalidade": -1,"idcategoria": 192,"data": "2016-08-15 09:00:00","nome": "Forte de Copacabana","idlocal": 13}, {"idevento": 478,"idesporte": 31,"idmodalidade": -1,"idcategoria": 297,"data": "2016-08-15 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 478,"idesporte": 31,"idmodalidade": -1,"idcategoria": 299,"data": "2016-08-15 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 478,"idesporte": 31,"idmodalidade": -1,"idcategoria": 300,"data": "2016-08-15 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 478,"idesporte": 31,"idmodalidade": -1,"idcategoria": 294,"data": "2016-08-15 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 478,"idesporte": 31,"idmodalidade": -1,"idcategoria": 301,"data": "2016-08-15 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 478,"idesporte": 31,"idmodalidade": -1,"idcategoria": 296,"data": "2016-08-15 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 479,"idesporte": 5,"idmodalidade": 8,"idcategoria": 76,"data": "2016-08-15 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 479,"idesporte": 5,"idmodalidade": 8,"idcategoria": 80,"data": "2016-08-15 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 479,"idesporte": 5,"idmodalidade": 8,"idcategoria": 81,"data": "2016-08-15 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 479,"idesporte": 5,"idmodalidade": 8,"idcategoria": 73,"data": "2016-08-15 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 480,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-15 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 481,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-15 15:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 482,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-15 20:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 483,"idesporte": 21,"idmodalidade": -1,"idcategoria": 230,"data": "2016-08-15 14:10:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 484,"idesporte": 21,"idmodalidade": -1,"idcategoria": 230,"data": "2016-08-15 18:20:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 485,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-15 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 486,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-15 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 487,"idesporte": 1,"idmodalidade": 1,"idcategoria": 21,"data": "2016-08-15 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 487,"idesporte": 1,"idmodalidade": 1,"idcategoria": 22,"data": "2016-08-15 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 487,"idesporte": 1,"idmodalidade": 1,"idcategoria": 9,"data": "2016-08-15 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 487,"idesporte": 1,"idmodalidade": 1,"idcategoria": 10,"data": "2016-08-15 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 487,"idesporte": 1,"idmodalidade": 1,"idcategoria": 22,"data": "2016-08-15 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 487,"idesporte": 1,"idmodalidade": 3,"idcategoria": 34,"data": "2016-08-15 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 487,"idesporte": 1,"idmodalidade": 4,"idcategoria": 38,"data": "2016-08-15 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 3,"idcategoria": 33,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 1,"idcategoria": 8,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 4,"idcategoria": 42,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 3,"idcategoria": 34,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 1,"idcategoria": 14,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 4,"idcategoria": 35,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 1,"idcategoria": 3,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 1,"idcategoria": 4,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 1,"idcategoria": 1,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 3,"idcategoria": 33,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 488,"idesporte": 1,"idmodalidade": 1,"idcategoria": 15,"data": "2016-08-15 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 489,"idesporte": 15,"idmodalidade": -1,"idcategoria": 164,"data": "2016-08-15 15:30:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 490,"idesporte": 15,"idmodalidade": -1,"idcategoria": 164,"data": "2016-08-15 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 491,"idesporte": 27,"idmodalidade": -1,"idcategoria": 271,"data": "2016-08-15 10:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 492,"idesporte": 27,"idmodalidade": -1,"idcategoria": 269,"data": "2016-08-15 15:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 493,"idesporte": 27,"idmodalidade": -1,"idcategoria": 269,"data": "2016-08-15 19:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 494,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-15 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 494,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-15 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 494,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-15 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 495,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-15 17:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 495,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-15 17:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 495,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-15 17:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 496,"idesporte": 4,"idmodalidade": -1,"idcategoria": 60,"data": "2016-08-15 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 496,"idesporte": 4,"idmodalidade": -1,"idcategoria": 56,"data": "2016-08-15 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 496,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-15 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 496,"idesporte": 4,"idmodalidade": -1,"idcategoria": 66,"data": "2016-08-15 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 497,"idesporte": 4,"idmodalidade": -1,"idcategoria": 56,"data": "2016-08-15 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 497,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-15 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 497,"idesporte": 4,"idmodalidade": -1,"idcategoria": 66,"data": "2016-08-15 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 497,"idesporte": 4,"idmodalidade": -1,"idcategoria": 63,"data": "2016-08-15 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 497,"idesporte": 4,"idmodalidade": -1,"idcategoria": 60,"data": "2016-08-15 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 497,"idesporte": 4,"idmodalidade": -1,"idcategoria": 63,"data": "2016-08-15 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 498,"idesporte": 9,"idmodalidade": 16,"idcategoria": 126,"data": "2016-08-15 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 498,"idesporte": 9,"idmodalidade": 16,"idcategoria": 118,"data": "2016-08-15 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 498,"idesporte": 9,"idmodalidade": 16,"idcategoria": 116,"data": "2016-08-15 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 499,"idesporte": 6,"idmodalidade": 11,"idcategoria": 99,"data": "2016-08-15 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 499,"idesporte": 6,"idmodalidade": 11,"idcategoria": 94,"data": "2016-08-15 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 499,"idesporte": 6,"idmodalidade": 11,"idcategoria": 95,"data": "2016-08-15 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 500,"idesporte": 6,"idmodalidade": 11,"idcategoria": 99,"data": "2016-08-15 16:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 500,"idesporte": 6,"idmodalidade": 11,"idcategoria": 95,"data": "2016-08-15 16:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 500,"idesporte": 6,"idmodalidade": 11,"idcategoria": 94,"data": "2016-08-15 16:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}]
},
{"data":"2016-08-16",
"conteudo": [{"idevento": 501,"idesporte": 18,"idmodalidade": -1,"idcategoria": 193,"data": "2016-08-16 14:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 502,"idesporte": 24,"idmodalidade": -1,"idcategoria": 247,"data": "2016-08-16 10:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 503,"idesporte": 24,"idmodalidade": -1,"idcategoria": 252,"data": "2016-08-16 18:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 504,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-16 16:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 504,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-16 16:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 505,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-16 23:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 505,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-16 23:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 506,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-16 11:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 507,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-16 14:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 508,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-16 18:45:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 509,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-16 22:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 510,"idesporte": 16,"idmodalidade": 22,"idcategoria": 173,"data": "2016-08-16 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 510,"idesporte": 16,"idmodalidade": 22,"idcategoria": 175,"data": "2016-08-16 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 511,"idesporte": 16,"idmodalidade": 22,"idcategoria": 173,"data": "2016-08-16 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 511,"idesporte": 16,"idmodalidade": 22,"idcategoria": 175,"data": "2016-08-16 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 512,"idesporte": 12,"idmodalidade": 21,"idcategoria": 140,"data": "2016-08-16 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 513,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-16 10:00:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 514,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-16 13:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 515,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-16 17:00:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 516,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-16 20:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 517,"idesporte": 17,"idmodalidade": -1,"idcategoria": 191,"data": "2016-08-16 09:00:00","nome": "Forte de Copacabana","idlocal": 13}, {"idevento": 518,"idesporte": 31,"idmodalidade": -1,"idcategoria": 297,"data": "2016-08-16 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 518,"idesporte": 31,"idmodalidade": -1,"idcategoria": 302,"data": "2016-08-16 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 518,"idesporte": 31,"idmodalidade": -1,"idcategoria": 295,"data": "2016-08-16 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 518,"idesporte": 31,"idmodalidade": -1,"idcategoria": 301,"data": "2016-08-16 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 519,"idesporte": 5,"idmodalidade": 8,"idcategoria": 80,"data": "2016-08-16 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 519,"idesporte": 5,"idmodalidade": 8,"idcategoria": 73,"data": "2016-08-16 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 519,"idesporte": 5,"idmodalidade": 8,"idcategoria": 76,"data": "2016-08-16 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 519,"idesporte": 5,"idmodalidade": 8,"idcategoria": 76,"data": "2016-08-16 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 520,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-16 16:00:00","nome": "Minerao","idlocal": 18}, {"idevento": 521,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-16 10:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 522,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-16 14:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 523,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-16 18:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 524,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-16 22:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 525,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-16 13:00:00","nome": "Maracana","idlocal": 20}, {"idevento": 526,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-16 11:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 527,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-16 15:10:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 529,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-16 12:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 530,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-16 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 531,"idesporte": 1,"idmodalidade": 4,"idcategoria": 38,"data": "2016-08-16 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 531,"idesporte": 1,"idmodalidade": 1,"idcategoria": 20,"data": "2016-08-16 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 531,"idesporte": 1,"idmodalidade": 4,"idcategoria": 39,"data": "2016-08-16 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 531,"idesporte": 1,"idmodalidade": 1,"idcategoria": 2,"data": "2016-08-16 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 531,"idesporte": 1,"idmodalidade": 1,"idcategoria": 5,"data": "2016-08-16 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 531,"idesporte": 1,"idmodalidade": 1,"idcategoria": 18,"data": "2016-08-16 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 531,"idesporte": 1,"idmodalidade": 3,"idcategoria": 33,"data": "2016-08-16 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 531,"idesporte": 1,"idmodalidade": 4,"idcategoria": 38,"data": "2016-08-16 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 1,"idcategoria": 17,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 1,"idcategoria": 9,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 4,"idcategoria": 35,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 4,"idcategoria": 36,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 1,"idcategoria": 8,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 1,"idcategoria": 14,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 1,"idcategoria": 21,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 1,"idcategoria": 8,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 1,"idcategoria": 15,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 3,"idcategoria": 33,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 3,"idcategoria": 32,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 4,"idcategoria": 41,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 3,"idcategoria": 32,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 532,"idesporte": 1,"idmodalidade": 1,"idcategoria": 4,"data": "2016-08-16 20:15:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 533,"idesporte": 15,"idmodalidade": -1,"idcategoria": 165,"data": "2016-08-16 15:30:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 534,"idesporte": 15,"idmodalidade": -1,"idcategoria": 165,"data": "2016-08-16 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 535,"idesporte": 27,"idmodalidade": -1,"idcategoria": 271,"data": "2016-08-16 11:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 536,"idesporte": 27,"idmodalidade": -1,"idcategoria": 271,"data": "2016-08-16 19:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 537,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-16 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 537,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-16 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 538,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-16 17:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 538,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-16 17:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 539,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-16 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 539,"idesporte": 4,"idmodalidade": -1,"idcategoria": 65,"data": "2016-08-16 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 539,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-16 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 539,"idesporte": 4,"idmodalidade": -1,"idcategoria": 64,"data": "2016-08-16 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 539,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-16 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 540,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-16 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 540,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-16 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 540,"idesporte": 4,"idmodalidade": -1,"idcategoria": 64,"data": "2016-08-16 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 540,"idesporte": 4,"idmodalidade": -1,"idcategoria": 58,"data": "2016-08-16 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 540,"idesporte": 4,"idmodalidade": -1,"idcategoria": 65,"data": "2016-08-16 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 540,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-16 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 540,"idesporte": 4,"idmodalidade": -1,"idcategoria": 58,"data": "2016-08-16 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 541,"idesporte": 9,"idmodalidade": 16,"idcategoria": 124,"data": "2016-08-16 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 541,"idesporte": 9,"idmodalidade": 16,"idcategoria": 120,"data": "2016-08-16 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 541,"idesporte": 9,"idmodalidade": 16,"idcategoria": 121,"data": "2016-08-16 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 542,"idesporte": 6,"idmodalidade": 11,"idcategoria": 99,"data": "2016-08-16 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 542,"idesporte": 6,"idmodalidade": 11,"idcategoria": 92,"data": "2016-08-16 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 542,"idesporte": 6,"idmodalidade": 11,"idcategoria": 95,"data": "2016-08-16 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 543,"idesporte": 6,"idmodalidade": 11,"idcategoria": 92,"data": "2016-08-16 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 543,"idesporte": 6,"idmodalidade": 11,"idcategoria": 99,"data": "2016-08-16 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 543,"idesporte": 24,"idmodalidade": -1,"idcategoria": 252,"data": "2016-08-16 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 543,"idesporte": 6,"idmodalidade": 11,"idcategoria": 94,"data": "2016-08-16 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 543,"idesporte": 6,"idmodalidade": 11,"idcategoria": 95,"data": "2016-08-16 10:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}]
},
{"data":"2016-08-17",
"conteudo": [{"idevento": 544,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-17 15:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 545,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-17 22:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 546,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-17 11:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 547,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-17 14:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 548,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-17 18:45:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 549,"idesporte": 16,"idmodalidade": 23,"idcategoria": 185,"data": "2016-08-17 22:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 549,"idesporte": 16,"idmodalidade": 23,"idcategoria": 189,"data": "2016-08-17 22:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 549,"idesporte": 16,"idmodalidade": 23,"idcategoria": 187,"data": "2016-08-17 22:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 550,"idesporte": 16,"idmodalidade": 23,"idcategoria": 187,"data": "2016-08-17 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 550,"idesporte": 16,"idmodalidade": 23,"idcategoria": 185,"data": "2016-08-17 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 550,"idesporte": 16,"idmodalidade": 23,"idcategoria": 189,"data": "2016-08-17 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 551,"idesporte": 25,"idmodalidade": -1,"idcategoria": 259,"data": "2016-08-17 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 551,"idesporte": 25,"idmodalidade": -1,"idcategoria": 255,"data": "2016-08-17 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 552,"idesporte": 25,"idmodalidade": -1,"idcategoria": 259,"data": "2016-08-17 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 552,"idesporte": 25,"idmodalidade": -1,"idcategoria": 255,"data": "2016-08-17 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 553,"idesporte": 25,"idmodalidade": -1,"idcategoria": 255,"data": "2016-08-17 15:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 553,"idesporte": 25,"idmodalidade": -1,"idcategoria": 259,"data": "2016-08-17 15:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 554,"idesporte": 12,"idmodalidade": 21,"idcategoria": 140,"data": "2016-08-17 20:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 555,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-17 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 556,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-17 10:00:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 557,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-17 13:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 558,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-17 17:00:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 559,"idesporte": 31,"idmodalidade": -1,"idcategoria": 296,"data": "2016-08-17 20:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 559,"idesporte": 31,"idmodalidade": -1,"idcategoria": 300,"data": "2016-08-17 20:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 560,"idesporte": 5,"idmodalidade": 8,"idcategoria": 77,"data": "2016-08-17 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 560,"idesporte": 5,"idmodalidade": 8,"idcategoria": 72,"data": "2016-08-17 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 560,"idesporte": 5,"idmodalidade": 8,"idcategoria": 81,"data": "2016-08-17 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 560,"idesporte": 5,"idmodalidade": 8,"idcategoria": 78,"data": "2016-08-17 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 561,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-17 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 562,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-17 10:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 563,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-17 14:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 564,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-17 18:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 565,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-17 22:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 566,"idesporte": 21,"idmodalidade": -1,"idcategoria": 230,"data": "2016-08-17 13:00:00","nome": "Maracana","idlocal": 20}, {"idevento": 567,"idesporte": 21,"idmodalidade": -1,"idcategoria": 230,"data": "2016-08-17 11:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 568,"idesporte": 10,"idmodalidade": -1,"idcategoria": 133,"data": "2016-08-17 15:10:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 568,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-17 15:10:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 569,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-17 08:00:00","nome": "Campo Olimpico de Golfe","idlocal": 22}, {"idevento": 570,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-17 14:15:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 571,"idesporte": 1,"idmodalidade": 1,"idcategoria": 10,"data": "2016-08-17 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 571,"idesporte": 1,"idmodalidade": 5,"idcategoria": 37,"data": "2016-08-17 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 571,"idesporte": 1,"idmodalidade": 5,"idcategoria": 1,"data": "2016-08-17 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 571,"idesporte": 1,"idmodalidade": 3,"idcategoria": 30,"data": "2016-08-17 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 571,"idesporte": 1,"idmodalidade": 1,"idcategoria": 6,"data": "2016-08-17 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 571,"idesporte": 1,"idmodalidade": 5,"idcategoria": 27,"data": "2016-08-17 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 571,"idesporte": 1,"idmodalidade": 1,"idcategoria": 16,"data": "2016-08-17 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 571,"idesporte": 1,"idmodalidade": 3,"idcategoria": 30,"data": "2016-08-17 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 572,"idesporte": 1,"idmodalidade": 1,"idcategoria": 10,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 1,"idcategoria": 14,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 5,"idcategoria": 3,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 1,"idcategoria": 20,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 5,"idcategoria": 36,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 1,"idcategoria": 20,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 1,"idcategoria": 2,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 4,"idcategoria": 41,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 3,"idcategoria": 28,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 1,"idcategoria": 8,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 3,"idcategoria": 28,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 1,"idcategoria": 17,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 572,"idesporte": 1,"idmodalidade": 4,"idcategoria": 36,"data": "2016-08-17 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 573,"idesporte": 27,"idmodalidade": -1,"idcategoria": 269,"data": "2016-08-17 17:45:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 574,"idesporte": 27,"idmodalidade": -1,"idcategoria": 269,"data": "2016-08-17 11:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 575,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-17 19:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 575,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-17 19:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 575,"idesporte": 2,"idmodalidade": -1,"idcategoria": 52,"data": "2016-08-17 19:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 576,"idesporte": 4,"idmodalidade": -1,"idcategoria": 60,"data": "2016-08-17 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 576,"idesporte": 4,"idmodalidade": -1,"idcategoria": 66,"data": "2016-08-17 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 576,"idesporte": 4,"idmodalidade": -1,"idcategoria": 56,"data": "2016-08-17 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 576,"idesporte": 4,"idmodalidade": -1,"idcategoria": 60,"data": "2016-08-17 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 576,"idesporte": 4,"idmodalidade": -1,"idcategoria": 67,"data": "2016-08-17 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 579,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-17 15:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 580,"idesporte": 18,"idmodalidade": -1,"idcategoria": 194,"data": "2016-08-17 16:00:00","nome": "Arena Corinthians","idlocal": 35}]
},
{"data":"2016-08-18",
"conteudo": [{"idevento": 582,"idesporte": 24,"idmodalidade": -1,"idcategoria": 248,"data": "2016-08-18 11:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 583,"idesporte": 6,"idmodalidade": 9,"idcategoria": 84,"data": "2016-08-18 16:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 584,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-18 13:30:00","nome": "Centro Olimpico de BMX","idlocal": 3}, {"idevento": 585,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-18 22:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 586,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-18 15:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 587,"idesporte": 16,"idmodalidade": 23,"idcategoria": 188,"data": "2016-08-18 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 587,"idesporte": 16,"idmodalidade": 23,"idcategoria": 186,"data": "2016-08-18 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 587,"idesporte": 16,"idmodalidade": 23,"idcategoria": 190,"data": "2016-08-18 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 588,"idesporte": 16,"idmodalidade": 23,"idcategoria": 186,"data": "2016-08-18 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 588,"idesporte": 16,"idmodalidade": 23,"idcategoria": 190,"data": "2016-08-18 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 588,"idesporte": 16,"idmodalidade": 23,"idcategoria": 188,"data": "2016-08-18 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 589,"idesporte": 25,"idmodalidade": -1,"idcategoria": 260,"data": "2016-08-18 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 589,"idesporte": 25,"idmodalidade": -1,"idcategoria": 256,"data": "2016-08-18 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 590,"idesporte": 25,"idmodalidade": -1,"idcategoria": 260,"data": "2016-08-18 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 590,"idesporte": 25,"idmodalidade": -1,"idcategoria": 256,"data": "2016-08-18 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 591,"idesporte": 25,"idmodalidade": -1,"idcategoria": 260,"data": "2016-08-18 15:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 591,"idesporte": 25,"idmodalidade": -1,"idcategoria": 256,"data": "2016-08-18 15:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 592,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-18 20:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 593,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-18 15:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 594,"idesporte": 30,"idmodalidade": -1,"idcategoria": 291,"data": "2016-08-18 20:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 594,"idesporte": 30,"idmodalidade": -1,"idcategoria": 291,"data": "2016-08-18 20:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 595,"idesporte": 31,"idmodalidade": -1,"idcategoria": 297,"data": "2016-08-18 11:00:00","nome": "Forte de Copacabana","idlocal": 13}, {"idevento": 595,"idesporte": 31,"idmodalidade": -1,"idcategoria": 301,"data": "2016-08-18 11:00:00","nome": "Forte de Copacabana","idlocal": 13}, {"idevento": 596,"idesporte": 5,"idmodalidade": 8,"idcategoria": 77,"data": "2016-08-18 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 596,"idesporte": 5,"idmodalidade": 8,"idcategoria": 78,"data": "2016-08-18 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 596,"idesporte": 5,"idmodalidade": 8,"idcategoria": 72,"data": "2016-08-18 13:00:00","nome": "Marina da Gloria","idlocal": 14}, {"idevento": 597,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-18 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 598,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-18 13:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 599,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-18 22:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 600,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-18 11:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 601,"idesporte": 10,"idmodalidade": -1,"idcategoria": 133,"data": "2016-08-18 15:10:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 602,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-18 08:00:00","nome": "Campo Olimpico de Golfe","idlocal": 22}, {"idevento": 603,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-18 14:15:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 604,"idesporte": 1,"idmodalidade": 5,"idcategoria": 35,"data": "2016-08-18 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 604,"idesporte": 1,"idmodalidade": 1,"idcategoria": 11,"data": "2016-08-18 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 604,"idesporte": 1,"idmodalidade": 4,"idcategoria": 40,"data": "2016-08-18 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 604,"idesporte": 1,"idmodalidade": 1,"idcategoria": 9,"data": "2016-08-18 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 604,"idesporte": 1,"idmodalidade": 1,"idcategoria": 23,"data": "2016-08-18 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 604,"idesporte": 1,"idmodalidade": 3,"idcategoria": 27,"data": "2016-08-18 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 604,"idesporte": 1,"idmodalidade": 5,"idcategoria": 29,"data": "2016-08-18 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 604,"idesporte": 1,"idmodalidade": 5,"idcategoria": 29,"data": "2016-08-18 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 604,"idesporte": 1,"idmodalidade": 5,"idcategoria": 8,"data": "2016-08-18 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 605,"idesporte": 1,"idmodalidade": 3,"idcategoria": 32,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 3,"idcategoria": 27,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 1,"idcategoria": 20,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 1,"idcategoria": 2,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 5,"idcategoria": 5,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 1,"idcategoria": 9,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 1,"idcategoria": 14,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 4,"idcategoria": 41,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 3,"idcategoria": 27,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 1,"idcategoria": 16,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 1,"idcategoria": 5,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 5,"idcategoria": 28,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 5,"idcategoria": 28,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 605,"idesporte": 1,"idmodalidade": 1,"idcategoria": 21,"data": "2016-08-18 09:30:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 606,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-18 18:35:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 606,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-18 18:35:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 606,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-18 18:35:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 606,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-18 18:35:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 606,"idesporte": 2,"idmodalidade": -1,"idcategoria": 49,"data": "2016-08-18 18:35:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 607,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-18 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 607,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-18 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 607,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-18 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 607,"idesporte": 4,"idmodalidade": -1,"idcategoria": 65,"data": "2016-08-18 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 607,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-18 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 610,"idesporte": 20,"idmodalidade": -1,"idcategoria": 227,"data": "2016-08-18 14:50:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 611,"idesporte": 20,"idmodalidade": -1,"idcategoria": 228,"data": "2016-08-18 10:00:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 612,"idesporte": 18,"idmodalidade": -1,"idcategoria": 194,"data": "2016-08-18 14:30:00","nome": "Arena da Juventude","idlocal": 37}]
},
{"data":"2016-08-19",
"conteudo": [{"idevento": 613,"idesporte": 24,"idmodalidade": -1,"idcategoria": 248,"data": "2016-08-19 12:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 614,"idesporte": 6,"idmodalidade": 9,"idcategoria": 84,"data": "2016-08-19 16:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 614,"idesporte": 6,"idmodalidade": 9,"idcategoria": 85,"data": "2016-08-19 16:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 616,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-19 11:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 617,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-19 15:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 618,"idesporte": 16,"idmodalidade": 23,"idcategoria": 179,"data": "2016-08-19 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 618,"idesporte": 16,"idmodalidade": 23,"idcategoria": 181,"data": "2016-08-19 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 619,"idesporte": 16,"idmodalidade": 23,"idcategoria": 181,"data": "2016-08-19 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 619,"idesporte": 16,"idmodalidade": 23,"idcategoria": 179,"data": "2016-08-19 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 620,"idesporte": 25,"idmodalidade": -1,"idcategoria": 257,"data": "2016-08-19 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 620,"idesporte": 25,"idmodalidade": -1,"idcategoria": 261,"data": "2016-08-19 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 621,"idesporte": 25,"idmodalidade": -1,"idcategoria": 261,"data": "2016-08-19 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 621,"idesporte": 25,"idmodalidade": -1,"idcategoria": 257,"data": "2016-08-19 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 622,"idesporte": 25,"idmodalidade": -1,"idcategoria": 261,"data": "2016-08-19 15:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 622,"idesporte": 25,"idmodalidade": -1,"idcategoria": 257,"data": "2016-08-19 15:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 624,"idesporte": 20,"idmodalidade": -1,"idcategoria": 228,"data": "2016-08-19 10:00:00","nome": "Centro Aquatico de Deodoro","idlocal": 8}, {"idevento": 625,"idesporte": 12,"idmodalidade": 21,"idcategoria": 141,"data": "2016-08-19 15:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 626,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-19 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 627,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-19 15:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 628,"idesporte": 5,"idmodalidade": 8,"idcategoria": 83,"data": "2016-08-19 20:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 628,"idesporte": 5,"idmodalidade": 8,"idcategoria": 74,"data": "2016-08-19 20:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 628,"idesporte": 5,"idmodalidade": 8,"idcategoria": 79,"data": "2016-08-19 20:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 628,"idesporte": 5,"idmodalidade": 8,"idcategoria": 75,"data": "2016-08-19 20:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 629,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-19 09:00:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 630,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-19 13:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 631,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-19 22:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 632,"idesporte": 21,"idmodalidade": -1,"idcategoria": 230,"data": "2016-08-19 17:30:00","nome": "Maracana","idlocal": 20}, {"idevento": 633,"idesporte": 21,"idmodalidade": -1,"idcategoria": 230,"data": "2016-08-19 10:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 634,"idesporte": 10,"idmodalidade": -1,"idcategoria": 133,"data": "2016-08-19 14:10:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 635,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-19 08:00:00","nome": "Campo Olimpico de Golfe","idlocal": 22}, {"idevento": 636,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-19 14:15:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 1,"idcategoria": 21,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 3,"idcategoria": 32,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 5,"idcategoria": 43,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 1,"idcategoria": 2,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 1,"idcategoria": 6,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 1,"idcategoria": 23,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 1,"idcategoria": 12,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 1,"idcategoria": 24,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 6,"idcategoria": 47,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 1,"idcategoria": 11,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 1,"idcategoria": 18,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 3,"idcategoria": 30,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 4,"idcategoria": 39,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 637,"idesporte": 1,"idmodalidade": 6,"idcategoria": 46,"data": "2016-08-19 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 638,"idesporte": 1,"idmodalidade": 6,"idcategoria": 46,"data": "2016-08-19 20:10:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 639,"idesporte": 1,"idmodalidade": 6,"idcategoria": 47,"data": "2016-08-19 08:00:00","nome": "Pontal","idlocal": 27}, {"idevento": 640,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-19 14:30:00","nome": "Pontal","idlocal": 27}, {"idevento": 640,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-19 14:30:00","nome": "Pontal","idlocal": 27}, {"idevento": 640,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-19 14:30:00","nome": "Pontal","idlocal": 27}, {"idevento": 640,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-19 14:30:00","nome": "Pontal","idlocal": 27}, {"idevento": 640,"idesporte": 2,"idmodalidade": -1,"idcategoria": 51,"data": "2016-08-19 14:30:00","nome": "Pontal","idlocal": 27}, {"idevento": 640,"idesporte": 2,"idmodalidade": -1,"idcategoria": 48,"data": "2016-08-19 14:30:00","nome": "Pontal","idlocal": 27}, {"idevento": 641,"idesporte": 4,"idmodalidade": -1,"idcategoria": 64,"data": "2016-08-19 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 641,"idesporte": 4,"idmodalidade": -1,"idcategoria": 67,"data": "2016-08-19 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 641,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-19 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 641,"idesporte": 4,"idmodalidade": -1,"idcategoria": 66,"data": "2016-08-19 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 641,"idesporte": 4,"idmodalidade": -1,"idcategoria": 56,"data": "2016-08-19 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 641,"idesporte": 4,"idmodalidade": -1,"idcategoria": 66,"data": "2016-08-19 08:00:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 642,"idesporte": 9,"idmodalidade": 18,"idcategoria": 129,"data": "2016-08-19 14:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 643,"idesporte": 9,"idmodalidade": 18,"idcategoria": 129,"data": "2016-08-19 10:20:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 644,"idesporte": 9,"idmodalidade": 18,"idcategoria": 567,"data": "2016-08-19 14:50:00","nome": "Arena Olimpica do Rio","idlocal": 32}]
},
{"data":"2016-08-20",
"conteudo": [{"idevento": 645,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-20 10:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 647,"idesporte": 24,"idmodalidade": -1,"idcategoria": 248,"data": "2016-08-19 12:00:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 648,"idesporte": 24,"idmodalidade": -1,"idcategoria": 248,"data": "2016-08-20 11:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 650,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-20 15:45:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 651,"idesporte": 16,"idmodalidade": 23,"idcategoria": 182,"data": "2016-08-20 15:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 651,"idesporte": 16,"idmodalidade": 23,"idcategoria": 184,"data": "2016-08-20 15:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 652,"idesporte": 16,"idmodalidade": 23,"idcategoria": 184,"data": "2016-08-20 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 652,"idesporte": 16,"idmodalidade": 23,"idcategoria": 182,"data": "2016-08-20 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 653,"idesporte": 25,"idmodalidade": -1,"idcategoria": 258,"data": "2016-08-20 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 653,"idesporte": 25,"idmodalidade": -1,"idcategoria": 262,"data": "2016-08-20 16:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 654,"idesporte": 25,"idmodalidade": -1,"idcategoria": 262,"data": "2016-08-20 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 654,"idesporte": 25,"idmodalidade": -1,"idcategoria": 258,"data": "2016-08-20 09:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 655,"idesporte": 25,"idmodalidade": -1,"idcategoria": 262,"data": "2016-08-20 15:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 655,"idesporte": 25,"idmodalidade": -1,"idcategoria": 258,"data": "2016-08-20 15:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 656,"idesporte": 20,"idmodalidade": -1,"idcategoria": 227,"data": "2016-08-20 20:00:00","nome": "Arena Carioca 3","idlocal": 7}, {"idevento": 657,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-20 15:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 658,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-20 11:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 659,"idesporte": 30,"idmodalidade": -1,"idcategoria": 292,"data": "2016-08-20 15:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 659,"idesporte": 30,"idmodalidade": -1,"idcategoria": 292,"data": "2016-08-20 15:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 660,"idesporte": 5,"idmodalidade": 8,"idcategoria": 75,"data": "2016-08-20 11:00:00","nome": "Forte de Copacabana","idlocal": 13}, {"idevento": 660,"idesporte": 5,"idmodalidade": 8,"idcategoria": 79,"data": "2016-08-20 11:00:00","nome": "Forte de Copacabana","idlocal": 13}, {"idevento": 660,"idesporte": 5,"idmodalidade": 8,"idcategoria": 74,"data": "2016-08-20 11:00:00","nome": "Forte de Copacabana","idlocal": 13}, {"idevento": 660,"idesporte": 5,"idmodalidade": 8,"idcategoria": 83,"data": "2016-08-20 11:00:00","nome": "Forte de Copacabana","idlocal": 13}, {"idevento": 662,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-20 13:00:00","nome": "Minerao","idlocal": 18}, {"idevento": 663,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-20 13:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 664,"idesporte": 8,"idmodalidade": 0,"idcategoria": 112,"data": "2016-08-20 22:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 665,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-20 17:30:00","nome": "Maracana","idlocal": 20}, {"idevento": 666,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-20 11:40:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 24,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 16,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 11,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 4,"idcategoria": 39,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 4,"idcategoria": 40,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 18,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 16,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 6,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 4,"idcategoria": 40,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 3,"idcategoria": 30,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 12,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 3,"idcategoria": 28,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 5,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 6,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 3,"idcategoria": 28,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 23,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 24,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 667,"idesporte": 1,"idmodalidade": 1,"idcategoria": 12,"data": "2016-08-20 16:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 668,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-20 20:10:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 668,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-20 20:10:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 668,"idesporte": 2,"idmodalidade": -1,"idcategoria": 50,"data": "2016-08-20 20:10:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 669,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-20 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 669,"idesporte": 4,"idmodalidade": -1,"idcategoria": 65,"data": "2016-08-20 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 669,"idesporte": 4,"idmodalidade": -1,"idcategoria": 67,"data": "2016-08-20 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 669,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-20 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 669,"idesporte": 4,"idmodalidade": -1,"idcategoria": 65,"data": "2016-08-20 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 669,"idesporte": 4,"idmodalidade": -1,"idcategoria": 61,"data": "2016-08-20 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 669,"idesporte": 4,"idmodalidade": -1,"idcategoria": 57,"data": "2016-08-20 08:30:00","nome": "Riocentro - Pavilhao 4","idlocal": 30}, {"idevento": 671,"idesporte": 20,"idmodalidade": -1,"idcategoria": 227,"data": "2016-08-20 11:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 672,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-20 12:00:00","nome": "Centro Aquatico de Deodoro","idlocal": 8}]
},
{"data":"2016-08-21",
"conteudo": [{"idevento": 673,"idesporte": 16,"idmodalidade": 23,"idcategoria": 183,"data": "2016-08-21 11:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 673,"idesporte": 16,"idmodalidade": 23,"idcategoria": 180,"data": "2016-08-21 11:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 674,"idesporte": 16,"idmodalidade": 23,"idcategoria": 183,"data": "2016-08-21 08:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 674,"idesporte": 16,"idmodalidade": 23,"idcategoria": 180,"data": "2016-08-21 08:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 675,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-21 12:45:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 676,"idesporte": 11,"idmodalidade": -1,"idcategoria": 134,"data": "2016-08-21 10:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 677,"idesporte": 6,"idmodalidade": 12,"idcategoria": 100,"data": "2016-08-21 14:00:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 678,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-21 12:30:00","nome": "Centro de Mountain Bike","idlocal": 16}, {"idevento": 679,"idesporte": 33,"idmodalidade": -1,"idcategoria": 305,"data": "2016-08-21 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 680,"idesporte": 4,"idmodalidade": -1,"idcategoria": 64,"data": "2016-08-21 13:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 680,"idesporte": 4,"idmodalidade": -1,"idcategoria": 56,"data": "2016-08-21 13:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 680,"idesporte": 4,"idmodalidade": -1,"idcategoria": 67,"data": "2016-08-21 13:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 680,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-21 13:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 680,"idesporte": 4,"idmodalidade": -1,"idcategoria": 56,"data": "2016-08-21 13:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 680,"idesporte": 4,"idmodalidade": -1,"idcategoria": 64,"data": "2016-08-21 13:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 680,"idesporte": 4,"idmodalidade": -1,"idcategoria": 59,"data": "2016-08-21 13:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 680,"idesporte": 4,"idmodalidade": -1,"idcategoria": 67,"data": "2016-08-21 13:15:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 681,"idesporte": 1,"idmodalidade": 2,"idcategoria": 25,"data": "2016-08-21 14:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 682,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-21 09:30:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 682,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-21 09:30:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 682,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-21 09:30:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 683,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-06 17:30:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 683,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-06 17:30:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 683,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-06 17:30:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 684,"idesporte": 5,"idmodalidade": 7,"idcategoria": 71,"data": "2016-08-06 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 684,"idesporte": 5,"idmodalidade": 7,"idcategoria": 69,"data": "2016-08-06 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 684,"idesporte": 5,"idmodalidade": 7,"idcategoria": 69,"data": "2016-08-06 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 684,"idesporte": 5,"idmodalidade": 7,"idcategoria": 71,"data": "2016-08-06 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 685,"idesporte": 1,"idmodalidade": 6,"idcategoria": 45,"data": "2016-08-08 12:30:00","nome": "Estadio de Canoagem Slalom","idlocal": 36}, {"idevento": 686,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-12 14:30:00","nome": "Pontal","idlocal": 27}, {"idevento": 688,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-07 17:30:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 689,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-10 10:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 690,"idesporte": 29,"idmodalidade": -1,"idcategoria": 286,"data": "2016-08-08 17:30:00","nome": "Arena da Juventude","idlocal": 37}, {"idevento": 691,"idesporte": 29,"idmodalidade": -1,"idcategoria": 281,"data": "2016-08-06 10:30:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 692,"idesporte": 5,"idmodalidade": 7,"idcategoria": 70,"data": "2016-08-06 15:30:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 692,"idesporte": 5,"idmodalidade": 7,"idcategoria": 70,"data": "2016-08-06 15:30:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 694,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-20 07:00:00","nome": "Campo Olimpico de Golfe","idlocal": 22}, {"idevento": 695,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-09 14:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 696,"idesporte": 5,"idmodalidade": 7,"idcategoria": 71,"data": "2016-08-09 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 696,"idesporte": 5,"idmodalidade": 7,"idcategoria": 71,"data": "2016-08-09 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 696,"idesporte": 5,"idmodalidade": 7,"idcategoria": 69,"data": "2016-08-09 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 696,"idesporte": 5,"idmodalidade": 7,"idcategoria": 69,"data": "2016-08-09 19:00:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 697,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-11 12:30:00","nome": "Estadio de Canoagem Slalom","idlocal": 36}, {"idevento": 699,"idesporte": 29,"idmodalidade": -1,"idcategoria": 281,"data": "2016-08-16 19:30:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 700,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-06 08:30:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 702,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "0000-00-00 00:00:00","nome": "Arena Corinthians","idlocal": 35}, {"idevento": 703,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-21 15:45:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 703,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-21 15:45:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 704,"idesporte": 29,"idmodalidade": -1,"idcategoria": 282,"data": "2016-08-06 15:30:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 705,"idesporte": 15,"idmodalidade": -1,"idcategoria": 160,"data": "2016-08-07 09:00:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 706,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-09 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 706,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-09 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 707,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-09 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 707,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-09 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 707,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-09 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 707,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-09 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 708,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-08 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 708,"idesporte": 28,"idmodalidade": -1,"idcategoria": 274,"data": "2016-08-08 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 708,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-08 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 708,"idesporte": 28,"idmodalidade": -1,"idcategoria": 272,"data": "2016-08-08 09:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 709,"idesporte": 29,"idmodalidade": -1,"idcategoria": 287,"data": "2016-08-08 15:00:00","nome": "Sambodromo","idlocal": 34}, {"idevento": 710,"idesporte": 24,"idmodalidade": -1,"idcategoria": 247,"data": "2016-08-09 15:30:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 711,"idesporte": 6,"idmodalidade": 10,"idcategoria": 88,"data": "2016-08-14 16:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 712,"idesporte": 10,"idmodalidade": -1,"idcategoria": 133,"data": "2016-08-06 09:30:00","nome": "Forte de Copacabana","idlocal": 13}, {"idevento": 713,"idesporte": 24,"idmodalidade": -1,"idcategoria": 252,"data": "2016-08-20 07:30:00","nome": "Campo Olimpico de Golfe","idlocal": 22}, {"idevento": 715,"idesporte": 12,"idmodalidade": 20,"idcategoria": 139,"data": "2016-08-06 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 715,"idesporte": 12,"idmodalidade": 20,"idcategoria": 138,"data": "2016-08-06 10:00:00","nome": "Centro Olimpico de Hipismo","idlocal": 10}, {"idevento": 717,"idesporte": 6,"idmodalidade": 11,"idcategoria": 93,"data": "2016-08-14 19:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 717,"idesporte": 6,"idmodalidade": 11,"idcategoria": 91,"data": "2016-08-14 19:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 717,"idesporte": 6,"idmodalidade": 11,"idcategoria": 98,"data": "2016-08-14 19:30:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 718,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-12 16:00:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 719,"idesporte": 6,"idmodalidade": 11,"idcategoria": 93,"data": "2016-08-10 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 719,"idesporte": 6,"idmodalidade": 11,"idcategoria": 90,"data": "2016-08-10 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 719,"idesporte": 6,"idmodalidade": 10,"idcategoria": 86,"data": "2016-08-10 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 719,"idesporte": 6,"idmodalidade": 11,"idcategoria": 96,"data": "2016-08-10 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 720,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-10 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 720,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-10 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 720,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-10 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 720,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-10 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 721,"idesporte": 26,"idmodalidade": -1,"idcategoria": 267,"data": "2016-08-10 18:45:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 721,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-10 18:45:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 721,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-10 18:45:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 721,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-10 18:45:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 721,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-10 18:45:00","nome": "Velodromo Olimpico do Rio","idlocal": 33}, {"idevento": 722,"idesporte": 6,"idmodalidade": 10,"idcategoria": 87,"data": "2016-08-19 12:00:00","nome": "Centro Aquatico de Deodoro","idlocal": 8}, {"idevento": 722,"idesporte": 6,"idmodalidade": 11,"idcategoria": 94,"data": "2016-08-19 12:00:00","nome": "Centro Aquatico de Deodoro","idlocal": 8}, {"idevento": 722,"idesporte": 6,"idmodalidade": 11,"idcategoria": 95,"data": "2016-08-19 12:00:00","nome": "Centro Aquatico de Deodoro","idlocal": 8}, {"idevento": 722,"idesporte": 6,"idmodalidade": 11,"idcategoria": 90,"data": "2016-08-19 12:00:00","nome": "Centro Aquatico de Deodoro","idlocal": 8}, {"idevento": 723,"idesporte": 20,"idmodalidade": -1,"idcategoria": 228,"data": "2016-08-19 14:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 724,"idesporte": 20,"idmodalidade": -1,"idcategoria": 228,"data": "2016-08-20 14:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 725,"idesporte": 20,"idmodalidade": -1,"idcategoria": 227,"data": "2016-08-17 13:30:00","nome": "Centro Olimpico de BMX","idlocal": 3}, {"idevento": 726,"idesporte": 6,"idmodalidade": 9,"idcategoria": 85,"data": "2016-08-14 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 726,"idesporte": 6,"idmodalidade": 9,"idcategoria": 84,"data": "2016-08-14 12:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 727,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-14 12:00:00","nome": "Centro de Mountain Bike","idlocal": 16}, {"idevento": 727,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-14 12:00:00","nome": "Centro de Mountain Bike","idlocal": 16}, {"idevento": 727,"idesporte": 26,"idmodalidade": -1,"idcategoria": 267,"data": "2016-08-14 12:00:00","nome": "Centro de Mountain Bike","idlocal": 16}, {"idevento": 728,"idesporte": 6,"idmodalidade": 12,"idcategoria": 101,"data": "2016-08-12 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 729,"idesporte": 9,"idmodalidade": 18,"idcategoria": 130,"data": "2016-08-13 14:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 730,"idesporte": 9,"idmodalidade": 18,"idcategoria": 566,"data": "2016-08-20 12:40:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 731,"idesporte": 9,"idmodalidade": 18,"idcategoria": 567,"data": "2016-08-20 15:20:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 732,"idesporte": 9,"idmodalidade": 18,"idcategoria": 129,"data": "2016-08-21 11:00:00","nome": "Arena Olimpica do Rio","idlocal": 32}]
}
] | },
{"data":"2016-08-06",
"conteudo": [{"idevento": 18,"idesporte": 7,"idmodalidade": 13,"idcategoria": 104,"data": "2016-08-06 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 18,"idesporte": 7,"idmodalidade": 13,"idcategoria": 104,"data": "2016-08-06 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 18,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-06 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 18,"idesporte": 7,"idmodalidade": 13,"idcategoria": 104,"data": "2016-08-06 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 18,"idesporte": 7,"idmodalidade": 13,"idcategoria": 104,"data": "2016-08-06 09:00:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 19,"idesporte": 21,"idmodalidade": -1,"idcategoria": 229,"data": "2016-08-06 19:30:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 19,"idesporte": 7,"idmodalidade": 13,"idcategoria": 104,"data": "2016-08-06 19:30:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 19,"idesporte": 7,"idmodalidade": 13,"idcategoria": 104,"data": "2016-08-06 19:30:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 19,"idesporte": 7,"idmodalidade": 13,"idcategoria": 104,"data": "2016-08-06 19:30:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 19,"idesporte": 7,"idmodalidade": 13,"idcategoria": 104,"data": "2016-08-06 19:30:00","nome": "Centro Aquático Maria Lenk","idlocal": 2}, {"idevento": 20,"idesporte": 14,"idmodalidade": -1,"idcategoria": 144,"data": "2016-08-06 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 20,"idesporte": 14,"idmodalidade": -1,"idcategoria": 151,"data": "2016-08-06 10:00:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 21,"idesporte": 14,"idmodalidade": -1,"idcategoria": 144,"data": "2016-08-06 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 21,"idesporte": 14,"idmodalidade": -1,"idcategoria": 151,"data": "2016-08-06 15:30:00","nome": "Arena Carioca 2","idlocal": 6}, {"idevento": 22,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-06 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 22,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-06 21:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 23,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-06 14:15:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 25,"idesporte": 3,"idmodalidade": -1,"idcategoria": 54,"data": "2016-08-06 22:30:00","nome": "Arena Carioca 1","idlocal": 5}, {"idevento": 26,"idesporte": 32,"idmodalidade": -1,"idcategoria": 304,"data": "2016-08-06 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 26,"idesporte": 32,"idmodalidade": -1,"idcategoria": 303,"data": "2016-08-06 10:00:00","nome": "Arena de Volei de Praia","idlocal": 4}, {"idevento": 30,"idesporte": 23,"idmodalidade": -1,"idcategoria": 246,"data": "2016-08-06 11:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 31,"idesporte": 23,"idmodalidade": -1,"idcategoria": 246,"data": "2016-08-06 16:00:00","nome": "Estadio de Deodoro","idlocal": 9}, {"idevento": 33,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-06 09:30:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 34,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-06 14:40:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 35,"idesporte": 11,"idmodalidade": -1,"idcategoria": 135,"data": "2016-08-06 19:50:00","nome": "Arena do Futuro","idlocal": 12}, {"idevento": 36,"idesporte": 22,"idmodalidade": -1,"idcategoria": 233,"data": "2016-08-06 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 36,"idesporte": 22,"idmodalidade": -1,"idcategoria": 239,"data": "2016-08-06 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 36,"idesporte": 22,"idmodalidade": -1,"idcategoria": 236,"data": "2016-08-06 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 36,"idesporte": 22,"idmodalidade": -1,"idcategoria": 237,"data": "2016-08-06 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 36,"idesporte": 22,"idmodalidade": -1,"idcategoria": 232,"data": "2016-08-06 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 36,"idesporte": 22,"idmodalidade": -1,"idcategoria": 243,"data": "2016-08-06 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 36,"idesporte": 22,"idmodalidade": -1,"idcategoria": 231,"data": "2016-08-06 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 36,"idesporte": 22,"idmodalidade": -1,"idcategoria": 241,"data": "2016-08-06 08:30:00","nome": "Estadio da Lagoa","idlocal": 15}, {"idevento": 37,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-06 17:00:00","nome": "Minerao","idlocal": 18}, {"idevento": 38,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-06 09:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 39,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-06 15:00:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 40,"idesporte": 33,"idmodalidade": -1,"idcategoria": 306,"data": "2016-08-06 20:30:00","nome": "Maracanazinho","idlocal": 19}, {"idevento": 41,"idesporte": 19,"idmodalidade": 24,"idcategoria": 198,"data": "2016-08-06 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 41,"idesporte": 19,"idmodalidade": 26,"idcategoria": 213,"data": "2016-08-06 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 41,"idesporte": 19,"idmodalidade": 24,"idcategoria": 207,"data": "2016-08-06 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 41,"idesporte": 19,"idmodalidade": 27,"idcategoria": 219,"data": "2016-08-06 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 41,"idesporte": 19,"idmodalidade": 28,"idcategoria": 225,"data": "2016-08-06 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 41,"idesporte": 19,"idmodalidade": 24,"idcategoria": 196,"data": "2016-08-06 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 41,"idesporte": 19,"idmodalidade": 28,"idcategoria": 222,"data": "2016-08-06 13:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 42,"idesporte": 19,"idmodalidade": 27,"idcategoria": 219,"data": "2016-08-06 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 42,"idesporte": 19,"idmodalidade": 26,"idcategoria": 213,"data": "2016-08-06 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 42,"idesporte": 19,"idmodalidade": 28,"idcategoria": 225,"data": "2016-08-06 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 42,"idesporte": 19,"idmodalidade": 28,"idcategoria": 222,"data": "2016-08-06 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 42,"idesporte": 19,"idmodalidade": 24,"idcategoria": 196,"data": "2016-08-06 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 42,"idesporte": 19,"idmodalidade": 24,"idcategoria": 207,"data": "2016-08-06 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 42,"idesporte": 19,"idmodalidade": 28,"idcategoria": 222,"data": "2016-08-06 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 42,"idesporte": 19,"idmodalidade": 24,"idcategoria": 198,"data": "2016-08-06 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 42,"idesporte": 19,"idmodalidade": 28,"idcategoria": 225,"data": "2016-08-06 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 42,"idesporte": 19,"idmodalidade": 24,"idcategoria": 207,"data": "2016-08-06 22:00:00","nome": "Estadio Aquatico Olimpico","idlocal": 21}, {"idevento": 43,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-06 10:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 44,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-06 18:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 45,"idesporte": 13,"idmodalidade": -1,"idcategoria": 143,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 46,"idesporte": 13,"idmodalidade": -1,"idcategoria": 142,"data": "2016-08-06 17:00:00","nome": "Centro Olimpico de Hoquei","idlocal": 23}, {"idevento": 47,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-06 19:00:00","nome": "Estadio Olimpico João Havelange","idlocal": 24}, {"idevento": 48,"idesporte": 29,"idmodalidade": -1,"idcategoria": 286,"data": "2016-08-06 08:30:00","nome": "Centro Olimpico de Tiro","idlocal": 25}, {"idevento": 49,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-06 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 49,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-06 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 49,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-06 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 49,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-06 10:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 50,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-06 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 50,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-06 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 50,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-06 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 50,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-06 18:45:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 51,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 51,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 51,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 51,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 52,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 52,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 52,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 52,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 53,"idesporte": 26,"idmodalidade": -1,"idcategoria": 266,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 53,"idesporte": 26,"idmodalidade": -1,"idcategoria": 263,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 53,"idesporte": 26,"idmodalidade": -1,"idcategoria": 264,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 53,"idesporte": 26,"idmodalidade": -1,"idcategoria": 265,"data": "2016-08-06 11:00:00","nome": "Centro Olimpico de Tenis","idlocal": 26}, {"idevento": 55,"idesporte": 15,"idmodalidade": -1,"idcategoria": 166,"data": "2016-08-06 19:00:00","nome": "Riocentro - Pavilhao 2","idlocal": 28}, {"idevento": 56,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-06 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 56,"idesporte": 4,"idmodalidade": -1,"idcategoria": 58,"data": "2016-08-06 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 56,"idesporte": 4,"idmodalidade": -1,"idcategoria": 63,"data": "2016-08-06 11:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 57,"idesporte": 4,"idmodalidade": -1,"idcategoria": 62,"data": "2016-08-06 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 57,"idesporte": 4,"idmodalidade": -1,"idcategoria": 58,"data": "2016-08-06 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 57,"idesporte": 4,"idmodalidade": -1,"idcategoria": 63,"data": "2016-08-06 17:00:00","nome": "Riocentro - Pavilhao 6","idlocal": 31}, {"idevento": 58,"idesporte": 9,"idmodalidade": 16,"idcategoria": 119,"data": "2016-08-06 10:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 58,"idesporte": 9,"idmodalidade": 16,"idcategoria": 116,"data": "2016-08-06 10:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 58,"idesporte": 9,"idmodalidade": 16,"idcategoria": 121,"data": "2016-08-06 10:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 58,"idesporte": 9,"idmodalidade": 16,"idcategoria": 118,"data": "2016-08-06 10:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 58,"idesporte": 9,"idmodalidade": 16,"idcategoria": 120,"data": "2016-08-06 10:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 58,"idesporte": 9,"idmodalidade": 16,"idcategoria": 117,"data": "2016-08-06 10:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 59,"idesporte": 9,"idmodalidade": 16,"idcategoria": 116,"data": "2016-08-06 14:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 59,"idesporte": 9,"idmodalidade": 16,"idcategoria": 121,"data": "2016-08-06 14:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 59,"idesporte": 9,"idmodalidade": 16,"idcategoria": 118,"data": "2016-08-06 14:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 59,"idesporte": 9,"idmodalidade": 16,"idcategoria": 120,"data": "2016-08-06 14:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 59,"idesporte": 9,"idmodalidade": 16,"idcategoria": 117,"data": "2016-08-06 14:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 59,"idesporte": 9,"idmodalidade": 16,"idcategoria": 119,"data": "2016-08-06 14:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 60,"idesporte": 9,"idmodalidade": 16,"idcategoria": 121,"data": "2016-08-06 18:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 60,"idesporte": 9,"idmodalidade": 16,"idcategoria": 118,"data": "2016-08-06 18:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 60,"idesporte": 9,"idmodalidade": 16,"idcategoria": 120,"data": "2016-08-06 18:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 60,"idesporte": 9,"idmodalidade": 16,"idcategoria": 117,"data": "2016-08-06 18:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 60,"idesporte": 9,"idmodalidade": 16,"idcategoria": 119,"data": "2016-08-06 18:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 60,"idesporte": 9,"idmodalidade": 16,"idcategoria": 116,"data": "2016-08-06 18:30:00","nome": "Arena Olimpica do Rio","idlocal": 32}, {"idevento": 61,"idesporte": 27,"idmodalidade": -1,"idcategoria": 268,"data": "2016-08-06 09:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 61,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-06 09:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 61,"idesporte": 27,"idmodalidade": -1,"idcategoria": 270,"data": "2016-08-06 09:00:00","nome": "Riocentro - Pavilhao 3","idlocal": 29}, {"idevento": 63,"idesporte": 8,"idmodalidade": 0,"idcategoria": 113,"data": "2016-08-06 15:00:00","nome": "Arena Corinthians","idlocal": 35}, {"idevento": 64,"idesporte": 3,"idmodalidade": -1,"idcategoria": 53,"data": "2016-08-06 12:00:00","nome": "Arena da Juventude","idlocal": 37}] |
lib.rs | // DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
//! This documentation was generated from *Container* crate version *3.1.0+20220215*, where *20220215* is the exact revision of the *container:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v3.1.0*.
//!
//! Everything else about the *Container* *v1* API can be found at the
//! [official documentation site](https://cloud.google.com/container-engine/).
//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/main/gen/container1).
//! # Features
//!
//! Handle the following *Resources* with ease from the central [hub](Container) ...
//!
//! * projects
//! * [*aggregated usable subnetworks list*](api::ProjectAggregatedUsableSubnetworkListCall), [*locations clusters complete ip rotation*](api::ProjectLocationClusterCompleteIpRotationCall), [*locations clusters create*](api::ProjectLocationClusterCreateCall), [*locations clusters delete*](api::ProjectLocationClusterDeleteCall), [*locations clusters get*](api::ProjectLocationClusterGetCall), [*locations clusters get jwks*](api::ProjectLocationClusterGetJwkCall), [*locations clusters list*](api::ProjectLocationClusterListCall), [*locations clusters node pools create*](api::ProjectLocationClusterNodePoolCreateCall), [*locations clusters node pools delete*](api::ProjectLocationClusterNodePoolDeleteCall), [*locations clusters node pools get*](api::ProjectLocationClusterNodePoolGetCall), [*locations clusters node pools list*](api::ProjectLocationClusterNodePoolListCall), [*locations clusters node pools rollback*](api::ProjectLocationClusterNodePoolRollbackCall), [*locations clusters node pools set autoscaling*](api::ProjectLocationClusterNodePoolSetAutoscalingCall), [*locations clusters node pools set management*](api::ProjectLocationClusterNodePoolSetManagementCall), [*locations clusters node pools set size*](api::ProjectLocationClusterNodePoolSetSizeCall), [*locations clusters node pools update*](api::ProjectLocationClusterNodePoolUpdateCall), [*locations clusters set addons*](api::ProjectLocationClusterSetAddonCall), [*locations clusters set legacy abac*](api::ProjectLocationClusterSetLegacyAbacCall), [*locations clusters set locations*](api::ProjectLocationClusterSetLocationCall), [*locations clusters set logging*](api::ProjectLocationClusterSetLoggingCall), [*locations clusters set maintenance policy*](api::ProjectLocationClusterSetMaintenancePolicyCall), [*locations clusters set master auth*](api::ProjectLocationClusterSetMasterAuthCall), [*locations clusters set monitoring*](api::ProjectLocationClusterSetMonitoringCall), [*locations clusters set network policy*](api::ProjectLocationClusterSetNetworkPolicyCall), [*locations clusters set resource labels*](api::ProjectLocationClusterSetResourceLabelCall), [*locations clusters start ip rotation*](api::ProjectLocationClusterStartIpRotationCall), [*locations clusters update*](api::ProjectLocationClusterUpdateCall), [*locations clusters update master*](api::ProjectLocationClusterUpdateMasterCall), [*locations clusters well-known get openid-configuration*](api::ProjectLocationClusterWellKnownGetOpenidConfigurationCall), [*locations get server config*](api::ProjectLocationGetServerConfigCall), [*locations operations cancel*](api::ProjectLocationOperationCancelCall), [*locations operations get*](api::ProjectLocationOperationGetCall), [*locations operations list*](api::ProjectLocationOperationListCall), [*zones clusters addons*](api::ProjectZoneClusterAddonCall), [*zones clusters complete ip rotation*](api::ProjectZoneClusterCompleteIpRotationCall), [*zones clusters create*](api::ProjectZoneClusterCreateCall), [*zones clusters delete*](api::ProjectZoneClusterDeleteCall), [*zones clusters get*](api::ProjectZoneClusterGetCall), [*zones clusters legacy abac*](api::ProjectZoneClusterLegacyAbacCall), [*zones clusters list*](api::ProjectZoneClusterListCall), [*zones clusters locations*](api::ProjectZoneClusterLocationCall), [*zones clusters logging*](api::ProjectZoneClusterLoggingCall), [*zones clusters master*](api::ProjectZoneClusterMasterCall), [*zones clusters monitoring*](api::ProjectZoneClusterMonitoringCall), [*zones clusters node pools autoscaling*](api::ProjectZoneClusterNodePoolAutoscalingCall), [*zones clusters node pools create*](api::ProjectZoneClusterNodePoolCreateCall), [*zones clusters node pools delete*](api::ProjectZoneClusterNodePoolDeleteCall), [*zones clusters node pools get*](api::ProjectZoneClusterNodePoolGetCall), [*zones clusters node pools list*](api::ProjectZoneClusterNodePoolListCall), [*zones clusters node pools rollback*](api::ProjectZoneClusterNodePoolRollbackCall), [*zones clusters node pools set management*](api::ProjectZoneClusterNodePoolSetManagementCall), [*zones clusters node pools set size*](api::ProjectZoneClusterNodePoolSetSizeCall), [*zones clusters node pools update*](api::ProjectZoneClusterNodePoolUpdateCall), [*zones clusters resource labels*](api::ProjectZoneClusterResourceLabelCall), [*zones clusters set maintenance policy*](api::ProjectZoneClusterSetMaintenancePolicyCall), [*zones clusters set master auth*](api::ProjectZoneClusterSetMasterAuthCall), [*zones clusters set network policy*](api::ProjectZoneClusterSetNetworkPolicyCall), [*zones clusters start ip rotation*](api::ProjectZoneClusterStartIpRotationCall), [*zones clusters update*](api::ProjectZoneClusterUpdateCall), [*zones get serverconfig*](api::ProjectZoneGetServerconfigCall), [*zones operations cancel*](api::ProjectZoneOperationCancelCall), [*zones operations get*](api::ProjectZoneOperationGetCall) and [*zones operations list*](api::ProjectZoneOperationListCall)
//!
//!
//!
//!
//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](http://byron.github.io/google-apis-rs).
//!
//! # Structure of this Library
//!
//! The API is structured into the following primary items:
//!
//! * **[Hub](Container)**
//! * a central object to maintain state and allow accessing all *Activities*
//! * creates [*Method Builders*](client::MethodsBuilder) which in turn
//! allow access to individual [*Call Builders*](client::CallBuilder)
//! * **[Resources](client::Resource)**
//! * primary types that you can apply *Activities* to
//! * a collection of properties and *Parts*
//! * **[Parts](client::Part)**
//! * a collection of properties
//! * never directly used in *Activities*
//! * **[Activities](client::CallBuilder)**
//! * operations to apply to *Resources*
//!
//! All *structures* are marked with applicable traits to further categorize them and ease browsing.
//!
//! Generally speaking, you can invoke *Activities* like this:
//!
//! ```Rust,ignore
//! let r = hub.resource().activity(...).doit().await
//! ```
//!
//! Or specifically ...
//!
//! ```ignore
//! let r = hub.projects().locations_clusters_node_pools_create(...).doit().await
//! let r = hub.projects().locations_clusters_node_pools_delete(...).doit().await
//! let r = hub.projects().locations_clusters_node_pools_rollback(...).doit().await
//! let r = hub.projects().locations_clusters_node_pools_set_autoscaling(...).doit().await
//! let r = hub.projects().locations_clusters_node_pools_set_management(...).doit().await
//! let r = hub.projects().locations_clusters_node_pools_set_size(...).doit().await
//! let r = hub.projects().locations_clusters_node_pools_update(...).doit().await
//! let r = hub.projects().locations_clusters_complete_ip_rotation(...).doit().await
//! let r = hub.projects().locations_clusters_create(...).doit().await
//! let r = hub.projects().locations_clusters_delete(...).doit().await
//! let r = hub.projects().locations_clusters_set_addons(...).doit().await
//! let r = hub.projects().locations_clusters_set_legacy_abac(...).doit().await
//! let r = hub.projects().locations_clusters_set_locations(...).doit().await
//! let r = hub.projects().locations_clusters_set_logging(...).doit().await
//! let r = hub.projects().locations_clusters_set_maintenance_policy(...).doit().await
//! let r = hub.projects().locations_clusters_set_master_auth(...).doit().await
//! let r = hub.projects().locations_clusters_set_monitoring(...).doit().await | //! let r = hub.projects().locations_clusters_start_ip_rotation(...).doit().await
//! let r = hub.projects().locations_clusters_update(...).doit().await
//! let r = hub.projects().locations_clusters_update_master(...).doit().await
//! let r = hub.projects().locations_operations_get(...).doit().await
//! let r = hub.projects().zones_clusters_node_pools_autoscaling(...).doit().await
//! let r = hub.projects().zones_clusters_node_pools_create(...).doit().await
//! let r = hub.projects().zones_clusters_node_pools_delete(...).doit().await
//! let r = hub.projects().zones_clusters_node_pools_rollback(...).doit().await
//! let r = hub.projects().zones_clusters_node_pools_set_management(...).doit().await
//! let r = hub.projects().zones_clusters_node_pools_set_size(...).doit().await
//! let r = hub.projects().zones_clusters_node_pools_update(...).doit().await
//! let r = hub.projects().zones_clusters_addons(...).doit().await
//! let r = hub.projects().zones_clusters_complete_ip_rotation(...).doit().await
//! let r = hub.projects().zones_clusters_create(...).doit().await
//! let r = hub.projects().zones_clusters_delete(...).doit().await
//! let r = hub.projects().zones_clusters_legacy_abac(...).doit().await
//! let r = hub.projects().zones_clusters_locations(...).doit().await
//! let r = hub.projects().zones_clusters_logging(...).doit().await
//! let r = hub.projects().zones_clusters_master(...).doit().await
//! let r = hub.projects().zones_clusters_monitoring(...).doit().await
//! let r = hub.projects().zones_clusters_resource_labels(...).doit().await
//! let r = hub.projects().zones_clusters_set_maintenance_policy(...).doit().await
//! let r = hub.projects().zones_clusters_set_master_auth(...).doit().await
//! let r = hub.projects().zones_clusters_set_network_policy(...).doit().await
//! let r = hub.projects().zones_clusters_start_ip_rotation(...).doit().await
//! let r = hub.projects().zones_clusters_update(...).doit().await
//! let r = hub.projects().zones_operations_get(...).doit().await
//! ```
//!
//! The `resource()` and `activity(...)` calls create [builders][builder-pattern]. The second one dealing with `Activities`
//! supports various methods to configure the impending operation (not shown here). It is made such that all required arguments have to be
//! specified right away (i.e. `(...)`), whereas all optional ones can be [build up][builder-pattern] as desired.
//! The `doit()` method performs the actual communication with the server and returns the respective result.
//!
//! # Usage
//!
//! ## Setting up your Project
//!
//! To use this library, you would put the following lines into your `Cargo.toml` file:
//!
//! ```toml
//! [dependencies]
//! google-container1 = "*"
//! serde = "^1.0"
//! serde_json = "^1.0"
//! ```
//!
//! ## A complete example
//!
//! ```test_harness,no_run
//! extern crate hyper;
//! extern crate hyper_rustls;
//! extern crate google_container1 as container1;
//! use container1::{Result, Error};
//! # async fn dox() {
//! use std::default::Default;
//! use container1::{Container, oauth2, hyper, hyper_rustls};
//!
//! // Get an ApplicationSecret instance by some means. It contains the `client_id` and
//! // `client_secret`, among other things.
//! let secret: oauth2::ApplicationSecret = Default::default();
//! // Instantiate the authenticator. It will choose a suitable authentication flow for you,
//! // unless you replace `None` with the desired Flow.
//! // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
//! // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
//! // retrieve them from storage.
//! let auth = oauth2::InstalledFlowAuthenticator::builder(
//! secret,
//! oauth2::InstalledFlowReturnMethod::HTTPRedirect,
//! ).build().await.unwrap();
//! let mut hub = Container::new(hyper::Client::builder().build(hyper_rustls::HttpsConnector::with_native_roots().https_or_http().enable_http1().enable_http2().build()), auth);
//! // You can configure optional parameters by calling the respective setters at will, and
//! // execute the final call using `doit()`.
//! // Values shown here are possibly random and not representative !
//! let result = hub.projects().locations_clusters_node_pools_delete("name")
//! .zone("sanctus")
//! .project_id("sed")
//! .node_pool_id("amet.")
//! .cluster_id("takimata")
//! .doit().await;
//!
//! match result {
//! Err(e) => match e {
//! // The Error enum provides details about what exactly happened.
//! // You can also just use its `Debug`, `Display` or `Error` traits
//! Error::HttpError(_)
//! |Error::Io(_)
//! |Error::MissingAPIKey
//! |Error::MissingToken(_)
//! |Error::Cancelled
//! |Error::UploadSizeLimitExceeded(_, _)
//! |Error::Failure(_)
//! |Error::BadRequest(_)
//! |Error::FieldClash(_)
//! |Error::JsonDecodeError(_, _) => println!("{}", e),
//! },
//! Ok(res) => println!("Success: {:?}", res),
//! }
//! # }
//! ```
//! ## Handling Errors
//!
//! All errors produced by the system are provided either as [Result](client::Result) enumeration as return value of
//! the doit() methods, or handed as possibly intermediate results to either the
//! [Hub Delegate](client::Delegate), or the [Authenticator Delegate](https://docs.rs/yup-oauth2/*/yup_oauth2/trait.AuthenticatorDelegate.html).
//!
//! When delegates handle errors or intermediate values, they may have a chance to instruct the system to retry. This
//! makes the system potentially resilient to all kinds of errors.
//!
//! ## Uploads and Downloads
//! If a method supports downloads, the response body, which is part of the [Result](client::Result), should be
//! read by you to obtain the media.
//! If such a method also supports a [Response Result](client::ResponseResult), it will return that by default.
//! You can see it as meta-data for the actual media. To trigger a media download, you will have to set up the builder by making
//! this call: `.param("alt", "media")`.
//!
//! Methods supporting uploads can do so using up to 2 different protocols:
//! *simple* and *resumable*. The distinctiveness of each is represented by customized
//! `doit(...)` methods, which are then named `upload(...)` and `upload_resumable(...)` respectively.
//!
//! ## Customization and Callbacks
//!
//! You may alter the way an `doit()` method is called by providing a [delegate](client::Delegate) to the
//! [Method Builder](client::CallBuilder) before making the final `doit()` call.
//! Respective methods will be called to provide progress information, as well as determine whether the system should
//! retry on failure.
//!
//! The [delegate trait](client::Delegate) is default-implemented, allowing you to customize it with minimal effort.
//!
//! ## Optional Parts in Server-Requests
//!
//! All structures provided by this library are made to be [encodable](client::RequestValue) and
//! [decodable](client::ResponseResult) via *json*. Optionals are used to indicate that partial requests are responses
//! are valid.
//! Most optionals are are considered [Parts](client::Part) which are identifiable by name, which will be sent to
//! the server to indicate either the set parts of the request or the desired parts in the response.
//!
//! ## Builder Arguments
//!
//! Using [method builders](client::CallBuilder), you are able to prepare an action call by repeatedly calling it's methods.
//! These will always take a single argument, for which the following statements are true.
//!
//! * [PODs][wiki-pod] are handed by copy
//! * strings are passed as `&str`
//! * [request values](client::RequestValue) are moved
//!
//! Arguments will always be copied or cloned into the builder, to make them independent of their original life times.
//!
//! [wiki-pod]: http://en.wikipedia.org/wiki/Plain_old_data_structure
//! [builder-pattern]: http://en.wikipedia.org/wiki/Builder_pattern
//! [google-go-api]: https://github.com/google/google-api-go-client
//!
//!
// Unused attributes happen thanks to defined, but unused structures
// We don't warn about this, as depending on the API, some data structures or facilities are never used.
// Instead of pre-determining this, we just disable the lint. It's manually tuned to not have any
// unused imports in fully featured APIs. Same with unused_mut ... .
#![allow(unused_imports, unused_mut, dead_code)]
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
#[macro_use]
extern crate serde_derive;
// Re-export the hyper and hyper_rustls crate, they are required to build the hub
pub extern crate hyper;
pub extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;
// Re-export the yup_oauth2 crate, that is required to call some methods of the hub and the client
pub extern crate yup_oauth2 as oauth2;
extern crate mime;
extern crate url;
pub mod api;
pub mod client;
// Re-export the hub type and some basic client structs
pub use api::Container;
pub use client::{Result, Error, Delegate}; | //! let r = hub.projects().locations_clusters_set_network_policy(...).doit().await
//! let r = hub.projects().locations_clusters_set_resource_labels(...).doit().await |
nested_closures.rs | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Check that we can codegen various nesting structures of boxes and
// pointer to closures.
pub fn | () {
// Create a nested boxed once-callable closure
let f: Box<Box<dyn FnOnce(i32)>> = Box::new(Box::new(|x| assert!(x == 1)));
f(1);
// Create a pointer to a closure
let g = |x: f32, y: i32| {
assert!(x == 1.0);
assert!(y == 2)
};
let p: &dyn Fn(f32, i32) = &g;
p(1.0, 2);
// Additional level of pointer nesting
let q: &dyn Fn(f32, i32) = &p;
q(1.0, 2);
// Create a boxed pointer to a closure
let r: Box<&dyn Fn(f32, i32, bool)> = Box::new(&|x: f32, y: i32, z: bool| {
assert!(x == 1.0);
assert!(y == 2);
assert!(z);
});
r(1.0, 2, true);
// Another boxed box
let s: Box<Box<dyn Fn(i32)>> = Box::new(Box::new(|x| assert!(x == 3)));
s(3);
// A pointer to the boxed box
let t: &Box<Box<dyn Fn(i32)>> = &s;
t(3);
}
| main |
udp_linux_test.go | // +build linux testrareexceptions
package udpnofrag
import (
"net"
"reflect"
"syscall"
"testing"
"unsafe" |
func TestUdpSetNoFragment_negative(t *testing.T) {
assert.Equal(t, syscall.EINVAL, UDPSetNoFragment(&net.UDPConn{}))
conn, err := net.Dial("udp", "127.0.0.1:1")
udpConn := conn.(*net.UDPConn)
assert.NoError(t, err)
fd := (**struct{ a [65536]byte })((unsafe.Pointer)(reflect.ValueOf(unsafetools.FieldByName(udpConn, `fd`)).Elem().UnsafeAddr()))
*fd = &struct{ a [65536]byte }{}
assert.Equal(t, syscall.ENOTSOCK, UDPSetNoFragment(udpConn))
} |
"github.com/stretchr/testify/assert"
"github.com/xaionaro-go/unsafetools"
) |
visualize_court.py | import numpy as np
# import plotly
import plotly.graph_objects as go
def draw_plotly_half_court(fig, fig_width=600, margins=10):
# From: https://community.plot.ly/t/arc-shape-with-path/7205/5
def ellipse_arc(x_center=0.0, y_center=0.0, a=10.5, b=10.5, start_angle=0.0, end_angle=2 * np.pi, N=200, closed=False):
t = np.linspace(start_angle, end_angle, N)
x = x_center + a * np.cos(t)
y = y_center + b * np.sin(t)
path = f'M {x[0]}, {y[0]}'
for k in range(1, len(t)):
path += f'L{x[k]}, {y[k]}'
if closed:
path += ' Z'
return path
fig_height = fig_width * (470 + 2 * margins) / (500 + 2 * margins)
fig.update_layout(width=fig_width, height=fig_height)
# Set axes ranges
fig.update_xaxes(range=[-250 - margins, 250 + margins])
fig.update_yaxes(range=[-52.5 - margins, 417.5 + margins])
threept_break_y = 89.47765084
three_line_col = "#777777"
main_line_col = "#777777"
fig.update_layout(
# Line Horizontal
margin=dict(l=20, r=20, t=20, b=20),
paper_bgcolor="white",
plot_bgcolor="white",
yaxis=dict(
scaleanchor="x",
scaleratio=1,
showgrid=False,
zeroline=False,
showline=False,
ticks='',
showticklabels=False,
fixedrange=True,
),
xaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
ticks='',
showticklabels=False,
fixedrange=True,
),
shapes=[
# half_layout=[
dict(
type="rect", x0=-250, y0=-52.5, x1=250, y1=417.5,
line=dict(color=main_line_col, width=1),
# fillcolor='#333333',
layer='below'
), ## sideline rect
dict(
type="rect", x0=-80, y0=-52.5, x1=80, y1=137.5,
line=dict(color=main_line_col, width=1),
# fillcolor='#333333',
layer='below'
),# lane line rect
dict(
type="rect", x0=-60, y0=-52.5, x1=60, y1=137.5,
line=dict(color=main_line_col, width=1),
# fillcolor='#333333',
layer='below'
), # foul line rect
dict(
type="circle", x0=-60, y0=77.5, x1=60, y1=197.5, xref="x", yref="y",
line=dict(color=main_line_col, width=1),
# fillcolor='#dddddd',
layer='below'
), # free-throw circle
dict(
type="line", x0=-60, y0=137.5, x1=60, y1=137.5,
line=dict(color=main_line_col, width=1),
layer='below'
), # foul line
dict(
type="rect", x0=-2, y0=-7.25, x1=2, y1=-12.5,
line=dict(color="#ec7607", width=1),
fillcolor='#ec7607',
), # hoop rect
dict(
type="circle", x0=-7.5, y0=-7.5, x1=7.5, y1=7.5, xref="x", yref="y",
line=dict(color="#ec7607", width=1),
), # hoop circle
dict(
type="line", x0=-30, y0=-12.5, x1=30, y1=-12.5,
line=dict(color="#ec7607", width=1),
), # backboard
dict(type="path",
path=ellipse_arc(a=40, b=40, start_angle=0, end_angle=np.pi),
line=dict(color=main_line_col, width=1), layer='below'), # no-change semi-circle
dict(type="path",
path=ellipse_arc(a=237.5, b=237.5, start_angle=0.386283101, end_angle=np.pi - 0.386283101),
line=dict(color=main_line_col, width=1), layer='below'), # three-point line:arc
dict(
type="line", x0=-220, y0=-52.5, x1=-220, y1=threept_break_y,
line=dict(color=three_line_col, width=1), layer='below'
), # three-point line:left edge
# dict(
# type="line", x0=-220, y0=-52.5, x1=-220, y1=threept_break_y,
# line=dict(color=three_line_col, width=1), layer='below'
# ),
dict(
type="line", x0=220, y0=-52.5, x1=220, y1=threept_break_y,
line=dict(color=three_line_col, width=1), layer='below'
), # three-point line:right edge
dict(
type="line", x0=-250, y0=227.5, x1=-220, y1=227.5,
line=dict(color=main_line_col, width=1), layer='below'
), # midcourt area marker:left
dict(
type="line", x0=250, y0=227.5, x1=220, y1=227.5,
line=dict(color=main_line_col, width=1), layer='below'
), # midcourt area marker:right
dict(
type="line", x0=-90, y0=17.5, x1=-80, y1=17.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=-90, y0=27.5, x1=-80, y1=27.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=-90, y0=57.5, x1=-80, y1=57.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=-90, y0=87.5, x1=-80, y1=87.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=90, y0=17.5, x1=80, y1=17.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=90, y0=27.5, x1=80, y1=27.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=90, y0=57.5, x1=80, y1=57.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=90, y0=87.5, x1=80, y1=87.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(type="path",
path=ellipse_arc(y_center=417.5, a=60, b=60, start_angle=-0, end_angle=-np.pi),
line=dict(color=main_line_col, width=1), layer='below'), # center circle: half
]
)
return True
def draw_plotly_whole_court(fig, fig_width=600, margins=10):
# From: https://community.plot.ly/t/arc-shape-with-path/7205/5
def ellipse_arc(x_center=0.0, y_center=0.0, a=10.5, b=10.5, start_angle=0.0, end_angle=2 * np.pi, N=200, closed=False):
|
fig_height = fig_width * (470*2 + 2 * margins) / (500 + 2 * margins)
fig.update_layout(width=fig_width, height=fig_height)
# Set axes ranges
fig.update_xaxes(range=[-250 - margins, 250 + margins])
fig.update_yaxes(range=[-52.5 - margins, 417.5+470 + margins])
# fig.update_xaxes(range=[ margins, 500 + margins])
# fig.update_yaxes(range=[margins, 470*2 + margins])
threept_break_y = 89.47765084
three_line_col = "#777777"
main_line_col = "#777777"
fig.update_layout(
# Line Horizontal
margin=dict(l=20, r=20, t=20, b=20),
paper_bgcolor="white",
plot_bgcolor="white",
yaxis=dict(
scaleanchor="x",
scaleratio=1,
showgrid=False,
zeroline=False,
showline=False,
ticks='',
showticklabels=False,
fixedrange=True,
),
xaxis=dict(
showgrid=False,
zeroline=False,
showline=False,
ticks='',
showticklabels=False,
fixedrange=True,
),
# width:500, height: 470
shapes=[
dict(
type="rect", x0=-250, y0=-52.5, x1=250, y1=417.5+470,
line=dict(color=main_line_col, width=1),
# fillcolor='#333333',
layer='below'
), ## sideline rect
# dict(
# type="rect", x0=-250, y0=-52.5, x1=250, y1=417.5,
# line=dict(color=main_line_col, width=1),
# # fillcolor='#333333',
# layer='below'
# ), ## sideline rect
dict(
type="rect", x0=-80, y0=-52.5, x1=80, y1=137.5,
line=dict(color=main_line_col, width=1),
# fillcolor='#333333',
layer='below'
),# lane line rect
dict(
type="rect", x0=-60, y0=-52.5, x1=60, y1=137.5,
line=dict(color=main_line_col, width=1),
# fillcolor='#333333',
layer='below'
), # foul line rect
dict(
type="circle", x0=-60, y0=77.5, x1=60, y1=197.5, xref="x", yref="y",
line=dict(color=main_line_col, width=1),
# fillcolor='#dddddd',
layer='below'
), # free-throw circle
dict(
type="line", x0=-60, y0=137.5, x1=60, y1=137.5,
line=dict(color=main_line_col, width=1),
layer='below'
), # foul line
dict(
type="rect", x0=-2, y0=-7.25, x1=2, y1=-12.5,
line=dict(color="#ec7607", width=1),
fillcolor='#ec7607',
), # hoop rect
dict(
type="circle", x0=-7.5, y0=-7.5, x1=7.5, y1=7.5, xref="x", yref="y",
line=dict(color="#ec7607", width=1),
), # hoop circle
dict(
type="line", x0=-30, y0=-12.5, x1=30, y1=-12.5,
line=dict(color="#ec7607", width=1),
), # backboard
dict(type="path",
path=ellipse_arc(a=40, b=40, start_angle=0, end_angle=np.pi),
line=dict(color=main_line_col, width=1), layer='below'), # no-change semi-circle
dict(type="path",
path=ellipse_arc(a=237.5, b=237.5, start_angle=0.386283101, end_angle=np.pi - 0.386283101),
line=dict(color=main_line_col, width=1), layer='below'), # three-point line:arc
dict(
type="line", x0=-220, y0=-52.5, x1=-220, y1=threept_break_y,
line=dict(color=three_line_col, width=1), layer='below'
), # three-point line:left edge
# dict(
# type="line", x0=-220, y0=-52.5, x1=-220, y1=threept_break_y,
# line=dict(color=three_line_col, width=1), layer='below'
# ),
dict(
type="line", x0=220, y0=-52.5, x1=220, y1=threept_break_y,
line=dict(color=three_line_col, width=1), layer='below'
), # three-point line:right edge
dict(
type="line", x0=-250, y0=227.5, x1=-220, y1=227.5,
line=dict(color=main_line_col, width=1), layer='below'
), # midcourt area marker:left
dict(
type="line", x0=250, y0=227.5, x1=220, y1=227.5,
line=dict(color=main_line_col, width=1), layer='below'
), # midcourt area marker:right
dict(
type="line", x0=-90, y0=17.5, x1=-80, y1=17.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=-90, y0=27.5, x1=-80, y1=27.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=-90, y0=57.5, x1=-80, y1=57.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=-90, y0=87.5, x1=-80, y1=87.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=90, y0=17.5, x1=80, y1=17.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=90, y0=27.5, x1=80, y1=27.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=90, y0=57.5, x1=80, y1=57.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(
type="line", x0=90, y0=87.5, x1=80, y1=87.5,
line=dict(color=main_line_col, width=1), layer='below'
), # lane line marker
dict(type="path",
path=ellipse_arc(y_center=417.5, a=60, b=60, start_angle=-0, end_angle=-np.pi),
line=dict(color=main_line_col, width=1), layer='below'), # center circle: half
## upper
# dict(
# type="rect", x0=-250, y0=-52.5, x1=250, y1=417.5,
# line=dict(color=main_line_col, width=1),
# # fillcolor='#333333',
# layer='below'
# ), ## sideline rect
# dict(
# type="rect", x0=-80, y0=-52.5, x1=80, y1=137.5,
# line=dict(color=main_line_col, width=1),
# # fillcolor='#333333',
# layer='below'
# ), # lane line rect
# dict(
# type="rect", x0=-60, y0=-52.5, x1=60, y1=137.5,
# line=dict(color=main_line_col, width=1),
# # fillcolor='#333333',
# layer='below'
# ), # foul line rect
# dict(
# type="circle", x0=-60, y0=77.5, x1=60, y1=197.5, xref="x", yref="y",
# line=dict(color=main_line_col, width=1),
# # fillcolor='#dddddd',
# layer='below'
# ), # free-throw circle
# dict(
# type="line", x0=-60, y0=137.5, x1=60, y1=137.5,
# line=dict(color=main_line_col, width=1),
# layer='below'
# ), # foul line
#
# dict(
# type="rect", x0=-2, y0=-7.25, x1=2, y1=-12.5,
# line=dict(color="#ec7607", width=1),
# fillcolor='#ec7607',
# ), # hoop rect
# dict(
# type="circle", x0=-7.5, y0=-7.5, x1=7.5, y1=7.5, xref="x", yref="y",
# line=dict(color="#ec7607", width=1),
# ), # hoop circle
# dict(
# type="line", x0=-30, y0=-12.5, x1=30, y1=-12.5,
# line=dict(color="#ec7607", width=1),
# ), # backboard
#
# dict(type="path",
# path=ellipse_arc(a=40, b=40, start_angle=0, end_angle=np.pi),
# line=dict(color=main_line_col, width=1), layer='below'), # no-change semi-circle
# dict(type="path",
# path=ellipse_arc(a=237.5, b=237.5, start_angle=0.386283101, end_angle=np.pi - 0.386283101),
# line=dict(color=main_line_col, width=1), layer='below'), # three-point line:arc
# dict(
# type="line", x0=-220, y0=-52.5, x1=-220, y1=threept_break_y,
# line=dict(color=three_line_col, width=1), layer='below'
# ), # three-point line:left edge
# # dict(
# # type="line", x0=-220, y0=-52.5, x1=-220, y1=threept_break_y,
# # line=dict(color=three_line_col, width=1), layer='below'
# # ),
# dict(
# type="line", x0=220, y0=-52.5, x1=220, y1=threept_break_y,
# line=dict(color=three_line_col, width=1), layer='below'
# ), # three-point line:right edge
#
# dict(
# type="line", x0=-250, y0=227.5, x1=-220, y1=227.5,
# line=dict(color=main_line_col, width=1), layer='below'
# ), # midcourt area marker:left
# dict(
# type="line", x0=250, y0=227.5, x1=220, y1=227.5,
# line=dict(color=main_line_col, width=1), layer='below'
# ), # midcourt area marker:right
# dict(
# type="line", x0=-90, y0=17.5, x1=-80, y1=17.5,
# line=dict(color=main_line_col, width=1), layer='below'
# ), # lane line marker
# dict(
# type="line", x0=-90, y0=27.5, x1=-80, y1=27.5,
# line=dict(color=main_line_col, width=1), layer='below'
# ), # lane line marker
# dict(
# type="line", x0=-90, y0=57.5, x1=-80, y1=57.5,
# line=dict(color=main_line_col, width=1), layer='below'
# ), # lane line marker
# dict(
# type="line", x0=-90, y0=87.5, x1=-80, y1=87.5,
# line=dict(color=main_line_col, width=1), layer='below'
# ), # lane line marker
# dict(
# type="line", x0=90, y0=17.5, x1=80, y1=17.5,
# line=dict(color=main_line_col, width=1), layer='below'
# ), # lane line marker
# dict(
# type="line", x0=90, y0=27.5, x1=80, y1=27.5,
# line=dict(color=main_line_col, width=1), layer='below'
# ), # lane line marker
# dict(
# type="line", x0=90, y0=57.5, x1=80, y1=57.5,
# line=dict(color=main_line_col, width=1), layer='below'
# ), # lane line marker
# dict(
# type="line", x0=90, y0=87.5, x1=80, y1=87.5,
# line=dict(color=main_line_col, width=1), layer='below'
# ), # lane line marker
#
# dict(type="path",
# path=ellipse_arc(y_center=417.5, a=60, b=60, start_angle=-0, end_angle=-np.pi),
# line=dict(color=main_line_col, width=1), layer='below'), # center circle: half
]
)
return True
max_freq = 0.002
# freq_by_hex = np.array([min(max_freq, i) for i in league_hexbin_stats['freq_by_hex']])
colorscale = 'YlOrRd'
marker_cmin = 0.1
marker_cmax = 0.6
ticktexts = [str(marker_cmin*100)+'%-', "", str(marker_cmax*100)+'%+']
fig = go.Figure()
# draw_plotly_half_court(fig)
draw_plotly_whole_court(fig)
# fig.add_trace(go.Scatter(
# x=xlocs, y=ylocs, mode='markers', name='markers',
# marker=dict(
# size=freq_by_hex, sizemode='area', sizeref=2. * max(freq_by_hex) / (11. ** 2), sizemin=2.5,
# color=accs_by_hex, colorscale=colorscale,
# colorbar=dict(
# thickness=15,
# x=0.84,
# y=0.87,
# yanchor='middle',
# len=0.2,
# title=dict(
# text="<B>Accuracy</B>",
# font=dict(
# size=11,
# color='#4d4d4d'
# ),
# ),
# tickvals=[marker_cmin, (marker_cmin + marker_cmax) / 2, marker_cmax],
# ticktext=ticktexts,
# tickfont=dict(
# size=11,
# color='#4d4d4d'
# )
# ),
# cmin=marker_cmin, cmax=marker_cmax,
# line=dict(width=1, color='#333333'), symbol='hexagon',
# ),
# ))
# fig.show(config=dict(displayModeBar=False))
# fig.show()
vis_dir='/media/felicia/Data/sgan_results/vis/'
fig.write_image(vis_dir+"court.svg")
| t = np.linspace(start_angle, end_angle, N)
x = x_center + a * np.cos(t)
y = y_center + b * np.sin(t)
path = f'M {x[0]}, {y[0]}'
for k in range(1, len(t)):
path += f'L{x[k]}, {y[k]}'
if closed:
path += ' Z'
return path |
tanh.go | package math32
// The original C code, the long comment, and the constants
// below were from http://netlib.sandia.gov/cephes/cmath/tanh.c,
// available from http://www.netlib.org/cephes/single.tgz.
// The go code is a simplified version of the original C.
// tanhf.c
//
// Hyperbolic tangent
//
//
//
// SYNOPSIS:
//
// float x, y, tanhf();
//
// y = tanhf( x );
//
//
//
// DESCRIPTION:
//
// Returns hyperbolic tangent of argument in the range MINLOG to
// MAXLOG.
//
// A polynomial approximation is used for |x| < 0.625.
// Otherwise,
//
// tanh(x) = sinh(x)/cosh(x) = 1 - 2/(exp(2x) + 1).
//
//
//
// ACCURACY:
//
// Relative error:
// arithmetic domain # trials peak rms
// IEEE -2,2 100000 1.3e-7 2.6e-8
//
//
/*
Cephes Math Library Release 2.2: June, 1992
Copyright 1984, 1987, 1989, 1992 by Stephen L. Moshier
Direct inquiries to 30 Frost Street, Cambridge, MA 02140
*/
/* Single precision hyperbolic tangent
* test interval: [-0.625, +0.625]
* trials: 10000
* peak relative error: 7.2e-8
* rms relative error: 2.6e-8
*/
func Tanh(x float32) float32 | {
const MAXLOG = 88.02969187150841
z := Abs(x)
switch {
case z > 0.5*MAXLOG:
if x < 0 {
return -1
}
return 1
case z >= 0.625:
s := Exp(z + z)
z = 1 - 2/(s+1)
if x < 0 {
z = -z
}
default:
if x == 0 {
return x
}
s := x * x
z = ((((-5.70498872745E-3*s+2.06390887954E-2)*s-5.37397155531E-2)*s+1.33314422036E-1)*s-3.33332819422E-1)*s*x + x
}
return z
} |
|
images.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""Manages the details on the images used in the build and the run stage."""
import json
import os.path
#: Global variable used to cache in memory the content of images.json
_data = None
def data():
"""Returns a dictionary with the static data on the images.
The dictionary is read from a JSON file lazily the first time
this function is called.
"""
global _data
if not _data:
json_dir = os.path.abspath(os.path.dirname(__file__))
json_file = os.path.join(json_dir, 'images.json')
with open(json_file) as f:
_data = json.load(f)
return _data
def build_info(image, spack_version):
"""Returns the name of the build image and its tag.
Args:
image (str): image to be used at run-time. Should be of the form
<image_name>:<image_tag> e.g. "ubuntu:18.04"
spack_version (str): version of Spack that we want to use to build
Returns:
A tuple with (image_name, image_tag) for the build image
"""
# Don't handle error here, as a wrong image should have been
# caught by the JSON schema
image_data = data()[image]
build_image = image_data['build']
# Try to check if we have a tag for this Spack version
try:
# Translate version from git to docker if necessary
build_tag = image_data['build_tags'].get(spack_version, spack_version)
except KeyError:
msg = ('the image "{0}" has no tag for Spack version "{1}" '
'[valid versions are {2}]')
msg = msg.format(build_image, spack_version,
', '.join(image_data['build_tags'].keys()))
raise ValueError(msg)
return build_image, build_tag
def package_info(image):
"""Returns the commands used to update system repositories, install
system packages and clean afterwards.
Args:
image (str): image to be used at run-time. Should be of the form
<image_name>:<image_tag> e.g. "ubuntu:18.04"
| image_data = data()[image]
update = image_data['update']
install = image_data['install']
clean = image_data['clean']
return update, install, clean | Returns:
A tuple of (update, install, clean) commands.
""" |
build.py | # coding=utf-8
"""
Build tasks
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import glob
import json
import os
import subprocess
import sys
from pynt import task
from pyntcontrib import execute, safe_cd
from semantic_version import Version
PROJECT_NAME = "simple_calls"
SRC = '.'
# for multitargeting
PYTHON = "python"
IS_DJANGO = False
IS_TRAVIS = 'TRAVIS' in os.environ
if IS_TRAVIS:
PIPENV = ""
else:
PIPENV = "pipenv run"
GEM_FURY = ""
CURRENT_HASH = None
MAC_LIBS = "" # ":" # TODO this breaks on windows
sys.path.append(os.path.join(os.path.dirname(__file__), '.'))
from build_utils import check_is_aws, skip_if_no_change, execute_with_environment, get_versions, execute_get_text, run_gitleaks
@task()
@skip_if_no_change("git_leaks")
def git_leaks():
run_gitleaks()
@task()
@skip_if_no_change("git_secrets")
def git_secrets():
"""
Install git secrets if possible.
"""
print("turning off because I'm on windows ...")
return
if check_is_aws():
# no easy way to install git secrets on ubuntu.
return
if IS_TRAVIS:
# nothing is edited on travis
return
try:
commands = ["git secrets --install", "git secrets --register-aws"]
for command in commands:
cp = subprocess.run(command.split(" "),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=False, check=True)
for stream in [cp.stdout, cp.stderr]:
if stream:
for line in stream.decode().split("\n"):
print("*" + line)
except subprocess.CalledProcessError as cpe:
print(cpe)
installed = False
for stream in [cpe.stdout, cpe.stderr]:
if stream:
for line in stream.decode().split("\n"):
print("-" + line)
if "commit-msg already exists" in line:
print("git secrets installed.")
installed = True
break
if not installed:
raise
execute(*("git secrets --scan".strip().split(" ")))
@task()
def clean():
"""
Delete all outputs. Blank until I think of a better way to do this.
"""
return
@task()
@skip_if_no_change("formatting")
def formatting():
with safe_cd(SRC):
if sys.version_info < (3, 6):
print("Black doesn't work on python 2")
return
command = "{0} black {1}".format(PIPENV, PROJECT_NAME).strip()
print(command)
result = execute_get_text(command)
assert result
changed =[]
for line in result.split("\n"):
if "reformatted " in line:
file = line[len("reformatted "):].strip()
changed.append(file)
for change in changed:
command ="git add {0}".format(change)
print(command)
execute(*(command.split(" ")))
@task()
@skip_if_no_change("compile_py")
def compile_py():
"""
Catch on the worst syntax errors
"""
with safe_cd(SRC):
execute(PYTHON, "-m", "compileall", PROJECT_NAME)
@task(formatting, compile_py)
@skip_if_no_change("prospector")
def prospector():
"""
Catch a few things with a non-strict propector run
"""
with safe_cd(SRC):
command = "{0} prospector {1} --profile {1}_style --pylint-config-file=pylintrc.ini --profile-path=.prospector".format(
PIPENV, PROJECT_NAME).strip().replace(" ", " ")
print(command)
execute(*(command
.split(" ")))
@task()
@skip_if_no_change("detect_secrets")
def detect_secrets():
"""
Call detect-secrets tool
"""
# use
# blah blah = "foo" # pragma: whitelist secret
# to ignore a false posites
errors_file = "detect-secrets-results.txt"
# TODO: not windows compat
# print(execute_get_text("pwd"))
command = "{0} detect-secrets --scan --base64-limit 4 --exclude .idea|.js|.min.js|.html|.xsd|" \
"lock.json|synced_folders|.scss|Pipfile.lock|" \
"lint.txt|{1}".format(PIPENV, errors_file).strip()
print(command)
bash_process = subprocess.Popen(command.split(" "),
#shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
foo = bash_process.wait()
out, err = bash_process.communicate() # wait
with open(errors_file, "w+") as file_handle:
if len(out)==0:
print("Warning- no output from detect secrets. Happens with git hook, but not from ordinary command line.")
return
file_handle.write(out.decode())
with open(errors_file) as f:
try:
data = json.load(f)
except Exception:
print("Can't read json")
exit(-1)
return
if data["results"]:
for result in data["results"]:
print(result)
print("detect-secrets has discovered high entropy strings, possibly passwords?")
exit(-1)
@task(compile_py, formatting, prospector)
@skip_if_no_change("lint")
def lint():
"""
Lint
"""
with safe_cd(SRC):
if os.path.isfile("lint.txt"):
# TODO: detect OS
try:
execute("rm", "lint.txt")
except:
# execute("DEL", "lint.txt") # fails... why?
os.remove("lint.txt")
with safe_cd(SRC):
if IS_DJANGO:
django_bits = "--load-plugins pylint_django "
else:
django_bits = ""
# command += "{0}--rcfile=pylintrc.ini {1}".format(django_bits, PROJECT_NAME).split(" ")
command = "{0} pylint {1} --rcfile=pylintrc.ini {2}".format(PIPENV, django_bits, PROJECT_NAME) \
.strip() \
.replace(" ", " ")
print(command)
command = command.split(" ")
# keep out of src tree, causes extraneous change detections
lint_output_file_name = "lint.txt"
with open(lint_output_file_name, "w") as outfile:
env = config_pythonpath()
subprocess.call(command, stdout=outfile, env=env)
fatal_errors = sum(1 for line in open(lint_output_file_name)
if "no-member" in line or \
"no-name-in-module" in line or \
"import-error" in line)
if fatal_errors > 0:
for line in open(lint_output_file_name):
if "no-member" in line or \
"no-name-in-module" in line or \
"import-error" in line:
print(line)
print("Fatal lint errors : {0}".format(fatal_errors))
exit(-1)
cutoff = 100
num_lines = sum(1 for line in open(lint_output_file_name)
if "*************" not in line
and "---------------------" not in line
and "Your code has been rated at" not in line)
if num_lines > cutoff:
raise TypeError("Too many lines of lint : {0}, max {1}".format(num_lines, cutoff))
@task(lint)
@skip_if_no_change("nose_tests")
def nose_tests():
"""
Nose tests
"""
# with safe_cd(SRC):
if IS_DJANGO:
command = "{0} manage.py test -v 2".format(PYTHON)
# We'd expect this to be MAC or a build server.
my_env = config_pythonpath()
execute_with_environment(command, env=my_env)
else:
my_env = config_pythonpath()
if IS_TRAVIS:
command = "{0} -m nose {1}".format(PYTHON, "test").strip()
else:
command = "{0} {1} -m nose {2}".format(PIPENV, PYTHON, "simple_calls").strip()
print(command)
execute_with_environment(command, env=my_env)
def config_pythonpath():
"""
Add to PYTHONPATH
"""
if check_is_aws():
env = "DEV"
else:
env = "MAC"
my_env = {'ENV': env}
for key, value in os.environ.items():
my_env[key] = value
my_env["PYTHONPATH"] = my_env.get("PYTHONPATH",
"") + MAC_LIBS
print(my_env["PYTHONPATH"])
return my_env
@task()
def coverage():
"""
Coverage, which is a bit redundant with nose test
"""
print("coverage broken on windows... don't know why yet")
return # will get back to this..
print("Coverage tests always re-run")
with safe_cd(SRC):
my_env = config_pythonpath()
command = "{0} py.test {1} --cov={2} --cov-report html:coverage --cov-fail-under 1 --verbose".format(
PIPENV,
"simple_calls", PROJECT_NAME)
print(command)
execute_with_environment(command, my_env)
@task()
@skip_if_no_change("docs")
def docs():
"""
Docs
"""
with safe_cd(SRC):
with safe_cd("docs"):
my_env = config_pythonpath()
command = "{0} make html".format(PIPENV).strip()
print(command)
execute_with_environment(command, env=my_env)
@task()
def pip_check():
"""
Are packages ok?
"""
execute("pip", "check")
if PIPENV and not IS_TRAVIS:
execute("pipenv", "check")
execute("safety", "check", "-r", "requirements_dev.txt")
@task()
def compile_mark_down():
"""
Convert MD to RST
"""
print("Not compiling README.md because moderately complex MD makes pypi rst parser puke.")
# with safe_cd(SRC):
# if IS_TRAVIS:
# command = "pandoc --from=markdown --to=rst --output=README.rst README.md".strip().split(
# " ")
# else:
# command = "{0} pandoc --from=markdown --to=rst --output=README.rst README.md".format(PIPENV).strip().split(
# " ")
# execute(*(command))
@task()
@skip_if_no_change("mypy")
def mypy():
"""
Are types ok?
"""
if sys.version_info < (3, 4):
print("Mypy doesn't work on python < 3.4")
return
if IS_TRAVIS:
command = "{0} -m mypy {1} --ignore-missing-imports --strict".format(PYTHON, PROJECT_NAME).strip()
else:
command = "{0} mypy {1} --ignore-missing-imports --strict".format(PIPENV, PROJECT_NAME).strip()
bash_process = subprocess.Popen(command.split(" "),
# shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
out, err = bash_process.communicate() # wait
mypy_file = "mypy_errors.txt"
with open(mypy_file, "w+") as lint_file:
lines = out.decode().split("\n")
for line in lines:
if "build_utils.py" in line:
continue
if "test.py" in line:
continue
if "tests.py" in line:
continue
if "/test_" in line:
continue
if "/tests_" in line:
continue
else:
lint_file.writelines([line + "\n"])
num_lines = sum(1 for line in open(mypy_file) if line and line.strip(" \n"))
max_lines = 25
if num_lines > max_lines:
raise TypeError("Too many lines of mypy : {0}, max {1}".format(num_lines, max_lines))
@task()
def pin_dependencies():
"""
Create requirement*.txt
"""
with safe_cd(SRC):
execute(*("{0} pipenv_to_requirements".format(PIPENV).strip().split(" ")))
@task()
def jiggle_version():
command = "{0} jiggle_version --project={1} --source={2}".format(PIPENV, PROJECT_NAME, "").strip()
execute(*(command.split(" ")))
@task()
def check_setup_py():
# if
# ValueError: ZIP does not support timestamps before 1980
# then run this to ID
# find . -mtime +13700 -ls
with safe_cd(SRC):
if IS_TRAVIS:
execute(PYTHON, *("setup.py check -r -s".split(" ")))
else:
execute(*("{0} {1} setup.py check -r -s".format(PIPENV, PYTHON).strip().split(" ")))
@task()
@skip_if_no_change("vulture", expect_files="dead_code.txt")
def dead_code():
"""
This also finds code you are working on today!
"""
with safe_cd(SRC):
if IS_TRAVIS:
command = "{0} vulture {1}".format(PYTHON, PROJECT_NAME).strip().split()
else:
command = "{0} vulture {1}".format(PIPENV, PROJECT_NAME).strip().split()
output_file_name = "dead_code.txt"
with open(output_file_name, "w") as outfile:
env = config_pythonpath()
subprocess.call(command, stdout=outfile, env=env)
cutoff = 20
num_lines = sum(1 for line in open(output_file_name) if line)
if num_lines > cutoff:
print("Too many lines of dead code : {0}, max {1}".format(num_lines, cutoff))
exit(-1)
@task(formatting, mypy, detect_secrets, git_secrets,dead_code, nose_tests, coverage, compile_py, lint,
compile_mark_down, check_setup_py, pin_dependencies, jiggle_version) # docs ... later
@skip_if_no_change("package")
def package():
"""
package, but don't upload
"""
with safe_cd(SRC):
for folder in ["build", "dist", PROJECT_NAME + ".egg-info"]:
# execute("rm", "-rf", folder)
if os.path.exists(folder):
os.rmdir(folder)
with safe_cd(SRC):
execute(PYTHON, "setup.py", "sdist", "--formats=gztar,zip")
@task(package)
def gemfury():
"""
Push to gem fury, a repo with private options
"""
# fury login
# fury push dist/*.gz --as=YOUR_ACCT
# fury push dist/*.whl --as=YOUR_ACCT
cp = subprocess.run(("fury login --as={0}".format(GEM_FURY).split(" ")),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=False, check=True)
print(cp.stdout)
about = {}
with open(os.path.join(SRC, PROJECT_NAME, "__version__.py")) as f:
exec(f.read(), about)
version = Version(about["__version__"])
print("Have version : " + str(version))
print("Preparing to upload")
if version not in get_versions():
for kind in ["gz", "whl"]:
try:
files = glob.glob("{0}dist/*.{1}".format(SRC.replace(".", ""), kind))
for file_name in files:
cp = subprocess.run(("fury push {0} --as={1}".format(file_name, GEM_FURY).split(" ")),
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=False, check=True)
print("result of fury push")
for stream in [cp.stdout, cp.stderr]:
if stream:
for line in stream.decode().split("\n"):
print(line)
except subprocess.CalledProcessError as cpe:
print("result of fury push- got error")
for stream in [cp.stdout, cp.stderr]:
if stream:
for line in stream.decode().split("\n"):
print(line)
print(cpe)
raise
# FAST. FATAL ERRORS. DON'T CHANGE THINGS THAT CHECK IN
@task(mypy, detect_secrets, git_secrets, check_setup_py, compile_py, dead_code)
@skip_if_no_change("pre_commit_hook")
def pre_commit_hook():
# Don't format or update version
# Don't do slow stuff- discourages frequent check in
# Run checks that are likely to have FATAL errors, not just sloppy coding.
pass
# Don't break the build, but don't change source tree either.
@task(mypy, detect_secrets, git_secrets, nose_tests, coverage, check_setup_py, compile_py, dead_code)
@skip_if_no_change("pre_push_hook")
def pre_push_hook():
# Don't format or update version
# Don't do slow stuff- discourages frequent check in
# Run checks that are likely to have FATAL errors, not just sloppy coding.
pass
def do_check_manifest(output_file_name, env):
if IS_TRAVIS:
command = "check-manifest".format(PYTHON).strip().split()
else:
command = "{0} check-manifest".format(PIPENV).strip().split()
with open(output_file_name, "w") as outfile:
subprocess.call(command, stdout=outfile, env=env)
@task()
@skip_if_no_change("check_manifest", "manifest_errors.txt")
def check_manifest():
env = config_pythonpath()
output_file_name = "manifest_errors.txt"
do_check_manifest(output_file_name, env)
with open(output_file_name) as outfile_reader:
text = outfile_reader.read()
print(text)
if not os.path.isfile("MANIFEST.in") and "no MANIFEST.in found" in text:
command = "{0} check-manifest -c".format(PIPENV).strip().split()
subprocess.call(command, env=env)
# print("Had to create MANIFEST.in, please review and redo")
do_check_manifest(output_file_name, env)
else:
pass
# print("found it")
cutoff = 20
num_lines = sum(1 for line in open(output_file_name) if line)
if num_lines > cutoff:
print("Too many lines of manifest problems : {0}, max {1}".format(num_lines, cutoff))
exit(-1)
@task()
def echo(*args, **kwargs):
|
# Default task (if specified) is run when no task is specified in the command line
# make sure you define the variable __DEFAULT__ after the task is defined
# A good convention is to define it at the end of the module
# __DEFAULT__ is an optional member
__DEFAULT__ = echo | """
Pure diagnostics
"""
print(args)
print(kwargs) |
2d_array.test.js | /******************************************************************************
*
* Copyright (c) 2020, the Regular Table Authors.
*
* This file is part of the Regular Table library, distributed under the terms
* of the Apache License 2.0. The full license can be found in the LICENSE
* file.
*
*/
describe("2d_array.html", () => {
beforeAll(async () => {
await page.setViewport({width: 400, height: 100});
});
describe("creates a `<table>` body when attached to `document`", () => {
beforeAll(async () => {
await page.goto("http://localhost:8081/dist/examples/2d_array.html");
await page.waitFor("regular-table table tbody tr td");
});
test("with the correct # of rows", async () => {
const tbody = await page.$("regular-table tbody");
const num_rows = await page.evaluate((tbody) => tbody.children.length, tbody);
expect(num_rows).toEqual(5);
});
test("with the correct # of columns", async () => {
const first_tr = await page.$("regular-table tbody tr:first-child");
const num_cells = await page.evaluate((first_tr) => first_tr.children.length, first_tr);
expect(num_cells).toEqual(3);
});
test("with the first row's cell test correct", async () => {
const first_tr = await page.$("regular-table tbody tr:first-child");
const cell_values = await page.evaluate((first_tr) => Array.from(first_tr.children).map((x) => x.textContent), first_tr);
expect(cell_values).toEqual(["0", "A", "true"]);
});
});
describe("scrolls via scrollToCell() method", () => {
beforeAll(async () => {
await page.goto("http://localhost:8081/dist/examples/2d_array.html");
await page.waitFor("regular-table table tbody tr td"); | test("to (0, 1)", async () => {
const table = await page.$("regular-table");
await page.evaluate(async (table) => {
table._invalid_schema = true;
table.scrollToCell(0, 1, 3, 26);
await table.draw({invalid_viewport: true});
}, table);
const first_tr = await page.$("regular-table tbody tr:first-child");
const cell_values = await page.evaluate((first_tr) => Array.from(first_tr.children).map((x) => x.textContent), first_tr);
expect(cell_values).toEqual(["1", "B", "false"]);
});
test("to (0, 4)", async () => {
const table = await page.$("regular-table");
await page.evaluate(async (table) => {
table._invalid_schema = true;
table.scrollToCell(0, 4, 3, 26);
await table.draw({invalid_viewport: true});
}, table);
const first_tr = await page.$("regular-table tbody tr:first-child");
const cell_values = await page.evaluate((first_tr) => Array.from(first_tr.children).map((x) => x.textContent), first_tr);
expect(cell_values).toEqual(["3", "D", "false"]);
});
});
}); | });
|
lolcats_storage.py | # -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2008, Benjamin Kampmann <[email protected]>
"""
This is a Media Backend that allows you to access the cool and cute pictures
from lolcats.com. This is mainly meant as a Sample Media Backend to learn how to
write a Media Backend.
So. You are still reading which allows me to assume that you want to learn how
to write a Media Backend for Coherence. NICE :) .
Once again: This is a SIMPLE Media Backend. It does not contain any big
requests, searches or even transcoding. The only thing we want to do in this
simple example, is to fetch a rss link on startup, parse it, save it and restart
the process one hour later again. Well, on top of this, we also want to provide
these informations as a Media Server in the UPnP/DLNA Network of course ;) .
Wow. You are still reading. You must be really interessted. Then let's go.
"""
########## NOTE:
# Please don't complain about the coding style of this document - I know. It is
# just this way to make it easier to document and to understand.
########## The imports
# The entry point for each kind of Backend is a 'BackendStore'. The BackendStore
# is the instance that does everything Usually. In this Example it can be
# understood as the 'Server', the object retrieving and serving the data.
from coherence.backend import BackendStore
# The data itself is stored in BackendItems. They are also the first things we
# are going to create.
from coherence.backend import BackendItem
# To make the data 'renderable' we need to define the DIDLite-Class of the Media
# we are providing. For that we have a bunch of helpers that we also want to
# import
from coherence.upnp.core import DIDLLite
# Coherence relies on the Twisted backend. I hope you are familar with the
# concept of deferreds. If not please read:
# http://twistedmatrix.com/projects/core/documentation/howto/async.html
#
# It is a basic concept that you need to understand to understand the following
# code. But why am I talking about it? Oh, right, because we use a http-client
# based on the twisted.web.client module to do our requests.
from coherence.upnp.core.utils import getPage
# And we also import the reactor, that allows us to specify an action to happen
# later
from twisted.internet import reactor
# And to parse the RSS-Data (which is XML), we use the coherence helper
from coherence.extern.et import parse_xml
########## The models
# After the download and parsing of the data is done, we want to save it. In
# this case, we want to fetch the images and store their URL and the title of
# the image. That is the LolcatsImage class:
class LolcatsImage(BackendItem):
# We inherit from BackendItem as it already contains a lot of helper methods
# and implementations. For this simple example, we only have to fill the
# item with data.
def __init__(self, parent_id, id, title, url):
BackendItem.__init__(self)
self.parentid = parent_id # used to be able to 'go back'
self.update_id = 0
self.id = id # each item has its own and unique id
self.location = url # the url of the picture
self.name = title # the title of the picture. Inside
# coherence this is called 'name'
# Item.item is a special thing. This is used to explain the client what
# kind of data this is. For e.g. A VideoItem or a MusicTrack. In our | self.item = DIDLLite.ImageItem(id, parent_id, self.name)
# each Item.item has to have one or more Resource objects
# these hold detailed information about the media data
# and can represent variants of it (different sizes, transcoded formats)
res = DIDLLite.Resource(self.location, 'http-get:*:image/jpeg:*')
res.size = None # FIXME: we should have a size here
# and a resolution entry would be nice too
self.item.res.append(res)
class LolcatsContainer(BackendItem):
# The LolcatsContainer will hold the reference to all our LolcatsImages. This
# kind of BackenedItem is a bit different from the normal BackendItem,
# because it has 'children' (the lolcatsimages). Because of that we have
# some more stuff to do in here.
def __init__(self, parent_id, id):
BackendItem.__init__(self)
# the ids as above
self.parent_id = parent_id
self.id = id
# we never have a different name anyway
self.name = 'LOLCats'
# but we need to set it to a certain mimetype to explain it, that we
# contain 'children'.
self.mimetype = 'directory'
# As we are updating our data periodically, we increase this value so
# that our clients can check easier if something has changed since their
# last request.
self.update_id = 0
# that is where we hold the children
self.children = []
# and we need to give a DIDLLite again. This time we want to be
# understood as 'Container'.
self.item = DIDLLite.Container(id, parent_id, self.name)
self.item.childCount = None # will be set as soon as we have images
def get_children(self, start=0, end=0):
# This is the only important implementation thing: we have to return our
# list of children
if end != 0:
return self.children[start:end]
return self.children[start:]
# there is nothing special in here
# FIXME: move it to a base BackendContainer class
def get_child_count(self):
return len(self.children)
def get_item(self):
return self.item
def get_name(self):
return self.name
def get_id(self):
return self.id
########## The server
# As already said before the implementation of the server is done in an
# inheritance of a BackendStore. This is where the real code happens (usually).
# In our case this would be: downloading the page, parsing the content, saving
# it in the models and returning them on request.
class LolcatsStore(BackendStore):
# this *must* be set. Because the (most used) MediaServer Coherence also
# allows other kind of Backends (like remote lights).
implements = ['MediaServer']
# this is only for this implementation: the http link to the lolcats rss
# feed that we want to read and parse:
rss_url = "http://feeds.feedburner.com/ICanHasCheezburger?format=xml"
# as we are going to build a (very small) tree with the items, we need to
# define the first (the root) item:
ROOT_ID = 0
def __init__(self, server, *args, **kwargs):
# first we inizialize our heritage
BackendStore.__init__(self, server, **kwargs)
# When a Backend is initialized, the configuration is given as keyword
# arguments to the initialization. We receive it here as a dicitonary
# and allow some values to be set:
# the name of the MediaServer as it appears in the network
self.name = kwargs.get('name', 'Lolcats')
# timeout between updates in hours:
self.refresh = int(kwargs.get('refresh', 1)) * (60 * 60)
# the UPnP device that's hosting that backend, that's already done
# in the BackendStore.__init__, just left here the sake of completeness
self.server = server
# internally used to have a new id for each item
self.next_id = 1000
# we store the last update from the rss feed so that we know if we have
# to parse again, or not:
self.last_updated = None
# initialize our lolcats container (no parent, this is the root)
self.container = LolcatsContainer(None, self.ROOT_ID)
# but as we also have to return them on 'get_by_id', we have our local
# store of images per id:
self.images = {}
# we tell that if an XBox sends a request for images we'll
# map the WMC id of that request to our local one
self.wmc_mapping = {'16': 0}
# and trigger an update of the data
dfr = self.update_data()
# So, even though the initialize is kind of done, Coherence does not yet
# announce our Media Server.
# Coherence does wait for signal send by us that we are ready now.
# And we don't want that to happen as long as we don't have succeeded
# in fetching some first data, so we delay this signaling after the update is done:
dfr.addCallback(self.init_completed)
dfr.addCallback(self.queue_update)
def get_by_id(self, id):
print "asked for", id, type(id)
# what ever we are asked for, we want to return the container only
if isinstance(id, basestring):
id = id.split('@', 1)
id = id[0]
if int(id) == self.ROOT_ID:
return self.container
return self.images.get(int(id), None)
def upnp_init(self):
# after the signal was triggered, this method is called by coherence and
# from now on self.server is existing and we can do
# the necessary setup here
# that allows us to specify our server options in more detail.
# here we define what kind of media content we do provide
# mostly needed to make some naughty DLNA devices behave
# will probably move into Coherence internals one day
self.server.connection_manager_server.set_variable( \
0, 'SourceProtocolInfo', ['http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_SM;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_MED;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
'http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_LRG;DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000',
'http-get:*:image/jpeg:*'])
# and as it was done after we fetched the data the first time
# we want to take care about the server wide updates as well
self._update_container()
def _update_container(self, result=None):
# we need to inform Coherence about these changes
# again this is something that will probably move
# into Coherence internals one day
if self.server:
self.server.content_directory_server.set_variable(0,
'SystemUpdateID', self.update_id)
value = (self.ROOT_ID, self.container.update_id)
self.server.content_directory_server.set_variable(0,
'ContainerUpdateIDs', value)
return result
def update_loop(self):
# in the loop we want to call update_data
dfr = self.update_data()
# aftert it was done we want to take care about updating
# the container
dfr.addCallback(self._update_container)
# in ANY case queue an update of the data
dfr.addBoth(self.queue_update)
def update_data(self):
# trigger an update of the data
# fetch the rss
dfr = getPage(self.rss_url)
# push it through our xml parser
dfr.addCallback(parse_xml)
# then parse the data into our models
dfr.addCallback(self.parse_data)
return dfr
def parse_data(self, xml_data):
# So. xml_data is a cElementTree Element now. We can read our data from
# it now.
# each xml has a root element
root = xml_data.getroot()
# from there, we look for the newest update and compare it with the one
# we have saved. If they are the same, we don't need to go on:
pub_date = root.find('./channel/lastBuildDate').text
if pub_date == self.last_updated:
return
# not the case, set this as the last update and continue
self.last_updated = pub_date
# and reset the childrens list of the container and the local storage
self.container.children = []
self.images = {}
# Attention, as this is an example, this code is meant to be as simple
# as possible and not as efficient as possible. IMHO the following code
# pretty much sucks, because it is totally blocking (even though we have
# 'only' 20 elements)
# we go through our entries and do something specific to the
# lolcats-rss-feed to fetch the data out of it
url_item = './{http://search.yahoo.com/mrss/}content'
for item in root.findall('./channel/item'):
title = item.find('./title').text
try:
url = item.findall(url_item)[1].get('url', None)
except IndexError:
continue
if url is None:
continue
image = LolcatsImage(self.ROOT_ID, self.next_id, title, url)
self.container.children.append(image)
self.images[self.next_id] = image
# increase the next_id entry every time
self.next_id += 1
# and increase the container update id and the system update id
# so that the clients can refresh with the new data
self.container.update_id += 1
self.update_id += 1
def queue_update(self, error_or_failure):
# We use the reactor to queue another updating of our data
print error_or_failure
reactor.callLater(self.refresh, self.update_loop) | # case, we have an image. |
chmod.go | package wrfs
// Chmod is a file with a Chmod method.
type ChmodFile interface {
File
// Chmod changes the mode of the file to mode.
Chmod(mode FileMode) error
}
// ChmodFS is a file system with a Chmod method.
type ChmodFS interface {
FS
// Chmod changes the mode of the named file to mode.
// If the file is a symbolic link, it changes the mode of the link's target.
Chmod(name string, mode FileMode) error
}
// Chmod changes the mode of the named file to mode.
// If the file is a symbolic link, it changes the mode of the link's target.
func Chmod(fsys FS, name string, mode FileMode) (err error) | {
if fsys, ok := fsys.(ChmodFS); ok {
return fsys.Chmod(name, mode)
}
// Open the file and attempt to call chmod on it.
file, err := fsys.Open(name)
if err != nil {
return err
}
defer safeClose(file, &err)
if file, ok := file.(ChmodFile); ok {
return file.Chmod(mode)
}
return &PathError{Op: "chmod", Path: name, Err: ErrUnsupported}
} |
|
left_recursion.rs | extern crate peg;
peg::parser!(grammar foo() for str {
rule rec() = rec //~ ERROR left recursive rules create an infinite loop: rec -> rec
rule foo()
= "foo" foo
/ bar //~ ERROR left recursive rules create an infinite loop: bar -> foo -> bar
rule bar()
= "bar" bar
/ foo //~ ERROR left recursive rules create an infinite loop: foo -> bar -> foo
});
fn | () {}
| main |
orderedcollections.py | # Copyright (c) 2009 Raymond Hettinger
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
from urllib.parse import urlparse
from collections import Callable, defaultdict
try:
from UserDict import UserDict
from UserDict import DictMixin
except ImportError:
from collections import UserDict
from collections import MutableMapping as DictMixin
class OrderedDict(dict, DictMixin):
def __init__(self, *args, **kwds):
if len(args) > 1:
raise TypeError('expected at most 1 arguments, got %d' % len(args))
try:
self.__end
except AttributeError:
self.clear()
self.update(*args, **kwds)
def clear(self):
self.__end = end = []
end += [None, end, end] # sentinel node for doubly linked list
self.__map = {} # key --> [key, prev, next]
dict.clear(self)
def __setitem__(self, key, value):
if key not in self:
end = self.__end
curr = end[1]
curr[2] = end[1] = self.__map[key] = [key, curr, end]
dict.__setitem__(self, key, value)
def __delitem__(self, key):
dict.__delitem__(self, key)
key, prev, next = self.__map.pop(key)
prev[2] = next
next[1] = prev
def __iter__(self):
end = self.__end
curr = end[2]
while curr is not end:
yield curr[0]
curr = curr[2]
def __reversed__(self):
end = self.__end
curr = end[1]
while curr is not end:
yield curr[0]
curr = curr[1]
def popitem(self, last=True):
if not self:
raise KeyError('dictionary is empty')
if last:
key = reversed(self).next()
else:
key = iter(self).next()
value = self.pop(key)
return key, value
def __reduce__(self):
items = [[k, self[k]] for k in self]
tmp = self.__map, self.__end
del self.__map, self.__end
inst_dict = vars(self).copy()
self.__map, self.__end = tmp
if inst_dict:
return (self.__class__, (items,), inst_dict)
return self.__class__, (items,)
def keys(self):
return list(self)
setdefault = DictMixin.setdefault
update = DictMixin.update
pop = DictMixin.pop
values = DictMixin.values
items = DictMixin.items
#iterkeys = DictMixin.iterkeys
#itervalues = DictMixin.itervalues
#iteritems = DictMixin.iteritems
def __repr__(self):
if not self:
return '%s()' % (self.__class__.__name__,)
return '%s(%r)' % (self.__class__.__name__, self.items())
def copy(self):
return self.__class__(self)
@classmethod
def fromkeys(cls, iterable, value=None):
d = cls()
for key in iterable:
d[key] = value
return d
def __eq__(self, other):
if isinstance(other, OrderedDict):
if len(self) != len(other):
return False
for p, q in zip(self.items(), other.items()):
if p != q:
return False
return True
return dict.__eq__(self, other)
def __ne__(self, other):
return not self == other
"""
<http://stackoverflow.com/questions/6190331/can-i-do-an-ordered-default-dict-in-python>
"""
class DefaultOrderedDict(OrderedDict):
def __init__(self, default_factory=None, *a, **kw):
if (default_factory is not None and
not isinstance(default_factory, Callable)):
raise TypeError('first argument must be callable')
OrderedDict.__init__(self, *a, **kw)
self.default_factory = default_factory
def __getitem__(self, key):
try:
return OrderedDict.__getitem__(self, key)
except KeyError:
return self.__missing__(key)
def __missing__(self, key):
if self.default_factory is None:
raise KeyError(key)
self[key] = value = self.default_factory()
return value
def __reduce__(self):
if self.default_factory is None:
args = tuple()
else:
args = self.default_factory,
return type(self), args, None, None, self.items()
def copy(self):
return self.__copy__()
def __copy__(self):
return type(self)(self.default_factory, self)
def __deepcopy__(self, memo):
import copy
return type(self)(self.default_factory,
copy.deepcopy(self.items()))
def __repr__(self):
return 'OrderedDefaultDict(%s, %s)' % (self.default_factory,
OrderedDict.__repr__(self))
def parse_qs(qs, keep_blank_values=0, strict_parsing=0, keep_attr_order=True):
"""
Kind of like urlparse.parse_qs, except returns an ordered dict.
Also avoids replicating that function's bad habit of overriding the
built-in 'dict' type.
Taken from below with modification:
<https://bitbucket.org/btubbs/thumpy/raw/8cdece404f15/thumpy.py>
"""
od = DefaultOrderedDict(list) if keep_attr_order else defaultdict(list)
for name, value in urlparse.parse_qsl(qs, keep_blank_values, strict_parsing):
od[name].append(value)
return od
"""
Recipe from <http://code.activestate.com/recipes/577197-sortedcollection/>.
"""
from bisect import bisect_left, bisect_right
class SortedCollection(object):
'''Sequence sorted by a key function.
SortedCollection() is much easier to work with than using bisect() directly.
It supports key functions like those use in sorted(), min(), and max().
The result of the key function call is saved so that keys can be searched
efficiently.
Instead of returning an insertion-point which can be hard to interpret, the
five find-methods return a specific item in the sequence. They can scan for
exact matches, the last item less-than-or-equal to a key, or the first item
greater-than-or-equal to a key. | Old items can be deleted with the remove() method.
The usual sequence methods are provided to support indexing, slicing,
length lookup, clearing, copying, forward and reverse iteration, contains
checking, item counts, item removal, and a nice looking repr.
Finding and indexing are O(log n) operations while iteration and insertion
are O(n). The initial sort is O(n log n).
The key function is stored in the 'key' attibute for easy introspection or
so that you can assign a new key function (triggering an automatic re-sort).
In short, the class was designed to handle all of the common use cases for
bisect but with a simpler API and support for key functions.
>>> from pprint import pprint
>>> from operator import itemgetter
>>> s = SortedCollection(key=itemgetter(2))
>>> for record in [
... ('roger', 'young', 30),
... ('angela', 'jones', 28),
... ('bill', 'smith', 22),
... ('david', 'thomas', 32)]:
... s.insert(record)
>>> pprint(list(s)) # show records sorted by age
[('bill', 'smith', 22),
('angela', 'jones', 28),
('roger', 'young', 30),
('david', 'thomas', 32)]
>>> s.find_le(29) # find oldest person aged 29 or younger
('angela', 'jones', 28)
>>> s.find_lt(28) # find oldest person under 28
('bill', 'smith', 22)
>>> s.find_gt(28) # find youngest person over 28
('roger', 'young', 30)
>>> r = s.find_ge(32) # find youngest person aged 32 or older
>>> s.index(r) # get the index of their record
3
>>> s[3] # fetch the record at that index
('david', 'thomas', 32)
>>> s.key = itemgetter(0) # now sort by first name
>>> pprint(list(s))
[('angela', 'jones', 28),
('bill', 'smith', 22),
('david', 'thomas', 32),
('roger', 'young', 30)]
'''
def __init__(self, iterable=(), key=None):
self._given_key = key
key = (lambda x: x) if key is None else key
decorated = sorted((key(item), item) for item in iterable)
self._keys = [k for k, item in decorated]
self._items = [item for k, item in decorated]
self._key = key
def _getkey(self):
return self._key
def _setkey(self, key):
if key is not self._key:
self.__init__(self._items, key=key)
def _delkey(self):
self._setkey(None)
key = property(_getkey, _setkey, _delkey, 'key function')
def clear(self):
self.__init__([], self._key)
def copy(self):
return self.__class__(self, self._key)
def __len__(self):
return len(self._items)
def __getitem__(self, i):
return self._items[i]
def __iter__(self):
return iter(self._items)
def __reversed__(self):
return reversed(self._items)
def __repr__(self):
return '%s(%r, key=%s)' % (
self.__class__.__name__,
self._items,
getattr(self._given_key, '__name__', repr(self._given_key))
)
def __reduce__(self):
return self.__class__, (self._items, self._given_key)
def __contains__(self, item):
k = self._key(item)
i = bisect_left(self._keys, k)
j = bisect_right(self._keys, k)
return item in self._items[i:j]
def index(self, item):
'Find the position of an item. Raise ValueError if not found.'
k = self._key(item)
i = bisect_left(self._keys, k)
j = bisect_right(self._keys, k)
return self._items[i:j].index(item) + i
def count(self, item):
'Return number of occurrences of item'
k = self._key(item)
i = bisect_left(self._keys, k)
j = bisect_right(self._keys, k)
return self._items[i:j].count(item)
def insert(self, item):
'Insert a new item. If equal keys are found, add to the left'
k = self._key(item)
i = bisect_left(self._keys, k)
self._keys.insert(i, k)
self._items.insert(i, item)
def insert_right(self, item):
'Insert a new item. If equal keys are found, add to the right'
k = self._key(item)
i = bisect_right(self._keys, k)
self._keys.insert(i, k)
self._items.insert(i, item)
def remove(self, item):
'Remove first occurence of item. Raise ValueError if not found'
i = self.index(item)
del self._keys[i]
del self._items[i]
def find(self, item):
'Return first item with a key == item. Raise ValueError if not found.'
k = self._key(item)
i = bisect_left(self._keys, k)
if i != len(self) and self._keys[i] == k:
return self._items[i]
raise ValueError('No item found with key equal to: %r' % (k,))
def find_le(self, item):
'Return last item with a key <= item. Raise ValueError if not found.'
k = self._key(item)
i = bisect_right(self._keys, k)
if i:
return self._items[i - 1]
raise ValueError('No item found with key at or below: %r' % (k,))
def find_lt(self, item):
'Return last item with a key < item. Raise ValueError if not found.'
k = self._key(item)
i = bisect_left(self._keys, k)
if i:
return self._items[i - 1]
raise ValueError('No item found with key below: %r' % (k,))
def find_ge(self, item):
'Return first item with a key >= equal to item. Raise ValueError if not found'
k = self._key(item)
i = bisect_left(self._keys, k)
if i != len(self):
return self._items[i]
raise ValueError('No item found with key at or above: %r' % (k,))
def find_gt(self, item):
'Return first item with a key > item. Raise ValueError if not found'
k = self._key(item)
i = bisect_right(self._keys, k)
if i != len(self):
return self._items[i]
raise ValueError('No item found with key above: %r' % (k,)) |
Once found, an item's ordinal position can be located with the index() method.
New items can be added with the insert() and insert_right() methods. |
gloomy-utils.js | function gloomyAjaxUpdater()
{
var url = arguments[0];
var div = arguments[1];
var options = arguments[2] || {};
var spinner = options['spinner'] || null; | $(spinner).show();
$.ajax({
url: url,
cache: false,
type: type,
data: data,
success: function (html) {
$(div).html(html);
$(spinner).hide();
onsuccess();
},
error: function () {
$(spinner).hide();
$.jGrowl('Une erreur est survenue', {theme: 'error'});
}
});
return ( false );
};
// TODO : a fusionner avec la fonction gloomyAjaxUpdater() ??
function gloomyAjaxUpdaterDialog()
{
var url = arguments[0];
var dialog = arguments[1];
var options = arguments[2] || {};
var spinner = options['spinner'] || null;
var onsuccess = options['onsuccess'] || function() {};
$(spinner).show();
$.ajax({
url: url,
cache: false,
success: function (html) {
$(dialog).html(html);
$(spinner).hide();
onsuccess();
$(dialog).dialog('open');
},
error: function () {
$(spinner).hide();
$.jGrowl('Une erreur est survenue', {theme: 'error'});
}
});
return ( false );
}
// jQuery-ui Dialog
function gloomyAjaxDialogAction()
{
var dialog = arguments[0];
var options = arguments[1] || {};
var form = options['form'] || $(dialog).find('form:first');
var spinner = options['spinner'] || null;
var onsuccess = options['onsuccess'] || function() {};
var onformerror = options['onformerror'] || function() {};
$(spinner).show();
$.ajax({type: 'POST',
url: $(form).attr('action'),
data: $(form).serializeArray(),
success: function (data, textStatus, jqXHR) {
$(spinner).hide();
// La réponse est du JSON
if (typeof(data) == 'object' && jqXHR.getResponseHeader( "content-type" ).indexOf('json') != -1) {
try {
if (data['success']) {
$(dialog).dialog( "close" );
onsuccess();
$.jGrowl(data['message'], {theme: 'success'});
}
else {
$.jGrowl(data['message'], {theme: 'error'});
}
}
catch (e) {
$.jGrowl('Une erreur est survenue', {theme: 'error'});
}
}
else {
$.jGrowl('Le formulaire comporte des erreurs', {theme: 'warning'});
$(dialog).html(data);
onformerror();
}
},
error: function () {
$(spinner).hide();
$.jGrowl('Une erreur est survenue', {theme: 'error'});
}
});
return ( false );
}
// Twitter Bootstrap Modal
function gloomyAjaxModalAction()
{
var modal = arguments[0];
var options = arguments[1] || {};
var form = options['form'] || $(modal).find('form:first');
var spinner = options['spinner'] || null;
var onsuccess = options['onsuccess'] || function() {};
var onformerror = options['onformerror'] || function() {};
var body = options['body'] || $(modal).find('.modal-body:first');
$(spinner).show();
$.ajax({type: 'POST',
url: $(form).attr('action'),
data: $(form).serializeArray(),
success: function (data, textStatus, jqXHR) {
$(spinner).hide();
// La réponse est du JSON
if (typeof(data) == 'object' && jqXHR.getResponseHeader( "content-type" ).indexOf('json') != -1) {
try {
if (data['success']) {
$(modal).modal( "hide" );
onsuccess();
$.jGrowl(data['message'], {theme: 'success'});
}
else {
$.jGrowl(data['message'], {theme: 'error'});
}
}
catch (e) {
$.jGrowl('Une erreur est survenue', {theme: 'error'});
}
}
else {
$.jGrowl('Le formulaire comporte des erreurs', {theme: 'warning'});
$(body).html(data);
onformerror();
}
},
error: function () {
$(spinner).hide();
$.jGrowl('Une erreur est survenue', {theme: 'error'});
}
});
return ( false );
}
function gloomyAjaxAction()
{
var url = arguments[0];
var options = arguments[1] || {};
var spinner = options['spinner'] || null;
var onsuccess = options['onsuccess'] || function() {};
var type = options['type'] || 'get';
var data = options['data'] || null;
$(spinner).show();
$.ajax({ url: url,
type: type,
data: data,
success: function (data) { // La réponse est normalement toujours en JSON
$(spinner).hide();
if (data['success']) {
onsuccess();
$.jGrowl(data['message'], {theme: 'success'});
}
else {
$.jGrowl(data['message'], {theme: 'error'});
}
},
error: function () {
$(spinner).hide();
$.jGrowl('Une erreur est survenue', {theme: 'error'});
}
});
return ( false );
}
function gloomyFormURL(form)
{
return $(form).attr('action')+'&'+$(form).serialize();
} | var onsuccess = options['onsuccess'] || function() {};
var type = options['type'] || 'get';
var data = options['data'] || null;
|
window.rs | // Copyright 2016 Joe Wilm, The Alacritty Project Contributors
//
// 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 std::convert::From;
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
use std::ffi::c_void;
use std::fmt::Display;
use crate::gl;
use glutin::dpi::{LogicalPosition, LogicalSize, PhysicalSize};
#[cfg(target_os = "macos")]
use glutin::os::macos::WindowExt;
#[cfg(not(any(target_os = "macos", windows)))]
use glutin::os::unix::{EventsLoopExt, WindowExt};
#[cfg(not(target_os = "macos"))]
use glutin::Icon;
use glutin::{
self, ContextBuilder, ControlFlow, Event, EventsLoop, MouseCursor, PossiblyCurrent,
WindowBuilder,
};
#[cfg(not(target_os = "macos"))]
use image::ImageFormat;
use crate::config::{Config, Decorations, StartupMode, WindowConfig};
// It's required to be in this directory due to the `windows.rc` file
#[cfg(not(target_os = "macos"))]
static WINDOW_ICON: &[u8] = include_bytes!("../../extra/windows/alacritty.ico");
/// Default Alacritty name, used for window title and class.
pub const DEFAULT_NAME: &str = "Alacritty";
/// Window errors
#[derive(Debug)]
pub enum Error {
/// Error creating the window
ContextCreation(glutin::CreationError),
/// Error manipulating the rendering context
Context(glutin::ContextError),
}
/// Result of fallible operations concerning a Window.
type Result<T> = ::std::result::Result<T, Error>;
/// A window which can be used for displaying the terminal
///
/// Wraps the underlying windowing library to provide a stable API in Alacritty
pub struct Window {
event_loop: EventsLoop,
windowed_context: glutin::WindowedContext<PossiblyCurrent>,
mouse_visible: bool,
/// Whether or not the window is the focused window.
pub is_focused: bool,
}
/// Threadsafe APIs for the window
pub struct Proxy {
inner: glutin::EventsLoopProxy,
}
/// Information about where the window is being displayed
///
/// Useful for subsystems like the font rasterized which depend on DPI and scale
/// factor.
pub struct DeviceProperties {
/// Scale factor for pixels <-> points.
///
/// This will be 1. on standard displays and may have a different value on
/// hidpi displays.
pub scale_factor: f64,
}
impl ::std::error::Error for Error {
fn cause(&self) -> Option<&dyn (::std::error::Error)> {
match *self {
Error::ContextCreation(ref err) => Some(err),
Error::Context(ref err) => Some(err),
}
}
fn description(&self) -> &str {
match *self {
Error::ContextCreation(ref _err) => "Error creating gl context",
Error::Context(ref _err) => "Error operating on render context",
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
match *self {
Error::ContextCreation(ref err) => write!(f, "Error creating GL context; {}", err),
Error::Context(ref err) => write!(f, "Error operating on render context; {}", err),
}
}
}
impl From<glutin::CreationError> for Error {
fn from(val: glutin::CreationError) -> Error {
Error::ContextCreation(val)
}
}
impl From<glutin::ContextError> for Error {
fn from(val: glutin::ContextError) -> Error {
Error::Context(val)
}
}
fn create_gl_window(
mut window: WindowBuilder,
event_loop: &EventsLoop,
srgb: bool,
dimensions: Option<LogicalSize>,
) -> Result<glutin::WindowedContext<PossiblyCurrent>> {
if let Some(dimensions) = dimensions {
window = window.with_dimensions(dimensions);
}
let windowed_context = ContextBuilder::new()
.with_srgb(srgb)
.with_vsync(true)
.with_hardware_acceleration(None)
.build_windowed(window, event_loop)?;
// Make the context current so OpenGL operations can run
let windowed_context = unsafe { windowed_context.make_current().map_err(|(_, e)| e)? };
Ok(windowed_context)
}
impl Window {
/// Create a new window
///
/// This creates a window and fully initializes a window.
pub fn new(
event_loop: EventsLoop,
config: &Config,
dimensions: Option<LogicalSize>,
) -> Result<Window> {
let title = config.window.title.as_ref().map_or(DEFAULT_NAME, |t| t);
let class = config.window.class.as_ref().map_or(DEFAULT_NAME, |c| c);
let window_builder = Window::get_platform_window(title, class, &config.window);
let windowed_context =
create_gl_window(window_builder.clone(), &event_loop, false, dimensions)
.or_else(|_| create_gl_window(window_builder, &event_loop, true, dimensions))?;
let window = windowed_context.window();
// Text cursor
window.set_cursor(MouseCursor::Text);
// Set OpenGL symbol loader. This call MUST be after window.make_current on windows.
gl::load_with(|symbol| windowed_context.get_proc_address(symbol) as *const _);
let window =
Window { event_loop, windowed_context, mouse_visible: true, is_focused: false };
window.run_os_extensions();
Ok(window)
}
/// Get some properties about the device
///
/// Some window properties are provided since subsystems like font
/// rasterization depend on DPI and scale factor.
pub fn device_properties(&self) -> DeviceProperties {
DeviceProperties { scale_factor: self.window().get_hidpi_factor() }
}
pub fn inner_size_pixels(&self) -> Option<LogicalSize> {
self.window().get_inner_size()
}
pub fn set_inner_size(&mut self, size: LogicalSize) {
self.window().set_inner_size(size);
}
#[inline]
pub fn hidpi_factor(&self) -> f64 {
self.window().get_hidpi_factor()
}
#[inline]
pub fn create_window_proxy(&self) -> Proxy {
Proxy { inner: self.event_loop.create_proxy() }
}
#[inline]
pub fn swap_buffers(&self) -> Result<()> {
self.windowed_context.swap_buffers().map_err(From::from)
}
/// Poll for any available events
#[inline]
pub fn poll_events<F>(&mut self, func: F)
where
F: FnMut(Event),
{
self.event_loop.poll_events(func);
}
#[inline]
pub fn resize(&self, size: PhysicalSize) {
self.windowed_context.resize(size);
}
/// Show window
#[inline]
pub fn show(&self) {
self.window().show();
}
/// Block waiting for events
#[inline]
pub fn wait_events<F>(&mut self, func: F)
where
F: FnMut(Event) -> ControlFlow,
{
self.event_loop.run_forever(func);
}
/// Set the window title
#[inline]
pub fn | (&self, title: &str) {
self.window().set_title(title);
}
#[inline]
pub fn set_mouse_cursor(&self, cursor: MouseCursor) {
self.window().set_cursor(cursor);
}
/// Set mouse cursor visible
pub fn set_mouse_visible(&mut self, visible: bool) {
if visible != self.mouse_visible {
self.mouse_visible = visible;
self.window().hide_cursor(!visible);
}
}
#[cfg(not(any(target_os = "macos", windows)))]
pub fn get_platform_window(
title: &str,
class: &str,
window_config: &WindowConfig,
) -> WindowBuilder {
use glutin::os::unix::WindowBuilderExt;
let decorations = match window_config.decorations {
Decorations::None => false,
_ => true,
};
let icon = Icon::from_bytes_with_format(WINDOW_ICON, ImageFormat::ICO);
WindowBuilder::new()
.with_title(title)
.with_visibility(false)
.with_transparency(true)
.with_decorations(decorations)
.with_maximized(window_config.startup_mode() == StartupMode::Maximized)
.with_window_icon(icon.ok())
// X11
.with_class(class.into(), DEFAULT_NAME.into())
// Wayland
.with_app_id(class.into())
}
#[cfg(windows)]
pub fn get_platform_window(
title: &str,
_class: &str,
window_config: &WindowConfig,
) -> WindowBuilder {
let decorations = match window_config.decorations {
Decorations::None => false,
_ => true,
};
let icon = Icon::from_bytes_with_format(WINDOW_ICON, ImageFormat::ICO);
WindowBuilder::new()
.with_title(title)
.with_visibility(cfg!(windows))
.with_decorations(decorations)
.with_transparency(true)
.with_maximized(window_config.startup_mode() == StartupMode::Maximized)
.with_window_icon(icon.ok())
}
#[cfg(target_os = "macos")]
pub fn get_platform_window(
title: &str,
_class: &str,
window_config: &WindowConfig,
) -> WindowBuilder {
use glutin::os::macos::WindowBuilderExt;
let window = WindowBuilder::new()
.with_title(title)
.with_visibility(false)
.with_transparency(true)
.with_maximized(window_config.startup_mode() == StartupMode::Maximized);
match window_config.decorations {
Decorations::Full => window,
Decorations::Transparent => window
.with_title_hidden(true)
.with_titlebar_transparent(true)
.with_fullsize_content_view(true),
Decorations::Buttonless => window
.with_title_hidden(true)
.with_titlebar_buttons_hidden(true)
.with_titlebar_transparent(true)
.with_fullsize_content_view(true),
Decorations::None => window.with_titlebar_hidden(true),
}
}
#[cfg(any(
target_os = "linux",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd"
))]
pub fn set_urgent(&self, is_urgent: bool) {
self.window().set_urgent(is_urgent);
}
#[cfg(target_os = "macos")]
pub fn set_urgent(&self, is_urgent: bool) {
self.window().request_user_attention(is_urgent);
}
#[cfg(windows)]
pub fn set_urgent(&self, _is_urgent: bool) {}
pub fn set_ime_spot(&self, pos: LogicalPosition) {
self.window().set_ime_spot(pos);
}
pub fn set_position(&self, pos: LogicalPosition) {
self.window().set_position(pos);
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub fn get_window_id(&self) -> Option<usize> {
match self.window().get_xlib_window() {
Some(xlib_window) => Some(xlib_window as usize),
None => None,
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub fn is_x11(&self) -> bool {
self.event_loop.is_x11()
}
#[cfg(any(target_os = "macos", target_os = "windows"))]
pub fn get_window_id(&self) -> Option<usize> {
None
}
/// Hide the window
pub fn hide(&self) {
self.window().hide();
}
/// Fullscreens the window on the current monitor.
pub fn set_fullscreen(&self, fullscreen: bool) {
let glutin_window = self.window();
if fullscreen {
let current_monitor = glutin_window.get_current_monitor();
glutin_window.set_fullscreen(Some(current_monitor));
} else {
glutin_window.set_fullscreen(None);
}
}
pub fn set_maximized(&self, maximized: bool) {
self.window().set_maximized(maximized);
}
#[cfg(target_os = "macos")]
pub fn set_simple_fullscreen(&self, fullscreen: bool) {
use glutin::os::macos::WindowExt;
self.window().set_simple_fullscreen(fullscreen);
}
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
pub fn get_wayland_display(&self) -> Option<*mut c_void> {
self.window().get_wayland_display()
}
fn window(&self) -> &glutin::Window {
self.windowed_context.window()
}
}
pub trait OsExtensions {
fn run_os_extensions(&self) {}
}
#[cfg(not(any(
target_os = "linux",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd"
)))]
impl OsExtensions for Window {}
#[cfg(any(
target_os = "linux",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "openbsd"
))]
impl OsExtensions for Window {
fn run_os_extensions(&self) {
use libc::getpid;
use std::ffi::CStr;
use std::ptr;
use x11_dl::xlib::{self, PropModeReplace, XA_CARDINAL};
let xlib_display = self.window().get_xlib_display();
let xlib_window = self.window().get_xlib_window();
if let (Some(xlib_window), Some(xlib_display)) = (xlib_window, xlib_display) {
let xlib = xlib::Xlib::open().expect("get xlib");
// Set _NET_WM_PID to process pid
unsafe {
let _net_wm_pid = CStr::from_ptr(b"_NET_WM_PID\0".as_ptr() as *const _);
let atom = (xlib.XInternAtom)(xlib_display as *mut _, _net_wm_pid.as_ptr(), 0);
let pid = getpid();
(xlib.XChangeProperty)(
xlib_display as _,
xlib_window as _,
atom,
XA_CARDINAL,
32,
PropModeReplace,
&pid as *const i32 as *const u8,
1,
);
}
// Although this call doesn't actually pass any data, it does cause
// WM_CLIENT_MACHINE to be set. WM_CLIENT_MACHINE MUST be set if _NET_WM_PID is set
// (which we do above).
unsafe {
(xlib.XSetWMProperties)(
xlib_display as _,
xlib_window as _,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
0,
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
);
}
}
}
}
impl Proxy {
/// Wakes up the event loop of the window
///
/// This is useful for triggering a draw when the renderer would otherwise
/// be waiting on user input.
pub fn wakeup_event_loop(&self) {
self.inner.wakeup().unwrap();
}
}
| set_title |
filehound.go | package filehound
import (
"os"
"path/filepath"
"regexp"
"strings"
)
type filterFn func(path string, info os.FileInfo) bool
// Option is a filehound filter option
type Option func(*Filehound)
// Filehound will search for files apply zero or more file filters.
type Filehound struct {
root string
filters []filterFn
maxDepth int
}
// Query adds a search Option
func (f *Filehound) Query(opts ...Option) {
for _, opt := range opts {
opt(f)
}
}
// New returns an instance of Filehound
func New() *Filehound {
cwd, _ := os.Getwd()
return &Filehound{root: cwd, maxDepth: 100}
}
// Depth sets the max recursion depth for the search
func Depth(depth int) Option {
return func(f *Filehound) {
f.maxDepth = depth
}
}
// Size filters files by size
func Size(size int64) Option {
return func(f *Filehound) {
f.Filter(func(path string, info os.FileInfo) bool {
return info.Size() == size
})
}
}
// IsEmpty filters files that are zero length (empty files)
func IsEmpty() Option {
return Size(0)
}
// Path sets the root of the search path. Defaults to the cwd
func Path(root string) Option |
// Ext filters by one or more file extensions
func Ext(exts ...string) Option {
return func(f *Filehound) {
f.Filter(func(path string, info os.FileInfo) bool {
for _, ext := range exts {
if strings.HasPrefix(ext, ".") {
ext = ext[1:]
}
if filepath.Ext(path)[1:] == ext {
return true
}
}
return false
})
}
}
// Match filters by file using a given regexp
func Match(pattern string) Option {
return func(f *Filehound) {
f.Filter(func(path string, info os.FileInfo) bool {
return regexp.MustCompile(pattern).MatchString(path)
})
}
}
// Glob matches files using a file glob
func Glob(pattern string) Option {
return func(f *Filehound) {
f.Filter(func(path string, info os.FileInfo) bool {
isMatch, _ := filepath.Match(pattern, filepath.Base(path))
return isMatch
})
}
}
// Find executes the search
func (f *Filehound) Find() []string {
var files []string
filepath.Walk(f.root, func(path string, info os.FileInfo, err error) error {
if f.atMaxDepth(path) {
return nil
}
if !info.IsDir() && f.isMatch(path, info) {
files = append(files, path)
}
return nil
})
return files
}
// Filter adds fn as a search filter
func (f *Filehound) Filter(fn filterFn) {
f.filters = append(f.filters, fn)
}
func (f *Filehound) isMatch(path string, info os.FileInfo) bool {
if len(f.filters) == 0 {
return true
}
for _, fn := range f.filters {
if fn(path, info) {
return true
}
}
return false
}
func depth(path string) int {
parts := strings.Split(path, string(filepath.Separator))
return len(parts) - 1
}
func (f *Filehound) atMaxDepth(path string) bool {
depth := depth(filepath.Dir(path)) - depth(f.root)
return depth > f.maxDepth
}
| {
return func(f *Filehound) {
f.root = root
}
} |
Resizeable.d.ts | import { ElementRef, EventEmitter } from '@angular/core';
export declare class | {
resizeEnabled: boolean;
minWidth: number;
maxWidth: number;
onResize: EventEmitter<any>;
private element;
private subscription;
private prevScreenX;
private resizing;
constructor(element: ElementRef);
onMouseup(): void;
onMousedown(event: any): void;
move(event: any): void;
}
| Resizeable |
asset.rs | use anchor_lang::prelude::*;
use super::address::Category;
#[account]
pub struct Asset {
/// Community account, which this address belongs to |
/// Network account, which this address belongs to
pub network: Pubkey,
/// Asset mint account
pub mint: Pubkey,
/// Asset ID
pub asset_id: [u8; 32],
/// Seed bump for PDA
pub bump: u8,
/// ID of the associated case
pub case_id: u64,
/// Reporter account public key
pub reporter: Pubkey,
/// Category of illicit activity identified with this address
pub category: Category,
/// Address risk score 0..10 (0 is safe, 10 is maximum risk)
pub risk: u8,
/// Confirmation count for this address
pub confirmations: u8,
} | pub community: Pubkey, |
img-placeholder.py | import sublime
import sublime_plugin
import re
completions = []
def plugin_loaded():
init_settings()
def init_settings():
get_settings()
sublime.load_settings('img-placeholder.sublime-settings').add_on_change('get_settings', get_settings)
def get_settings():
settings = sublime.load_settings('img-placeholder.sublime-settings')
domains = settings.get('domains', [])
protocol = settings.get('protocol', 'http:')
width = str(settings.get('width', 600))
height = str(settings.get('height', 300))
background_color = settings.get('backgroundColor', 'ccc')
text_color = settings.get('textColor', '333')
file_ext = settings.get('format', 'png')
text = settings.get('text', '')
del completions[:]
for domain in domains:
url = protocol + '//' + domain + '/'
completions.append(
(
domain,
url + '${1:' + width + 'x' + height + '}'
)
)
completions.append(
(
domain + ' (full version)',
url + '${1:' + width + 'x' + height + '/' + background_color + '/' + text_color + '.' + file_ext + '?text=' + text + '}'
)
)
def pos(view, pos):
point = view.sel()[0].begin()
return view.substr(sublime.Region(point - pos, point))
def before(view, location):
lineLocation = view.line(location)
return view.substr(sublime.Region(lineLocation.a, location))
def get_before_text(view):
point = view.sel()[0].begin()
lineLocation = view.line(point)
return view.substr(sublime.Region(lineLocation.a, point))
def is_trigger(text, syntax):
text = text.lower()
syntax = syntax.lower()
if syntax.find(u'html'):
search = re.search(r"(?:(?:^|\s))(?:src|poster|srcset)=[\"\']?$", text)
if (search):
return True
for s in (u'html', u'css', u'less', u'sass', u'scss', u'stylus'):
if syntax.find(s):
search = re.search(r"(?:(?:^|\s))url\([\"\']?$", text)
if (search):
return True
for s in (u'markdown', u'multimarkdown'):
if syntax.find(s):
search = re.search(r"(?:(?:^|\s))\!\[.*?\]\(?$", text)
if (search):
|
return False
class imgHolder(sublime_plugin.EventListener):
def on_query_completions(self, view, prefix, locations):
syntax = view.settings().get('syntax')
before_text = before(view, locations[0]);
if is_trigger(before_text, syntax):
return (completions, sublime.INHIBIT_EXPLICIT_COMPLETIONS)
return
| return True |
process-stats-dir.py | #!/usr/bin/python
#
# ==-- process-stats-dir - summarize one or more Swift -stats-output-dirs --==#
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014-2017 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
#
# ==------------------------------------------------------------------------==#
#
# This file processes the contents of one or more directories generated by
# `swiftc -stats-output-dir` and emits summary data, traces etc. for analysis.
import argparse
import csv
import json
import os
import random
import re
import sys
class JobStats:
def __init__(self, jobkind, jobid, module, start_usec, dur_usec,
jobargs, stats):
self.jobkind = jobkind
self.jobid = jobid
self.module = module
self.start_usec = start_usec
self.dur_usec = dur_usec
self.jobargs = jobargs
self.stats = stats
def is_driver_job(self):
return self.jobkind == 'driver'
def is_frontend_job(self):
return self.jobkind == 'frontend'
def driver_jobs_ran(self):
assert(self.is_driver_job())
return self.stats.get("Driver.NumDriverJobsRun", 0)
def driver_jobs_skipped(self):
assert(self.is_driver_job())
return self.stats.get("Driver.NumDriverJobsSkipped", 0)
def driver_jobs_total(self):
assert(self.is_driver_job())
return self.driver_jobs_ran() + self.driver_jobs_skipped()
def merged_with(self, other):
merged_stats = {}
for k, v in self.stats.items() + other.stats.items():
merged_stats[k] = v + merged_stats.get(k, 0.0)
merged_kind = self.jobkind
if other.jobkind != merged_kind:
merged_kind = "<merged>"
merged_module = self.module
if other.module != merged_module:
merged_module = "<merged>"
merged_start = min(self.start_usec, other.start_usec)
merged_end = max(self.start_usec + self.dur_usec,
other.start_usec + other.dur_usec)
merged_dur = merged_end - merged_start
return JobStats(merged_kind, random.randint(0, 1000000000),
merged_module, merged_start, merged_dur,
self.jobargs + other.jobargs, merged_stats)
def incrementality_percentage(self):
assert(self.is_driver_job())
ran = self.driver_jobs_ran() | return round((float(ran) / float(total)) * 100.0, 2)
# Return a JSON-formattable object of the form preferred by google chrome's
# 'catapult' trace-viewer.
def to_catapult_trace_obj(self):
return {"name": self.module,
"cat": self.jobkind,
"ph": "X", # "X" == "complete event"
"pid": self.jobid,
"tid": 1,
"ts": self.start_usec,
"dur": self.dur_usec,
"args": self.jobargs}
# Return an array of JobStats objects
def load_stats_dir(path):
jobstats = []
fpat = r"^stats-(?P<start>\d+)-swift-(?P<kind>\w+)-(?P<pid>\d+).json$"
for root, dirs, files in os.walk(path):
for f in files:
m = re.match(fpat, f)
if m:
# NB: "pid" in fpat is a random number, not unix pid.
mg = m.groupdict()
jobkind = mg['kind']
jobid = int(mg['pid'])
start_usec = int(mg['start'])
j = json.load(open(os.path.join(root, f)))
dur_usec = 1
jobargs = None
module = "module"
patstr = (r"time\.swift-" + jobkind +
r"\.(?P<module>[^\.]+)(?P<filename>.*)\.wall$")
pat = re.compile(patstr)
stats = dict()
for (k, v) in j.items():
if k.startswith("time."):
v = int(1000000.0 * float(v))
stats[k] = v
tm = re.match(pat, k)
if tm:
tmg = tm.groupdict()
dur_usec = v
module = tmg['module']
if 'filename' in tmg:
ff = tmg['filename']
if ff.startswith('.'):
ff = ff[1:]
jobargs = [ff]
e = JobStats(jobkind=jobkind, jobid=jobid,
module=module, start_usec=start_usec,
dur_usec=dur_usec, jobargs=jobargs,
stats=stats)
jobstats.append(e)
return jobstats
# Passed args with 2-element remainder ["old", "new"], return a list of tuples
# of the form [(name, (oldstats, newstats))] where each name is a common subdir
# of each of "old" and "new", and the stats are those found in the respective
# dirs.
def load_paired_stats_dirs(args):
assert(len(args.remainder) == 2)
paired_stats = []
(old, new) = args.remainder
for p in sorted(os.listdir(old)):
full_old = os.path.join(old, p)
full_new = os.path.join(new, p)
if not (os.path.exists(full_old) and os.path.isdir(full_old) and
os.path.exists(full_new) and os.path.isdir(full_new)):
continue
old_stats = load_stats_dir(full_old)
new_stats = load_stats_dir(full_new)
if len(old_stats) == 0 or len(new_stats) == 0:
continue
paired_stats.append((p, (old_stats, new_stats)))
return paired_stats
def write_catapult_trace(args):
allstats = []
for path in args.remainder:
allstats += load_stats_dir(path)
json.dump([s.to_catapult_trace_obj() for s in allstats], args.output)
def merge_all_jobstats(jobstats):
m = None
for j in jobstats:
if m is None:
m = j
else:
m = m.merged_with(j)
return m
def show_paired_incrementality(args):
fieldnames = ["old_pct", "old_skip",
"new_pct", "new_skip",
"delta_pct", "delta_skip",
"name"]
out = csv.DictWriter(args.output, fieldnames, dialect='excel-tab')
out.writeheader()
for (name, (oldstats, newstats)) in load_paired_stats_dirs(args):
olddriver = merge_all_jobstats([x for x in oldstats
if x.is_driver_job()])
newdriver = merge_all_jobstats([x for x in newstats
if x.is_driver_job()])
if olddriver is None or newdriver is None:
continue
oldpct = olddriver.incrementality_percentage()
newpct = newdriver.incrementality_percentage()
deltapct = newpct - oldpct
oldskip = olddriver.driver_jobs_skipped()
newskip = newdriver.driver_jobs_skipped()
deltaskip = newskip - oldskip
out.writerow(dict(name=name,
old_pct=oldpct, old_skip=oldskip,
new_pct=newpct, new_skip=newskip,
delta_pct=deltapct, delta_skip=deltaskip))
def show_incrementality(args):
fieldnames = ["incrementality", "name"]
out = csv.DictWriter(args.output, fieldnames, dialect='excel-tab')
out.writeheader()
for path in args.remainder:
stats = load_stats_dir(path)
for s in stats:
if s.is_driver_job():
pct = s.incrementality_percentage()
out.writerow(dict(name=os.path.basename(path),
incrementality=pct))
def compare_frontend_stats(args):
assert(len(args.remainder) == 2)
(olddir, newdir) = args.remainder
regressions = 0
fieldnames = ["old", "new", "delta_pct", "name"]
out = csv.DictWriter(args.output, fieldnames, dialect='excel-tab')
out.writeheader()
old_stats = load_stats_dir(olddir)
new_stats = load_stats_dir(newdir)
old_merged = merge_all_jobstats([x for x in old_stats
if x.is_frontend_job()])
new_merged = merge_all_jobstats([x for x in new_stats
if x.is_frontend_job()])
if old_merged is None or new_merged is None:
return regressions
for stat_name in sorted(old_merged.stats.keys()):
if stat_name in new_merged.stats:
old = old_merged.stats[stat_name]
new = new_merged.stats.get(stat_name, 0)
if old == 0 or new == 0:
continue
delta = (new - old)
delta_pct = round((float(delta) / float(new)) * 100.0, 2)
if (stat_name.startswith("time.") and
abs(delta) < args.delta_usec_thresh):
continue
if abs(delta_pct) < args.delta_pct_thresh:
continue
out.writerow(dict(name=stat_name, old=old, new=new,
delta_pct=delta_pct))
if delta > 0:
regressions += 1
return regressions
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--verbose", action="store_true",
help="Report activity verbosely")
parser.add_argument("--output", default="-",
type=argparse.FileType('wb', 0),
help="Write output to file")
parser.add_argument("--paired", action="store_true",
help="Process two dirs-of-stats-dirs, pairwise")
parser.add_argument("--delta-pct-thresh", type=float, default=0.01,
help="Percentage change required to report")
parser.add_argument("--delta-usec-thresh", type=int, default=100000,
help="Absolute delta on times required to report")
modes = parser.add_mutually_exclusive_group(required=True)
modes.add_argument("--catapult", action="store_true",
help="emit a 'catapult'-compatible trace of events")
modes.add_argument("--incrementality", action="store_true",
help="summarize the 'incrementality' of a build")
modes.add_argument("--compare-frontend-stats", action="store_true",
help="Compare frontend stats from two stats-dirs")
parser.add_argument('remainder', nargs=argparse.REMAINDER,
help="stats-dirs to process")
args = parser.parse_args()
if len(args.remainder) == 0:
parser.print_help()
return 1
if args.catapult:
write_catapult_trace(args)
elif args.compare_frontend_stats:
return compare_frontend_stats(args)
elif args.incrementality:
if args.paired:
show_paired_incrementality(args)
else:
show_incrementality(args)
return None
sys.exit(main()) | total = self.driver_jobs_total() |
test.rs | // Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use anyhow::format_err;
use derivative::Derivative;
use fidl_fuchsia_hardware_audio::*;
use fuchsia_async as fasync;
use futures::{Future, StreamExt};
use std::sync::{Arc, Mutex};
use vfs::{directory::entry::DirectoryEntry, mut_pseudo_directory, service};
use crate::driver::{ensure_dai_format_is_supported, ensure_pcm_format_is_supported};
use crate::DigitalAudioInterface;
/// The status of the current device. Retrievable via `TestHandle::status`.
#[derive(Derivative, Clone, Debug)]
#[derivative(Default)]
pub enum TestStatus {
#[derivative(Default)]
Idle,
Configured {
dai_format: DaiFormat,
pcm_format: PcmFormat,
},
Started {
dai_format: DaiFormat,
pcm_format: PcmFormat,
},
}
impl TestStatus {
fn start(&mut self) -> Result<(), ()> {
if let Self::Configured { dai_format, pcm_format } = self {
*self = Self::Started { dai_format: *dai_format, pcm_format: *pcm_format };
Ok(())
} else {
Err(())
}
}
fn stop(&mut self) |
}
#[derive(Clone)]
pub struct TestHandle(Arc<Mutex<TestStatus>>);
impl TestHandle {
pub fn new() -> Self {
Self(Arc::new(Mutex::new(TestStatus::default())))
}
pub fn status(&self) -> TestStatus {
self.0.lock().unwrap().clone()
}
pub fn is_started(&self) -> bool {
let lock = self.0.lock().unwrap();
match *lock {
TestStatus::Started { .. } => true,
_ => false,
}
}
fn set_configured(&self, dai_format: DaiFormat, pcm_format: PcmFormat) {
let mut lock = self.0.lock().unwrap();
*lock = TestStatus::Configured { dai_format, pcm_format };
}
fn start(&self) -> Result<(), ()> {
self.0.lock().unwrap().start()
}
fn stop(&self) {
self.0.lock().unwrap().stop()
}
}
/// Logs and breaks out of the loop if the result is an Error.
macro_rules! log_error {
($result:expr, $tag:expr) => {
if let Err(e) = $result {
log::warn!("Error sending {}: {:?}", $tag, e);
break;
}
};
}
async fn handle_ring_buffer(mut requests: RingBufferRequestStream, handle: TestHandle) {
while let Some(req) = requests.next().await {
if let Err(e) = req {
log::warn!("Error processing RingBuffer request stream: {:?}", e);
break;
}
match req.unwrap() {
RingBufferRequest::Start { responder } => match handle.start() {
Ok(()) => log_error!(responder.send(0), "ring buffer start response"),
Err(()) => {
log::warn!("Started when we couldn't expect it, shutting down");
}
},
RingBufferRequest::Stop { responder } => {
handle.stop();
log_error!(responder.send(), "ring buffer stop response");
}
x => unimplemented!("RingBuffer Request not implemented: {:?}", x),
};
}
}
async fn test_handle_dai_requests(
dai_formats: DaiSupportedFormats,
pcm_formats: SupportedFormats,
as_input: bool,
mut requests: DaiRequestStream,
handle: TestHandle,
) {
use std::slice::from_ref;
let properties = DaiProperties {
is_input: Some(as_input),
manufacturer: Some("Fuchsia".to_string()),
..DaiProperties::EMPTY
};
let mut _rb_task = None;
while let Some(req) = requests.next().await {
if let Err(e) = req {
log::warn!("Error processing DAI request stream: {:?}", e);
break;
}
match req.unwrap() {
DaiRequest::GetProperties { responder } => {
log_error!(responder.send(properties.clone()), "properties response");
}
DaiRequest::GetDaiFormats { responder } => {
log_error!(responder.send(&mut Ok(vec![dai_formats.clone()])), "formats response");
}
DaiRequest::GetRingBufferFormats { responder } => {
log_error!(responder.send(&mut Ok(vec![pcm_formats.clone()])), "pcm response");
}
DaiRequest::CreateRingBuffer {
dai_format, ring_buffer_format, ring_buffer, ..
} => {
let shutdown_bad_args =
|server: fidl::endpoints::ServerEnd<RingBufferMarker>, err: anyhow::Error| {
log::warn!("CreateRingBuffer: {:?}", err);
if let Err(e) =
server.close_with_epitaph(fuchsia_zircon::Status::INVALID_ARGS)
{
log::warn!("Couldn't send ring buffer epitaph: {:?}", e);
}
};
if let Err(e) = ensure_dai_format_is_supported(from_ref(&dai_formats), &dai_format)
{
shutdown_bad_args(ring_buffer, e);
continue;
}
let pcm_format = match ring_buffer_format.pcm_format {
Some(f) => f,
None => {
shutdown_bad_args(ring_buffer, format_err!("Only PCM format supported"));
continue;
}
};
if let Err(e) = ensure_pcm_format_is_supported(from_ref(&pcm_formats), &pcm_format)
{
shutdown_bad_args(ring_buffer, e);
continue;
}
handle.set_configured(dai_format, pcm_format);
let requests = ring_buffer.into_stream().expect("stream from server end");
_rb_task = Some(fasync::Task::spawn(handle_ring_buffer(requests, handle.clone())));
}
x => unimplemented!("DAI request not implemented: {:?}", x),
};
}
}
/// Represents a mock DAI device that processes `Dai` requests from the provided `requests`
/// stream.
/// Returns a Future representing the processing task and a `TestHandle` which can be used
/// to validate behavior.
fn mock_dai_device(
as_input: bool,
requests: DaiRequestStream,
) -> (impl Future<Output = ()>, TestHandle) {
let supported_dai_formats = DaiSupportedFormats {
number_of_channels: vec![1],
sample_formats: vec![DaiSampleFormat::PcmSigned],
frame_formats: vec![DaiFrameFormat::FrameFormatStandard(DaiFrameFormatStandard::Tdm1)],
frame_rates: vec![8000, 16000, 32000, 48000, 96000],
bits_per_slot: vec![16],
bits_per_sample: vec![16],
};
let number_of_channels = 1usize;
let attributes = vec![ChannelAttributes::EMPTY; number_of_channels];
let channel_set = ChannelSet { attributes: Some(attributes), ..ChannelSet::EMPTY };
let supported_pcm_formats = SupportedFormats {
pcm_supported_formats: Some(PcmSupportedFormats {
channel_sets: Some(vec![channel_set]),
sample_formats: Some(vec![SampleFormat::PcmSigned]),
bytes_per_sample: Some(vec![2]),
valid_bits_per_sample: Some(vec![16]),
frame_rates: Some(vec![8000, 16000, 32000, 48000, 96000]),
..PcmSupportedFormats::EMPTY
}),
..SupportedFormats::EMPTY
};
let handle = TestHandle::new();
let handler_fut = test_handle_dai_requests(
supported_dai_formats,
supported_pcm_formats,
as_input,
requests,
handle.clone(),
);
(handler_fut, handle)
}
/// Builds and returns a DigitalAudioInterface for testing scenarios. Returns the
/// `TestHandle` associated with this device which can be used to validate behavior.
pub fn test_digital_audio_interface(as_input: bool) -> (DigitalAudioInterface, TestHandle) {
let (proxy, requests) =
fidl::endpoints::create_proxy_and_stream::<DaiMarker>().expect("proxy creation");
let (handler, handle) = mock_dai_device(as_input, requests);
fasync::Task::spawn(handler).detach();
(DigitalAudioInterface::from_proxy(proxy), handle)
}
async fn handle_dai_connect_requests(as_input: bool, mut stream: DaiConnectorRequestStream) {
while let Some(request) = stream.next().await {
if let Ok(DaiConnectorRequest::Connect { dai_protocol, .. }) = request {
let (handler, _test_handle) =
mock_dai_device(as_input, dai_protocol.into_stream().unwrap());
fasync::Task::spawn(handler).detach();
}
}
}
/// Builds and returns a VFS with a mock input and output DAI device.
pub fn mock_dai_dev_with_io_devices(input: String, output: String) -> Arc<dyn DirectoryEntry> {
mut_pseudo_directory! {
"class" => mut_pseudo_directory! {
"dai" => mut_pseudo_directory! {
&input => service::host(
move |stream: DaiConnectorRequestStream| handle_dai_connect_requests(true,
stream)
),
&output => service::host(
move |stream: DaiConnectorRequestStream| handle_dai_connect_requests(false,
stream)
),
}
}
}
}
| {
if let Self::Started { dai_format, pcm_format } = *self {
*self = Self::Configured { dai_format, pcm_format };
}
} |
Maps.go | package main
import (
"fmt"
)
var Commands map[string]string
func main() {
fmt.Println("Demo for maps")
LinuxCommands();
for k, v := range Commands {
fmt.Println(k, "=>", v)
}
WindowsCommands();
for k, v := range Commands {
fmt.Println(k, "=>", v)
}
delete(Commands , "Dir")
fmt.Println("Delete key and print agian")
for k, v := range Commands {
fmt.Println(k, "=>", v)
}
}
func LinuxCommands() {
Commands = make(map[string]string)
Commands["ls"] = "Show all files and folders in directory"
Commands["cat"] = "read a file"
Commands["touch"] = "create a new file"
}
| "Dir" : "Show all files and folders in dir",
"cd" : "Change Directory",
"md" : "Make Directory",
}
} | func WindowsCommands(){
Commands = map[string]string{ |
users.service.ts | import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class | {
private url: string = "http://jsonplaceholder.typicode.com/users";
constructor(private http: Http) { }
getUsers(){
return this.http.get(this.url)
.map(res => res.json());
}
getUser(id){
return this.http.get(this.getUserUrl(id))
.map(res => res.json());
}
addUser(user){
return this.http.post(this.url, JSON.stringify(user))
.map(res => res.json());
}
updateUser(user){
return this.http.put(this.getUserUrl(user.id), JSON.stringify(user))
.map(res => res.json());
}
deleteUser(id){
return this.http.delete(this.getUserUrl(id))
.map(res => res.json());
}
private getUserUrl(id){
return this.url + "/" + id;
}
}
| UsersService |
cloudtrail.py | """
Copyright 2017-present, Airbnb Inc.
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 json
from stream_alert.shared.logger import get_logger
LOGGER = get_logger(__name__)
def generate_cloudtrail(cluster_name, cluster_dict, config):
"""Add the CloudTrail module to the Terraform cluster dict.
Args:
cluster_name (str): The name of the currently generating cluster
cluster_dict (defaultdict): The dict containing all Terraform config for a given cluster.
config (dict): The loaded config from the 'conf/' directory
Returns:
bool: Result of applying the cloudtrail module
"""
modules = config['clusters'][cluster_name]['modules']
cloudtrail_module = 'cloudtrail_{}'.format(cluster_name)
enabled_legacy = modules['cloudtrail'].get('enabled')
cloudtrail_enabled = modules['cloudtrail'].get('enable_logging', True)
kinesis_enabled = modules['cloudtrail'].get('enable_kinesis', True)
send_to_cloudwatch = modules['cloudtrail'].get('send_to_cloudwatch', False)
exclude_home_region = modules['cloudtrail'].get('exclude_home_region_events', False)
account_ids = list(
set([config['global']['account']['aws_account_id']] + modules['cloudtrail'].get(
'cross_account_ids', [])))
# Allow for backwards compatibility
if enabled_legacy:
del config['clusters'][cluster_name]['modules']['cloudtrail']['enabled']
config['clusters'][cluster_name]['modules']['cloudtrail']['enable_logging'] = True
config['clusters'][cluster_name]['modules']['cloudtrail']['enable_kinesis'] = True
LOGGER.info('Converting legacy CloudTrail config')
config.write()
kinesis_enabled = True
cloudtrail_enabled = True
existing_trail = modules['cloudtrail'].get('existing_trail', False)
is_global_trail = modules['cloudtrail'].get('is_global_trail', True)
region = config['global']['account']['region']
event_pattern_default = {'account': [config['global']['account']['aws_account_id']]}
event_pattern = modules['cloudtrail'].get('event_pattern', event_pattern_default)
# From here: http://amzn.to/2zF7CS0
valid_event_pattern_keys = {
'version', 'id', 'detail-type', 'source', 'account', 'time', 'region', 'resources', 'detail'
}
if not set(event_pattern.keys()).issubset(valid_event_pattern_keys):
LOGGER.error('Config Error: Invalid CloudWatch Event Pattern!')
return False
module_info = {
'source': 'modules/tf_stream_alert_cloudtrail',
'primary_account_id': config['global']['account']['aws_account_id'],
'account_ids': account_ids,
'cluster': cluster_name,
'prefix': config['global']['account']['prefix'],
'enable_logging': cloudtrail_enabled,
'enable_kinesis': kinesis_enabled,
's3_logging_bucket': config['global']['s3_access_logging']['logging_bucket'],
'existing_trail': existing_trail,
'send_to_cloudwatch': send_to_cloudwatch,
'exclude_home_region_events': exclude_home_region,
'region': region,
'is_global_trail': is_global_trail
}
# use the kinesis output from the kinesis streams module
if kinesis_enabled:
|
if send_to_cloudwatch:
destination_arn = modules['cloudtrail'].get(
'cloudwatch_destination_arn',
'${{module.cloudwatch_{}_{}.cloudwatch_destination_arn}}'.format(cluster_name,
region)
)
module_info['cloudwatch_destination_arn'] = destination_arn
cluster_dict['module'][cloudtrail_module] = module_info
return True
| module_info['kinesis_arn'] = '${{module.kinesis_{}.arn}}'.format(cluster_name)
module_info['event_pattern'] = json.dumps(event_pattern) |
doc.go | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance |
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 client-gen. DO NOT EDIT.
// This package has the automatically generated typed clients.
package v1alpha1 | with the License. You may obtain a copy of the License at |
PlaceholderCard.js | import React from "react";
import PropTypes from "prop-types";
import classnames from "classnames";
import { withStyles } from "material-ui/styles";
import Typography from "material-ui/Typography";
import Card from "material-ui/Card";
const styles = () => ({ | justifyContent: "center",
},
tall: {
minHeight: 360,
},
});
class PlaceholderCard extends React.Component {
static propTypes = {
tall: PropTypes.bool,
...Card.propTypes,
};
static defaultProps = {
tall: false,
};
render() {
const { classes, tall, children, ...props } = this.props;
const className = classnames(classes.root, { [classes.tall]: tall });
return (
<Typography
component={Card}
variant="body1"
className={className}
{...props}
>
[ placeholder ]
</Typography>
);
}
}
export default withStyles(styles)(PlaceholderCard); | root: {
display: "flex",
minHeight: 180,
alignItems: "center", |
post.controller.js | /**
* Seanica
*
* User: sean
* Date: 13/04/13
* Time: 10:57 PM
*
*/
define(['sf1','modules/post/post.models','modules/post/post.views','text!modules/post/post.templates.html','uirte'],
function(sf1, Model, View, template, RTE){
var anchorSelector = '#TemplateContainer';
_.templateSettings.variable = 'S';
var baseMarkup = $(template);
// attach the module template markup to the DOM
$(anchorSelector).append(baseMarkup);
var editorMode = 'new';
var userId;
/*
*
* Index View
*
* */
var indexView = function(slug){
var targetLayoutView = new View.IndexLayout();
var indexView = new View.IndexView();
// targetLayoutView.container.show(targetView);
var indexContainerRegion = new Backbone.Marionette.Region({
el: ".view-index"
});
targetLayoutView.on('show',function(layout){
indexContainerRegion.show(indexView);
var editorRegion = new Marionette.Region({
el:'[data-region="editorRegion"]'
});
var composerRegion = new Marionette.Region({
el:'[data-region="composerRegion"]'
});
composerRegion.show(new View.PostEditorLayout());
editorRegion.show(new RTE.RTE());
// check if slug passed in
if (slug){
sf1.EventBus.trigger('post.loadEditPostBySlug',slug);
}
if (sf1.isUserAuth()){
$('.form-controls-container').show();
userId = sf1.currUserId();
sf1.EventBus.trigger('post.loadUserPosts',userId);
}
});
//targetLayoutView.container.show(targetView);
//
return targetLayoutView;
};
/*
*
* Functions
*
*
* */
function createNewPost(postObj){
postObj.status = 'draft';
// save new post
sf1.io.ajax({
type:'POST',
url:'/posts',
data:postObj,
success:function(response){
sf1.log('success saving post: ' + response);
sf1.EventBus.trigger('post.createNewPostSuccess');
},
error:function(response){
sf1.log('error saving post: ' + response);
sf1.EventBus.trigger('post.createNewPostFailed');
}
});
}
function getPostBySlug(slug){
if (slug){
var postObj = {
slug:slug
};
// get post
sf1.io.ajax({
type:'POST',
url:'/postbyslug/' + slug,
data:postObj, | sf1.EventBus.trigger('post.getPostBySlugSuccess',response);
},
error:function(response){
sf1.log('error getting post: ' + response);
sf1.EventBus.trigger('post.getPostBySlugFailed');
}
});
}
}
function publishPostDialog(options){
return new View.PublishPostDialog({
model:new Model.PostModel(options.data)
});
}
/*
*
* EVENT BINDING
*
*
* */
/*
*
* Load Edit Post by Slug
*
* */
sf1.EventBus.bind('post.loadEditPostBySlug',function(slug){
if (slug){
sf1.io.ajax({
type:'GET',
url:'/postbyslug/' + slug,
success:function(response){
sf1.log('success retrieve post: ' + response);
sf1.EventBus.trigger('post.initializeEditForm',response);
},
error:function(response){
sf1.log('error getting post: ' + response);
}
});
}
});
/*
*
* Load User Post List
*
* */
sf1.EventBus.bind('post.loadUserPosts',function(userId){
if (userId){
var postCollection = new Model.PostCollection();
var postsUrl = '/userposts/' + userId;
postCollection.fetch({
url:postsUrl,
success:function(response){
sf1.log('success get posts: ' + response);
var postListRegion = new Marionette.Region({
el:'[data-region="postListRegion"]'
});
// postListRegion.show(new View.PostListView());
postListRegion.show(new View.PostListView({
model:new Backbone.Model({'collectionTitle':'Your Posts'}),
collection:postCollection
}));
},
error:function(response){
sf1.log('error get posts: ' + response);
}
});
}
});
/*
*
* Initialize Edit Post Form
*
* */
sf1.EventBus.bind('post.initializeEditForm',function(post){
editorMode = 'update';
$('#PostId').val(post._id);
$('#PostTitle').val(post.title);
$('#PostSlug').text(post.slug);
CKEDITOR.instances.sf1RTEEditor.setData(post.body);
$('#PostStatus').val(post.status);
});
/*
*
* Load Post to Edit
*
*
* */
sf1.EventBus.bind('post.loadEditPost',function(postId){
if (postId){
sf1.io.ajax({
type:'GET',
url:'/posts/' + postId,
success:function(response){
sf1.log('success retrieve post: ' + response);
sf1.EventBus.trigger('post.initializeEditForm',response);
},
error:function(response){
sf1.log('error getting post: ' + response);
}
});
}
});
/*
*
* Save Button
*
* */
sf1.EventBus.bind('post.savePostButtonClicked',function(event){
sf1.log('save post button click event');
sf1.log('Post Contents: ' + CKEDITOR.instances.sf1RTEEditor.getData());
if (userId){
var postObj = {};
postObj.userId = userId;
postObj.title = $('#PostTitle').val();
postObj.body = CKEDITOR.instances.sf1RTEEditor.getData();
if ('new' === editorMode){
postObj.status = 'draft';
// save new post
sf1.io.ajax({
type:'POST',
url:'/posts',
data:postObj,
success:function(response){
sf1.log('success saving post: ' + response);
},
error:function(response){
sf1.log('error saving post: ' + response);
}
});
}
if ('update' === editorMode){
var postId = $('#PostId').val();
if (postId){
postObj.id = postId;
postObj.status = $('#PostStatus').val();
// update post
sf1.io.ajax({
type:'PUT',
url:'/posts/' + postObj.id,
data:postObj,
success:function(response){
sf1.log('success saving post: ' + response);
},
error:function(response){
sf1.log('error saving post: ' + response);
}
});
}
}
}
else{
sf1.log('warn - no user id');
}
});
/*
*
* Preview Button
*
* */
sf1.EventBus.bind('post.previewPostButtonClicked',function(event){
sf1.log('Preview post button click event');
sf1.log('Post Contents: ' + CKEDITOR.instances.sf1RTEEditor.getData());
var postData = CKEDITOR.instances.sf1RTEEditor.getData();
if (postData){
$('.btn-close-preview').show();
$('.post-preview').html(postData);
}
});
/*
*
* Reset Button
*
* */
sf1.EventBus.bind('post.resetPostButtonClicked',function(event){
sf1.log('Reset post button click event');
sf1.log('Post Contents: ' + CKEDITOR.instances.sf1RTEEditor.getData());
});
/*
*
* Close Preview Button
*
* */
sf1.EventBus.bind('post.closePostPreviewButtonClicked',function(event){
sf1.log('close preview post button click event');
sf1.log('Post Contents: ' + CKEDITOR.instances.sf1RTEEditor.getData());
$('.btn-close-preview').hide();
$('.post-preview').empty();
});
/*
* Change Post Status
*
* */
sf1.EventBus.bind('post.changePostStatusClicked',function(event){
// replace link with select control
// set the value of the control
var postId = $(event.target).data('id');
var postStatus = $(event.target).data('status');
if (postId){
sf1.log('in post.changePostStatusClicked: ' + postId);
var postItemStatusRegion = new Marionette.Region({
el:'td.col-post-status[data-id="' + postId + '"]'
});
// hide the link
// show the select
postItemStatusRegion.show(new View.PostStatusSelectView({
model:new Backbone.Model({'_id':postId,'status':postStatus})
}));
// set the value of the select
// set the event listener on select change
}
else{
sf1.log('attempt to edit status chang but no post id');
}
});
/*
*
* Change Post Status Select Element Change Event
*
* */
sf1.EventBus.bind('post.postStatusSelectChanged',function(data){
var postId = data.id;
var postStatus = data.status;
var postData = {};
postData.id = postId;
postData.status = postStatus;
postData.title = $('a[data-id="' + postId + '"]').prop('title');
if (postId){
switch(postStatus){
/*
*
*
* Publish
*
*
* */
case 'published':
sf1.EventBus.trigger('post.publishPostDialogRequest',postData);
break;
case 'draft':
sf1.log('TO BE IMPLEMENTED change to draft THIS POST: ' + postId);
break;
case 'deleted':
if (confirm('delete this post?')){
sf1.log('DELETE THIS POST: ' + postId);
}
break;
default:
sf1.log('warn - attempt to change post status with no status');
}
}
else{
sf1.log('warn - attempt to change status with no post id');
}
});
/*
*
* Edit Post
*
* */
sf1.EventBus.bind('post.editPostRequest',function(event){
var postId = $(event.target).data('id');
if (postId){
sf1.EventBus.trigger('post.loadEditPost',postId);
}
});
/*
*
* Publish Post Request
*
* */
sf1.EventBus.bind('post.publishPostDialogRequest',function(post){
// set the author
var author = sf1.currUserName();
if (sf1.hasStorage){
if (localStorage.getItem('sf1UserPrefs')){
var userPrefsObj = JSON.parse(localStorage.getItem('sf1UserPrefs'));
if (userPrefsObj){
if (userPrefsObj.publishSettings){
if (userPrefsObj.publishSettings.authorName){
author = userPrefsObj.publishSettings.authorName;
}
}
}
}
}
post.author = author;
sf1.EventBus.trigger('ia.loadRegionContentRequest',{
region:'modalRegion',
module:'post',
view:'PublishPostDialog',
data:{data:post},
callback:function(){
sf1.EventBus.bind('post.publishPostSuccess',function(){
$.modal.close();
userId = sf1.currUserId();
sf1.EventBus.trigger('post.loadUserPosts',userId);
});
}
});
});
sf1.EventBus.bind('post.publishPostBtnClicked',function(event){
// get the post data
var postId = $(event.target).data('id');
var postAuthor = $('#InputPublishPostAuthor').val();
if (sf1.hasStorage){
if (!localStorage.getItem('sf1UserPrefs')){
localStorage.setItem('sf1UserPrefs','');
}
var userPrefs = localStorage.getItem('sf1UserPrefs');
if (!userPrefs){
userPrefs = '{}';
}
var userPrefsObj = JSON.parse(userPrefs);
if (userPrefsObj){
if (!userPrefsObj.publishSettings){
userPrefsObj.publishSettings = {};
}
userPrefsObj.publishSettings.authorName = postAuthor;
localStorage.setItem('sf1UserPrefs',JSON.stringify(userPrefsObj));
}
}
var postData = {};
postData.id = postId;
postData.author = postAuthor;
sf1.EventBus.trigger('post.publishPostRequest',postData);
});
/*
*
* AJAX
*
* Publish Post
*
*
* */
sf1.EventBus.bind('post.publishPostRequest',function(postObj){
sf1.io.ajax({
type:'PUT',
url:'/publishpost/' + postObj.id,
data:postObj,
error:function(response){
sf1.log('error publishing: ' + response);
},
success:function(response){
sf1.log('SUCCESS PUBLISH');
//close modal window
sf1.EventBus.trigger('post.publishPostSuccess');
}
});
});
return{
IndexView:indexView,
PostEditor:function(){
return new View.PostEditorLayout();
},
createNewPost:createNewPost,
getPostBySlug:getPostBySlug,
PostListView:View.PostListView,
PostCollection:Model.PostCollection,
RecentPostListView:View.RecentPostListView,
PublishPostDialog:publishPostDialog
};
}
); | success:function(response){
sf1.log('success getting post: ' + response); |
genesis_gas_schedule.rs | // Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
//! This file contains the starting gas schedule published at genesis.
use move_core_types::gas_schedule::GasCost;
use once_cell::sync::Lazy;
use vm::{
file_format::{
Bytecode, ConstantPoolIndex, FieldHandleIndex, FieldInstantiationIndex,
FunctionHandleIndex, FunctionInstantiationIndex, StructDefInstantiationIndex,
StructDefinitionIndex, NUMBER_OF_NATIVE_FUNCTIONS,
},
file_format_common::instruction_key,
};
pub(crate) static INITIAL_GAS_SCHEDULE: Lazy<(Vec<u8>, Vec<u8>)> = Lazy::new(|| {
use Bytecode::*;
let mut instrs = vec![
(
MoveToSender(StructDefinitionIndex::new(0)),
GasCost::new(774, 1),
),
(
MoveToSenderGeneric(StructDefInstantiationIndex::new(0)),
GasCost::new(774, 1),
),
(
MoveTo(StructDefinitionIndex::new(0)),
/* MoveToSender + ReadRef == 774 + 51 == 825 */
GasCost::new(825, 1),
),
(
MoveToGeneric(StructDefInstantiationIndex::new(0)),
/* MoveToSender + ReadRef == 774 + 51 == 825 */
GasCost::new(825, 1),
),
(GetTxnSenderAddress, GasCost::new(30, 1)),
(
MoveFrom(StructDefinitionIndex::new(0)),
GasCost::new(917, 1),
),
(
MoveFromGeneric(StructDefInstantiationIndex::new(0)),
GasCost::new(917, 1),
),
(BrTrue(0), GasCost::new(31, 1)),
(WriteRef, GasCost::new(65, 1)),
(Mul, GasCost::new(41, 1)),
(MoveLoc(0), GasCost::new(41, 1)),
(And, GasCost::new(49, 1)),
(Pop, GasCost::new(27, 1)),
(BitAnd, GasCost::new(44, 1)),
(ReadRef, GasCost::new(51, 1)),
(Sub, GasCost::new(44, 1)),
(
MutBorrowField(FieldHandleIndex::new(0)),
GasCost::new(58, 1),
),
(
MutBorrowFieldGeneric(FieldInstantiationIndex::new(0)),
GasCost::new(58, 1),
),
(
ImmBorrowField(FieldHandleIndex::new(0)),
GasCost::new(58, 1),
),
(
ImmBorrowFieldGeneric(FieldInstantiationIndex::new(0)),
GasCost::new(58, 1),
),
(Add, GasCost::new(45, 1)), | (Lt, GasCost::new(49, 1)),
(LdU8(0), GasCost::new(29, 1)),
(LdU64(0), GasCost::new(29, 1)),
(LdU128(0), GasCost::new(29, 1)),
(CastU8, GasCost::new(29, 1)),
(CastU64, GasCost::new(29, 1)),
(CastU128, GasCost::new(29, 1)),
(Abort, GasCost::new(39, 1)),
(MutBorrowLoc(0), GasCost::new(45, 1)),
(ImmBorrowLoc(0), GasCost::new(45, 1)),
(LdConst(ConstantPoolIndex::new(0)), GasCost::new(36, 1)),
(Ge, GasCost::new(46, 1)),
(Xor, GasCost::new(46, 1)),
(Shl, GasCost::new(46, 1)),
(Shr, GasCost::new(46, 1)),
(Neq, GasCost::new(51, 1)),
(Not, GasCost::new(35, 1)),
(Call(FunctionHandleIndex::new(0)), GasCost::new(197, 1)),
(
CallGeneric(FunctionInstantiationIndex::new(0)),
GasCost::new(197, 1),
),
(Le, GasCost::new(47, 1)),
(Branch(0), GasCost::new(10, 1)),
(Unpack(StructDefinitionIndex::new(0)), GasCost::new(94, 1)),
(
UnpackGeneric(StructDefInstantiationIndex::new(0)),
GasCost::new(94, 1),
),
(Or, GasCost::new(43, 1)),
(LdFalse, GasCost::new(30, 1)),
(LdTrue, GasCost::new(29, 1)),
(Mod, GasCost::new(42, 1)),
(BrFalse(0), GasCost::new(29, 1)),
(Exists(StructDefinitionIndex::new(0)), GasCost::new(856, 1)),
(
ExistsGeneric(StructDefInstantiationIndex::new(0)),
GasCost::new(856, 1),
),
(BitOr, GasCost::new(45, 1)),
(FreezeRef, GasCost::new(10, 1)),
(
MutBorrowGlobal(StructDefinitionIndex::new(0)),
GasCost::new(929, 1),
),
(
MutBorrowGlobalGeneric(StructDefInstantiationIndex::new(0)),
GasCost::new(929, 1),
),
(
ImmBorrowGlobal(StructDefinitionIndex::new(0)),
GasCost::new(929, 1),
),
(
ImmBorrowGlobalGeneric(StructDefInstantiationIndex::new(0)),
GasCost::new(929, 1),
),
(Div, GasCost::new(41, 1)),
(Eq, GasCost::new(48, 1)),
(Gt, GasCost::new(46, 1)),
(Pack(StructDefinitionIndex::new(0)), GasCost::new(73, 1)),
(
PackGeneric(StructDefInstantiationIndex::new(0)),
GasCost::new(73, 1),
),
(Nop, GasCost::new(10, 1)),
];
// Note that the LibraVM is expecting the table sorted by instruction order.
instrs.sort_by_key(|cost| instruction_key(&cost.0));
let raw_instruction_table = instrs.into_iter().map(|(_, cost)| cost).collect::<Vec<_>>();
// TODO Zero for now, this is going to be filled in later
let native_table = (0..NUMBER_OF_NATIVE_FUNCTIONS)
.map(|_| GasCost::new(0, 0))
.collect::<Vec<GasCost>>();
(
lcs::to_bytes(&raw_instruction_table)
.expect("Unable to serialize genesis gas schedule for instructions"),
lcs::to_bytes(&native_table)
.expect("Unable to serialize genesis gas schedule for instructions"),
)
}); | (CopyLoc(0), GasCost::new(41, 1)),
(StLoc(0), GasCost::new(28, 1)),
(Ret, GasCost::new(28, 1)), |
init_pointer.go | package main
import "fmt"
func main() { | var a = 26.9
var p = &a
fmt.Println("Value stored in variable a = ", a)
fmt.Println("Address of variable a = ", &a)
fmt.Println("Value stored in variable p = ", p)
} | |
CarsForSaleResultList.js | import React from 'react';
import CarForSaleCard from './CarForSaleCard';
import { connect } from 'react-redux';
import { Card } from 'semantic-ui-react';
class CarsForSaleResultList extends React.Component {
state = {
open: false
};
mapNewCars = (props) => {
let i = this.props.render_option
let arr = this.props.new_cars
let newArr = (arr.slice(0, i))
// console.log(newArr)
return newArr.map((car) => {
return <CarForSaleCard key={car.id} car={car} />;
});
}
mapUsedCars = (props) => {
return this.props.used_cars.map((car) => {
return <CarForSaleCard key={car.id} car={car} />;
});
};
render() {
return (
<div>
<Card.Group textAlign='center' itemsPerRow={5} style={{ display: 'flex', margin: '1.125em auto' }}>
{this.props.activeIndex === 0 && this.props.new_cars ? this.mapNewCars() : null}
</Card.Group>
<Card.Group textAlign='center' itemsPerRow={5} style={{ display: 'flex', margin: '1.125em auto' }}>
{this.props.activeIndex === 1 && this.props.used_cars ? this.mapUsedCars() : null}
</Card.Group>
</div>
);
}
}
const mapStateToProps = (state) => {
return { | render_option: state.new_cars.render_option,
activeIndex: state.user.activeTab
};
}
const mapDispatchToProps = (dispatch) => ({
functionName: (param) => dispatch({ type: 'ACTION_NAME', param })
})
export default connect(mapStateToProps, mapDispatchToProps)(CarsForSaleResultList); | used_cars: state.used_cars.listings,
new_cars: state.new_cars.listings, |
interface.go | package filter
import (
"log"
"net"
"github.com/millken/tcpwder/config"
"github.com/millken/tcpwder/core"
"github.com/millken/tcpwder/firewall"
)
type FilterInterface interface {
Init(cf config.Server) bool
Connect(client net.Conn) error
Read(client net.Conn, rwc core.ReadWriteCount)
Write(client net.Conn, rwc core.ReadWriteCount)
Request([]byte) error
Disconnect(client net.Conn) | Stop()
}
var filters = make(map[string]func() interface{})
type Filter struct {
cfg config.Server
filters map[string]FilterInterface
stop chan bool
}
func RegisterFilter(name string, filter func() interface{}) {
if filter == nil {
return
}
if _, ok := filters[name]; ok {
log.Fatalln("Register called twice for filter " + name)
}
filters[name] = filter
}
func New(cfg config.Server) *Filter {
return &Filter{
cfg: cfg,
filters: make(map[string]FilterInterface),
}
}
func (this *Filter) Start() {
log.Printf("[INFO] Starting filter")
this.stop = make(chan bool)
for name, filter := range filters {
ff := filter().(FilterInterface)
if ff.Init(this.cfg) {
this.filters[name] = ff
}
}
go func() {
for {
select {
case <-this.stop:
log.Printf("Stopping filter")
return
}
}
}()
}
func (this *Filter) Stop() {
for _, filter := range this.filters {
filter.Stop()
}
this.stop <- true
}
func (this *Filter) HandleClientConnect(client net.Conn) error {
for _, filter := range this.filters {
if err := filter.Connect(client); err != nil {
host, _, _ := net.SplitHostPort(client.RemoteAddr().String())
firewall.SetDeny(host, 3600)
return err
}
}
return nil
}
func (this *Filter) HandleClientDisconnect(client net.Conn) {
for _, filter := range this.filters {
filter.Disconnect(client)
}
}
func (this *Filter) HandleClientWrite(client net.Conn, rwc core.ReadWriteCount) {
for _, filter := range this.filters {
filter.Write(client, rwc)
}
}
func (this *Filter) HandleClientRead(client net.Conn, rwc core.ReadWriteCount) {
for _, filter := range this.filters {
filter.Read(client, rwc)
}
}
func (this *Filter) HandleClientRequest(buf []byte) error {
for _, filter := range this.filters {
if err := filter.Request(buf); err != nil {
return err
}
}
return nil
} | |
jwt.go | package jwt
import (
"net/http"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"github.com/ujjwalmishra/fodie/pkg/e"
"github.com/ujjwalmishra/fodie/pkg/util"
)
// JWT is jwt middleware
func JWT() gin.HandlerFunc | {
return func(c *gin.Context) {
var code int
var data interface{}
code = e.SUCCESS
token := c.Query("token")
if token == "" {
code = e.INVALID_PARAMS
} else {
_, err := util.ParseToken(token)
if err != nil {
switch err.(*jwt.ValidationError).Errors {
case jwt.ValidationErrorExpired:
code = e.ERROR_AUTH_CHECK_TOKEN_TIMEOUT
default:
code = e.ERROR_AUTH_CHECK_TOKEN_FAIL
}
}
}
if code != e.SUCCESS {
c.JSON(http.StatusUnauthorized, gin.H{
"code": code,
"msg": e.GetMsg(code),
"data": data,
})
c.Abort()
return
}
c.Next()
}
} |
|
models.py | from django.db import models
from django.utils import timezone
from django.db.models import Q
import asyncio
from ib_insync import IB, Stock, MarketOrder, util
from core.common import empty_append
from core.indicators import rel_dif
import vectorbtpro as vbt
import sys
import math
import pandas as pd
import numpy as np
from trading_bot.settings import (PERFORM_ORDER, USE_IB_FOR_DATA,DIC_PERFORM_ORDER,
IB_LOCALHOST, IB_PORT)
### Interactive brockers and data retrieval ###
'''
Contains:
- Communication with Interactive brokers
- Retrieval of live data (Interactive brokers or YFinance)
- Performing order
- Models for financial products, stock exchanges...
Note: for some reasons, it does not work if myIB class is not in models
'''
## All symbols must be from same stock exchange
def retrieve_data(symbols,period,**kwargs):
try:
IBok=True
for symbol in symbols:
if kwargs.get("index",False):
action=Index.objects.get(symbol=symbol)
else:
action=Action.objects.get(symbol=symbol)
if action.stock_ex.ib_ticker in ["BVME.ETF"]:
IBok=False
break
index_symbol=exchange_to_symbol(action)
if (USE_IB_FOR_DATA and IBok) or kwargs.get("useIB",False):
fig= ''.join(x for x in period if x.isdigit())
if period.find("d")!=-1:
period_ib=fig +" D"
elif period.find("mo")!=-1:
period_ib=fig +" M"
elif period.find("y")!=-1:
period_ib=fig +" Y"
#Time period of one bar. Must be one of: ‘1 secs’, ‘5 secs’, ‘10 secs’ 15 secs’, ‘30 secs’, ‘1 min’, ‘2 mins’, ‘3 mins’, ‘5 mins’, ‘10 mins’, ‘15 mins’, ‘20 mins’, ‘30 mins’, ‘1 hour’, ‘2 hours’, ‘3 hours’, ‘4 hours’, ‘8 hours’, ‘1 day’, ‘1 week’, ‘1 month’.
if kwargs.get("interval",False):
fig= ''.join(x for x in kwargs.get("interval") if x.isdigit())
if period.find("m")!=-1:
interval=fig +" mins"
elif period.find("h")!=-1:
interval=fig +" hours"
elif period.find("d")!=-1:
interval=fig +" day"
else:
interval='1 day'
open_=[]
close=[]
low=[]
high=[]
myIB=MyIB()
for symbol in symbols:
action=Action.objects.get(symbol=symbol)
contract = Stock(action.ib_ticker(),action.stock_ex.ib_ticker, action.currency.symbol)
bars = myIB.ib.reqHistoricalData(
contract,
endDateTime='',
durationStr=period_ib, #"10 D","1 M"
barSizeSetting=interval, #"1 day", "1 min"
whatToShow='TRADES',
useRTH=True,
formatDate=1)
df=util.df(bars)
open_=empty_append(open_,df["open"].values,axis=1)
close=empty_append(close,df["close"].values,axis=1)
high=empty_append(high,df["high"].values,axis=1)
low=empty_append(low,df["low"].values,axis=1)
volume=empty_append(low,df["volume"].values,axis=1)
cours_open=pd.DataFrame(data=open_,index=df["date"],columns=symbols)
cours_close=pd.DataFrame(data=close,index=df["date"],columns=symbols)
cours_low=pd.DataFrame(data=low,index=df["date"],columns=symbols)
cours_high=pd.DataFrame(data=high,index=df["date"],columns=symbols)
cours_volume=pd.DataFrame(data=volume,index=df["date"],columns=symbols)
action=Action.objects.get(symbol=index_symbol)
contract = Stock(action.ib_ticker(),action.stock_ex.ib_ticker, action.currency.symbol)
bars = myIB.ib.reqHistoricalData(
contract,
endDateTime='',
durationStr=period_ib, #"10 D","1 M"
barSizeSetting=interval, #"1 day", "1 min"
whatToShow='TRADES',
useRTH=True,
formatDate=1)
df=util.df(bars)
cours_open_ind=df["open"]
cours_close_ind=df["close"]
cours_high_ind=df["high"]
cours_low_ind=df["low"]
cours_volume_ind=df["volume"]
#Volume
if len(cours_close_ind)!=len(cours_close):
print("cours index is different from cours length")
myIB.disconnect()
else:
all_symbols=symbols+[index_symbol]
cours=vbt.YFData.fetch(all_symbols, period=period,missing_index='drop',**kwargs)
cours_action=cours.select(symbols)
cours_open =cours_action.get('Open')
cours_high=cours_action.get('High')
cours_low=cours_action.get('Low')
cours_close=cours_action.get('Close')
cours_volume=cours_action.get('Volume')
print("number of days retrieved: " + str(np.shape(cours_close)[0]))
cours_index=cours.select(index_symbol)
cours_open_ind =cours_index.get('Open')
cours_high_ind=cours_index.get('High')
cours_low_ind=cours_index.get('Low')
cours_close_ind=cours_index.get('Close')
cours_volume_ind=cours_index.get('Volume')
debug=False
if debug:
for symbol in all_symbols:
data=vbt.YFData.fetch(symbol, period=period,**kwargs)
#knowing what we drop
close_debug=data.get("Close")
for ii in range(len(close_debug)):
if math.isnan(close_debug.values[ii]):
print(symbol)
print("dropping at least " + str(close_debug.index[ii]))
return cours_high, cours_low, cours_close, cours_open, cours_volume, \
cours_high_ind, cours_low_ind, cours_close_ind, cours_open_ind,\
cours_volume_ind
except Exception as msg:
print(msg)
print("exception in " + __name__)
_, e_, exc_tb = sys.exc_info()
print("line " + str(exc_tb.tb_lineno))
print(msg)
def exchange_to_symbol(action):
if action.stock_ex.ib_ticker=="SBF":
return "^FCHI"
elif action.stock_ex.ib_ticker=="IBIS":
return "^GDAXI"
elif action.stock_ex.ib_ticker=="NASDAQ":
return "^IXIC"
elif action.stock_ex.ib_ticker=="BVME.ETF":
return "^IXIC" #it is only ETF anyhow
def get_exchange_actions(exchange):
cat=ActionCategory.objects.get(short="ACT")
stockEx=StockEx.objects.get(name=exchange)
c1 = Q(category=cat)
c2 = Q(stock_ex=stockEx)
actions=Action.objects.filter(c1 & c2)
return [ob.symbol for ob in actions]
def retrieve_ib_pf():
myIB=MyIB()
pf=[]
pf_short=[]
for pos in myIB.ib.positions():
contract=pos.contract
action=Action.objects.get(ib_ticker=contract.localSymbol)
if pos.position>0:
pf.append(action.symbol)
else:
pf_short.append(action.symbol)
myIB.disconnect()
return pf, pf_short
#for SL check
def get_last_price(symbol,**kwargs):
try:
if kwargs.get("index",False):
action=Index.objects.get(symbol=symbol)
else:
action=Action.objects.get(symbol=symbol)
if USE_IB_FOR_DATA and action.stock_ex.ib_ticker not in ["BVME.ETF"]:
myIB=MyIB()
contract = Stock(action.ib_ticker(),action.stock_ex.ib_ticker, action.currency.symbol)
cours_pres=myIB.get_last_price(contract)
myIB.disconnect()
else: #YF
cours=vbt.YFData.fetch([symbol], period="2d")
cours_close=cours.get("Close")
cours_pres=cours_close[symbol].iloc[-1]
return cours_pres
except Exception as msg:
print(symbol)
print("exception in " + __name__)
print(msg)
def get_ratio(symbol,**kwargs):
try:
if kwargs.get("index",False):
action=Index.objects.get(symbol=symbol)
else:
action=Action.objects.get(symbol=symbol)
if USE_IB_FOR_DATA and action.stock_ex.ib_ticker not in ["BVME.ETF"]:
myIB=MyIB()
contract = Stock(action.ib_ticker(),action.stock_ex.ib_ticker, action.currency.symbol)
cours_pres=myIB.get_last_price(contract)
cours_ref, cours_open=myIB.get_past_closing_price(contract)
if kwargs.get("opening",False):
cours_pres=cours_open
myIB.disconnect()
else: #YF
cours=vbt.YFData.fetch([symbol], period="2d")
cours_close=cours.get("Close")
cours_ref=cours_close[symbol].iloc[0]
if kwargs.get("opening",False):
cours_open=cours.get("Open")
cours_pres=cours_open[symbol].iloc[-1]
else:
cours_pres=cours_close[symbol].iloc[-1]
return rel_dif(cours_pres,
cours_ref
)*100
except Exception as msg:
print(symbol)
print("exception in " + __name__)
print(msg)
class MyIB():
def __init__(self):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
self.ib = IB()
self.ib.connect(host=IB_LOCALHOST, port=IB_PORT, clientId=1)
def cash_balance(self):
try:
for v in self.ib.accountSummary():
if v.tag == 'CashBalance':
return float(v.value)
except:
return 0
def test(self,symbol):
action=Action.objects.get(symbol=symbol)
contract = Stock(action.ib_ticker(),action.stock_ex.ib_ticker, action.currency.symbol)
print(self.ib.qualifyContracts(contract))
def retrieve(self,contract,period):
bars = self.ib.reqHistoricalData(
contract,
endDateTime='',
durationStr=period, #"10 D","1 M"
barSizeSetting='1 hour', #"1 day", "1 min"
whatToShow='TRADES',
useRTH=True,
formatDate=1)
return util.df(bars)
def get_last_price(self,contract):
m_data = self.ib.reqMktData(contract)
while m_data.last != m_data.last: #Wait until data is in.
self.ib.sleep(0.01)
self.ib.cancelMktData(contract)
return m_data.last
def get_past_closing_price(self,contract):
period="2 D"
bars = self.ib.reqHistoricalData(
contract,
endDateTime='',
durationStr=period, #"10 D","1 M"
barSizeSetting='1 day', #"1 day", "1 min"
whatToShow='TRADES',
useRTH=True,
formatDate=1)
df=util.df(bars)
return df.iloc[0]["close"], df.iloc[-1]["open"]
def place(self,buy,ticker,currency,exchange,**kwargs): #quantity in euros
if ticker=="AAA":
print("ticker not found")
return "", 0
else:
contract = Stock(ticker, exchange, currency)
self.ib.qualifyContracts(contract)
if buy:
order_size=kwargs.get("order_size",0)
last_price=self.get_last_price(contract)
quantity=math.floor(order_size/last_price)
order = MarketOrder('BUY', quantity)
else:
quantity=kwargs.get("quantity",0)
order = MarketOrder('SELL', quantity)
trade = self.ib.placeOrder(contract, order)
self.ib.sleep(1.0)
if trade.orderStatus.status == 'Filled':
fill = trade.fills[-1]
txt=f'{fill.time} - {fill.execution.side} {fill.contract.symbol} {fill.execution.shares} @ {fill.execution.avgPrice}'
price=fill.execution.avgPrice
return txt, price, quantity
def exit_order(self,symbol,strategy, exchange,short,**kwargs):
#type check necessary for indexes
try:
pf= get_pf(strategy, exchange,short)
ocap=get_order_capital(strategy, exchange,short)
if kwargs.get("index",False):
index=Index.objects.get(symbol=symbol) #actually should be more complex
if short:
action=index.etf_short
else:
action=index.etf_long
else:
action=Action.objects.get(symbol=symbol)
if symbol in pf.retrieve():
c1 = Q(action=action)
c2 = Q(active=True)
order=Order.objects.filter(c1 & c2)
#profit
if len(order)>0:
txt, order[0].exiting_price, quantity= self.place(False,
action.ib_ticker(),
action.currency.symbol,
action.stock_ex.ib_ticker,
quantity=order[0].quantity)
order[0].exiting_date=timezone.now()
if order[0].entering_price is not None:
order[0].profit=order[0].exiting_price-order[0].entering_price
order[0].profit_percent=(order[0].exiting_price/order[0].entering_price-1)*100
order[0].active=False
order[0].save()
ocap.capital+=1
ocap.save()
pf.remove(symbol)
pf.save()
return True
else:
print("order not found " + symbol)
return False
return False
except Exception as msg:
print("exception in exit")
print(msg)
_, e_, exc_tb = sys.exc_info()
print("line " + str(exc_tb.tb_lineno))
pass
def entry_order(self,symbol,strategy, exchange,short,**kwargs):
try:
#type check necessary for indexes
pf= get_pf(strategy, exchange,short)
order_size=5000
ocap=get_order_capital(strategy, exchange,short)
#accountSummary
if kwargs.get("index",False):
index=Index.objects.get(symbol=symbol)
if short:
action=index.etf_short
else:
action=index.etf_long
else:
action=Action.objects.get(symbol=symbol)
excluded=Excluded.objects.get(name="all") #list of actions completely excluded from entries
if (symbol not in pf.retrieve() and
symbol not in excluded.retrieve() and
ocap.capital>0 and
order_size<=self.cash_balance()):
order=Order(action=action, pf=pf)
txt, order.entering_price, order.quantity= self.place(True,
action.ib_ticker(),
action.currency.symbol,
action.stock_ex.ib_ticker,
order_size=order_size)
if kwargs.get("sl",False):
sl=kwargs.get("sl")
order.sl_threshold=order.entering_price*(1-sl)
order.save()
pf.append(symbol)
pf.save()
ocap.capital-=1
ocap.save()
return True
return False
except Exception as msg:
print("exception in " + __name__)
print(msg)
_, e_, exc_tb = sys.exc_info()
print("line " + str(exc_tb.tb_lineno))
pass
def disconnect(self):
self.ib.disconnect()
def check_hold_duration(symbol,strategy, exchange,short,**kwargs):
#type check necessary for indexes
try:
pf= get_pf(strategy, exchange,short)
#accountSummary
if kwargs.get("index",False):
index=Index.objects.get(symbol=symbol)
if short:
action=index.etf_short
else:
action=index.etf_long
else:
action=Action.objects.get(symbol=symbol)
if symbol in pf.retrieve():
c1 = Q(action=action)
c2 = Q(active=True)
order=Order.objects.filter(c1 & c2)
if len(order)>0:
delta=timezone.now()-order[0].entering_date
return delta.days
return 0
except Exception as msg:
print("exception in " + __name__)
print(msg)
return 0
def entry_order(symbol,strategy, exchange,short,**kwargs):
if PERFORM_ORDER and DIC_PERFORM_ORDER[strategy]:
myIB=MyIB()
return myIB.entry_order(symbol,strategy, exchange,short,**kwargs), True
else:
return entry_order_test(symbol,strategy, exchange,short,**kwargs), False
def exit_order(symbol,strategy, exchange,short,**kwargs):
if PERFORM_ORDER and DIC_PERFORM_ORDER[strategy]:
myIB=MyIB()
return myIB.exit_order(symbol,strategy, exchange,short,**kwargs), True
else:
return exit_order_test(symbol,strategy, exchange,short,**kwargs), False
def entry_order_test(symbol,strategy, exchange,short,**kwargs):
try:
#type check necessary for indexes
pf= get_pf(strategy, exchange,short)
ocap=get_order_capital(strategy, exchange,short)
if kwargs.get("index",False):
index=Index.objects.get(symbol=symbol)
if short:
action=index.etf_short
else:
action=index.etf_long
else:
action=Action.objects.get(symbol=symbol)
symbol2=action.symbol
excluded=Excluded.objects.get(name="all") #list of actions completely excluded from entries
if (symbol2 not in pf.retrieve() and
symbol2 not in excluded.retrieve() and
ocap.capital>0):
order=Order(action=action, pf=pf)
order.entering_price=1.0
order.save()
#post telegram
pf.append(symbol2)
pf.save()
ocap.capital-=1 #also for short
ocap.save()
return True
return False
except Exception as msg:
print("exception in " + __name__)
print(msg)
_, e_, exc_tb = sys.exc_info()
print("line " + str(exc_tb.tb_lineno))
pass
def exit_order_test(symbol,strategy, exchange,short,**kwargs):
try:
pf= get_pf(strategy, exchange,short)
ocap=get_order_capital(strategy, exchange,short)
if kwargs.get("index",False):
index=Index.objects.get(symbol=symbol) #actually should be more complex
if short:
action=index.etf_short
else:
action=index.etf_long
else:
action=Action.objects.get(symbol=symbol)
symbol2=action.symbol
if symbol2 in pf.retrieve():
c1 = Q(action=action)
c2 = Q(active=True)
order=Order.objects.filter(c1 & c2)
#post telegram
#price
#profit
if len(order)>0:
order[0].exiting_date=timezone.now()
order[0].active=False
order[0].save()
ocap.capital+=1 #also for short
ocap.save()
pf.remove(symbol2)
pf.save()
return True
return False
except Exception as msg:
print("exception in " + __name__)
print(msg)
_, e_, exc_tb = sys.exc_info()
print("line " + str(exc_tb.tb_lineno))
pass
class Currency(models.Model):
name=models.CharField(max_length=100, blank=False)
symbol=models.CharField(max_length=100, blank=False,default="A")
def __str__(self):
return self.name
class Fees(models.Model):
name=models.CharField(max_length=100, blank=False, default="fee")
fixed=models.DecimalField(max_digits=100, decimal_places=5)
percent=models.DecimalField(max_digits=100, decimal_places=5)
def __str__(self):
return self.name
class StockEx(models.Model):
name=models.CharField(max_length=100, blank=False)
fees=models.ForeignKey('Fees',on_delete=models.CASCADE)
ib_ticker=models.CharField(max_length=15, blank=True,default="AAA")
opening_time=models.TimeField(default="09:00:00")
closing_time=models.TimeField(default="17:00:00")
def __str__(self):
return self.name
class Strategy(models.Model):
name=models.CharField(max_length=100, blank=False)
def __str__(self):
return self.name
### Index is like action, but it had to be separated, as an index cannot be bought directly
class Index(models.Model):
symbol=models.CharField(max_length=15, blank=False, primary_key=True)
ib_ticker=models.CharField(max_length=15, blank=True,default="AAA")
name=models.CharField(max_length=100, blank=False)
stock_ex=models.ForeignKey('StockEx',on_delete=models.CASCADE)
currency=models.ForeignKey('Currency',on_delete=models.CASCADE)
etf_long=models.ForeignKey('Action',on_delete=models.PROTECT,default=0,related_name='etf_long')
etf_short=models.ForeignKey('Action',on_delete=models.PROTECT, default=0,related_name='etf_short')
class Meta:
ordering = ["name"]
def ib_ticker(self):
return self.ib_ticker
def __str__(self):
return self.name
class Action(models.Model):
symbol=models.CharField(max_length=15, blank=False, primary_key=True)
ib_ticker=models.CharField(max_length=15, blank=True,default="AAA")
name=models.CharField(max_length=100, blank=False)
stock_ex=models.ForeignKey('StockEx',on_delete=models.CASCADE)
currency=models.ForeignKey('Currency',on_delete=models.CASCADE)
category=models.ForeignKey('ActionCategory',on_delete=models.CASCADE,blank=True)
strategy=models.ForeignKey('Strategy',on_delete=models.CASCADE,blank=True,default=0)
class Meta:
ordering = ["name"]
def ib_ticker(self):
t=self.symbol.split(".")
return t[0]
def __str__(self):
return self.name
class Order(models.Model):
action=models.ForeignKey('Action',on_delete=models.CASCADE)
pf=models.ForeignKey('PF',on_delete=models.SET_NULL,blank=True,null=True)
active=models.BooleanField(blank=False,default=True)
entering_date=models.DateTimeField(null=False, blank=False, auto_now_add=True)#default=timezone.now())
exiting_date=models.DateTimeField(null=True, blank=True)
entering_price=models.DecimalField(max_digits=100, decimal_places=5,blank=True,null=True)
exiting_price=models.DecimalField(max_digits=100, decimal_places=5,blank=True,null=True)
sl_threshold=models.DecimalField(max_digits=100, decimal_places=5,blank=True,null=True)
profit=models.DecimalField(max_digits=100, decimal_places=5,blank=True,null=True)
profit_percent=models.DecimalField(max_digits=100, decimal_places=5,blank=True,null=True)
quantity=models.DecimalField(max_digits=100, decimal_places=5,blank=True,null=True)
def __str__(self):
return self.action.name + " "+ str(self.entering_date)
def pf_retrieve_all(**kwargs):
arr=[]
for pf in PF.objects.filter(short=kwargs.get("short",False)):
cat=ActionCategory.objects.get(short="ACT")
c1 = Q(category=cat)
if kwargs.get("opening")=="9h":
stockEx1=StockEx.objects.filter(name="Paris")
stockEx2=StockEx.objects.filter(name="XETRA")
c2 = Q(stock_ex=stockEx1[0])
c3 = Q(stock_ex=stockEx2[0])
actions=pf.actions.filter(c1 & (c2|c3))
elif kwargs.get("opening")=="15h":
stockEx1=StockEx.objects.filter(name="Nasdaq")
c2 = Q(stock_ex=stockEx1[0])
actions=pf.actions.filter(c1 & c2)
else:
actions=pf.actions.filter(c1)
for action in actions:
if not action.symbol in arr:
arr.append(action.symbol)
return arr
### Portfolio for a given strategy (used as name presently)
class PF(models.Model):
# can be replaced with ib.positions() or ib.portfolio()
name=models.CharField(max_length=100, blank=False)
actions=models.ManyToManyField(Action,blank=True)
short=models.BooleanField(blank=False,default=False)
strategy=models.ForeignKey('Strategy',on_delete=models.CASCADE,blank=True)
stock_ex=models.ForeignKey('StockEx',on_delete=models.CASCADE,blank=True,default=2)
def __str__(self):
return self.name
def retrieve(self):
arr=[]
for action in self.actions.all():
arr.append(action.symbol)
return arr
def remove(self,symbol):
a = Action.objects.get(symbol=symbol)
try:
self.actions.remove(a)
self.save()
except Exception as msg:
print("exception in remove_symbol")
print(symbol)
print(msg)
_, e_, exc_tb = sys.exc_info()
print("line " + str(exc_tb.tb_lineno))
pass
def append(self,symbol):
try:
a = Action.objects.get(symbol=symbol)
self.actions.add(a)
self.save()
except Exception as msg:
print("exception in " + __name__)
print(symbol)
print(msg)
_, e_, exc_tb = sys.exc_info()
print("line " + str(exc_tb.tb_lineno))
pass
def get_pf(strategy, exchange,short):
s=Strategy.objects.get(name=strategy)
e=StockEx.objects.get(name=exchange)
c1 = Q(stock_ex=e)
c2 = Q(strategy=s)
c3 = Q(short=short)
return PF.objects.get(c1 & c2 & c3)
### To distinguish between ETF, actions, indexes...
class ActionCategory(models.Model):
short=models.CharField(max_length=15, blank=False, default="AAA", primary_key=True)
name=models.CharField(max_length=100, blank=False)
def __str__(self):
return self.name
###To define the capital assigned to one strategy.
###Not used presently
class Capital(models.Model):
#self.ib.accountSummary()
capital=models.DecimalField(max_digits=100, decimal_places=5,blank=True,null=True)
name=models.CharField(max_length=100, blank=False,default="")
strategy=models.ForeignKey('Strategy',on_delete=models.CASCADE,blank=True)
stock_ex=models.ForeignKey('StockEx',on_delete=models.CASCADE,blank=True,default=2)
def __str__(self):
return self.name
def get_capital(strategy, exchange,short):
s=Strategy.objects.get(name=strategy)
e=StockEx.objects.get(name=exchange)
c1 = Q(stock_ex=e)
c2 = Q(strategy=s)
c3 = Q(short=short)
return Capital.objects.get(c1 & c2 & c3)
###To define the number of orders assigned to one strategy
###1 means that only one action can be owned at a time using this strategy
class OrderCapital(models.Model):
capital=models.DecimalField(max_digits=100, decimal_places=5,blank=True,null=True)
name=models.CharField(max_length=100, blank=False,default="")
strategy=models.ForeignKey('Strategy',on_delete=models.CASCADE,blank=True)
stock_ex=models.ForeignKey('StockEx',on_delete=models.CASCADE,blank=True,default=2)
def __str__(self):
return self.name
def get_order_capital(strategy, exchange,short):
s=Strategy.objects.get(name=strategy)
e=StockEx.objects.get(name=exchange)
c1 = Q(stock_ex=e)
c2 = Q(strategy=s)
return OrderCapital.objects.get(c1 & c2)
###For strategy using two time frame, in the slow one (10 days) candidates are defined
###And on daily basis the other strategy decides which of the candidate is really bought or sold
class Candidates(models.Model):
name=models.CharField(max_length=100, blank=False)
actions=models.ManyToManyField(Action,blank=True)
strategy=models.ForeignKey('Strategy',on_delete=models.CASCADE,blank=True,default=1)
stock_ex=models.ForeignKey('StockEx',on_delete=models.CASCADE,blank=True,default=2)
def reset(self):
for a in self.actions.all():
self.actions.remove(a)
self.save()
def append(self,symbol): #so we can name as for list
a = Action.objects.get(symbol=symbol)
self.actions.add(a)
self.sav | s.all():
arr.append(action.symbol)
return arr
def __str__(self):
return self.name
def get_candidates(strategy, exchange):
s=Strategy.objects.get(name=strategy)
e=StockEx.objects.get(name=exchange)
c1 = Q(stock_ex=e)
c2 = Q(strategy=s)
return Candidates.objects.get(c1 & c2)
### List of actions provisory excluded for a strategy as it risks to perform bad
class Excluded(models.Model):
name=models.CharField(max_length=100, blank=False)
actions=models.ManyToManyField(Action,blank=True)
strategy=models.ForeignKey('Strategy',on_delete=models.CASCADE,blank=True)
def reset(self):
for a in self.actions.all():
self.actions.remove(a)
self.save()
def append(self,symbol):
a = Action.objects.get(symbol=symbol)
self.actions.add(a)
self.save()
def remove(self,symbol):
a = Action.objects.get(symbol=symbol)
try:
self.actions.remove(a)
self.save()
except Exception as msg:
print("exception in " + __name__)
print(symbol)
print(msg)
_, e_, exc_tb = sys.exc_info()
print("line " + str(exc_tb.tb_lineno))
pass
def retrieve(self):
arr=[]
for action in self.actions.all():
arr.append(action.symbol)
return arr
def __str__(self):
return self.name
### Define a list of actions and indexes that can be traded using the defined strategy
class StratCandidates(models.Model):
name=models.CharField(max_length=100, blank=False)
actions=models.ManyToManyField(Action,blank=True)
indexes=models.ManyToManyField(Index,blank=True)
strategy=models.ForeignKey('Strategy',on_delete=models.CASCADE,blank=True,default=0)
def retrieve(self):
arr=[]
for action in self.actions.all():
arr.append(action.symbol)
return arr
def __str__(self):
return self.name | e()
def retrieve(self):
arr=[]
for action in self.action |
0002_auto_20210715_1151.py | # Generated by Django 2.2.24 on 2021-07-15 11:51
from django.db import migrations, models
class Migration(migrations.Migration):
| dependencies = [
('users', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='last_updated',
field=models.DateTimeField(auto_now=True, null=True),
),
migrations.AddField(
model_name='user',
name='timestamp_created',
field=models.DateTimeField(auto_now_add=True, null=True),
),
migrations.AlterField(
model_name='user',
name='email',
field=models.EmailField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='user',
name='first_name',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='user',
name='last_name',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='user',
name='name',
field=models.CharField(blank=True, max_length=255, null=True),
),
] |
|
message_id.py |
class MessageId:
"""The CAN MessageId of an PDU.
The MessageId consists of three parts:
* Priority
* Parameter Group Number
* Source Address
"""
def __init__(self, **kwargs): #priority=0, parameter_group_number=0, source_address=0):
"""
:param priority:
3-bit Priority
:param parameter_group_number:
18-bit Parameter Group Number
:param source_address:
8-bit Source Address
There is a total of 253 addresses available and every address must
be unique within the network.
:param can_id:
A 29-bit CAN-Id the MessageId should be parsed from.
"""
if 'can_id' in kwargs:
# let the property can_id parse the given value
self.can_id = kwargs.get('can_id')
else:
self.priority = kwargs.get('priority', 0) & 7
self.parameter_group_number = kwargs.get('parameter_group_number', 0) & 0x3FFFF
self.source_address = kwargs.get('source_address', 0) & 0xFF
@property
def can_id(self):
|
@can_id.setter
def can_id(self, can_id):
"""Fill the MessageId with the information given in the 29 bit CAN-Id"""
self.source_address = can_id & 0xFF
self.parameter_group_number = (can_id >> 8) & 0x3FFFF
self.priority = (can_id >> 26) & 0x7
| """Transforms the MessageId object to a 29 bit CAN-Id"""
return (self.priority << 26) | (self.parameter_group_number << 8) | (self.source_address) |
utils.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import argparse
import copy
import inspect
import logging.config
import os
import sys
import warnings
from dataclasses import dataclass
from os.path import dirname, join, normpath, realpath
from traceback import print_exc, print_exception
from types import FrameType
from typing import Any, Callable, List, Optional, Sequence, Tuple, Type, Union
from omegaconf import DictConfig, OmegaConf, read_write
from omegaconf.errors import OmegaConfBaseException
from hydra._internal.config_search_path_impl import ConfigSearchPathImpl
from hydra.core.config_search_path import ConfigSearchPath, SearchPathQuery
from hydra.core.utils import get_valid_filename, split_config_path
from hydra.errors import (
CompactHydraException,
InstantiationException,
SearchPathException,
)
from hydra.types import ObjectConf, TaskFunction
log = logging.getLogger(__name__)
def _get_module_name_override() -> Optional[str]:
module_envs = ["HYDRA_MAIN_MODULE", "FB_PAR_MAIN_MODULE", "FB_XAR_MAIN_MODULE"]
for module_env in module_envs:
if module_env in os.environ:
return os.environ[module_env]
return None
def detect_calling_file_or_module_from_task_function(
task_function: Any,
) -> Tuple[Optional[str], Optional[str], str]:
mdl = task_function.__module__
override = _get_module_name_override()
if override is not None:
mdl = override
calling_file: Optional[str]
calling_module: Optional[str]
if mdl not in (None, "__main__"):
calling_file = None
calling_module = mdl
else:
calling_file = task_function.__code__.co_filename
calling_module = None
task_name = detect_task_name(calling_file, mdl)
return calling_file, calling_module, task_name
def detect_calling_file_or_module_from_stack_frame(
stack_depth: int,
) -> Tuple[Optional[str], Optional[str]]:
stack = inspect.stack()
frame = stack[stack_depth]
if is_notebook() and "_dh" in frame[0].f_globals:
pynb_dir = frame[0].f_globals["_dh"][0]
calling_file = join(pynb_dir, "notebook.ipynb")
return calling_file, None
calling_file = frame.filename
calling_module = None
try:
calling_module = _get_module_name_override()
if calling_module is None:
calling_module = frame[0].f_globals[frame[3]].__module__
except KeyError:
try:
calling_module = frame[0].f_locals["self"].__module__
except KeyError:
pass
return calling_file, calling_module
def is_notebook() -> bool:
try:
shell = get_ipython().__class__.__name__ # type: ignore
if shell == "ZMQInteractiveShell":
return True # Jupyter notebook or qtconsole
elif shell == "TerminalInteractiveShell":
return False # Terminal running IPython
else:
return False # Other type (?)
except NameError:
return False
def detect_task_name(calling_file: Optional[str], calling_module: Optional[str]) -> str:
if calling_file is not None:
target_file = os.path.basename(calling_file)
task_name = get_valid_filename(os.path.splitext(target_file)[0])
elif calling_module is not None:
last_dot = calling_module.rfind(".")
if last_dot != -1:
task_name = calling_module[last_dot + 1 :]
else:
task_name = calling_module
else:
raise ValueError()
return task_name
def compute_search_path_dir(
calling_file: Optional[str],
calling_module: Optional[str],
config_path: Optional[str],
) -> str:
if calling_file is not None:
abs_base_dir = realpath(dirname(calling_file))
if config_path is not None:
search_path_dir = join(abs_base_dir, config_path)
else:
search_path_dir = abs_base_dir
search_path_dir = normpath(search_path_dir)
elif calling_module is not None:
last_dot = calling_module.rfind(".")
if last_dot != -1:
calling_module = calling_module[0:last_dot]
else:
calling_module = ""
if config_path is not None:
config_path = config_path.replace(os.path.sep, "/")
while str.startswith(config_path, "../"):
config_path = config_path[len("../") :]
last_dot = calling_module.rfind(".")
if last_dot != -1:
calling_module = calling_module[0:last_dot]
else:
calling_module = ""
search_path_dir = "pkg://" + calling_module
if config_path is not None:
if calling_module != "":
search_path_dir = search_path_dir + "/" + config_path
else:
search_path_dir = search_path_dir + config_path
else:
raise ValueError()
return search_path_dir
def create_automatic_config_search_path(
calling_file: Optional[str],
calling_module: Optional[str],
config_path: Optional[str],
) -> ConfigSearchPath:
search_path_dir = compute_search_path_dir(calling_file, calling_module, config_path)
return create_config_search_path(search_path_dir)
def create_config_search_path(search_path_dir: Optional[str]) -> ConfigSearchPath:
from hydra.core.plugins import Plugins
from hydra.plugins.search_path_plugin import SearchPathPlugin
search_path = ConfigSearchPathImpl()
search_path.append("hydra", "pkg://hydra.conf")
if search_path_dir is not None:
search_path.append("main", search_path_dir)
search_path_plugins = Plugins.instance().discover(SearchPathPlugin)
for spp in search_path_plugins:
plugin = spp()
assert isinstance(plugin, SearchPathPlugin)
plugin.manipulate_search_path(search_path)
search_path.append("schema", "structured://")
return search_path
def _is_env_set(name: str) -> bool:
return name in os.environ and os.environ[name] == "1"
def run_and_report(func: Any) -> Any:
try:
return func()
except Exception as ex:
if _is_env_set("HYDRA_FULL_ERROR"):
raise ex
else:
if isinstance(ex, CompactHydraException):
sys.stderr.write(str(ex) + os.linesep)
if isinstance(ex.__cause__, OmegaConfBaseException):
sys.stderr.write(str(ex.__cause__) + os.linesep)
else:
# Custom printing that strips the Hydra related stack frames from the top
# And any omegaconf frames from the bottom.
# It is possible to add additional libraries to sanitize from the bottom later,
# maybe even make it configurable.
tb: Any = ex.__traceback__
search_max = 10
# strip Hydra frames from start of stack
# will strip until it hits run_job()
while search_max > 0:
if tb is None:
break
frame = tb.tb_frame
tb = tb.tb_next
search_max = search_max - 1
if inspect.getframeinfo(frame).function == "run_job":
break
if search_max == 0 or tb is None:
# could not detect run_job, probably a runtime exception before we got there.
# do not sanitize the stack trace.
print_exc()
sys.exit(1)
# strip OmegaConf frames from bottom of stack
end = tb
num_frames = 0
while end is not None:
frame = end.tb_frame
mdl = inspect.getmodule(frame)
assert mdl is not None
name = mdl.__name__
if name.startswith("omegaconf."):
break
end = end.tb_next
num_frames = num_frames + 1
@dataclass
class FakeTracebackType:
tb_next: Any = None # Optional[FakeTracebackType]
tb_frame: Optional[FrameType] = None
tb_lasti: Optional[int] = None
tb_lineno: Optional[int] = None
iter_tb = tb
final_tb = FakeTracebackType()
cur = final_tb
added = 0
while True:
cur.tb_lasti = iter_tb.tb_lasti
cur.tb_lineno = iter_tb.tb_lineno
cur.tb_frame = iter_tb.tb_frame
if added == num_frames - 1:
break
added = added + 1
cur.tb_next = FakeTracebackType()
cur = cur.tb_next
iter_tb = iter_tb.tb_next
print_exception(etype=None, value=ex, tb=final_tb) # type: ignore
sys.stderr.write(
"\nSet the environment variable HYDRA_FULL_ERROR=1 for a complete stack trace.\n"
)
sys.exit(1)
def _run_hydra(
args_parser: argparse.ArgumentParser,
task_function: TaskFunction,
config_path: Optional[str],
config_name: Optional[str],
strict: Optional[bool],
) -> None:
from hydra.core.global_hydra import GlobalHydra
from .hydra import Hydra
args = args_parser.parse_args()
if args.config_name is not None:
config_name = args.config_name
if args.config_path is not None:
config_path = args.config_path
(
calling_file,
calling_module,
task_name,
) = detect_calling_file_or_module_from_task_function(task_function)
config_dir, config_name = split_config_path(config_path, config_name)
search_path = create_automatic_config_search_path(
calling_file, calling_module, config_dir
)
def add_conf_dir() -> None:
if args.config_dir is not None:
abs_config_dir = os.path.abspath(args.config_dir)
if not os.path.isdir(abs_config_dir):
raise SearchPathException(
f"Additional config directory '{abs_config_dir}' not found"
)
search_path.prepend(
provider="command-line",
path=f"file://{abs_config_dir}",
anchor=SearchPathQuery(provider="schema"),
)
run_and_report(add_conf_dir)
hydra = run_and_report(
lambda: Hydra.create_main_hydra2(
task_name=task_name, config_search_path=search_path, strict=strict
)
)
try:
if args.help:
hydra.app_help(config_name=config_name, args_parser=args_parser, args=args)
sys.exit(0)
if args.hydra_help:
hydra.hydra_help(
config_name=config_name, args_parser=args_parser, args=args
)
sys.exit(0)
has_show_cfg = args.cfg is not None
num_commands = (
args.run + has_show_cfg + args.multirun + args.shell_completion + args.info
)
if num_commands > 1:
raise ValueError(
"Only one of --run, --multirun, -cfg, --info and --shell_completion can be specified"
)
if num_commands == 0:
args.run = True
if args.run:
run_and_report(
lambda: hydra.run(
config_name=config_name,
task_function=task_function,
overrides=args.overrides,
)
)
elif args.multirun:
run_and_report(
lambda: hydra.multirun(
config_name=config_name,
task_function=task_function,
overrides=args.overrides,
)
)
elif args.cfg:
run_and_report(
lambda: hydra.show_cfg(
config_name=config_name,
overrides=args.overrides,
cfg_type=args.cfg,
package=args.package,
)
)
elif args.shell_completion:
run_and_report(
lambda: hydra.shell_completion(
config_name=config_name, overrides=args.overrides
)
)
elif args.info:
hydra.show_info(config_name=config_name, overrides=args.overrides)
else:
sys.stderr.write("Command not specified\n")
sys.exit(1)
finally:
GlobalHydra.instance().clear()
def _get_exec_command() -> str:
if sys.argv[0].endswith(".py"):
return f"python {sys.argv[0]}"
else:
# Running as an installed app (setuptools entry point)
executable = os.path.basename(sys.argv[0])
return executable
def _get_completion_help() -> str:
|
def get_args_parser() -> argparse.ArgumentParser:
from .. import __version__
parser = argparse.ArgumentParser(add_help=False, description="Hydra")
parser.add_argument("--help", "-h", action="store_true", help="Application's help")
parser.add_argument("--hydra-help", action="store_true", help="Hydra's help")
parser.add_argument(
"--version",
action="version",
help="Show Hydra's version and exit",
version=f"Hydra {__version__}",
)
parser.add_argument(
"overrides",
nargs="*",
help="Any key=value arguments to override config values (use dots for.nested=overrides)",
)
parser.add_argument(
"--cfg",
"-c",
choices=["job", "hydra", "all"],
help="Show config instead of running [job|hydra|all]",
)
parser.add_argument("--package", "-p", help="Config package to show")
parser.add_argument("--run", "-r", action="store_true", help="Run a job")
parser.add_argument(
"--multirun",
"-m",
action="store_true",
help="Run multiple jobs with the configured launcher and sweeper",
)
parser.add_argument(
"--shell-completion",
"-sc",
action="store_true",
help=f"Install or Uninstall shell completion:\n{_get_completion_help()}",
)
parser.add_argument(
"--config-path",
"-cp",
help="""Overrides the config_path specified in hydra.main().
The config_path is relative to the Python file declaring @hydra.main()""",
)
parser.add_argument(
"--config-name",
"-cn",
help="Overrides the config_name specified in hydra.main()",
)
parser.add_argument(
"--config-dir",
"-cd",
help="Adds an additional config dir to the config search path",
)
parser.add_argument(
"--info", "-i", action="store_true", help="Print Hydra information"
)
return parser
def get_args(args: Optional[Sequence[str]] = None) -> Any:
return get_args_parser().parse_args(args=args)
def get_column_widths(matrix: List[List[str]]) -> List[int]:
num_cols = 0
for row in matrix:
num_cols = max(num_cols, len(row))
widths: List[int] = [0] * num_cols
for row in matrix:
for idx, col in enumerate(row):
widths[idx] = max(widths[idx], len(col))
return widths
def _instantiate_class(
clazz: Type[Any], config: Union[ObjectConf, DictConfig], *args: Any, **kwargs: Any
) -> Any:
# TODO: pull out to caller?
final_kwargs = _get_kwargs(config, **kwargs)
return clazz(*args, **final_kwargs)
def _call_callable(
fn: Callable[..., Any],
config: Union[ObjectConf, DictConfig],
*args: Any,
**kwargs: Any,
) -> Any:
final_kwargs = _get_kwargs(config, **kwargs)
return fn(*args, **final_kwargs)
def _locate(path: str) -> Union[type, Callable[..., Any]]:
"""
Locate an object by name or dotted path, importing as necessary.
This is similar to the pydoc function `locate`, except that it checks for
the module from the given path from back to front.
"""
if path == "":
raise ImportError("Empty path")
import builtins
from importlib import import_module
parts = [part for part in path.split(".") if part]
module = None
for n in reversed(range(len(parts))):
try:
mod = ".".join(parts[:n])
module = import_module(mod)
except Exception as e:
if n == 0:
raise ImportError(f"Error loading module '{path}'") from e
continue
if module:
break
if module:
obj = module
else:
obj = builtins
for part in parts[n:]:
mod = mod + "." + part
if not hasattr(obj, part):
try:
import_module(mod)
except Exception as e:
raise ImportError(
f"Encountered error: `{e}` when loading module '{path}'"
) from e
obj = getattr(obj, part)
if isinstance(obj, type):
obj_type: type = obj
return obj_type
elif callable(obj):
obj_callable: Callable[..., Any] = obj
return obj_callable
else:
# dummy case
raise ValueError(f"Invalid type ({type(obj)}) found for {path}")
def _get_kwargs(config: Union[ObjectConf, DictConfig], **kwargs: Any) -> Any:
if isinstance(config, ObjectConf):
config = OmegaConf.structured(config)
if config.params is not None:
params = config.params
else:
params = OmegaConf.create()
else:
config = copy.deepcopy(config)
if "params" in config:
msg = (
"\nField 'params' is deprecated since Hydra 1.0 and will be removed in Hydra 1.1."
"\nInline the content of params directly at the containing node."
"\nSee https://hydra.cc/docs/next/upgrades/0.11_to_1.0/object_instantiation_changes"
)
warnings.warn(category=UserWarning, message=msg)
params = config.params
else:
params = config
assert isinstance(
params, DictConfig
), f"Input config params are expected to be a mapping, found {type(config.params).__name__}"
config_overrides = {}
passthrough = {}
for k, v in kwargs.items():
if k in params:
config_overrides[k] = v
else:
passthrough[k] = v
final_kwargs = {}
with read_write(params):
params.merge_with(config_overrides)
for k in params.keys():
if k == "_target_":
continue
if OmegaConf.is_missing(params, k) and k in passthrough:
continue
final_kwargs[k] = params[k]
for k, v in passthrough.items():
final_kwargs[k] = v
return final_kwargs
def _get_cls_name(config: DictConfig, pop: bool = True) -> str:
def _getcls(field: str) -> str:
if pop:
classname = config.pop(field)
else:
classname = config[field]
if not isinstance(classname, str):
raise InstantiationException(f"_target_ field '{field}' must be a string")
return classname
for field in ["target", "cls", "class"]:
if field in config:
key = config._get_full_key(field)
msg = (
f"\nConfig key '{key}' is deprecated since Hydra 1.0 and will be removed in Hydra 1.1."
f"\nUse '_target_' instead of '{field}'."
f"\nSee https://hydra.cc/docs/next/upgrades/0.11_to_1.0/object_instantiation_changes"
)
warnings.warn(message=msg, category=UserWarning)
if "_target_" in config:
return _getcls("_target_")
for field in ["target", "cls", "class"]:
if field in config:
return _getcls(field)
raise InstantiationException("Input config does not have a `_target_` field")
| from hydra.core.plugins import Plugins
from hydra.plugins.completion_plugin import CompletionPlugin
completion_plugins = Plugins.instance().discover(CompletionPlugin)
completion_info: List[str] = []
for plugin_cls in completion_plugins:
assert issubclass(plugin_cls, CompletionPlugin)
for cmd in ["install", "uninstall"]:
head = f"{plugin_cls.provides().capitalize()} - {cmd.capitalize()}:"
completion_info.append(head)
completion_info.append(plugin_cls.help(cmd).format(_get_exec_command()))
completion_info.append("")
completion_help = "\n".join([f" {x}" if x else x for x in completion_info])
return completion_help |
he.js |
CKEDITOR.plugins.setLang( 'placeholder', 'he',
{
placeholder :
{
title : 'מאפייני שומר מקום',
toolbar : 'צור שומר מקום', | }
}); | text : 'תוכן שומר המקום',
edit : 'ערוך שומר מקום',
textMissing : 'שומר המקום חייב להכיל טקסט.' |
affinity_test.go | /*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package trait
import (
"testing"
"github.com/stretchr/testify/assert"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
v1 "github.com/apache/camel-k/pkg/apis/camel/v1"
"github.com/apache/camel-k/pkg/util"
"github.com/apache/camel-k/pkg/util/kubernetes"
)
func TestConfigureAffinityTraitDoesSucceed(t *testing.T) {
affinityTrait, environment, _ := createNominalAffinityTest()
configured, err := affinityTrait.Configure(environment)
assert.True(t, configured)
assert.Nil(t, err)
}
func TestConfigureAffinityTraitWithConflictingAffinitiesFails(t *testing.T) {
affinityTrait, environment, _ := createNominalAffinityTest()
affinityTrait.PodAffinity = util.BoolP(true)
affinityTrait.PodAntiAffinity = util.BoolP(true)
configured, err := affinityTrait.Configure(environment) | assert.False(t, configured)
assert.NotNil(t, err)
}
func TestConfigureDisabledAffinityTraitFails(t *testing.T) {
affinityTrait, environment, _ := createNominalAffinityTest()
affinityTrait.Enabled = new(bool)
configured, err := affinityTrait.Configure(environment)
assert.False(t, configured)
assert.Nil(t, err)
}
func TestApplyEmptyAffinityLabelsDoesSucceed(t *testing.T) {
affinityTrait, environment, _ := createNominalAffinityTest()
err := affinityTrait.Apply(environment)
assert.Nil(t, err)
}
func TestApplyNodeAffinityLabelsDoesSucceed(t *testing.T) {
affinityTrait, environment, deployment := createNominalAffinityTest()
affinityTrait.NodeAffinityLabels = []string{"criteria = value"}
err := affinityTrait.Apply(environment)
assert.Nil(t, err)
assert.NotNil(t, deployment.Spec.Template.Spec.Affinity.NodeAffinity)
nodeAffinity := deployment.Spec.Template.Spec.Affinity.NodeAffinity
assert.NotNil(t, nodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms[0].MatchExpressions[0])
nodeSelectorRequirement := nodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms[0].MatchExpressions[0]
assert.Equal(t, "criteria", nodeSelectorRequirement.Key)
assert.Equal(t, corev1.NodeSelectorOpIn, nodeSelectorRequirement.Operator)
assert.ElementsMatch(t, [1]string{"value"}, nodeSelectorRequirement.Values)
}
func TestApplyPodAntiAffinityLabelsDoesSucceed(t *testing.T) {
affinityTrait, environment, deployment := createNominalAffinityTest()
affinityTrait.PodAntiAffinity = util.BoolP(true)
affinityTrait.PodAntiAffinityLabels = []string{"criteria != value"}
err := affinityTrait.Apply(environment)
assert.Nil(t, err)
assert.NotNil(t, deployment.Spec.Template.Spec.Affinity.PodAntiAffinity)
podAntiAffinity := deployment.Spec.Template.Spec.Affinity.PodAntiAffinity
assert.NotNil(t, podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution[0].LabelSelector.MatchExpressions[0])
userRequirement := podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution[0].LabelSelector.MatchExpressions[0]
assert.Equal(t, "criteria", userRequirement.Key)
assert.Equal(t, metav1.LabelSelectorOpNotIn, userRequirement.Operator)
assert.ElementsMatch(t, [1]string{"value"}, userRequirement.Values)
assert.NotNil(t, podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution[0].LabelSelector.MatchExpressions[1])
integrationRequirement := podAntiAffinity.RequiredDuringSchedulingIgnoredDuringExecution[0].LabelSelector.MatchExpressions[1]
assert.Equal(t, v1.IntegrationLabel, integrationRequirement.Key)
assert.Equal(t, metav1.LabelSelectorOpIn, integrationRequirement.Operator)
assert.ElementsMatch(t, [1]string{"integration-name"}, integrationRequirement.Values)
}
func TestApplyPodAffinityLabelsDoesSucceed(t *testing.T) {
affinityTrait, environment, deployment := createNominalAffinityTest()
affinityTrait.PodAffinity = util.BoolP(true)
affinityTrait.PodAffinityLabels = []string{"!criteria"}
err := affinityTrait.Apply(environment)
assert.Nil(t, err)
assert.NotNil(t, deployment.Spec.Template.Spec.Affinity.PodAffinity)
podAffinity := deployment.Spec.Template.Spec.Affinity.PodAffinity
assert.NotNil(t, podAffinity.RequiredDuringSchedulingIgnoredDuringExecution[0].LabelSelector.MatchExpressions[0])
userRequirement := podAffinity.RequiredDuringSchedulingIgnoredDuringExecution[0].LabelSelector.MatchExpressions[0]
assert.Equal(t, "criteria", userRequirement.Key)
assert.Equal(t, metav1.LabelSelectorOpDoesNotExist, userRequirement.Operator)
assert.NotNil(t, podAffinity.RequiredDuringSchedulingIgnoredDuringExecution[0].LabelSelector.MatchExpressions[1])
integrationRequirement := podAffinity.RequiredDuringSchedulingIgnoredDuringExecution[0].LabelSelector.MatchExpressions[1]
assert.Equal(t, v1.IntegrationLabel, integrationRequirement.Key)
assert.Equal(t, metav1.LabelSelectorOpIn, integrationRequirement.Operator)
assert.ElementsMatch(t, [1]string{"integration-name"}, integrationRequirement.Values)
}
func createNominalAffinityTest() (*affinityTrait, *Environment, *appsv1.Deployment) {
trait := newAffinityTrait().(*affinityTrait)
enabled := true
trait.Enabled = &enabled
deployment := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: "integration-name",
},
Spec: appsv1.DeploymentSpec{
Template: corev1.PodTemplateSpec{},
},
}
environment := &Environment{
Integration: &v1.Integration{
ObjectMeta: metav1.ObjectMeta{
Name: "integration-name",
},
Status: v1.IntegrationStatus{
Phase: v1.IntegrationPhaseDeploying,
},
},
Resources: kubernetes.NewCollection(deployment),
}
return trait, environment, deployment
} | |
node_modify_responses.go | // Code generated by go-swagger; DO NOT EDIT.
package cluster
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
"github.com/go-openapi/strfmt"
"github.com/netapp/trident/storage_drivers/ontap/api/rest/models"
)
// NodeModifyReader is a Reader for the NodeModify structure.
type NodeModifyReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *NodeModifyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 202:
result := NewNodeModifyAccepted()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
default:
result := NewNodeModifyDefault(response.Code())
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
if response.Code()/100 == 2 {
return result, nil
}
return nil, result
}
}
// NewNodeModifyAccepted creates a NodeModifyAccepted with default headers values
func | () *NodeModifyAccepted {
return &NodeModifyAccepted{}
}
/* NodeModifyAccepted describes a response with status code 202, with default header values.
Accepted
*/
type NodeModifyAccepted struct {
Payload *models.JobLinkResponse
}
func (o *NodeModifyAccepted) Error() string {
return fmt.Sprintf("[PATCH /cluster/nodes/{uuid}][%d] nodeModifyAccepted %+v", 202, o.Payload)
}
func (o *NodeModifyAccepted) GetPayload() *models.JobLinkResponse {
return o.Payload
}
func (o *NodeModifyAccepted) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.JobLinkResponse)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewNodeModifyDefault creates a NodeModifyDefault with default headers values
func NewNodeModifyDefault(code int) *NodeModifyDefault {
return &NodeModifyDefault{
_statusCode: code,
}
}
/* NodeModifyDefault describes a response with status code -1, with default header values.
ONTAP Error Response Codes
| Error Code | Description |
| ---------- | ----------- |
| 852046 | HA partner node |
| 852115 | The reboot/shutdown is prevented because LIFs cannot be moved away from the node |
| 3604514 | A reboot or shutdown request is already in progress. |
| 3604515 | Reboot or shutdown of all nodes results in data service failure and client disruption for the entire cluster. Use "allow-data-outage=true" to bypass this check. |
| 9240606 | The reboot/shutdown is prevented due to quorum warnings. |
*/
type NodeModifyDefault struct {
_statusCode int
Payload *models.ErrorResponse
}
// Code gets the status code for the node modify default response
func (o *NodeModifyDefault) Code() int {
return o._statusCode
}
func (o *NodeModifyDefault) Error() string {
return fmt.Sprintf("[PATCH /cluster/nodes/{uuid}][%d] node_modify default %+v", o._statusCode, o.Payload)
}
func (o *NodeModifyDefault) GetPayload() *models.ErrorResponse {
return o.Payload
}
func (o *NodeModifyDefault) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.ErrorResponse)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
| NewNodeModifyAccepted |
test.go | package main
import (
sw "./go-petstore"
"encoding/json"
"fmt"
)
func | () {
s := sw.NewPetApi()
// test POST(body)
newPet := (sw.Pet{Id: 12830, Name: "gopher",
PhotoUrls: []string{"http://1.com", "http://2.com"}, Status: "pending"})
jsonNewPet, _ := json.Marshal(newPet)
fmt.Println("newPet:", string(jsonNewPet))
s.AddPet(newPet)
// test POST(form)
s.UpdatePetWithForm(12830, "golang", "available")
// test GET
resp, err := s.GetPetById(12830)
fmt.Println("GetPetById: ", resp, err)
}
| main |
actions.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { localize } from 'vs/nls';
import { Registry } from 'vs/platform/registry/common/platform';
import { KeybindingsRegistry, KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ICommandHandler, CommandsRegistry } from 'vs/platform/commands/common/commands';
import { SyncActionDescriptor, MenuRegistry, MenuId, ICommandAction } from 'vs/platform/actions/common/actions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IDisposable, DisposableStore } from 'vs/base/common/lifecycle';
import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { INotificationService } from 'vs/platform/notification/common/notification';
import { ContextKeyExpr, ContextKeyExpression } from 'vs/platform/contextkey/common/contextkey';
export const Extensions = {
WorkbenchActions: 'workbench.contributions.actions'
};
export interface IWorkbenchActionRegistry {
/**
* Registers a workbench action to the platform. Workbench actions are not
* visible by default and can only be invoked through a keybinding if provided.
* @deprecated Register directly with KeybindingsRegistry and MenuRegistry or use registerAction2 instead.
*/
registerWorkbenchAction(descriptor: SyncActionDescriptor, alias: string, category?: string, when?: ContextKeyExpr): IDisposable;
}
Registry.add(Extensions.WorkbenchActions, new class implements IWorkbenchActionRegistry {
registerWorkbenchAction(descriptor: SyncActionDescriptor, alias: string, category?: string, when?: ContextKeyExpression): IDisposable {
return this.registerWorkbenchCommandFromAction(descriptor, alias, category, when);
}
private registerWorkbenchCommandFromAction(descriptor: SyncActionDescriptor, alias: string, category?: string, when?: ContextKeyExpression): IDisposable {
const registrations = new DisposableStore();
// command
registrations.add(CommandsRegistry.registerCommand(descriptor.id, this.createCommandHandler(descriptor)));
// keybinding
const weight = (typeof descriptor.keybindingWeight === 'undefined' ? KeybindingWeight.WorkbenchContrib : descriptor.keybindingWeight);
const keybindings = descriptor.keybindings;
KeybindingsRegistry.registerKeybindingRule({
id: descriptor.id,
weight: weight,
when:
descriptor.keybindingContext && when
? ContextKeyExpr.and(descriptor.keybindingContext, when)
: descriptor.keybindingContext || when || null,
primary: keybindings ? keybindings.primary : 0,
secondary: keybindings?.secondary,
win: keybindings?.win,
mac: keybindings?.mac,
linux: keybindings?.linux
});
// menu item
// TODO@Rob slightly weird if-check required because of
// https://github.com/microsoft/vscode/blob/master/src/vs/workbench/contrib/search/electron-browser/search.contribution.ts#L266
if (descriptor.label) {
let idx = alias.indexOf(': ');
let categoryOriginal = '';
if (idx > 0) {
categoryOriginal = alias.substr(0, idx);
alias = alias.substr(idx + 2);
}
const command: ICommandAction = {
id: descriptor.id,
title: { value: descriptor.label, original: alias },
category: category ? { value: category, original: categoryOriginal } : undefined
};
MenuRegistry.addCommand(command);
registrations.add(MenuRegistry.appendMenuItem(MenuId.CommandPalette, { command, when }));
}
// TODO@alex,joh
// support removal of keybinding rule
// support removal of command-ui
return registrations;
}
private createCommandHandler(descriptor: SyncActionDescriptor): ICommandHandler {
return async (accessor, args) => {
const notificationService = accessor.get(INotificationService); | try {
await this.triggerAndDisposeAction(instantiationService, lifecycleService, descriptor, args);
} catch (error) {
notificationService.error(error);
}
};
}
private async triggerAndDisposeAction(instantiationService: IInstantiationService, lifecycleService: ILifecycleService, descriptor: SyncActionDescriptor, args: unknown): Promise<void> {
// run action when workbench is created
await lifecycleService.when(LifecyclePhase.Ready);
const actionInstance = instantiationService.createInstance(descriptor.syncDescriptor);
actionInstance.label = descriptor.label || actionInstance.label;
// don't run the action when not enabled
if (!actionInstance.enabled) {
actionInstance.dispose();
return;
}
// otherwise run and dispose
try {
const from = (args as any)?.from || 'keybinding';
await actionInstance.run(undefined, { from });
} finally {
actionInstance.dispose();
}
}
});
export const CATEGORIES = {
View: { value: localize('view', "View"), original: 'View' },
Help: { value: localize('help', "Help"), original: 'Help' },
Developer: { value: localize({ key: 'developer', comment: ['A developer on Code itself or someone diagnosing issues in Code'] }, "Developer"), original: 'Developer' }
}; | const instantiationService = accessor.get(IInstantiationService);
const lifecycleService = accessor.get(ILifecycleService);
|
app.module.ts | import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { JwtModule } from '@auth0/angular-jwt';
import { RoutingModule } from './routing.module';
import { SharedModule } from './shared/shared.module';
import { CatService } from './services/cat.service';
import { UserService } from './services/user.service';
import { AuthService } from './services/auth.service';
import { InquiryService } from './services/inquiry.service';
import { NewsletterService } from './services/newsletter.service';
import { AuthGuardLogin } from './services/auth-guard-login.service';
import { AuthGuardAdmin } from './services/auth-guard-admin.service';
import { AppComponent } from './app.component';
import { CatsComponent } from './cats/cats.component';
import { AboutComponent } from './about/about.component';
import { RegisterComponent } from './register/register.component';
import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';
import { AccountComponent } from './account/account.component';
import { AdminComponent } from './admin/admin.component';
import { NotFoundComponent } from './not-found/not-found.component';
import { InquiryComponent } from './inquiry/inquiry.component';
import { MoreInfoComponent } from './more-info/more-info.component';
import { ThankYouComponent } from './thank-you/thank-you.component';
import { RecaptchaModule } from 'ng-recaptcha';
export function tokenGetter() {
return localStorage.getItem('token');
}
@NgModule({
declarations: [
AppComponent,
CatsComponent,
AboutComponent,
RegisterComponent,
LoginComponent,
LogoutComponent,
AccountComponent,
AdminComponent,
NotFoundComponent,
InquiryComponent,
MoreInfoComponent,
ThankYouComponent
],
imports: [
RoutingModule,
SharedModule,
RecaptchaModule.forRoot(),
JwtModule.forRoot({
config: {
tokenGetter: tokenGetter,
// whitelistedDomains: ['localhost:3000', 'localhost:4200']
}
})
],
providers: [
AuthService,
AuthGuardLogin,
AuthGuardAdmin,
CatService,
UserService,
InquiryService,
NewsletterService
],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
bootstrap: [AppComponent]
})
export class | { }
| AppModule |
Latex_generator.py | # Copyright (c) 2022, Leonardo Lamanna
# All rights reserved.
# This source code is licensed under the MIT-style license found in the
# LICENSE file in the root directory of this source tree.
import pandas as pd
import os
pd.options.display.max_colwidth = 100
def | (data_file, labels, tab_name, caption, header):
with open(tab_name + ".tex", "w") as f:
df = pd.read_excel(data_file, sheet_name="Summary")
df_restricted = df[labels]
f.write(df_restricted.to_latex(index=False, escape=False,
label="tab:{}".format(tab_name),
caption= caption,
header = header))
def generate_comparison_latex_table():
labels = ["Domain", "Neg precision A", "Neg recall A", "Overall precision A", "Overall recall A",
"Neg precision B", "Neg recall B", "Overall precision B", "Overall recall B"]
header = ["Domain", "$P_{\\eff^{-}}$", "$R_{\\eff^{-}}$", "$P$", "$R$",
"$P_{\\eff^{-}}$", "$R_{\\eff^{-}}$", "$P$", "$R$"]
caption = "For each domain:statistics on final metrics of the last instance grouped by " \
"negative effects."
tab_name = "comparison_summary_uncertain"
file_path = os.path.join("comparison_summary_uncertain.xlsx")
generate_latex_table(file_path, labels, tab_name, caption, header)
def generate_comparison_latex_table_fama():
labels = ["Domain", "Tot time", "Overall precision", "Overall recall", "FAMA tot time",
"FAMA precision", "FAMA recall", "Delta act"]
header = ["Domain", "$t$", "$P$", "$R$", "$t$", "$P$", "$R$", "$\delta_{A}$"]
caption = "Comparison among OLAM and FAMA with full observability. FAMA is run with all plan traces " \
"provided in \protect\cite{aineto_AIJ2019}. MODEL WITH UNCERTAIN NEGATIVE EFFECTS AND STRIPS ASSUMPTION."
tab_name = "comparison_fama"
file_path = os.path.join("comparison_fama.xlsx")
generate_latex_table(file_path, labels, tab_name, caption, header)
def generate_summary_latex_table():
# labels = ["Domain", "Instances", "Precs precision", "Precs recall","Pos precision", "Pos recall",
# "Neg precision", "Neg recall", "Overall precision", "Overall recall"]
labels = ["Domain", "Instances", "Precs precision", "Precs recall","Pos precision", "Pos recall",
"Neg precision", "Neg recall", "Average precision", "Average recall"]
header = ["Domain", "$I$", "$P_{\\prec}$", "$R_{\\prec}$", "$P_{\\eff^{+}}$", "$R_{\\eff^{+}}$", "$P_{\\eff^{-}}$",
"$R_{\\eff^{-}}$", "$P$", "$R$"]
caption = "For each domain:statistics on final metrics of the last instance grouped by " \
"preconditions, positive effects and negative ones."
tab_name = "overall_summary_certain_nostripsass"
folder = "../Analysis/IJCAI_Results/Results_certain_NOnegeff_assumption"
file_path = os.path.join(folder, "overall_summary.xlsx")
generate_latex_table(file_path, labels, tab_name, caption, header)
def generate_domain_objects_table():
header = ["Domain", "Objects"]
caption = "For each domain, problem objects of all problems in the generated set."
tab_name = "all_problem_objects"
df = pd.DataFrame({
"Domain":[],
"Objects":[]
})
# df.set_index('Domain', inplace=True)
domain_dataframes = [name for name in os.listdir(os.path.join("..", "Analysis", "Results_cert"))
if not name.startswith("overall")]
for domain_dataframe in domain_dataframes:
domain = domain_dataframe.split("_")[0]
df_domain = pd.read_excel(os.path.join("..", "Analysis", "Results_cert", domain_dataframe),
sheet_name="Objects")
domain_obj_types = [key.strip().lower() for key in list(df_domain) if key.strip().lower() != "total objs"]
for i, row in df_domain.iterrows():
problem_objs = []
for k in domain_obj_types:
problem_objs.append("{} {}".format(k,row["\t" + k]))
eval = {
"Domain":domain,
"Objects":", ".join(problem_objs)
}
df = df.append(eval, ignore_index=True)
with open(tab_name + ".tex", "w") as f:
f.write(df.to_latex(index=False,
label="tab:{}".format(tab_name),
caption= caption,
header = header))
if __name__ == "__main__":
generate_summary_latex_table()
#
# generate_domain_objects_table()
| generate_latex_table |
model.py | import logging
from abc import ABC, abstractmethod
from collections import defaultdict
from dataclasses import dataclass, field
from typing import (
Callable,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union
)
from sciencebeam_trainer_delft.sequence_labelling.reader import load_data_crf_lines
from sciencebeam_parser.utils.labels import get_split_prefix_label, strip_tag_prefix
from sciencebeam_parser.document.layout_document import (
LayoutToken,
LayoutLine,
LayoutBlock,
LayoutPage,
LayoutDocument
)
from sciencebeam_parser.models.data import (
AppFeaturesContext,
DocumentFeaturesContext,
LabeledLayoutModelData,
LayoutModelData,
ModelDataGenerator
)
from sciencebeam_parser.models.extract import ModelSemanticExtractor
from sciencebeam_parser.models.training_data import TeiTrainingDataGenerator
from sciencebeam_parser.document.semantic_document import SemanticContentWrapper
from sciencebeam_parser.models.model_impl import ModelImpl, T_ModelImplFactory
from sciencebeam_parser.utils.lazy import LazyLoaded, Preloadable
LOGGER = logging.getLogger(__name__)
T = TypeVar('T')
U = TypeVar('U')
@dataclass
class LayoutModelLabel:
label: str
label_token_text: str
layout_line: Optional[LayoutLine] = field(repr=False, default=None)
layout_token: Optional[LayoutToken] = field(repr=False, default=None)
class LabeledLayoutToken(NamedTuple):
label: str
layout_token: LayoutToken
class NewDocumentMarker:
pass
NEW_DOCUMENT_MARKER = NewDocumentMarker()
def iter_entities_including_other(seq: List[str]) -> Iterable[Tuple[str, int, int]]:
"""
Similar to get_entities, but also other (`O`) tag
"""
prev_tag = 'O'
prev_start = 0
for index, prefixed_tag in enumerate(seq):
prefix, tag = get_split_prefix_label(prefixed_tag)
if prefix == 'B' or tag != prev_tag:
if prev_start < index:
yield prev_tag, prev_start, index - 1
prev_tag = tag
prev_start = index
if prev_start < len(seq):
yield prev_tag, prev_start, len(seq) - 1
def get_entities_including_other(seq: List[str]) -> List[Tuple[str, int, int]]:
return list(iter_entities_including_other(seq))
class LayoutDocumentLabelResult:
def __init__(
self,
layout_document: LayoutDocument,
layout_model_label_iterable: Iterable[LayoutModelLabel]
):
self.layout_document = layout_document
self.layout_model_label_list = list(layout_model_label_iterable)
self.layout_document_labels_by_label: Dict[str, List[LayoutModelLabel]] = (
defaultdict(list)
)
for layout_model_label in self.layout_model_label_list:
tag_without_prefix = strip_tag_prefix(layout_model_label.label)
self.layout_document_labels_by_label[tag_without_prefix].append(
layout_model_label
)
def get_available_labels(self) -> Set[str]:
return set(self.layout_document_labels_by_label.keys())
def get_layout_document_labels_by_labels(self, labels: List[str]) -> List[LayoutModelLabel]:
if not labels:
return []
if len(labels) == 1:
return self.layout_document_labels_by_label.get(labels[0], [])
result: List[LayoutModelLabel] = []
for label in labels:
result.extend(self.layout_document_labels_by_label.get(label, []))
return result
def get_filtered_document_by_label(self, label: str) -> LayoutDocument:
return self.get_filtered_document_by_labels([label])
def get_filtered_document_by_labels(
self,
labels: List[str]
): # pylint: disable=too-many-branches
layout_document = LayoutDocument(pages=[])
layout_document_labels = self.get_layout_document_labels_by_labels(labels)
if not layout_document_labels:
LOGGER.warning(
'no layout_lines_to_include found for: %r, available keys=%r',
labels, self.layout_document_labels_by_label.keys()
)
return layout_document
layout_token_ids_to_include = {
id(layout_document_label.layout_token)
for layout_document_label in layout_document_labels
if layout_document_label.layout_token
}
LOGGER.debug('layout_tokens_to_include: %s', layout_token_ids_to_include)
layout_line_ids_to_include: Set[int] = set()
if not layout_token_ids_to_include:
layout_line_ids_to_include = {
id(layout_document_label.layout_line)
for layout_document_label in layout_document_labels
if layout_document_label.layout_line
}
LOGGER.debug('layout_line_ids_to_include: %s', layout_line_ids_to_include)
result_page: Optional[LayoutPage] = None
for page in self.layout_document.pages: # pylint: disable=too-many-nested-blocks
result_page = None
result_block: Optional[LayoutBlock] = None
for block in page.blocks:
result_block = None
for line in block.lines:
accepted_line: Optional[LayoutLine] = None
if layout_token_ids_to_include:
accepted_tokens: List[LayoutToken] = []
for token in line.tokens:
if id(token) in layout_token_ids_to_include:
accepted_tokens.append(token)
if not accepted_tokens:
continue
if len(line.tokens) == accepted_tokens:
accepted_line = line
else:
accepted_line = LayoutLine(tokens=accepted_tokens)
else:
if id(line) not in layout_line_ids_to_include:
continue
accepted_line = line
if result_page is None:
result_page = LayoutPage(blocks=[])
layout_document.pages.append(result_page)
if result_block is None:
result_block = LayoutBlock(lines=[])
result_page.blocks.append(result_block)
result_block.lines.append(accepted_line)
return layout_document
def iter_entity_layout_blocks_for_labeled_layout_tokens(
labeled_layout_tokens: Iterable[LabeledLayoutToken]
) -> Iterable[Tuple[str, LayoutBlock]]:
layout_tokens = [result.layout_token for result in labeled_layout_tokens]
labels = [result.label for result in labeled_layout_tokens]
LOGGER.debug('layout_tokens: %s', layout_tokens)
LOGGER.debug('labels: %s', labels)
for tag, start, end in get_entities_including_other(list(labels)):
yield tag, LayoutBlock.for_tokens(layout_tokens[start:end + 1])
def | (
tag_result: List[Tuple[str, str]]
) -> Iterable[Tuple[str, str]]:
tokens, labels = zip(*tag_result)
LOGGER.debug('tokens: %s', tokens)
LOGGER.debug('labels: %s', labels)
for tag, start, end in get_entities_including_other(list(labels)):
yield tag, ' '.join(tokens[start:end + 1])
def iter_labeled_layout_token_for_layout_model_label(
layout_model_label_iterable: Iterable[LayoutModelLabel]
) -> Iterable[LabeledLayoutToken]:
for layout_model_label in layout_model_label_iterable:
layout_token = layout_model_label.layout_token
assert layout_token is not None
yield LabeledLayoutToken(
layout_model_label.label,
layout_token
)
def iter_data_lines_for_model_data_iterables(
model_data_iterables: Iterable[Iterable[LayoutModelData]]
) -> Iterable[str]:
for index, model_data_list in enumerate(model_data_iterables):
if index > 0:
yield ''
for model_data in model_data_list:
yield model_data.data_line
class Model(ABC, Preloadable):
def __init__(
self,
model_impl_factory: Optional[T_ModelImplFactory],
model_config: Optional[dict] = None
) -> None:
self._model_impl_factory = model_impl_factory
self._lazy_model_impl = LazyLoaded[ModelImpl](self._load_model_impl)
self.model_config = model_config or {}
def __repr__(self) -> str:
return '%s(model_config=%r, loaded=%r)' % (
type(self).__name__, self.model_config, self._lazy_model_impl.is_loaded
)
@abstractmethod
def get_data_generator(
self,
document_features_context: DocumentFeaturesContext
) -> ModelDataGenerator:
pass
# @abstractmethod
def get_semantic_extractor(self) -> ModelSemanticExtractor:
raise NotImplementedError()
# @abstractmethod
def get_tei_training_data_generator(self) -> TeiTrainingDataGenerator:
raise NotImplementedError()
def _load_model_impl(self) -> ModelImpl:
assert self._model_impl_factory, 'model impl factory required'
LOGGER.info('creating model impl: %r', self._model_impl_factory)
model_impl = self._model_impl_factory()
if not isinstance(model_impl, ModelImpl):
raise TypeError('invalid model impl type: %r' % model_impl)
return model_impl
@property
def model_impl(self) -> ModelImpl:
was_loaded = self._lazy_model_impl.is_loaded
model_impl = self._lazy_model_impl.get()
if was_loaded:
LOGGER.info('model impl already loaded: %r', model_impl)
return model_impl
def preload(self):
model_impl = self.model_impl
model_impl.preload()
def iter_semantic_content_for_entity_blocks(
self,
entity_tokens: Iterable[Tuple[str, LayoutBlock]],
**kwargs
) -> Iterable[SemanticContentWrapper]:
return self.get_semantic_extractor().iter_semantic_content_for_entity_blocks(
entity_tokens,
**kwargs
)
def predict_labels(
self,
texts: List[List[str]],
features: List[List[List[str]]],
output_format: Optional[str] = None
) -> List[List[Tuple[str, str]]]:
return self.model_impl.predict_labels(texts, features, output_format)
def _iter_flat_label_model_data_lists_to( # pylint: disable=too-many-locals
self,
model_data_list_iterable: Iterable[Sequence[LayoutModelData]],
item_factory: Callable[[str, LayoutModelData], T]
) -> Iterable[Union[T, NewDocumentMarker]]:
# Note: currently we do need a list
model_data_lists = list(model_data_list_iterable)
if not model_data_lists:
return
data_lines = list(iter_data_lines_for_model_data_iterables(
model_data_lists
))
texts, features = load_data_crf_lines(data_lines)
texts = texts.tolist()
tag_result = self.predict_labels(
texts=texts, features=features, output_format=None
)
if not tag_result:
return
if len(tag_result) != len(model_data_lists):
raise AssertionError('tag result does not match number of docs: %d != %d' % (
len(tag_result), len(model_data_lists)
))
for index, (doc_tag_result, model_data_list) in enumerate(
zip(tag_result, model_data_lists)
):
if index > 0:
yield NEW_DOCUMENT_MARKER
if len(doc_tag_result) != len(model_data_list):
raise AssertionError('doc tag result does not match data: %d != %d' % (
len(doc_tag_result), len(model_data_list)
))
for token_tag_result, token_model_data in zip(doc_tag_result, model_data_list):
label_token_text, token_label = token_tag_result
if label_token_text != token_model_data.label_token_text:
raise AssertionError(
f'actual: {repr(label_token_text)}'
f', expected: {repr(token_model_data.label_token_text)}'
)
yield item_factory(
token_label,
token_model_data
)
def _iter_stacked_label_model_data_lists_to(
self,
model_data_list_iterable: Iterable[Sequence[LayoutModelData]],
item_factory: Callable[[str, LayoutModelData], T]
) -> Iterable[Sequence[T]]:
# Note: currently we do need a list
model_data_lists = list(model_data_list_iterable)
if not model_data_lists:
return
doc_items: List[T] = []
result_doc_count = 0
for item in self._iter_flat_label_model_data_lists_to(
model_data_lists,
item_factory=item_factory
):
if isinstance(item, NewDocumentMarker):
yield doc_items
doc_items = []
result_doc_count += 1
continue
doc_items.append(item)
if result_doc_count < len(model_data_lists):
yield doc_items
def iter_label_layout_documents(
self,
layout_documents: List[LayoutDocument],
app_features_context: AppFeaturesContext
) -> Iterable[List[LayoutModelLabel]]:
doc_layout_model_labels: List[LayoutModelLabel] = []
result_doc_count = 0
for layout_model_label in self._iter_label_layout_documents(
layout_documents,
app_features_context=app_features_context
):
if isinstance(layout_model_label, NewDocumentMarker):
yield doc_layout_model_labels
doc_layout_model_labels = []
result_doc_count += 1
continue
doc_layout_model_labels.append(layout_model_label)
if result_doc_count < len(layout_documents):
yield doc_layout_model_labels
def iter_label_layout_document(
self,
layout_document: LayoutDocument,
app_features_context: AppFeaturesContext
) -> Iterable[LayoutModelLabel]:
for layout_model_label in self._iter_label_layout_documents(
[layout_document],
app_features_context=app_features_context
):
assert isinstance(layout_model_label, LayoutModelLabel)
yield layout_model_label
def _iter_label_layout_documents( # pylint: disable=too-many-locals
self,
layout_documents: Iterable[LayoutDocument],
app_features_context: AppFeaturesContext
) -> Iterable[Union[LayoutModelLabel, NewDocumentMarker]]:
data_generator = self.get_data_generator(
document_features_context=DocumentFeaturesContext(
app_features_context=app_features_context
)
)
model_data_lists = [
list(data_generator.iter_model_data_for_layout_document(
layout_document
))
for layout_document in layout_documents
]
return self._iter_flat_label_model_data_lists_to(
model_data_lists,
lambda label, model_data: LayoutModelLabel(
label=label,
label_token_text=model_data.label_token_text,
layout_line=model_data.layout_line,
layout_token=model_data.layout_token
)
)
def iter_labeled_model_data_list_for_model_data_list_iterable(
self,
model_data_list_iterable: Iterable[Sequence[LayoutModelData]]
) -> Iterable[Sequence[LabeledLayoutModelData]]:
return self._iter_stacked_label_model_data_lists_to(
model_data_list_iterable,
lambda label, model_data: LabeledLayoutModelData.from_model_data(
model_data,
label=label
)
)
def get_label_layout_document_result(
self,
layout_document: LayoutDocument,
app_features_context: AppFeaturesContext
) -> LayoutDocumentLabelResult:
return LayoutDocumentLabelResult(
layout_document=layout_document,
layout_model_label_iterable=self.iter_label_layout_document(
layout_document,
app_features_context=app_features_context
)
)
def iter_predict_labels_for_layout_document(
self,
layout_document: LayoutDocument,
app_features_context: AppFeaturesContext
) -> Iterable[LabeledLayoutToken]:
# Note: this should get merged with Model.iter_label_layout_document
yield from iter_labeled_layout_token_for_layout_model_label(
self.iter_label_layout_document(
layout_document,
app_features_context=app_features_context
)
)
def predict_labels_for_layout_document(
self,
layout_document: LayoutDocument,
app_features_context: AppFeaturesContext
) -> List[LabeledLayoutToken]:
return list(self.iter_predict_labels_for_layout_document(
layout_document,
app_features_context=app_features_context
))
def predict_labels_for_layout_documents(
self,
layout_documents: List[LayoutDocument],
app_features_context: AppFeaturesContext
) -> List[List[LabeledLayoutToken]]:
return [
list(iter_labeled_layout_token_for_layout_model_label(
layout_model_labels
))
for layout_model_labels in self.iter_label_layout_documents(
layout_documents,
app_features_context=app_features_context
)
]
def iter_entity_layout_blocks_for_labeled_layout_tokens(
self,
labeled_layout_tokens: Iterable[LabeledLayoutToken]
) -> Iterable[Tuple[str, LayoutBlock]]:
return iter_entity_layout_blocks_for_labeled_layout_tokens(labeled_layout_tokens)
def iter_semantic_content_for_labeled_layout_tokens(
self,
labeled_layout_tokens: Iterable[LabeledLayoutToken],
**kwargs
) -> Iterable[SemanticContentWrapper]:
return self.iter_semantic_content_for_entity_blocks(
self.iter_entity_layout_blocks_for_labeled_layout_tokens(
labeled_layout_tokens
),
**kwargs
)
| iter_entity_values_predicted_labels |
health.rs | use crate::cache::cache_operations::CacheResponse;
use crate::utils::context::Context;
use crate::utils::errors::ApiResult;
use rocket::response::content;
#[get("/health")]
pub fn health(context: Context) -> ApiResult<content::Json<String>> | {
CacheResponse::new(String::from("/health"))
.resp_generator(|| Ok(String::new()))
.execute(context.cache())
} |
|
test_browser_play_youtube_video.py | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
from marionette.by import By
from gaiatest import GaiaTestCase
from gaiatest.apps.browser.app import Browser
from gaiatest.apps.browser.regions.html5_player import HTML5Player
class TestYouTube(GaiaTestCase):
video_URL = 'http://m.youtube.com/watch?v=5MzuGWFIfio'
acceptable_delay = 2.0
# YouTube video locators
_video_container_locator = (By.CSS_SELECTOR, 'div[style^="background-image"]')
_video_element_locator = (By.TAG_NAME, 'video')
def | (self):
GaiaTestCase.setUp(self)
self.connect_to_network()
def test_play_youtube_video(self):
"""Confirm YouTube video playback
https://moztrap.mozilla.org/manage/case/6073/
"""
browser = Browser(self.marionette)
browser.launch()
browser.go_to_url(self.video_URL)
browser.switch_to_content()
# Tap the video container
self.wait_for_element_present(*self._video_container_locator)
self.marionette.find_element(*self._video_container_locator).tap()
# Wait HTML5 player to appear
self.wait_for_element_present(*self._video_element_locator)
video = self.marionette.find_element(*self._video_element_locator)
player = HTML5Player(self.marionette, video)
# Check that video is playing
player.wait_for_video_loaded()
self.assertTrue(player.is_video_playing())
# Pause playback
player.pause()
stopped_at = player.current_timestamp
self.assertFalse(player.is_video_playing())
# Resume playback
player.play()
resumed_at = player.current_timestamp
self.assertTrue(player.is_video_playing())
# Ensure that video resumes to play
# from the place where it was paused
delay = resumed_at - stopped_at
self.assertLessEqual(delay, self.acceptable_delay,
'video resumed to play not from place where it was paused')
| setUp |
core.py | """
* SearchAThing.UnitTest, Copyright(C) 2015-2017 Lorenzo Delana, License under MIT
*
* The MIT License(MIT)
* Copyright(c) 2015-2017 Lorenzo Delana, https://searchathing.com
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
"""
import unittest
from searchathing_core.number import *
class Core(unittest.TestCase):
def test_equals_auto_tol(self):
self.assertTrue(equals_auto_tol(1, 1))
self.assertTrue(equals_auto_tol(1, 1 + 1e-20))
self.assertFalse(equals_auto_tol(1, 2))
self.assertTrue(equals_auto_tol(1, 2, precision=2))
def test_mround(self):
self.assertTrue(equals_tol(1e-10, mround(4, 3), 3))
self.assertTrue(equals_tol(1e-10, mround(5, 3), 6))
self.assertTrue(equals_tol(1e-10, mround(-3.21, .1), -3.2))
self.assertTrue(equals_tol(1e-10, mround(-3.29, .1), -3.3))
def test_angle(self):
|
if __name__ == '__main__':
unittest.main()
| self.assertTrue(equals_tol(1e-6, to_deg(.21294), 12.200563))
self.assertTrue(equals_tol(1e-6, to_rad(140.3), 2.448697)) |
main.rs | // DO NOT EDIT !
// This file was generated automatically from 'src/mako/cli/main.rs.mako'
// DO NOT EDIT !
#![allow(unused_variables, unused_imports, dead_code, unused_mut)]
#[macro_use]
extern crate clap;
extern crate yup_oauth2 as oauth2;
extern crate yup_hyper_mock as mock;
extern crate hyper_rustls;
extern crate serde;
extern crate serde_json;
extern crate hyper;
extern crate mime;
extern crate strsim;
extern crate google_remotebuildexecution2 as api;
use std::env;
use std::io::{self, Write};
use clap::{App, SubCommand, Arg};
mod cmn;
use cmn::{InvalidOptionsError, CLIError, JsonTokenStorage, arg_from_str, writer_from_opts, parse_kv_arg,
input_file_from_opts, input_mime_from_opts, FieldCursor, FieldError, CallType, UploadProtocol,
calltype_from_str, remove_json_null_values, ComplexType, JsonType, JsonTypeInfo};
use std::default::Default;
use std::str::FromStr;
use oauth2::{Authenticator, DefaultAuthenticatorDelegate, FlowType};
use serde_json as json;
use clap::ArgMatches;
enum DoitError {
IoError(String, io::Error),
ApiError(api::Error),
}
struct Engine<'n> {
opt: ArgMatches<'n>,
hub: api::RemoteBuildExecution<hyper::Client, Authenticator<DefaultAuthenticatorDelegate, JsonTokenStorage, hyper::Client>>,
gp: Vec<&'static str>,
gpm: Vec<(&'static str, &'static str)>,
}
impl<'n> Engine<'n> {
fn _action_results_get(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.action_results().get(opt.value_of("instance-name").unwrap_or(""), opt.value_of("hash").unwrap_or(""), opt.value_of("size-bytes").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"inline-stdout" => {
call = call.inline_stdout(arg_from_str(value.unwrap_or("false"), err, "inline-stdout", "boolean"));
},
"inline-stderr" => {
call = call.inline_stderr(arg_from_str(value.unwrap_or("false"), err, "inline-stderr", "boolean"));
},
"inline-output-files" => {
call = call.add_inline_output_files(value.unwrap_or(""));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["inline-output-files", "inline-stderr", "inline-stdout"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _action_results_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"execution-metadata.output-upload-start-timestamp" => Some(("executionMetadata.outputUploadStartTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"execution-metadata.worker-completed-timestamp" => Some(("executionMetadata.workerCompletedTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"execution-metadata.queued-timestamp" => Some(("executionMetadata.queuedTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"execution-metadata.worker" => Some(("executionMetadata.worker", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"execution-metadata.execution-start-timestamp" => Some(("executionMetadata.executionStartTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"execution-metadata.input-fetch-start-timestamp" => Some(("executionMetadata.inputFetchStartTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"execution-metadata.worker-start-timestamp" => Some(("executionMetadata.workerStartTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"execution-metadata.output-upload-completed-timestamp" => Some(("executionMetadata.outputUploadCompletedTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"execution-metadata.execution-completed-timestamp" => Some(("executionMetadata.executionCompletedTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"execution-metadata.input-fetch-completed-timestamp" => Some(("executionMetadata.inputFetchCompletedTimestamp", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"stderr-digest.size-bytes" => Some(("stderrDigest.sizeBytes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"stderr-digest.hash" => Some(("stderrDigest.hash", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"stdout-raw" => Some(("stdoutRaw", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"stderr-raw" => Some(("stderrRaw", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"stdout-digest.size-bytes" => Some(("stdoutDigest.sizeBytes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"stdout-digest.hash" => Some(("stdoutDigest.hash", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"exit-code" => Some(("exitCode", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["execution-completed-timestamp", "execution-metadata", "execution-start-timestamp", "exit-code", "hash", "input-fetch-completed-timestamp", "input-fetch-start-timestamp", "output-upload-completed-timestamp", "output-upload-start-timestamp", "queued-timestamp", "size-bytes", "stderr-digest", "stderr-raw", "stdout-digest", "stdout-raw", "worker", "worker-completed-timestamp", "worker-start-timestamp"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::BuildBazelRemoteExecutionV2ActionResult = json::value::from_value(object).unwrap();
let mut call = self.hub.action_results().update(request, opt.value_of("instance-name").unwrap_or(""), opt.value_of("hash").unwrap_or(""), opt.value_of("size-bytes").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"results-cache-policy-priority" => {
call = call.results_cache_policy_priority(arg_from_str(value.unwrap_or("-0"), err, "results-cache-policy-priority", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["results-cache-policy-priority"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _actions_execute(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
"results-cache-policy.priority" => Some(("resultsCachePolicy.priority", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
"skip-cache-lookup" => Some(("skipCacheLookup", JsonTypeInfo { jtype: JsonType::Boolean, ctype: ComplexType::Pod })),
"action-digest.size-bytes" => Some(("actionDigest.sizeBytes", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"action-digest.hash" => Some(("actionDigest.hash", JsonTypeInfo { jtype: JsonType::String, ctype: ComplexType::Pod })),
"execution-policy.priority" => Some(("executionPolicy.priority", JsonTypeInfo { jtype: JsonType::Int, ctype: ComplexType::Pod })),
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec!["action-digest", "execution-policy", "hash", "priority", "results-cache-policy", "size-bytes", "skip-cache-lookup"]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::BuildBazelRemoteExecutionV2ExecuteRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.actions().execute(request, opt.value_of("instance-name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _blobs_batch_read(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec![]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::BuildBazelRemoteExecutionV2BatchReadBlobsRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.blobs().batch_read(request, opt.value_of("instance-name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _blobs_batch_update(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec![]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::BuildBazelRemoteExecutionV2BatchUpdateBlobsRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.blobs().batch_update(request, opt.value_of("instance-name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => |
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _blobs_find_missing(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec![]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::BuildBazelRemoteExecutionV2FindMissingBlobsRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.blobs().find_missing(request, opt.value_of("instance-name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _blobs_get_tree(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.blobs().get_tree(opt.value_of("instance-name").unwrap_or(""), opt.value_of("hash").unwrap_or(""), opt.value_of("size-bytes").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
"page-token" => {
call = call.page_token(value.unwrap_or(""));
},
"page-size" => {
call = call.page_size(arg_from_str(value.unwrap_or("-0"), err, "page-size", "integer"));
},
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v.extend(["page-token", "page-size"].iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _methods_get_capabilities(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut call = self.hub.methods().get_capabilities(opt.value_of("instance-name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _operations_wait_execution(&self, opt: &ArgMatches<'n>, dry_run: bool, err: &mut InvalidOptionsError)
-> Result<(), DoitError> {
let mut field_cursor = FieldCursor::default();
let mut object = json::value::Value::Object(Default::default());
for kvarg in opt.values_of("kv").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let last_errc = err.issues.len();
let (key, value) = parse_kv_arg(&*kvarg, err, false);
let mut temp_cursor = field_cursor.clone();
if let Err(field_err) = temp_cursor.set(&*key) {
err.issues.push(field_err);
}
if value.is_none() {
field_cursor = temp_cursor.clone();
if err.issues.len() > last_errc {
err.issues.remove(last_errc);
}
continue;
}
let type_info: Option<(&'static str, JsonTypeInfo)> =
match &temp_cursor.to_string()[..] {
_ => {
let suggestion = FieldCursor::did_you_mean(key, &vec![]);
err.issues.push(CLIError::Field(FieldError::Unknown(temp_cursor.to_string(), suggestion, value.map(|v| v.to_string()))));
None
}
};
if let Some((field_cursor_str, type_info)) = type_info {
FieldCursor::from(field_cursor_str).set_json_value(&mut object, value.unwrap(), type_info, err, &temp_cursor);
}
}
let mut request: api::BuildBazelRemoteExecutionV2WaitExecutionRequest = json::value::from_value(object).unwrap();
let mut call = self.hub.operations().wait_execution(request, opt.value_of("name").unwrap_or(""));
for parg in opt.values_of("v").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
let (key, value) = parse_kv_arg(&*parg, err, false);
match key {
_ => {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
}
}
}
let protocol = CallType::Standard;
if dry_run {
Ok(())
} else {
assert!(err.issues.len() == 0);
for scope in self.opt.values_of("url").map(|i|i.collect()).unwrap_or(Vec::new()).iter() {
call = call.add_scope(scope);
}
let mut ostream = match writer_from_opts(opt.value_of("out")) {
Ok(mut f) => f,
Err(io_err) => return Err(DoitError::IoError(opt.value_of("out").unwrap_or("-").to_string(), io_err)),
};
match match protocol {
CallType::Standard => call.doit(),
_ => unreachable!()
} {
Err(api_err) => Err(DoitError::ApiError(api_err)),
Ok((mut response, output_schema)) => {
let mut value = json::value::to_value(&output_schema).expect("serde to work");
remove_json_null_values(&mut value);
json::to_writer_pretty(&mut ostream, &value).unwrap();
ostream.flush().unwrap();
Ok(())
}
}
}
}
fn _doit(&self, dry_run: bool) -> Result<Result<(), DoitError>, Option<InvalidOptionsError>> {
let mut err = InvalidOptionsError::new();
let mut call_result: Result<(), DoitError> = Ok(());
let mut err_opt: Option<InvalidOptionsError> = None;
match self.opt.subcommand() {
("action-results", Some(opt)) => {
match opt.subcommand() {
("get", Some(opt)) => {
call_result = self._action_results_get(opt, dry_run, &mut err);
},
("update", Some(opt)) => {
call_result = self._action_results_update(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("action-results".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("actions", Some(opt)) => {
match opt.subcommand() {
("execute", Some(opt)) => {
call_result = self._actions_execute(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("actions".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("blobs", Some(opt)) => {
match opt.subcommand() {
("batch-read", Some(opt)) => {
call_result = self._blobs_batch_read(opt, dry_run, &mut err);
},
("batch-update", Some(opt)) => {
call_result = self._blobs_batch_update(opt, dry_run, &mut err);
},
("find-missing", Some(opt)) => {
call_result = self._blobs_find_missing(opt, dry_run, &mut err);
},
("get-tree", Some(opt)) => {
call_result = self._blobs_get_tree(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("blobs".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("methods", Some(opt)) => {
match opt.subcommand() {
("get-capabilities", Some(opt)) => {
call_result = self._methods_get_capabilities(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("methods".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
("operations", Some(opt)) => {
match opt.subcommand() {
("wait-execution", Some(opt)) => {
call_result = self._operations_wait_execution(opt, dry_run, &mut err);
},
_ => {
err.issues.push(CLIError::MissingMethodError("operations".to_string()));
writeln!(io::stderr(), "{}\n", opt.usage()).ok();
}
}
},
_ => {
err.issues.push(CLIError::MissingCommandError);
writeln!(io::stderr(), "{}\n", self.opt.usage()).ok();
}
}
if dry_run {
if err.issues.len() > 0 {
err_opt = Some(err);
}
Err(err_opt)
} else {
Ok(call_result)
}
}
// Please note that this call will fail if any part of the opt can't be handled
fn new(opt: ArgMatches<'n>) -> Result<Engine<'n>, InvalidOptionsError> {
let (config_dir, secret) = {
let config_dir = match cmn::assure_config_dir_exists(opt.value_of("folder").unwrap_or("~/.google-service-cli")) {
Err(e) => return Err(InvalidOptionsError::single(e, 3)),
Ok(p) => p,
};
match cmn::application_secret_from_directory(&config_dir, "remotebuildexecution2-secret.json",
"{\"installed\":{\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\",\"client_secret\":\"hCsslbCUyfehWMmbkG8vTYxG\",\"token_uri\":\"https://accounts.google.com/o/oauth2/token\",\"client_email\":\"\",\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"oob\"],\"client_x509_cert_url\":\"\",\"client_id\":\"620010449518-9ngf7o4dhs0dka470npqvor6dc5lqb9b.apps.googleusercontent.com\",\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"}}") {
Ok(secret) => (config_dir, secret),
Err(e) => return Err(InvalidOptionsError::single(e, 4))
}
};
let auth = Authenticator::new( &secret, DefaultAuthenticatorDelegate,
if opt.is_present("debug-auth") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
},
JsonTokenStorage {
program_name: "remotebuildexecution2",
db_dir: config_dir.clone(),
}, Some(FlowType::InstalledRedirect(54324)));
let client =
if opt.is_present("debug") {
hyper::Client::with_connector(mock::TeeConnector {
connector: hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())
})
} else {
hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new()))
};
let engine = Engine {
opt: opt,
hub: api::RemoteBuildExecution::new(client, auth),
gp: vec!["$-xgafv", "access-token", "alt", "callback", "fields", "key", "oauth-token", "pretty-print", "quota-user", "upload-type", "upload-protocol"],
gpm: vec![
("$-xgafv", "$.xgafv"),
("access-token", "access_token"),
("oauth-token", "oauth_token"),
("pretty-print", "prettyPrint"),
("quota-user", "quotaUser"),
("upload-type", "uploadType"),
("upload-protocol", "upload_protocol"),
]
};
match engine._doit(true) {
Err(Some(err)) => Err(err),
Err(None) => Ok(engine),
Ok(_) => unreachable!(),
}
}
fn doit(&self) -> Result<(), DoitError> {
match self._doit(false) {
Ok(res) => res,
Err(_) => unreachable!(),
}
}
}
fn main() {
let mut exit_status = 0i32;
let arg_data = [
("action-results", "methods: 'get' and 'update'", vec![
("get",
Some(r##"Retrieve a cached execution result.
Implementations SHOULD ensure that any blobs referenced from the
ContentAddressableStorage
are available at the time of returning the
ActionResult and will be
for some period of time afterwards. The TTLs of the referenced blobs SHOULD be increased
if necessary and applicable.
Errors:
* `NOT_FOUND`: The requested `ActionResult` is not in the cache."##),
"Details at http://byron.github.io/google-apis-rs/google_remotebuildexecution2_cli/action-results_get",
vec![
(Some(r##"instance-name"##),
None,
Some(r##"The instance of the execution system to operate against. A server may
support multiple instances of the execution system (with their own workers,
storage, caches, etc.). The server MAY require use of this field to select
between them in an implementation-defined fashion, otherwise it can be
omitted."##),
Some(true),
Some(false)),
(Some(r##"hash"##),
None,
Some(r##"The hash. In the case of SHA-256, it will always be a lowercase hex string
exactly 64 characters long."##),
Some(true),
Some(false)),
(Some(r##"size-bytes"##),
None,
Some(r##"The size of the blob, in bytes."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("update",
Some(r##"Upload a new execution result.
In order to allow the server to perform access control based on the type of
action, and to assist with client debugging, the client MUST first upload
the Action that produced the
result, along with its
Command, into the
`ContentAddressableStorage`.
Errors:
* `INVALID_ARGUMENT`: One or more arguments are invalid.
* `FAILED_PRECONDITION`: One or more errors occurred in updating the
action result, such as a missing command or action.
* `RESOURCE_EXHAUSTED`: There is insufficient storage space to add the
entry to the cache."##),
"Details at http://byron.github.io/google-apis-rs/google_remotebuildexecution2_cli/action-results_update",
vec![
(Some(r##"instance-name"##),
None,
Some(r##"The instance of the execution system to operate against. A server may
support multiple instances of the execution system (with their own workers,
storage, caches, etc.). The server MAY require use of this field to select
between them in an implementation-defined fashion, otherwise it can be
omitted."##),
Some(true),
Some(false)),
(Some(r##"hash"##),
None,
Some(r##"The hash. In the case of SHA-256, it will always be a lowercase hex string
exactly 64 characters long."##),
Some(true),
Some(false)),
(Some(r##"size-bytes"##),
None,
Some(r##"The size of the blob, in bytes."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("actions", "methods: 'execute'", vec![
("execute",
Some(r##"Execute an action remotely.
In order to execute an action, the client must first upload all of the
inputs, the
Command to run, and the
Action into the
ContentAddressableStorage.
It then calls `Execute` with an `action_digest` referring to them. The
server will run the action and eventually return the result.
The input `Action`'s fields MUST meet the various canonicalization
requirements specified in the documentation for their types so that it has
the same digest as other logically equivalent `Action`s. The server MAY
enforce the requirements and return errors if a non-canonical input is
received. It MAY also proceed without verifying some or all of the
requirements, such as for performance reasons. If the server does not
verify the requirement, then it will treat the `Action` as distinct from
another logically equivalent action if they hash differently.
Returns a stream of
google.longrunning.Operation messages
describing the resulting execution, with eventual `response`
ExecuteResponse. The
`metadata` on the operation is of type
ExecuteOperationMetadata.
If the client remains connected after the first response is returned after
the server, then updates are streamed as if the client had called
WaitExecution
until the execution completes or the request reaches an error. The
operation can also be queried using Operations
API.
The server NEED NOT implement other methods or functionality of the
Operations API.
Errors discovered during creation of the `Operation` will be reported
as gRPC Status errors, while errors that occurred while running the
action will be reported in the `status` field of the `ExecuteResponse`. The
server MUST NOT set the `error` field of the `Operation` proto.
The possible errors include:
* `INVALID_ARGUMENT`: One or more arguments are invalid.
* `FAILED_PRECONDITION`: One or more errors occurred in setting up the
action requested, such as a missing input or command or no worker being
available. The client may be able to fix the errors and retry.
* `RESOURCE_EXHAUSTED`: There is insufficient quota of some resource to run
the action.
* `UNAVAILABLE`: Due to a transient condition, such as all workers being
occupied (and the server does not support a queue), the action could not
be started. The client should retry.
* `INTERNAL`: An internal error occurred in the execution engine or the
worker.
* `DEADLINE_EXCEEDED`: The execution timed out.
* `CANCELLED`: The operation was cancelled by the client. This status is
only possible if the server implements the Operations API CancelOperation
method, and it was called for the current execution.
In the case of a missing input or command, the server SHOULD additionally
send a PreconditionFailure error detail
where, for each requested blob not present in the CAS, there is a
`Violation` with a `type` of `MISSING` and a `subject` of
`"blobs/{hash}/{size}"` indicating the digest of the missing blob."##),
"Details at http://byron.github.io/google-apis-rs/google_remotebuildexecution2_cli/actions_execute",
vec![
(Some(r##"instance-name"##),
None,
Some(r##"The instance of the execution system to operate against. A server may
support multiple instances of the execution system (with their own workers,
storage, caches, etc.). The server MAY require use of this field to select
between them in an implementation-defined fashion, otherwise it can be
omitted."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("blobs", "methods: 'batch-read', 'batch-update', 'find-missing' and 'get-tree'", vec![
("batch-read",
Some(r##"Download many blobs at once.
The server may enforce a limit of the combined total size of blobs
to be downloaded using this API. This limit may be obtained using the
Capabilities API.
Requests exceeding the limit should either be split into smaller
chunks or downloaded using the
ByteStream API, as appropriate.
This request is equivalent to calling a Bytestream `Read` request
on each individual blob, in parallel. The requests may succeed or fail
independently.
Errors:
* `INVALID_ARGUMENT`: The client attempted to read more than the
server supported limit.
Every error on individual read will be returned in the corresponding digest
status."##),
"Details at http://byron.github.io/google-apis-rs/google_remotebuildexecution2_cli/blobs_batch-read",
vec![
(Some(r##"instance-name"##),
None,
Some(r##"The instance of the execution system to operate against. A server may
support multiple instances of the execution system (with their own workers,
storage, caches, etc.). The server MAY require use of this field to select
between them in an implementation-defined fashion, otherwise it can be
omitted."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("batch-update",
Some(r##"Upload many blobs at once.
The server may enforce a limit of the combined total size of blobs
to be uploaded using this API. This limit may be obtained using the
Capabilities API.
Requests exceeding the limit should either be split into smaller
chunks or uploaded using the
ByteStream API, as appropriate.
This request is equivalent to calling a Bytestream `Write` request
on each individual blob, in parallel. The requests may succeed or fail
independently.
Errors:
* `INVALID_ARGUMENT`: The client attempted to upload more than the
server supported limit.
Individual requests may return the following errors, additionally:
* `RESOURCE_EXHAUSTED`: There is insufficient disk quota to store the blob.
* `INVALID_ARGUMENT`: The
Digest does not match the
provided data."##),
"Details at http://byron.github.io/google-apis-rs/google_remotebuildexecution2_cli/blobs_batch-update",
vec![
(Some(r##"instance-name"##),
None,
Some(r##"The instance of the execution system to operate against. A server may
support multiple instances of the execution system (with their own workers,
storage, caches, etc.). The server MAY require use of this field to select
between them in an implementation-defined fashion, otherwise it can be
omitted."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("find-missing",
Some(r##"Determine if blobs are present in the CAS.
Clients can use this API before uploading blobs to determine which ones are
already present in the CAS and do not need to be uploaded again.
Servers SHOULD increase the TTLs of the referenced blobs if necessary and
applicable.
There are no method-specific errors."##),
"Details at http://byron.github.io/google-apis-rs/google_remotebuildexecution2_cli/blobs_find-missing",
vec![
(Some(r##"instance-name"##),
None,
Some(r##"The instance of the execution system to operate against. A server may
support multiple instances of the execution system (with their own workers,
storage, caches, etc.). The server MAY require use of this field to select
between them in an implementation-defined fashion, otherwise it can be
omitted."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
("get-tree",
Some(r##"Fetch the entire directory tree rooted at a node.
This request must be targeted at a
Directory stored in the
ContentAddressableStorage
(CAS). The server will enumerate the `Directory` tree recursively and
return every node descended from the root.
The GetTreeRequest.page_token parameter can be used to skip ahead in
the stream (e.g. when retrying a partially completed and aborted request),
by setting it to a value taken from GetTreeResponse.next_page_token of the
last successfully processed GetTreeResponse).
The exact traversal order is unspecified and, unless retrieving subsequent
pages from an earlier request, is not guaranteed to be stable across
multiple invocations of `GetTree`.
If part of the tree is missing from the CAS, the server will return the
portion present and omit the rest.
Errors:
* `NOT_FOUND`: The requested tree root is not present in the CAS."##),
"Details at http://byron.github.io/google-apis-rs/google_remotebuildexecution2_cli/blobs_get-tree",
vec![
(Some(r##"instance-name"##),
None,
Some(r##"The instance of the execution system to operate against. A server may
support multiple instances of the execution system (with their own workers,
storage, caches, etc.). The server MAY require use of this field to select
between them in an implementation-defined fashion, otherwise it can be
omitted."##),
Some(true),
Some(false)),
(Some(r##"hash"##),
None,
Some(r##"The hash. In the case of SHA-256, it will always be a lowercase hex string
exactly 64 characters long."##),
Some(true),
Some(false)),
(Some(r##"size-bytes"##),
None,
Some(r##"The size of the blob, in bytes."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("methods", "methods: 'get-capabilities'", vec![
("get-capabilities",
Some(r##"GetCapabilities returns the server capabilities configuration of the
remote endpoint.
Only the capabilities of the services supported by the endpoint will
be returned:
* Execution + CAS + Action Cache endpoints should return both
CacheCapabilities and ExecutionCapabilities.
* Execution only endpoints should return ExecutionCapabilities.
* CAS + Action Cache only endpoints should return CacheCapabilities."##),
"Details at http://byron.github.io/google-apis-rs/google_remotebuildexecution2_cli/methods_get-capabilities",
vec![
(Some(r##"instance-name"##),
None,
Some(r##"The instance of the execution system to operate against. A server may
support multiple instances of the execution system (with their own workers,
storage, caches, etc.). The server MAY require use of this field to select
between them in an implementation-defined fashion, otherwise it can be
omitted."##),
Some(true),
Some(false)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
("operations", "methods: 'wait-execution'", vec![
("wait-execution",
Some(r##"Wait for an execution operation to complete. When the client initially
makes the request, the server immediately responds with the current status
of the execution. The server will leave the request stream open until the
operation completes, and then respond with the completed operation. The
server MAY choose to stream additional updates as execution progresses,
such as to provide an update as to the state of the execution."##),
"Details at http://byron.github.io/google-apis-rs/google_remotebuildexecution2_cli/operations_wait-execution",
vec![
(Some(r##"name"##),
None,
Some(r##"The name of the Operation
returned by Execute."##),
Some(true),
Some(false)),
(Some(r##"kv"##),
Some(r##"r"##),
Some(r##"Set various fields of the request structure, matching the key=value form"##),
Some(true),
Some(true)),
(Some(r##"v"##),
Some(r##"p"##),
Some(r##"Set various optional parameters, matching the key=value form"##),
Some(false),
Some(true)),
(Some(r##"out"##),
Some(r##"o"##),
Some(r##"Specify the file into which to write the program's output"##),
Some(false),
Some(false)),
]),
]),
];
let mut app = App::new("remotebuildexecution2")
.author("Sebastian Thiel <[email protected]>")
.version("1.0.14+20200702")
.about("Supplies a Remote Execution API service for tools such as bazel.")
.after_help("All documentation details can be found at http://byron.github.io/google-apis-rs/google_remotebuildexecution2_cli")
.arg(Arg::with_name("url")
.long("scope")
.help("Specify the authentication a method should be executed in. Each scope requires the user to grant this application permission to use it.If unset, it defaults to the shortest scope url for a particular method.")
.multiple(true)
.takes_value(true))
.arg(Arg::with_name("folder")
.long("config-dir")
.help("A directory into which we will store our persistent data. Defaults to a user-writable directory that we will create during the first invocation.[default: ~/.google-service-cli")
.multiple(false)
.takes_value(true))
.arg(Arg::with_name("debug")
.long("debug")
.help("Output all server communication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false))
.arg(Arg::with_name("debug-auth")
.long("debug-auth")
.help("Output all communication related to authentication to standard error. `tx` and `rx` are placed into the same stream.")
.multiple(false)
.takes_value(false));
for &(main_command_name, about, ref subcommands) in arg_data.iter() {
let mut mcmd = SubCommand::with_name(main_command_name).about(about);
for &(sub_command_name, ref desc, url_info, ref args) in subcommands {
let mut scmd = SubCommand::with_name(sub_command_name);
if let &Some(desc) = desc {
scmd = scmd.about(desc);
}
scmd = scmd.after_help(url_info);
for &(ref arg_name, ref flag, ref desc, ref required, ref multi) in args {
let arg_name_str =
match (arg_name, flag) {
(&Some(an), _ ) => an,
(_ , &Some(f)) => f,
_ => unreachable!(),
};
let mut arg = Arg::with_name(arg_name_str)
.empty_values(false);
if let &Some(short_flag) = flag {
arg = arg.short(short_flag);
}
if let &Some(desc) = desc {
arg = arg.help(desc);
}
if arg_name.is_some() && flag.is_some() {
arg = arg.takes_value(true);
}
if let &Some(required) = required {
arg = arg.required(required);
}
if let &Some(multi) = multi {
arg = arg.multiple(multi);
}
scmd = scmd.arg(arg);
}
mcmd = mcmd.subcommand(scmd);
}
app = app.subcommand(mcmd);
}
let matches = app.get_matches();
let debug = matches.is_present("debug");
match Engine::new(matches) {
Err(err) => {
exit_status = err.exit_code;
writeln!(io::stderr(), "{}", err).ok();
},
Ok(engine) => {
if let Err(doit_err) = engine.doit() {
exit_status = 1;
match doit_err {
DoitError::IoError(path, err) => {
writeln!(io::stderr(), "Failed to open output file '{}': {}", path, err).ok();
},
DoitError::ApiError(err) => {
if debug {
writeln!(io::stderr(), "{:#?}", err).ok();
} else {
writeln!(io::stderr(), "{}", err).ok();
}
}
}
}
}
}
std::process::exit(exit_status);
} | {
let mut found = false;
for param in &self.gp {
if key == *param {
found = true;
call = call.param(self.gpm.iter().find(|t| t.0 == key).unwrap_or(&("", key)).1, value.unwrap_or("unset"));
break;
}
}
if !found {
err.issues.push(CLIError::UnknownParameter(key.to_string(),
{let mut v = Vec::new();
v.extend(self.gp.iter().map(|v|*v));
v } ));
}
} |
client.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# 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 collections import OrderedDict
from distutils import util
import os
import re
from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib # type: ignore
from google.api_core import exceptions as core_exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.auth.transport import mtls # type: ignore
from google.auth.transport.grpc import SslCredentials # type: ignore
from google.auth.exceptions import MutualTLSChannelError # type: ignore
from google.oauth2 import service_account # type: ignore
from google.cloud.monitoring_v3.services.alert_policy_service import pagers
from google.cloud.monitoring_v3.types import alert
from google.cloud.monitoring_v3.types import alert_service
from google.cloud.monitoring_v3.types import mutation_record
from google.protobuf import field_mask_pb2 # type: ignore
from google.protobuf import wrappers_pb2 # type: ignore
from google.rpc import status_pb2 # type: ignore
from .transports.base import AlertPolicyServiceTransport, DEFAULT_CLIENT_INFO
from .transports.grpc import AlertPolicyServiceGrpcTransport
from .transports.grpc_asyncio import AlertPolicyServiceGrpcAsyncIOTransport
class | (type):
"""Metaclass for the AlertPolicyService client.
This provides class-level methods for building and retrieving
support objects (e.g. transport) without polluting the client instance
objects.
"""
_transport_registry = (
OrderedDict()
) # type: Dict[str, Type[AlertPolicyServiceTransport]]
_transport_registry["grpc"] = AlertPolicyServiceGrpcTransport
_transport_registry["grpc_asyncio"] = AlertPolicyServiceGrpcAsyncIOTransport
def get_transport_class(
cls, label: str = None,
) -> Type[AlertPolicyServiceTransport]:
"""Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use.
"""
# If a specific transport is requested, return that one.
if label:
return cls._transport_registry[label]
# No transport is requested; return the default (that is, the first one
# in the dictionary).
return next(iter(cls._transport_registry.values()))
class AlertPolicyServiceClient(metaclass=AlertPolicyServiceClientMeta):
"""The AlertPolicyService API is used to manage (list, create, delete,
edit) alert policies in Stackdriver Monitoring. An alerting policy
is a description of the conditions under which some aspect of your
system is considered to be "unhealthy" and the ways to notify people
or services about this state. In addition to using this API, alert
policies can also be managed through `Stackdriver
Monitoring <https://cloud.google.com/monitoring/docs/>`__, which can
be reached by clicking the "Monitoring" tab in `Cloud
Console <https://console.cloud.google.com/>`__.
"""
@staticmethod
def _get_default_mtls_endpoint(api_endpoint):
"""Converts api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint.
"""
if not api_endpoint:
return api_endpoint
mtls_endpoint_re = re.compile(
r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
)
m = mtls_endpoint_re.match(api_endpoint)
name, mtls, sandbox, googledomain = m.groups()
if mtls or not googledomain:
return api_endpoint
if sandbox:
return api_endpoint.replace(
"sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
)
return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
DEFAULT_ENDPOINT = "monitoring.googleapis.com"
DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
DEFAULT_ENDPOINT
)
@classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
info.
Args:
info (dict): The service account private key info.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
AlertPolicyServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_info(info)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
@classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
AlertPolicyServiceClient: The constructed client.
"""
credentials = service_account.Credentials.from_service_account_file(filename)
kwargs["credentials"] = credentials
return cls(*args, **kwargs)
from_service_account_json = from_service_account_file
@property
def transport(self) -> AlertPolicyServiceTransport:
"""Returns the transport used by the client instance.
Returns:
AlertPolicyServiceTransport: The transport used by the client
instance.
"""
return self._transport
@staticmethod
def alert_policy_path(project: str, alert_policy: str,) -> str:
"""Returns a fully-qualified alert_policy string."""
return "projects/{project}/alertPolicies/{alert_policy}".format(
project=project, alert_policy=alert_policy,
)
@staticmethod
def parse_alert_policy_path(path: str) -> Dict[str, str]:
"""Parses a alert_policy path into its component segments."""
m = re.match(
r"^projects/(?P<project>.+?)/alertPolicies/(?P<alert_policy>.+?)$", path
)
return m.groupdict() if m else {}
@staticmethod
def alert_policy_condition_path(
project: str, alert_policy: str, condition: str,
) -> str:
"""Returns a fully-qualified alert_policy_condition string."""
return "projects/{project}/alertPolicies/{alert_policy}/conditions/{condition}".format(
project=project, alert_policy=alert_policy, condition=condition,
)
@staticmethod
def parse_alert_policy_condition_path(path: str) -> Dict[str, str]:
"""Parses a alert_policy_condition path into its component segments."""
m = re.match(
r"^projects/(?P<project>.+?)/alertPolicies/(?P<alert_policy>.+?)/conditions/(?P<condition>.+?)$",
path,
)
return m.groupdict() if m else {}
@staticmethod
def common_billing_account_path(billing_account: str,) -> str:
"""Returns a fully-qualified billing_account string."""
return "billingAccounts/{billing_account}".format(
billing_account=billing_account,
)
@staticmethod
def parse_common_billing_account_path(path: str) -> Dict[str, str]:
"""Parse a billing_account path into its component segments."""
m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_folder_path(folder: str,) -> str:
"""Returns a fully-qualified folder string."""
return "folders/{folder}".format(folder=folder,)
@staticmethod
def parse_common_folder_path(path: str) -> Dict[str, str]:
"""Parse a folder path into its component segments."""
m = re.match(r"^folders/(?P<folder>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_organization_path(organization: str,) -> str:
"""Returns a fully-qualified organization string."""
return "organizations/{organization}".format(organization=organization,)
@staticmethod
def parse_common_organization_path(path: str) -> Dict[str, str]:
"""Parse a organization path into its component segments."""
m = re.match(r"^organizations/(?P<organization>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_project_path(project: str,) -> str:
"""Returns a fully-qualified project string."""
return "projects/{project}".format(project=project,)
@staticmethod
def parse_common_project_path(path: str) -> Dict[str, str]:
"""Parse a project path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)$", path)
return m.groupdict() if m else {}
@staticmethod
def common_location_path(project: str, location: str,) -> str:
"""Returns a fully-qualified location string."""
return "projects/{project}/locations/{location}".format(
project=project, location=location,
)
@staticmethod
def parse_common_location_path(path: str) -> Dict[str, str]:
"""Parse a location path into its component segments."""
m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
return m.groupdict() if m else {}
def __init__(
self,
*,
credentials: Optional[ga_credentials.Credentials] = None,
transport: Union[str, AlertPolicyServiceTransport, None] = None,
client_options: Optional[client_options_lib.ClientOptions] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
) -> None:
"""Instantiates the alert policy service client.
Args:
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
transport (Union[str, AlertPolicyServiceTransport]): The
transport to use. If set to None, a transport is chosen
automatically.
client_options (google.api_core.client_options.ClientOptions): Custom options for the
client. It won't take effect if a ``transport`` instance is provided.
(1) The ``api_endpoint`` property can be used to override the
default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
environment variable can also be used to override the endpoint:
"always" (always use the default mTLS endpoint), "never" (always
use the default regular endpoint) and "auto" (auto switch to the
default mTLS endpoint if client certificate is present, this is
the default value). However, the ``api_endpoint`` property takes
precedence if provided.
(2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
is "true", then the ``client_cert_source`` property can be used
to provide client certificate for mutual TLS transport. If
not provided, the default SSL client certificate will be used if
present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
set, no client certificate will be used.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
Raises:
google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
creation failed for any reason.
"""
if isinstance(client_options, dict):
client_options = client_options_lib.from_dict(client_options)
if client_options is None:
client_options = client_options_lib.ClientOptions()
# Create SSL credentials for mutual TLS if needed.
use_client_cert = bool(
util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"))
)
client_cert_source_func = None
is_mtls = False
if use_client_cert:
if client_options.client_cert_source:
is_mtls = True
client_cert_source_func = client_options.client_cert_source
else:
is_mtls = mtls.has_default_client_cert_source()
if is_mtls:
client_cert_source_func = mtls.default_client_cert_source()
else:
client_cert_source_func = None
# Figure out which api endpoint to use.
if client_options.api_endpoint is not None:
api_endpoint = client_options.api_endpoint
else:
use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
if use_mtls_env == "never":
api_endpoint = self.DEFAULT_ENDPOINT
elif use_mtls_env == "always":
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
elif use_mtls_env == "auto":
if is_mtls:
api_endpoint = self.DEFAULT_MTLS_ENDPOINT
else:
api_endpoint = self.DEFAULT_ENDPOINT
else:
raise MutualTLSChannelError(
"Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted "
"values: never, auto, always"
)
# Save or instantiate the transport.
# Ordinarily, we provide the transport, but allowing a custom transport
# instance provides an extensibility point for unusual situations.
if isinstance(transport, AlertPolicyServiceTransport):
# transport is a AlertPolicyServiceTransport instance.
if credentials or client_options.credentials_file:
raise ValueError(
"When providing a transport instance, "
"provide its credentials directly."
)
if client_options.scopes:
raise ValueError(
"When providing a transport instance, provide its scopes "
"directly."
)
self._transport = transport
else:
Transport = type(self).get_transport_class(transport)
self._transport = Transport(
credentials=credentials,
credentials_file=client_options.credentials_file,
host=api_endpoint,
scopes=client_options.scopes,
client_cert_source_for_mtls=client_cert_source_func,
quota_project_id=client_options.quota_project_id,
client_info=client_info,
always_use_jwt_access=(
Transport == type(self).get_transport_class("grpc")
or Transport == type(self).get_transport_class("grpc_asyncio")
),
)
def list_alert_policies(
self,
request: alert_service.ListAlertPoliciesRequest = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListAlertPoliciesPager:
r"""Lists the existing alerting policies for the
workspace.
Args:
request (google.cloud.monitoring_v3.types.ListAlertPoliciesRequest):
The request object. The protocol for the
`ListAlertPolicies` request.
name (str):
Required. The
`project <https://cloud.google.com/monitoring/api/v3#project_name>`__
whose alert policies are to be listed. The format is:
::
projects/[PROJECT_ID_OR_NUMBER]
Note that this field names the parent container in which
the alerting policies to be listed are stored. To
retrieve a single alerting policy by name, use the
[GetAlertPolicy][google.monitoring.v3.AlertPolicyService.GetAlertPolicy]
operation, instead.
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.monitoring_v3.services.alert_policy_service.pagers.ListAlertPoliciesPager:
The protocol for the ListAlertPolicies response.
Iterating over this object will yield results and
resolve additional pages automatically.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a alert_service.ListAlertPoliciesRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, alert_service.ListAlertPoliciesRequest):
request = alert_service.ListAlertPoliciesRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.list_alert_policies]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# This method is paged; wrap the response in a pager, which provides
# an `__iter__` convenience method.
response = pagers.ListAlertPoliciesPager(
method=rpc, request=request, response=response, metadata=metadata,
)
# Done; return the response.
return response
def get_alert_policy(
self,
request: alert_service.GetAlertPolicyRequest = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> alert.AlertPolicy:
r"""Gets a single alerting policy.
Args:
request (google.cloud.monitoring_v3.types.GetAlertPolicyRequest):
The request object. The protocol for the
`GetAlertPolicy` request.
name (str):
Required. The alerting policy to retrieve. The format
is:
::
projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID]
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.monitoring_v3.types.AlertPolicy:
A description of the conditions under which some aspect of your system is
considered to be "unhealthy" and the ways to notify
people or services about this state. For an overview
of alert policies, see [Introduction to
Alerting](\ https://cloud.google.com/monitoring/alerts/).
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a alert_service.GetAlertPolicyRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, alert_service.GetAlertPolicyRequest):
request = alert_service.GetAlertPolicyRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.get_alert_policy]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def create_alert_policy(
self,
request: alert_service.CreateAlertPolicyRequest = None,
*,
name: str = None,
alert_policy: alert.AlertPolicy = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> alert.AlertPolicy:
r"""Creates a new alerting policy.
Args:
request (google.cloud.monitoring_v3.types.CreateAlertPolicyRequest):
The request object. The protocol for the
`CreateAlertPolicy` request.
name (str):
Required. The
`project <https://cloud.google.com/monitoring/api/v3#project_name>`__
in which to create the alerting policy. The format is:
::
projects/[PROJECT_ID_OR_NUMBER]
Note that this field names the parent container in which
the alerting policy will be written, not the name of the
created policy. \|name\| must be a host project of a
workspace, otherwise INVALID_ARGUMENT error will return.
The alerting policy that is returned will have a name
that contains a normalized representation of this name
as a prefix but adds a suffix of the form
``/alertPolicies/[ALERT_POLICY_ID]``, identifying the
policy in the container.
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
alert_policy (google.cloud.monitoring_v3.types.AlertPolicy):
Required. The requested alerting policy. You should omit
the ``name`` field in this policy. The name will be
returned in the new policy, including a new
``[ALERT_POLICY_ID]`` value.
This corresponds to the ``alert_policy`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.monitoring_v3.types.AlertPolicy:
A description of the conditions under which some aspect of your system is
considered to be "unhealthy" and the ways to notify
people or services about this state. For an overview
of alert policies, see [Introduction to
Alerting](\ https://cloud.google.com/monitoring/alerts/).
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name, alert_policy])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a alert_service.CreateAlertPolicyRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, alert_service.CreateAlertPolicyRequest):
request = alert_service.CreateAlertPolicyRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
if alert_policy is not None:
request.alert_policy = alert_policy
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.create_alert_policy]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
def delete_alert_policy(
self,
request: alert_service.DeleteAlertPolicyRequest = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> None:
r"""Deletes an alerting policy.
Args:
request (google.cloud.monitoring_v3.types.DeleteAlertPolicyRequest):
The request object. The protocol for the
`DeleteAlertPolicy` request.
name (str):
Required. The alerting policy to delete. The format is:
::
projects/[PROJECT_ID_OR_NUMBER]/alertPolicies/[ALERT_POLICY_ID]
For more information, see
[AlertPolicy][google.monitoring.v3.AlertPolicy].
This corresponds to the ``name`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([name])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a alert_service.DeleteAlertPolicyRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, alert_service.DeleteAlertPolicyRequest):
request = alert_service.DeleteAlertPolicyRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if name is not None:
request.name = name
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.delete_alert_policy]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
)
# Send the request.
rpc(
request, retry=retry, timeout=timeout, metadata=metadata,
)
def update_alert_policy(
self,
request: alert_service.UpdateAlertPolicyRequest = None,
*,
update_mask: field_mask_pb2.FieldMask = None,
alert_policy: alert.AlertPolicy = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> alert.AlertPolicy:
r"""Updates an alerting policy. You can either replace the entire
policy with a new one or replace only certain fields in the
current alerting policy by specifying the fields to be updated
via ``updateMask``. Returns the updated alerting policy.
Args:
request (google.cloud.monitoring_v3.types.UpdateAlertPolicyRequest):
The request object. The protocol for the
`UpdateAlertPolicy` request.
update_mask (google.protobuf.field_mask_pb2.FieldMask):
Optional. A list of alerting policy field names. If this
field is not empty, each listed field in the existing
alerting policy is set to the value of the corresponding
field in the supplied policy (``alert_policy``), or to
the field's default value if the field is not in the
supplied alerting policy. Fields not listed retain their
previous value.
Examples of valid field masks include ``display_name``,
``documentation``, ``documentation.content``,
``documentation.mime_type``, ``user_labels``,
``user_label.nameofkey``, ``enabled``, ``conditions``,
``combiner``, etc.
If this field is empty, then the supplied alerting
policy replaces the existing policy. It is the same as
deleting the existing policy and adding the supplied
policy, except for the following:
- The new policy will have the same
``[ALERT_POLICY_ID]`` as the former policy. This
gives you continuity with the former policy in your
notifications and incidents.
- Conditions in the new policy will keep their former
``[CONDITION_ID]`` if the supplied condition includes
the ``name`` field with that ``[CONDITION_ID]``. If
the supplied condition omits the ``name`` field, then
a new ``[CONDITION_ID]`` is created.
This corresponds to the ``update_mask`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
alert_policy (google.cloud.monitoring_v3.types.AlertPolicy):
Required. The updated alerting policy or the updated
values for the fields listed in ``update_mask``. If
``update_mask`` is not empty, any fields in this policy
that are not in ``update_mask`` are ignored.
This corresponds to the ``alert_policy`` field
on the ``request`` instance; if ``request`` is provided, this
should not be set.
retry (google.api_core.retry.Retry): Designation of what errors, if any,
should be retried.
timeout (float): The timeout for this request.
metadata (Sequence[Tuple[str, str]]): Strings which should be
sent along with the request as metadata.
Returns:
google.cloud.monitoring_v3.types.AlertPolicy:
A description of the conditions under which some aspect of your system is
considered to be "unhealthy" and the ways to notify
people or services about this state. For an overview
of alert policies, see [Introduction to
Alerting](\ https://cloud.google.com/monitoring/alerts/).
"""
# Create or coerce a protobuf request object.
# Sanity check: If we got a request object, we should *not* have
# gotten any keyword arguments that map to the request.
has_flattened_params = any([update_mask, alert_policy])
if request is not None and has_flattened_params:
raise ValueError(
"If the `request` argument is set, then none of "
"the individual field arguments should be set."
)
# Minor optimization to avoid making a copy if the user passes
# in a alert_service.UpdateAlertPolicyRequest.
# There's no risk of modifying the input as we've already verified
# there are no flattened fields.
if not isinstance(request, alert_service.UpdateAlertPolicyRequest):
request = alert_service.UpdateAlertPolicyRequest(request)
# If we have keyword arguments corresponding to fields on the
# request, apply these.
if update_mask is not None:
request.update_mask = update_mask
if alert_policy is not None:
request.alert_policy = alert_policy
# Wrap the RPC method; this adds retry and timeout information,
# and friendly error handling.
rpc = self._transport._wrapped_methods[self._transport.update_alert_policy]
# Certain fields should be provided within the metadata header;
# add these here.
metadata = tuple(metadata) + (
gapic_v1.routing_header.to_grpc_metadata(
(("alert_policy.name", request.alert_policy.name),)
),
)
# Send the request.
response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,)
# Done; return the response.
return response
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
"google-cloud-monitoring",
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
__all__ = ("AlertPolicyServiceClient",)
| AlertPolicyServiceClientMeta |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.