code
stringlengths 1
25.8M
| language
stringclasses 18
values | source
stringclasses 4
values | repo
stringclasses 78
values | path
stringlengths 0
268
|
|---|---|---|---|---|
//// [tests/cases/compiler/abstractPropertyNegative.ts] ////
//// [abstractPropertyNegative.ts]
interface A {
prop: string;
m(): string;
}
abstract class B implements A {
abstract prop: string;
public abstract readonly ro: string;
abstract get readonlyProp(): string;
abstract m(): string;
abstract get mismatch(): string;
abstract set mismatch(val: number);
}
class C extends B {
readonly ro = "readonly please";
abstract notAllowed: string;
get concreteWithNoBody(): string;
}
let c = new C();
c.ro = "error: lhs of assignment can't be readonly";
abstract class WrongTypeProperty {
abstract num: number;
}
class WrongTypePropertyImpl extends WrongTypeProperty {
num = "nope, wrong";
}
abstract class WrongTypeAccessor {
abstract get num(): number;
}
class WrongTypeAccessorImpl extends WrongTypeAccessor {
get num() { return "nope, wrong"; }
}
class WrongTypeAccessorImpl2 extends WrongTypeAccessor {
num = "nope, wrong";
}
abstract class AbstractAccessorMismatch {
abstract get p1(): string;
set p1(val: string) { };
get p2(): string { return "should work"; }
abstract set p2(val: string);
}
//// [abstractPropertyNegative.js]
"use strict";
class B {
}
class C extends B {
constructor() {
super(...arguments);
this.ro = "readonly please";
}
get concreteWithNoBody() { }
}
let c = new C();
c.ro = "error: lhs of assignment can't be readonly";
class WrongTypeProperty {
}
class WrongTypePropertyImpl extends WrongTypeProperty {
constructor() {
super(...arguments);
this.num = "nope, wrong";
}
}
class WrongTypeAccessor {
}
class WrongTypeAccessorImpl extends WrongTypeAccessor {
get num() { return "nope, wrong"; }
}
class WrongTypeAccessorImpl2 extends WrongTypeAccessor {
constructor() {
super(...arguments);
this.num = "nope, wrong";
}
}
class AbstractAccessorMismatch {
set p1(val) { }
;
get p2() { return "should work"; }
}
|
javascript
|
github
|
https://github.com/microsoft/TypeScript
|
tests/baselines/reference/abstractPropertyNegative(target=es2015).js
|
"""
Testing for mean shift clustering methods
"""
import numpy as np
import warnings
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_false
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raise_message
from sklearn.cluster import MeanShift
from sklearn.cluster import mean_shift
from sklearn.cluster import estimate_bandwidth
from sklearn.cluster import get_bin_seeds
from sklearn.datasets.samples_generator import make_blobs
n_clusters = 3
centers = np.array([[1, 1], [-1, -1], [1, -1]]) + 10
X, _ = make_blobs(n_samples=300, n_features=2, centers=centers,
cluster_std=0.4, shuffle=True, random_state=11)
def test_estimate_bandwidth():
# Test estimate_bandwidth
bandwidth = estimate_bandwidth(X, n_samples=200)
assert_true(0.9 <= bandwidth <= 1.5)
def test_mean_shift():
# Test MeanShift algorithm
bandwidth = 1.2
ms = MeanShift(bandwidth=bandwidth)
labels = ms.fit(X).labels_
labels_unique = np.unique(labels)
n_clusters_ = len(labels_unique)
assert_equal(n_clusters_, n_clusters)
cluster_centers, labels = mean_shift(X, bandwidth=bandwidth)
labels_unique = np.unique(labels)
n_clusters_ = len(labels_unique)
assert_equal(n_clusters_, n_clusters)
def test_parallel():
ms1 = MeanShift(n_jobs=2)
ms1.fit(X)
ms2 = MeanShift()
ms2.fit(X)
assert_array_equal(ms1.cluster_centers_,ms2.cluster_centers_)
assert_array_equal(ms1.labels_,ms2.labels_)
def test_meanshift_predict():
# Test MeanShift.predict
ms = MeanShift(bandwidth=1.2)
labels = ms.fit_predict(X)
labels2 = ms.predict(X)
assert_array_equal(labels, labels2)
def test_meanshift_all_orphans():
# init away from the data, crash with a sensible warning
ms = MeanShift(bandwidth=0.1, seeds=[[-9, -9], [-10, -10]])
msg = "No point was within bandwidth=0.1"
assert_raise_message(ValueError, msg, ms.fit, X,)
def test_unfitted():
# Non-regression: before fit, there should be not fitted attributes.
ms = MeanShift()
assert_false(hasattr(ms, "cluster_centers_"))
assert_false(hasattr(ms, "labels_"))
def test_bin_seeds():
# Test the bin seeding technique which can be used in the mean shift
# algorithm
# Data is just 6 points in the plane
X = np.array([[1., 1.], [1.4, 1.4], [1.8, 1.2],
[2., 1.], [2.1, 1.1], [0., 0.]])
# With a bin coarseness of 1.0 and min_bin_freq of 1, 3 bins should be
# found
ground_truth = set([(1., 1.), (2., 1.), (0., 0.)])
test_bins = get_bin_seeds(X, 1, 1)
test_result = set([tuple(p) for p in test_bins])
assert_true(len(ground_truth.symmetric_difference(test_result)) == 0)
# With a bin coarseness of 1.0 and min_bin_freq of 2, 2 bins should be
# found
ground_truth = set([(1., 1.), (2., 1.)])
test_bins = get_bin_seeds(X, 1, 2)
test_result = set([tuple(p) for p in test_bins])
assert_true(len(ground_truth.symmetric_difference(test_result)) == 0)
# With a bin size of 0.01 and min_bin_freq of 1, 6 bins should be found
# we bail and use the whole data here.
with warnings.catch_warnings(record=True):
test_bins = get_bin_seeds(X, 0.01, 1)
assert_array_equal(test_bins, X)
# tight clusters around [0, 0] and [1, 1], only get two bins
X, _ = make_blobs(n_samples=100, n_features=2, centers=[[0, 0], [1, 1]],
cluster_std=0.1, random_state=0)
test_bins = get_bin_seeds(X, 1)
assert_array_equal(test_bins, [[0, 0], [1, 1]])
|
unknown
|
codeparrot/codeparrot-clean
| ||
##########################################################################
#
# Copyright (c) 2012, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the following
# disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided with
# the distribution.
#
# * Neither the name of John Haddon nor the names of
# any other contributors to this software may be used to endorse or
# promote products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
##########################################################################
from PathFilter import PathFilter
## A PathFilter which filters based on an item from Path.info() and an
# arbitrary match function.
class InfoPathFilter( PathFilter ) :
def __init__( self, infoKey, matcher, leafOnly=True, userData={} ) :
PathFilter.__init__( self, userData )
self.__infoKey = infoKey
self.__matcher = matcher
self.__leafOnly = leafOnly
## Matcher and infoKey are set with one call, as otherwise
# the intermediate state may yield a new matcher which doesn't work
# with the old key.
def setMatcher( self, infoKey, matcher ) :
self.__infoKey = infoKey
self.__matcher = matcher
self.changedSignal()( self )
def getMatcher( self ) :
return self.__infoKey, self.__matcher
def _filter( self, paths ) :
if self.__matcher is None :
return paths
result = []
for p in paths :
if self.__leafOnly and not p.isLeaf() :
result.append( p )
else :
i = p.info()
if self.__infoKey in i :
if self.__matcher( i[self.__infoKey] ) :
result.append( p )
return result
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
class DuplicationError(frappe.ValidationError): pass
class ActivityCost(Document):
def validate(self):
self.set_title()
self.check_unique()
def set_title(self):
if self.employee:
if not self.employee_name:
self.employee_name = frappe.db.get_value("Employee", self.employee, "employee_name")
self.title = _("{0} for {1}").format(self.employee_name, self.activity_type)
else:
self.title = self.activity_type
def check_unique(self):
if self.employee:
if frappe.db.sql("""select name from `tabActivity Cost` where employee_name= %s and activity_type= %s and name != %s""",
(self.employee_name, self.activity_type, self.name)):
frappe.throw(_("Activity Cost exists for Employee {0} against Activity Type - {1}")
.format(self.employee, self.activity_type), DuplicationError)
else:
if frappe.db.sql("""select name from `tabActivity Cost` where ifnull(employee, '')='' and activity_type= %s and name != %s""",
(self.activity_type, self.name)):
frappe.throw(_("Default Activity Cost exists for Activity Type - {0}")
.format(self.activity_type), DuplicationError)
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
u"""Useful I/O operations
:copyright: Copyright (c) 2015 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from pykern import pkconst
import contextlib
import copy
import errno
import glob
import io
import locale
import os
import os.path
import py
import random
import re
import shutil
#: used during unit testing see ``pykern.pkunit.save_chdir``
pkunit_prefix = None
TEXT_ENCODING = 'utf-8'
def atomic_write(path, contents, **kwargs):
"""Overwrites an existing file with contents via rename to ensure integrity
Args:
path (str or py.path.Local): Path of file to overwrite
contents (str): New contents
kwargs (kwargs): to pass to `py.path.local.write`
"""
n = py_path(path).new(ext='pkio-tmp-' + random_base62())
assert not n.exists(), \
f'{n} already exists (file name collision)'
try:
n.write(contents, **kwargs)
n.rename(path)
finally:
# unchecked_remove is too brutal for this specific case
if n.exists():
try:
os.remove(str(n))
except Exception:
pass
def exception_is_not_found(exc):
"""True if exception is IOError and ENOENT
Args:
exc (BaseException): to check
Returns:
bool: True if is a file not found exception.
"""
return isinstance(exc, IOError) and exc.errno == errno.ENOENT or isinstance(exc, py.error.ENOENT)
def expand_user_path(path):
"""Calls expanduser on path
If `pkunit_prefix` is set, will prefix, too.
Args:
path (str): path to expand
Returns:
py.path.Local: expanded path
"""
return py_path(path)
def has_file_extension(filename, to_check):
"""if matches any of the file extensions
Args:
filename (str|py.path.local): what to check
to_check (str|tuple|list): is without '.' and lower
Returns:
bool: if any of the extensions matches
"""
if isinstance(to_check, pkconst.STRING_TYPES):
to_check = (to_check)
e = py_path(filename).ext[1:].lower()
return e in to_check
def mkdir_parent(path):
"""Create the directories and their parents (if necessary)
Args:
path (str): dir to create
Returns:
py.path.local: path
"""
return py_path(path).ensure(dir=True)
def mkdir_parent_only(path):
"""Create the paths' parent directories.
Args:
path (str): children of dir to create
Returns:
py.path.local: parent directory of path
"""
return mkdir_parent(py_path(path).dirname)
def open_text(filename, **kwargs):
"""Open file with utf-8 for text.
Args:
filename (str or py.path.Local): File to open
Returns:
object: open file handle
"""
kwargs.setdefault('mode', 'rt')
kwargs.setdefault('encoding', TEXT_ENCODING)
return io.open(str(py_path(filename)), **kwargs)
def py_path(path=None):
"""Creates a py.path.Local object
Will expanduser, if needed.
If `pkunit_prefix` is set, will prefix, too.
Args:
path (str): path to convert (or None for current dir)
Returns:
py.path.Local: path
"""
global pkunit_prefix
res = py.path.local(path, expanduser=True)
if pkunit_prefix:
# Allow for <test>_work and <test>_data so we don't add
# prefix if there's a common parent directory.
if not str(res).startswith(pkunit_prefix.dirname):
res = pkunit_prefix.join(res)
py.path.local(res.dirname).ensure(dir=True)
return res
def random_base62(length=16):
"""Returns a safe string of sufficient length to be a nonce.
The default is 62^16, which is 4e28. For comparison, 2^64 is 1e19 and
2^128 is 3e38.
Args:
length (int): how long to make the base62 string [16]
Returns:
str: random base62 characters
"""
r = random.SystemRandom()
return ''.join(r.choice(pkconst.BASE62_CHARS) for x in range(length))
def read_binary(filename):
"""Open file, read binary, and close.
Args:
filename (str or py.path.Local): File to open
Returns:
bytes: contents of `filename`
"""
return py_path(filename).read_binary()
def read_text(filename):
"""Open file, read with utf-8 text, and close.
Args:
filename (str or py.path.Local): File to open
Returns:
Str: contents of `filename`
"""
with open_text(filename) as f:
return f.read()
@contextlib.contextmanager
def save_chdir(dirname, mkdir=False, is_pkunit_prefix=False):
"""Save current directory, change to directory, and restore.
Args:
dirname (str): directory to change to
mkdir (bool): Make the directory?
is_pkunit_prefix (bool): If True, sets pkunit_prefix.
Returns:
str: current directory before `chdir`
"""
global pkunit_prefix
prev_d = py.path.local().realpath()
prev_ppp = pkunit_prefix
try:
if is_pkunit_prefix:
d = py.path.local(dirname)
else:
d = py_path(dirname)
if mkdir and not d.check(dir=1):
mkdir_parent(d)
os.chdir(str(d))
if is_pkunit_prefix:
pkunit_prefix = py.path.local(d)
yield d.realpath()
finally:
os.chdir(str(prev_d))
if is_pkunit_prefix:
pkunit_prefix = prev_ppp
def sorted_glob(path):
"""sorted list of py.path.Local objects, non-recursive
Args:
path (py.path.Local or str): pattern
Returns:
list: py.path.Local objects
"""
return sorted(py_path(f) for f in glob.glob(str(path)))
def unchecked_remove(*paths):
"""Remove files or directories, ignoring OSError.
Will not remove '/' or '.'
Args:
paths (str): paths to remove
"""
cwd = py_path()
for a in paths:
p = py_path(a)
assert len(p.parts()) > 1, \
'{}: will not remove root directory'.format(p)
assert cwd != p, \
'{}: will not remove current directory'.format(p)
try:
os.remove(str(a))
except OSError:
try:
shutil.rmtree(str(a), ignore_errors=True)
except OSError:
pass
def walk_tree(dirname, file_re=None):
"""Return list files (only) as py.path's, top down, sorted
If you want to go bottom up, just reverse the list.
Args:
dirname (str): directory to walk
file_re (re or str): Optionally, only return files which match file_re
Yields:
py.path.local: paths in sorted order
"""
fr = file_re
if fr and not hasattr(fr, 'search'):
fr = re.compile(fr)
dirname = py_path(dirname).realpath()
dn = str(dirname)
res = []
for r, d, files in os.walk(dn, topdown=True, onerror=None, followlinks=False):
for f in files:
p = py_path(r).join(f)
if fr and not fr.search(dirname.bestrelpath(p)):
continue
res.append(p)
# Not an iterator, but works as one. Don't assume always will return list
return sorted(res)
def write_binary(path, contents):
"""Open file, write binary, and close.
Args:
path (str or py.path.Local): Path of file to write to
contents (bytes): New contents
Returns:
py.path.local: `filename` as :class:`py.path.Local`
"""
p = py_path(path)
p.write_binary(contents)
return p
def write_text(path, contents):
"""Open file, write text with utf-8, and close.
Args:
path (str or py.path.Local): Path of file to write to
contents (str or bytes): New contents
Returns:
py.path.local: `filename` as :class:`py.path.Local`
"""
from pykern import pkcompat
fn = py_path(path)
with io.open(str(fn), 'wt', encoding=TEXT_ENCODING) as f:
f.write(pkcompat.from_bytes(contents))
return fn
|
unknown
|
codeparrot/codeparrot-clean
| ||
"""This module allows adding a semantic hub layout to NDEx CX networkx. This
is useful when a network is centered around a single hub node. The
layout generated here allocates different classes of nodes into segments
around the hub and then gives them random coordinates within that segment."""
import json
import math
import random
import networkx
from collections import defaultdict
def get_aspect(cx, aspect_name):
"""Return an aspect given the name of the aspect"""
if isinstance(cx, dict):
return cx.get(aspect_name)
for entry in cx:
if list(entry.keys())[0] == aspect_name:
return entry[aspect_name]
def edge_type_to_class(edge_type):
"""Return the edge class for layout purposes based on the edge type"""
if 'Amount' in edge_type:
return 'amount'
if edge_type in ('Activation', 'Inhibition'):
return 'activity'
if edge_type == 'Complex':
return 'complex'
else:
return 'modification'
def classify_nodes(graph, hub):
"""Classify each node based on its type and relationship to the hub."""
node_stats = defaultdict(lambda: defaultdict(list))
for u, v, data in graph.edges(data=True):
# This means the node is downstream of the hub
if hub == u:
h, o = u, v
if data['i'] != 'Complex':
node_stats[o]['up'].append(-1)
else:
node_stats[o]['up'].append(0)
# This means the node is upstream of the hub
elif hub == v:
h, o = v, u
if data['i'] != 'Complex':
node_stats[o]['up'].append(1)
else:
node_stats[o]['up'].append(0)
else:
continue
node_stats[o]['interaction'].append(edge_type_to_class(data['i']))
node_classes = {}
for node_id, stats in node_stats.items():
up = max(set(stats['up']), key=stats['up'].count)
# Special case: if up is not 0 then we should exclude complexes
# from the edge_type states so that we don't end up with
# (-1, complex, ...) or (1, complex, ...) as the node class
interactions = [i for i in stats['interaction'] if
not (up != 0 and i == 'complex')]
edge_type = max(set(interactions), key=interactions.count)
node_type = graph.nodes[node_id]['type']
node_classes[node_id] = (up, edge_type, node_type)
return node_classes
def get_attributes(aspect, id):
"""Return the attributes pointing to a given ID in a given aspect."""
attributes = {}
for entry in aspect:
if entry['po'] == id:
attributes[entry['n']] = entry['v']
return attributes
def cx_to_networkx(cx):
"""Return a MultiDiGraph representation of a CX network."""
graph = networkx.MultiDiGraph()
for node_entry in get_aspect(cx, 'nodes'):
id = node_entry['@id']
attrs = get_attributes(get_aspect(cx, 'nodeAttributes'), id)
attrs['n'] = node_entry['n']
graph.add_node(id, **attrs)
for edge_entry in get_aspect(cx, 'edges'):
id = edge_entry['@id']
attrs = get_attributes(get_aspect(cx, 'edgeAttributes'), id)
attrs['i'] = edge_entry['i']
graph.add_edge(edge_entry['s'], edge_entry['t'], key=id, **attrs)
return graph
def get_quadrant_from_class(node_class):
"""Return the ID of the segment of the plane corresponding to a class."""
up, edge_type, _ = node_class
if up == 0:
return 0 if random.random() < 0.5 else 7
mappings = {(-1, 'modification'): 1,
(-1, 'amount'): 2,
(-1, 'activity'): 3,
(1, 'activity'): 4,
(1, 'amount'): 5,
(1, 'modification'): 6}
return mappings[(up, edge_type)]
def get_coordinates(node_class):
"""Generate coordinates for a node in a given class."""
quadrant_size = (2 * math.pi / 8.0)
quadrant = get_quadrant_from_class(node_class)
begin_angle = quadrant_size * quadrant
r = 200 + 800*random.random()
alpha = begin_angle + random.random() * quadrant_size
x = r * math.cos(alpha)
y = r * math.sin(alpha)
return x, y
def get_layout_aspect(hub, node_classes):
"""Get the full layout aspect with coordinates for each node."""
aspect = [{'node': hub, 'x': 0.0, 'y': 0.0}]
for node, node_class in node_classes.items():
if node == hub:
continue
x, y = get_coordinates(node_class)
aspect.append({'node': node, 'x': x, 'y': y})
return aspect
def get_node_by_name(graph, name):
"""Return a node ID given its name."""
for id, attrs in graph.nodes(data=True):
if attrs['n'] == name:
return id
def add_semantic_hub_layout(cx, hub):
"""Attach a layout aspect to a CX network given a hub node."""
graph = cx_to_networkx(cx)
hub_node = get_node_by_name(graph, hub)
node_classes = classify_nodes(graph, hub_node)
layout_aspect = get_layout_aspect(hub_node, node_classes)
cx['cartesianLayout'] = layout_aspect
if __name__ == '__main__':
with open('CDK13.cx', 'r') as fh:
cx = json.load(fh)
add_semantic_hub_layout(cx, 'CDK13')
|
unknown
|
codeparrot/codeparrot-clean
| ||
'use strict';
const common = require('../common.js');
const { getCiphers, getCipherInfo } = require('node:crypto');
const bench = common.createBenchmark(main, {
cipher: getCiphers(),
n: 50,
});
function main({ n, cipher }) {
bench.start();
for (let i = 0; i < n; i++) {
getCipherInfo(cipher);
}
bench.end(n);
}
|
javascript
|
github
|
https://github.com/nodejs/node
|
benchmark/crypto/getcipherinfo.js
|
/*
* 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 org.apache.kafka.common.protocol.types;
import org.apache.kafka.common.KafkaException;
/**
* Thrown if the protocol schema validation fails while parsing request or response.
*/
public class SchemaException extends KafkaException {
private static final long serialVersionUID = 1L;
public SchemaException(String message) {
super(message);
}
public SchemaException(String message, Throwable cause) {
super(message, cause);
}
}
|
java
|
github
|
https://github.com/apache/kafka
|
clients/src/main/java/org/apache/kafka/common/protocol/types/SchemaException.java
|
# Copyright (c) 2017 Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from ansible.module_utils.ec2 import AWSRetry
# Non-ansible imports
try:
from botocore.exceptions import BotoCoreError, ClientError
except ImportError:
pass
def get_elb(connection, module, elb_name):
"""
Get an ELB based on name. If not found, return None.
:param connection: AWS boto3 elbv2 connection
:param module: Ansible module
:param elb_name: Name of load balancer to get
:return: boto3 ELB dict or None if not found
"""
try:
return _get_elb(connection, module, elb_name)
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e)
@AWSRetry.jittered_backoff()
def _get_elb(connection, module, elb_name):
"""
Get an ELB based on name using AWSRetry. If not found, return None.
:param connection: AWS boto3 elbv2 connection
:param module: Ansible module
:param elb_name: Name of load balancer to get
:return: boto3 ELB dict or None if not found
"""
try:
load_balancer_paginator = connection.get_paginator('describe_load_balancers')
return (load_balancer_paginator.paginate(Names=[elb_name]).build_full_result())['LoadBalancers'][0]
except (BotoCoreError, ClientError) as e:
if e.response['Error']['Code'] == 'LoadBalancerNotFound':
return None
else:
raise e
def get_elb_listener(connection, module, elb_arn, listener_port):
"""
Get an ELB listener based on the port provided. If not found, return None.
:param connection: AWS boto3 elbv2 connection
:param module: Ansible module
:param elb_arn: ARN of the ELB to look at
:param listener_port: Port of the listener to look for
:return: boto3 ELB listener dict or None if not found
"""
try:
listener_paginator = connection.get_paginator('describe_listeners')
listeners = (AWSRetry.jittered_backoff()(listener_paginator.paginate)(LoadBalancerArn=elb_arn).build_full_result())['Listeners']
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e)
l = None
for listener in listeners:
if listener['Port'] == listener_port:
l = listener
break
return l
def get_elb_listener_rules(connection, module, listener_arn):
"""
Get rules for a particular ELB listener using the listener ARN.
:param connection: AWS boto3 elbv2 connection
:param module: Ansible module
:param listener_arn: ARN of the ELB listener
:return: boto3 ELB rules list
"""
try:
return AWSRetry.jittered_backoff()(connection.describe_rules)(ListenerArn=listener_arn)['Rules']
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e)
def convert_tg_name_to_arn(connection, module, tg_name):
"""
Get ARN of a target group using the target group's name
:param connection: AWS boto3 elbv2 connection
:param module: Ansible module
:param tg_name: Name of the target group
:return: target group ARN string
"""
try:
response = AWSRetry.jittered_backoff()(connection.describe_target_groups)(Names=[tg_name])
except (BotoCoreError, ClientError) as e:
module.fail_json_aws(e)
tg_arn = response['TargetGroups'][0]['TargetGroupArn']
return tg_arn
|
unknown
|
codeparrot/codeparrot-clean
| ||
license="""
##############################################################
## ##
## Remaining HZ distribution ##
## Version v01 "indepence" ##
## (4th of July 2015) ##
## ##
##############################################################
## To be take with a grain of salt! ##
## ##
## Very unclear: future number of hallmarked nodes ##
## Unknown: regular bounties for other-than-node-bounties ##
## ##
## All this is open for discussion. Not truth, but maths. ##
##############################################################
## ##
## Done by: altsheets ##
## License: giveback license v04 ##
## http://altsheets.ddns.net/give/ ##
## Donate to: NHZ-Q675-SGBG-LQ43-D38L6 - thx ##
## ##
##############################################################
"""
## TODO: get this from https://explorer.horizonplatform.io/api.php?page=distributed
## 4/July/2015 13:15 UTC: 851306829.88887 HZ
undistributed = 1000000000 - 851306829.88887
dateToday = "4 July 2015"
## new rule was announced in
## https://bitcointalk.org/index.php?topic=823785.msg11784831#msg11784831
dailyRatePercent = 0.5
## choosable parameters:
## node bounty payment of the past 7 days were:
## 458.0852039, 495.5401388, 510.2040816, 571.1022273, 570.1254276, 591.7159763, 479.8464491
## --> average 525 HZ --> 10^6 / 525 = 1905
numberOfPaidNodes = 1905
## please give suggestions how that number might change with payout.
# starting values, they get changed once per table,
# table ends when the threshold is crossed:
stopAt = 100 # threshold: daily payout per node minimum HZ
HZdigits = 0 # digits for the last column (per node bounty)
printEveryXdays=15
## Not only hallmarked nodes get bounties.
## There are all kinds of other bounties, e.g. for the team;
## this is the starting value, later it might reduced?
otherBountiesPerDay = 0
## TODO: set to 0 until (e.g. an average value for the past 3 months) has been said.
## constants
dateformat = "%d %B %Y"
line = "%18s: left = %9d HZ -> per day --> other: %d HZ; nodes: %d HZ = %d * %s HZ"
import datetime
oneDay = datetime.timedelta(days=1)
def extrapolateNodeBounties(stopAt, printEveryXdays, firstDay,
ud, otherBountiesPerDay, HZdigits):
"it would be nice to have a comment which explains this *lol*"
day = datetime.datetime.strptime(firstDay, dateformat)
dayCount = 0 # for printEveryXdays
stopNow = False # flag for one more print if threshold crossed
while (True):
nodeBountiesThatDay = ud * dailyRatePercent / 100
dTD_perNode = nodeBountiesThatDay / numberOfPaidNodes
if (dayCount % printEveryXdays==0
or stopNow):
perNode = ("%." + "%d" % (HZdigits) + "f") % dTD_perNode
print line % (datetime.datetime.strftime(day, dateformat),
ud, otherBountiesPerDay,
nodeBountiesThatDay, numberOfPaidNodes, perNode)
ud = ud - nodeBountiesThatDay - otherBountiesPerDay
day = day + oneDay
dayCount += 1
if stopNow: break
if (dTD_perNode<stopAt): stopNow = True
return datetime.datetime.strftime(day, dateformat), ud
def successionOfTables(firstDay = dateToday, ud = undistributed):
# the 2 starting values get reduced in each iteration.
# print several successive tables:
global stopAt, printEveryXdays, otherBountiesPerDay, HZdigits
firstDay, ud = extrapolateNodeBounties(stopAt, printEveryXdays, firstDay,
ud, otherBountiesPerDay, HZdigits)
print "daily node bounty threshold crossed. Remaining: %d HZ for %s" % (ud, firstDay)
print
printEveryXdays *= 2
stopAt /= 10
HZdigits += 1
otherBountiesPerDay /= 5
firstDay, ud = extrapolateNodeBounties(stopAt, printEveryXdays, firstDay,
ud, otherBountiesPerDay, HZdigits)
print "daily node bounty threshold crossed. Remaining: %d HZ for %s" % (ud, firstDay)
print
printEveryXdays *= 2
stopAt /= 5
HZdigits += 1
otherBountiesPerDay /= 5
firstDay, ud = extrapolateNodeBounties(stopAt, printEveryXdays, firstDay,
ud, otherBountiesPerDay, HZdigits)
print "daily node bounty threshold crossed. Remaining: %d HZ for %s" % (ud, firstDay)
if __name__ == "__main__":
print license
successionOfTables()
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/env python
#
# Copyright (c) 2005 Niels Provos <provos@citi.umich.edu>
# All rights reserved.
#
# Generates marshaling code based on libevent.
import sys
import re
#
_NAME = "event_rpcgen.py"
_VERSION = "0.1"
_STRUCT_RE = '[a-z][a-z_0-9]*'
# Globals
line_count = 0
white = re.compile(r'^\s+')
cppcomment = re.compile(r'\/\/.*$')
headerdirect = []
cppdirect = []
# Holds everything that makes a struct
class Struct:
def __init__(self, name):
self._name = name
self._entries = []
self._tags = {}
print >>sys.stderr, ' Created struct: %s' % name
def AddEntry(self, entry):
if self._tags.has_key(entry.Tag()):
print >>sys.stderr, ( 'Entry "%s" duplicates tag number '
'%d from "%s" around line %d' ) % (
entry.Name(), entry.Tag(),
self._tags[entry.Tag()], line_count)
sys.exit(1)
self._entries.append(entry)
self._tags[entry.Tag()] = entry.Name()
print >>sys.stderr, ' Added entry: %s' % entry.Name()
def Name(self):
return self._name
def EntryTagName(self, entry):
"""Creates the name inside an enumeration for distinguishing data
types."""
name = "%s_%s" % (self._name, entry.Name())
return name.upper()
def PrintIdented(self, file, ident, code):
"""Takes an array, add indentation to each entry and prints it."""
for entry in code:
print >>file, '%s%s' % (ident, entry)
def PrintTags(self, file):
"""Prints the tag definitions for a structure."""
print >>file, '/* Tag definition for %s */' % self._name
print >>file, 'enum %s_ {' % self._name.lower()
for entry in self._entries:
print >>file, ' %s=%d,' % (self.EntryTagName(entry),
entry.Tag())
print >>file, ' %s_MAX_TAGS' % (self._name.upper())
print >>file, '};\n'
def PrintForwardDeclaration(self, file):
print >>file, 'struct %s;' % self._name
def PrintDeclaration(self, file):
print >>file, '/* Structure declaration for %s */' % self._name
print >>file, 'struct %s_access_ {' % self._name
for entry in self._entries:
dcl = entry.AssignDeclaration('(*%s_assign)' % entry.Name())
dcl.extend(
entry.GetDeclaration('(*%s_get)' % entry.Name()))
if entry.Array():
dcl.extend(
entry.AddDeclaration('(*%s_add)' % entry.Name()))
self.PrintIdented(file, ' ', dcl)
print >>file, '};\n'
print >>file, 'struct %s {' % self._name
print >>file, ' struct %s_access_ *base;\n' % self._name
for entry in self._entries:
dcl = entry.Declaration()
self.PrintIdented(file, ' ', dcl)
print >>file, ''
for entry in self._entries:
print >>file, ' ev_uint8_t %s_set;' % entry.Name()
print >>file, '};\n'
print >>file, \
"""struct %(name)s *%(name)s_new(void);
void %(name)s_free(struct %(name)s *);
void %(name)s_clear(struct %(name)s *);
void %(name)s_marshal(struct evbuffer *, const struct %(name)s *);
int %(name)s_unmarshal(struct %(name)s *, struct evbuffer *);
int %(name)s_complete(struct %(name)s *);
void evtag_marshal_%(name)s(struct evbuffer *, ev_uint32_t,
const struct %(name)s *);
int evtag_unmarshal_%(name)s(struct evbuffer *, ev_uint32_t,
struct %(name)s *);""" % { 'name' : self._name }
# Write a setting function of every variable
for entry in self._entries:
self.PrintIdented(file, '', entry.AssignDeclaration(
entry.AssignFuncName()))
self.PrintIdented(file, '', entry.GetDeclaration(
entry.GetFuncName()))
if entry.Array():
self.PrintIdented(file, '', entry.AddDeclaration(
entry.AddFuncName()))
print >>file, '/* --- %s done --- */\n' % self._name
def PrintCode(self, file):
print >>file, ('/*\n'
' * Implementation of %s\n'
' */\n') % self._name
print >>file, \
'static struct %(name)s_access_ __%(name)s_base = {' % \
{ 'name' : self._name }
for entry in self._entries:
self.PrintIdented(file, ' ', entry.CodeBase())
print >>file, '};\n'
# Creation
print >>file, (
'struct %(name)s *\n'
'%(name)s_new(void)\n'
'{\n'
' struct %(name)s *tmp;\n'
' if ((tmp = malloc(sizeof(struct %(name)s))) == NULL) {\n'
' event_warn("%%s: malloc", __func__);\n'
' return (NULL);\n'
' }\n'
' tmp->base = &__%(name)s_base;\n') % { 'name' : self._name }
for entry in self._entries:
self.PrintIdented(file, ' ', entry.CodeNew('tmp'))
print >>file, ' tmp->%s_set = 0;\n' % entry.Name()
print >>file, (
' return (tmp);\n'
'}\n')
# Adding
for entry in self._entries:
if entry.Array():
self.PrintIdented(file, '', entry.CodeAdd())
print >>file, ''
# Assigning
for entry in self._entries:
self.PrintIdented(file, '', entry.CodeAssign())
print >>file, ''
# Getting
for entry in self._entries:
self.PrintIdented(file, '', entry.CodeGet())
print >>file, ''
# Clearing
print >>file, ( 'void\n'
'%(name)s_clear(struct %(name)s *tmp)\n'
'{'
) % { 'name' : self._name }
for entry in self._entries:
self.PrintIdented(file, ' ', entry.CodeClear('tmp'))
print >>file, '}\n'
# Freeing
print >>file, ( 'void\n'
'%(name)s_free(struct %(name)s *tmp)\n'
'{'
) % { 'name' : self._name }
for entry in self._entries:
self.PrintIdented(file, ' ', entry.CodeFree('tmp'))
print >>file, (' free(tmp);\n'
'}\n')
# Marshaling
print >>file, ('void\n'
'%(name)s_marshal(struct evbuffer *evbuf, '
'const struct %(name)s *tmp)'
'{') % { 'name' : self._name }
for entry in self._entries:
indent = ' '
# Optional entries do not have to be set
if entry.Optional():
indent += ' '
print >>file, ' if (tmp->%s_set) {' % entry.Name()
self.PrintIdented(
file, indent,
entry.CodeMarshal('evbuf', self.EntryTagName(entry), 'tmp'))
if entry.Optional():
print >>file, ' }'
print >>file, '}\n'
# Unmarshaling
print >>file, ('int\n'
'%(name)s_unmarshal(struct %(name)s *tmp, '
' struct evbuffer *evbuf)\n'
'{\n'
' ev_uint32_t tag;\n'
' while (EVBUFFER_LENGTH(evbuf) > 0) {\n'
' if (evtag_peek(evbuf, &tag) == -1)\n'
' return (-1);\n'
' switch (tag) {\n'
) % { 'name' : self._name }
for entry in self._entries:
print >>file, ' case %s:\n' % self.EntryTagName(entry)
if not entry.Array():
print >>file, (
' if (tmp->%s_set)\n'
' return (-1);'
) % (entry.Name())
self.PrintIdented(
file, ' ',
entry.CodeUnmarshal('evbuf',
self.EntryTagName(entry), 'tmp'))
print >>file, ( ' tmp->%s_set = 1;\n' % entry.Name() +
' break;\n' )
print >>file, ( ' default:\n'
' return -1;\n'
' }\n'
' }\n' )
# Check if it was decoded completely
print >>file, ( ' if (%(name)s_complete(tmp) == -1)\n'
' return (-1);'
) % { 'name' : self._name }
# Successfully decoded
print >>file, ( ' return (0);\n'
'}\n')
# Checking if a structure has all the required data
print >>file, (
'int\n'
'%(name)s_complete(struct %(name)s *msg)\n'
'{' ) % { 'name' : self._name }
for entry in self._entries:
self.PrintIdented(
file, ' ',
entry.CodeComplete('msg'))
print >>file, (
' return (0);\n'
'}\n' )
# Complete message unmarshaling
print >>file, (
'int\n'
'evtag_unmarshal_%(name)s(struct evbuffer *evbuf, '
'ev_uint32_t need_tag, struct %(name)s *msg)\n'
'{\n'
' ev_uint32_t tag;\n'
' int res = -1;\n'
'\n'
' struct evbuffer *tmp = evbuffer_new();\n'
'\n'
' if (evtag_unmarshal(evbuf, &tag, tmp) == -1'
' || tag != need_tag)\n'
' goto error;\n'
'\n'
' if (%(name)s_unmarshal(msg, tmp) == -1)\n'
' goto error;\n'
'\n'
' res = 0;\n'
'\n'
' error:\n'
' evbuffer_free(tmp);\n'
' return (res);\n'
'}\n' ) % { 'name' : self._name }
# Complete message marshaling
print >>file, (
'void\n'
'evtag_marshal_%(name)s(struct evbuffer *evbuf, ev_uint32_t tag, '
'const struct %(name)s *msg)\n'
'{\n'
' struct evbuffer *_buf = evbuffer_new();\n'
' assert(_buf != NULL);\n'
' evbuffer_drain(_buf, -1);\n'
' %(name)s_marshal(_buf, msg);\n'
' evtag_marshal(evbuf, tag, EVBUFFER_DATA(_buf), '
'EVBUFFER_LENGTH(_buf));\n'
' evbuffer_free(_buf);\n'
'}\n' ) % { 'name' : self._name }
class Entry:
def __init__(self, type, name, tag):
self._type = type
self._name = name
self._tag = int(tag)
self._ctype = type
self._optional = 0
self._can_be_array = 0
self._array = 0
self._line_count = -1
self._struct = None
self._refname = None
def GetTranslation(self):
return { "parent_name" : self._struct.Name(),
"name" : self._name,
"ctype" : self._ctype,
"refname" : self._refname
}
def SetStruct(self, struct):
self._struct = struct
def LineCount(self):
assert self._line_count != -1
return self._line_count
def SetLineCount(self, number):
self._line_count = number
def Array(self):
return self._array
def Optional(self):
return self._optional
def Tag(self):
return self._tag
def Name(self):
return self._name
def Type(self):
return self._type
def MakeArray(self, yes=1):
self._array = yes
def MakeOptional(self):
self._optional = 1
def GetFuncName(self):
return '%s_%s_get' % (self._struct.Name(), self._name)
def GetDeclaration(self, funcname):
code = [ 'int %s(struct %s *, %s *);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def CodeGet(self):
code = (
'int',
'%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, '
'%(ctype)s *value)',
'{',
' if (msg->%(name)s_set != 1)',
' return (-1);',
' *value = msg->%(name)s_data;',
' return (0);',
'}' )
code = '\n'.join(code)
code = code % self.GetTranslation()
return code.split('\n')
def AssignFuncName(self):
return '%s_%s_assign' % (self._struct.Name(), self._name)
def AddFuncName(self):
return '%s_%s_add' % (self._struct.Name(), self._name)
def AssignDeclaration(self, funcname):
code = [ 'int %s(struct %s *, const %s);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def CodeAssign(self):
code = [ 'int',
'%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,'
' const %(ctype)s value)',
'{',
' msg->%(name)s_set = 1;',
' msg->%(name)s_data = value;',
' return (0);',
'}' ]
code = '\n'.join(code)
code = code % self.GetTranslation()
return code.split('\n')
def CodeClear(self, structname):
code = [ '%s->%s_set = 0;' % (structname, self.Name()) ]
return code
def CodeComplete(self, structname):
if self.Optional():
return []
code = [ 'if (!%s->%s_set)' % (structname, self.Name()),
' return (-1);' ]
return code
def CodeFree(self, name):
return []
def CodeBase(self):
code = [
'%(parent_name)s_%(name)s_assign,',
'%(parent_name)s_%(name)s_get,'
]
if self.Array():
code.append('%(parent_name)s_%(name)s_add,')
code = '\n'.join(code)
code = code % self.GetTranslation()
return code.split('\n')
def Verify(self):
if self.Array() and not self._can_be_array:
print >>sys.stderr, (
'Entry "%s" cannot be created as an array '
'around line %d' ) % (self._name, self.LineCount())
sys.exit(1)
if not self._struct:
print >>sys.stderr, (
'Entry "%s" does not know which struct it belongs to '
'around line %d' ) % (self._name, self.LineCount())
sys.exit(1)
if self._optional and self._array:
print >>sys.stderr, ( 'Entry "%s" has illegal combination of '
'optional and array around line %d' ) % (
self._name, self.LineCount() )
sys.exit(1)
class EntryBytes(Entry):
def __init__(self, type, name, tag, length):
# Init base class
Entry.__init__(self, type, name, tag)
self._length = length
self._ctype = 'ev_uint8_t'
def GetDeclaration(self, funcname):
code = [ 'int %s(struct %s *, %s **);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def AssignDeclaration(self, funcname):
code = [ 'int %s(struct %s *, const %s *);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def Declaration(self):
dcl = ['ev_uint8_t %s_data[%s];' % (self._name, self._length)]
return dcl
def CodeGet(self):
name = self._name
code = [ 'int',
'%s_%s_get(struct %s *msg, %s **value)' % (
self._struct.Name(), name,
self._struct.Name(), self._ctype),
'{',
' if (msg->%s_set != 1)' % name,
' return (-1);',
' *value = msg->%s_data;' % name,
' return (0);',
'}' ]
return code
def CodeAssign(self):
name = self._name
code = [ 'int',
'%s_%s_assign(struct %s *msg, const %s *value)' % (
self._struct.Name(), name,
self._struct.Name(), self._ctype),
'{',
' msg->%s_set = 1;' % name,
' memcpy(msg->%s_data, value, %s);' % (
name, self._length),
' return (0);',
'}' ]
return code
def CodeUnmarshal(self, buf, tag_name, var_name):
code = [ 'if (evtag_unmarshal_fixed(%s, %s, ' % (buf, tag_name) +
'%s->%s_data, ' % (var_name, self._name) +
'sizeof(%s->%s_data)) == -1) {' % (
var_name, self._name),
' event_warnx("%%s: failed to unmarshal %s", __func__);' % (
self._name ),
' return (-1);',
'}'
]
return code
def CodeMarshal(self, buf, tag_name, var_name):
code = ['evtag_marshal(%s, %s, %s->%s_data, sizeof(%s->%s_data));' % (
buf, tag_name, var_name, self._name, var_name, self._name )]
return code
def CodeClear(self, structname):
code = [ '%s->%s_set = 0;' % (structname, self.Name()),
'memset(%s->%s_data, 0, sizeof(%s->%s_data));' % (
structname, self._name, structname, self._name)]
return code
def CodeNew(self, name):
code = ['memset(%s->%s_data, 0, sizeof(%s->%s_data));' % (
name, self._name, name, self._name)]
return code
def Verify(self):
if not self._length:
print >>sys.stderr, 'Entry "%s" needs a length around line %d' % (
self._name, self.LineCount() )
sys.exit(1)
Entry.Verify(self)
class EntryInt(Entry):
def __init__(self, type, name, tag):
# Init base class
Entry.__init__(self, type, name, tag)
self._ctype = 'ev_uint32_t'
def CodeUnmarshal(self, buf, tag_name, var_name):
code = ['if (evtag_unmarshal_int(%s, %s, &%s->%s_data) == -1) {' % (
buf, tag_name, var_name, self._name),
' event_warnx("%%s: failed to unmarshal %s", __func__);' % (
self._name ),
' return (-1);',
'}' ]
return code
def CodeMarshal(self, buf, tag_name, var_name):
code = ['evtag_marshal_int(%s, %s, %s->%s_data);' % (
buf, tag_name, var_name, self._name)]
return code
def Declaration(self):
dcl = ['ev_uint32_t %s_data;' % self._name]
return dcl
def CodeNew(self, name):
code = ['%s->%s_data = 0;' % (name, self._name)]
return code
class EntryString(Entry):
def __init__(self, type, name, tag):
# Init base class
Entry.__init__(self, type, name, tag)
self._ctype = 'char *'
def CodeAssign(self):
name = self._name
code = """int
%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,
const %(ctype)s value)
{
if (msg->%(name)s_data != NULL)
free(msg->%(name)s_data);
if ((msg->%(name)s_data = strdup(value)) == NULL)
return (-1);
msg->%(name)s_set = 1;
return (0);
}""" % self.GetTranslation()
return code.split('\n')
def CodeUnmarshal(self, buf, tag_name, var_name):
code = ['if (evtag_unmarshal_string(%s, %s, &%s->%s_data) == -1) {' % (
buf, tag_name, var_name, self._name),
' event_warnx("%%s: failed to unmarshal %s", __func__);' % (
self._name ),
' return (-1);',
'}'
]
return code
def CodeMarshal(self, buf, tag_name, var_name):
code = ['evtag_marshal_string(%s, %s, %s->%s_data);' % (
buf, tag_name, var_name, self._name)]
return code
def CodeClear(self, structname):
code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
' free (%s->%s_data);' % (structname, self.Name()),
' %s->%s_data = NULL;' % (structname, self.Name()),
' %s->%s_set = 0;' % (structname, self.Name()),
'}'
]
return code
def CodeNew(self, name):
code = ['%s->%s_data = NULL;' % (name, self._name)]
return code
def CodeFree(self, name):
code = ['if (%s->%s_data != NULL)' % (name, self._name),
' free (%s->%s_data); ' % (name, self._name)]
return code
def Declaration(self):
dcl = ['char *%s_data;' % self._name]
return dcl
class EntryStruct(Entry):
def __init__(self, type, name, tag, refname):
# Init base class
Entry.__init__(self, type, name, tag)
self._can_be_array = 1
self._refname = refname
self._ctype = 'struct %s*' % refname
def CodeGet(self):
name = self._name
code = [ 'int',
'%s_%s_get(struct %s *msg, %s *value)' % (
self._struct.Name(), name,
self._struct.Name(), self._ctype),
'{',
' if (msg->%s_set != 1) {' % name,
' msg->%s_data = %s_new();' % (name, self._refname),
' if (msg->%s_data == NULL)' % name,
' return (-1);',
' msg->%s_set = 1;' % name,
' }',
' *value = msg->%s_data;' % name,
' return (0);',
'}' ]
return code
def CodeAssign(self):
name = self._name
code = """int
%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg,
const %(ctype)s value)
{
struct evbuffer *tmp = NULL;
if (msg->%(name)s_set) {
%(refname)s_clear(msg->%(name)s_data);
msg->%(name)s_set = 0;
} else {
msg->%(name)s_data = %(refname)s_new();
if (msg->%(name)s_data == NULL) {
event_warn("%%s: %(refname)s_new()", __func__);
goto error;
}
}
if ((tmp = evbuffer_new()) == NULL) {
event_warn("%%s: evbuffer_new()", __func__);
goto error;
}
%(refname)s_marshal(tmp, value);
if (%(refname)s_unmarshal(msg->%(name)s_data, tmp) == -1) {
event_warnx("%%s: %(refname)s_unmarshal", __func__);
goto error;
}
msg->%(name)s_set = 1;
evbuffer_free(tmp);
return (0);
error:
if (tmp != NULL)
evbuffer_free(tmp);
if (msg->%(name)s_data != NULL) {
%(refname)s_free(msg->%(name)s_data);
msg->%(name)s_data = NULL;
}
return (-1);
}""" % self.GetTranslation()
return code.split('\n')
def CodeComplete(self, structname):
if self.Optional():
code = [ 'if (%s->%s_set && %s_complete(%s->%s_data) == -1)' % (
structname, self.Name(),
self._refname, structname, self.Name()),
' return (-1);' ]
else:
code = [ 'if (%s_complete(%s->%s_data) == -1)' % (
self._refname, structname, self.Name()),
' return (-1);' ]
return code
def CodeUnmarshal(self, buf, tag_name, var_name):
code = ['%s->%s_data = %s_new();' % (
var_name, self._name, self._refname),
'if (%s->%s_data == NULL)' % (var_name, self._name),
' return (-1);',
'if (evtag_unmarshal_%s(%s, %s, %s->%s_data) == -1) {' % (
self._refname, buf, tag_name, var_name, self._name),
' event_warnx("%%s: failed to unmarshal %s", __func__);' % (
self._name ),
' return (-1);',
'}'
]
return code
def CodeMarshal(self, buf, tag_name, var_name):
code = ['evtag_marshal_%s(%s, %s, %s->%s_data);' % (
self._refname, buf, tag_name, var_name, self._name)]
return code
def CodeClear(self, structname):
code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
' %s_free(%s->%s_data);' % (
self._refname, structname, self.Name()),
' %s->%s_data = NULL;' % (structname, self.Name()),
' %s->%s_set = 0;' % (structname, self.Name()),
'}'
]
return code
def CodeNew(self, name):
code = ['%s->%s_data = NULL;' % (name, self._name)]
return code
def CodeFree(self, name):
code = ['if (%s->%s_data != NULL)' % (name, self._name),
' %s_free(%s->%s_data); ' % (
self._refname, name, self._name)]
return code
def Declaration(self):
dcl = ['%s %s_data;' % (self._ctype, self._name)]
return dcl
class EntryVarBytes(Entry):
def __init__(self, type, name, tag):
# Init base class
Entry.__init__(self, type, name, tag)
self._ctype = 'ev_uint8_t *'
def GetDeclaration(self, funcname):
code = [ 'int %s(struct %s *, %s *, ev_uint32_t *);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def AssignDeclaration(self, funcname):
code = [ 'int %s(struct %s *, const %s, ev_uint32_t);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def CodeAssign(self):
name = self._name
code = [ 'int',
'%s_%s_assign(struct %s *msg, '
'const %s value, ev_uint32_t len)' % (
self._struct.Name(), name,
self._struct.Name(), self._ctype),
'{',
' if (msg->%s_data != NULL)' % name,
' free (msg->%s_data);' % name,
' msg->%s_data = malloc(len);' % name,
' if (msg->%s_data == NULL)' % name,
' return (-1);',
' msg->%s_set = 1;' % name,
' msg->%s_length = len;' % name,
' memcpy(msg->%s_data, value, len);' % name,
' return (0);',
'}' ]
return code
def CodeGet(self):
name = self._name
code = [ 'int',
'%s_%s_get(struct %s *msg, %s *value, ev_uint32_t *plen)' % (
self._struct.Name(), name,
self._struct.Name(), self._ctype),
'{',
' if (msg->%s_set != 1)' % name,
' return (-1);',
' *value = msg->%s_data;' % name,
' *plen = msg->%s_length;' % name,
' return (0);',
'}' ]
return code
def CodeUnmarshal(self, buf, tag_name, var_name):
code = ['if (evtag_payload_length(%s, &%s->%s_length) == -1)' % (
buf, var_name, self._name),
' return (-1);',
# We do not want DoS opportunities
'if (%s->%s_length > EVBUFFER_LENGTH(%s))' % (
var_name, self._name, buf),
' return (-1);',
'if ((%s->%s_data = malloc(%s->%s_length)) == NULL)' % (
var_name, self._name, var_name, self._name),
' return (-1);',
'if (evtag_unmarshal_fixed(%s, %s, %s->%s_data, '
'%s->%s_length) == -1) {' % (
buf, tag_name, var_name, self._name, var_name, self._name),
' event_warnx("%%s: failed to unmarshal %s", __func__);' % (
self._name ),
' return (-1);',
'}'
]
return code
def CodeMarshal(self, buf, tag_name, var_name):
code = ['evtag_marshal(%s, %s, %s->%s_data, %s->%s_length);' % (
buf, tag_name, var_name, self._name, var_name, self._name)]
return code
def CodeClear(self, structname):
code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
' free (%s->%s_data);' % (structname, self.Name()),
' %s->%s_data = NULL;' % (structname, self.Name()),
' %s->%s_length = 0;' % (structname, self.Name()),
' %s->%s_set = 0;' % (structname, self.Name()),
'}'
]
return code
def CodeNew(self, name):
code = ['%s->%s_data = NULL;' % (name, self._name),
'%s->%s_length = 0;' % (name, self._name) ]
return code
def CodeFree(self, name):
code = ['if (%s->%s_data != NULL)' % (name, self._name),
' free (%s->%s_data); ' % (name, self._name)]
return code
def Declaration(self):
dcl = ['ev_uint8_t *%s_data;' % self._name,
'ev_uint32_t %s_length;' % self._name]
return dcl
class EntryArray(Entry):
def __init__(self, entry):
# Init base class
Entry.__init__(self, entry._type, entry._name, entry._tag)
self._entry = entry
self._refname = entry._refname
self._ctype = 'struct %s *' % self._refname
def GetDeclaration(self, funcname):
"""Allows direct access to elements of the array."""
translate = self.GetTranslation()
translate["funcname"] = funcname
code = [
'int %(funcname)s(struct %(parent_name)s *, int, %(ctype)s *);' %
translate ]
return code
def AssignDeclaration(self, funcname):
code = [ 'int %s(struct %s *, int, const %s);' % (
funcname, self._struct.Name(), self._ctype ) ]
return code
def AddDeclaration(self, funcname):
code = [ '%s %s(struct %s *);' % (
self._ctype, funcname, self._struct.Name() ) ]
return code
def CodeGet(self):
code = """int
%(parent_name)s_%(name)s_get(struct %(parent_name)s *msg, int offset,
%(ctype)s *value)
{
if (!msg->%(name)s_set || offset < 0 || offset >= msg->%(name)s_length)
return (-1);
*value = msg->%(name)s_data[offset];
return (0);
}""" % self.GetTranslation()
return code.split('\n')
def CodeAssign(self):
code = """int
%(parent_name)s_%(name)s_assign(struct %(parent_name)s *msg, int off,
const %(ctype)s value)
{
struct evbuffer *tmp = NULL;
if (!msg->%(name)s_set || off < 0 || off >= msg->%(name)s_length)
return (-1);
%(refname)s_clear(msg->%(name)s_data[off]);
if ((tmp = evbuffer_new()) == NULL) {
event_warn("%%s: evbuffer_new()", __func__);
goto error;
}
%(refname)s_marshal(tmp, value);
if (%(refname)s_unmarshal(msg->%(name)s_data[off], tmp) == -1) {
event_warnx("%%s: %(refname)s_unmarshal", __func__);
goto error;
}
evbuffer_free(tmp);
return (0);
error:
if (tmp != NULL)
evbuffer_free(tmp);
%(refname)s_clear(msg->%(name)s_data[off]);
return (-1);
}""" % self.GetTranslation()
return code.split('\n')
def CodeAdd(self):
code = \
"""%(ctype)s
%(parent_name)s_%(name)s_add(struct %(parent_name)s *msg)
{
if (++msg->%(name)s_length >= msg->%(name)s_num_allocated) {
int tobe_allocated = msg->%(name)s_num_allocated;
%(ctype)s* new_data = NULL;
tobe_allocated = !tobe_allocated ? 1 : tobe_allocated << 1;
new_data = (%(ctype)s*) realloc(msg->%(name)s_data,
tobe_allocated * sizeof(%(ctype)s));
if (new_data == NULL)
goto error;
msg->%(name)s_data = new_data;
msg->%(name)s_num_allocated = tobe_allocated;
}
msg->%(name)s_data[msg->%(name)s_length - 1] = %(refname)s_new();
if (msg->%(name)s_data[msg->%(name)s_length - 1] == NULL)
goto error;
msg->%(name)s_set = 1;
return (msg->%(name)s_data[msg->%(name)s_length - 1]);
error:
--msg->%(name)s_length;
return (NULL);
}
""" % self.GetTranslation()
return code.split('\n')
def CodeComplete(self, structname):
code = []
translate = self.GetTranslation()
if self.Optional():
code.append( 'if (%(structname)s->%(name)s_set)' % translate)
translate["structname"] = structname
tmp = """{
int i;
for (i = 0; i < %(structname)s->%(name)s_length; ++i) {
if (%(refname)s_complete(%(structname)s->%(name)s_data[i]) == -1)
return (-1);
}
}""" % translate
code.extend(tmp.split('\n'))
return code
def CodeUnmarshal(self, buf, tag_name, var_name):
translate = self.GetTranslation()
translate["var_name"] = var_name
translate["buf"] = buf
translate["tag_name"] = tag_name
code = """if (%(parent_name)s_%(name)s_add(%(var_name)s) == NULL)
return (-1);
if (evtag_unmarshal_%(refname)s(%(buf)s, %(tag_name)s,
%(var_name)s->%(name)s_data[%(var_name)s->%(name)s_length - 1]) == -1) {
--%(var_name)s->%(name)s_length;
event_warnx("%%s: failed to unmarshal %(name)s", __func__);
return (-1);
}""" % translate
return code.split('\n')
def CodeMarshal(self, buf, tag_name, var_name):
code = ['{',
' int i;',
' for (i = 0; i < %s->%s_length; ++i) {' % (
var_name, self._name),
' evtag_marshal_%s(%s, %s, %s->%s_data[i]);' % (
self._refname, buf, tag_name, var_name, self._name),
' }',
'}'
]
return code
def CodeClear(self, structname):
code = [ 'if (%s->%s_set == 1) {' % (structname, self.Name()),
' int i;',
' for (i = 0; i < %s->%s_length; ++i) {' % (
structname, self.Name()),
' %s_free(%s->%s_data[i]);' % (
self._refname, structname, self.Name()),
' }',
' free(%s->%s_data);' % (structname, self.Name()),
' %s->%s_data = NULL;' % (structname, self.Name()),
' %s->%s_set = 0;' % (structname, self.Name()),
' %s->%s_length = 0;' % (structname, self.Name()),
' %s->%s_num_allocated = 0;' % (structname, self.Name()),
'}'
]
return code
def CodeNew(self, name):
code = ['%s->%s_data = NULL;' % (name, self._name),
'%s->%s_length = 0;' % (name, self._name),
'%s->%s_num_allocated = 0;' % (name, self._name)]
return code
def CodeFree(self, name):
code = ['if (%s->%s_data != NULL) {' % (name, self._name),
' int i;',
' for (i = 0; i < %s->%s_length; ++i) {' % (
name, self._name),
' %s_free(%s->%s_data[i]); ' % (
self._refname, name, self._name),
' %s->%s_data[i] = NULL;' % (name, self._name),
' }',
' free(%s->%s_data);' % (name, self._name),
' %s->%s_data = NULL;' % (name, self._name),
' %s->%s_length = 0;' % (name, self._name),
' %s->%s_num_allocated = 0;' % (name, self._name),
'}'
]
return code
def Declaration(self):
dcl = ['struct %s **%s_data;' % (self._refname, self._name),
'int %s_length;' % self._name,
'int %s_num_allocated;' % self._name ]
return dcl
def NormalizeLine(line):
global white
global cppcomment
line = cppcomment.sub('', line)
line = line.strip()
line = white.sub(' ', line)
return line
def ProcessOneEntry(newstruct, entry):
optional = 0
array = 0
entry_type = ''
name = ''
tag = ''
tag_set = None
separator = ''
fixed_length = ''
tokens = entry.split(' ')
while tokens:
token = tokens[0]
tokens = tokens[1:]
if not entry_type:
if not optional and token == 'optional':
optional = 1
continue
if not array and token == 'array':
array = 1
continue
if not entry_type:
entry_type = token
continue
if not name:
res = re.match(r'^([^\[\]]+)(\[.*\])?$', token)
if not res:
print >>sys.stderr, 'Cannot parse name: \"%s\" around %d' % (
entry, line_count)
sys.exit(1)
name = res.group(1)
fixed_length = res.group(2)
if fixed_length:
fixed_length = fixed_length[1:-1]
continue
if not separator:
separator = token
if separator != '=':
print >>sys.stderr, 'Expected "=" after name \"%s\" got %s' % (
name, token)
sys.exit(1)
continue
if not tag_set:
tag_set = 1
if not re.match(r'^(0x)?[0-9]+$', token):
print >>sys.stderr, 'Expected tag number: \"%s\"' % entry
sys.exit(1)
tag = int(token, 0)
continue
print >>sys.stderr, 'Cannot parse \"%s\"' % entry
sys.exit(1)
if not tag_set:
print >>sys.stderr, 'Need tag number: \"%s\"' % entry
sys.exit(1)
# Create the right entry
if entry_type == 'bytes':
if fixed_length:
newentry = EntryBytes(entry_type, name, tag, fixed_length)
else:
newentry = EntryVarBytes(entry_type, name, tag)
elif entry_type == 'int' and not fixed_length:
newentry = EntryInt(entry_type, name, tag)
elif entry_type == 'string' and not fixed_length:
newentry = EntryString(entry_type, name, tag)
else:
res = re.match(r'^struct\[(%s)\]$' % _STRUCT_RE,
entry_type, re.IGNORECASE)
if res:
# References another struct defined in our file
newentry = EntryStruct(entry_type, name, tag, res.group(1))
else:
print >>sys.stderr, 'Bad type: "%s" in "%s"' % (entry_type, entry)
sys.exit(1)
structs = []
if optional:
newentry.MakeOptional()
if array:
newentry.MakeArray()
newentry.SetStruct(newstruct)
newentry.SetLineCount(line_count)
newentry.Verify()
if array:
# We need to encapsulate this entry into a struct
newname = newentry.Name()+ '_array'
# Now borgify the new entry.
newentry = EntryArray(newentry)
newentry.SetStruct(newstruct)
newentry.SetLineCount(line_count)
newentry.MakeArray()
newstruct.AddEntry(newentry)
return structs
def ProcessStruct(data):
tokens = data.split(' ')
# First three tokens are: 'struct' 'name' '{'
newstruct = Struct(tokens[1])
inside = ' '.join(tokens[3:-1])
tokens = inside.split(';')
structs = []
for entry in tokens:
entry = NormalizeLine(entry)
if not entry:
continue
# It's possible that new structs get defined in here
structs.extend(ProcessOneEntry(newstruct, entry))
structs.append(newstruct)
return structs
def GetNextStruct(file):
global line_count
global cppdirect
got_struct = 0
processed_lines = []
have_c_comment = 0
data = ''
while 1:
line = file.readline()
if not line:
break
line_count += 1
line = line[:-1]
if not have_c_comment and re.search(r'/\*', line):
if re.search(r'/\*.*\*/', line):
line = re.sub(r'/\*.*\*/', '', line)
else:
line = re.sub(r'/\*.*$', '', line)
have_c_comment = 1
if have_c_comment:
if not re.search(r'\*/', line):
continue
have_c_comment = 0
line = re.sub(r'^.*\*/', '', line)
line = NormalizeLine(line)
if not line:
continue
if not got_struct:
if re.match(r'#include ["<].*[>"]', line):
cppdirect.append(line)
continue
if re.match(r'^#(if( |def)|endif)', line):
cppdirect.append(line)
continue
if re.match(r'^#define', line):
headerdirect.append(line)
continue
if not re.match(r'^struct %s {$' % _STRUCT_RE,
line, re.IGNORECASE):
print >>sys.stderr, 'Missing struct on line %d: %s' % (
line_count, line)
sys.exit(1)
else:
got_struct = 1
data += line
continue
# We are inside the struct
tokens = line.split('}')
if len(tokens) == 1:
data += ' ' + line
continue
if len(tokens[1]):
print >>sys.stderr, 'Trailing garbage after struct on line %d' % (
line_count )
sys.exit(1)
# We found the end of the struct
data += ' %s}' % tokens[0]
break
# Remove any comments, that might be in there
data = re.sub(r'/\*.*\*/', '', data)
return data
def Parse(file):
"""
Parses the input file and returns C code and corresponding header file.
"""
entities = []
while 1:
# Just gets the whole struct nicely formatted
data = GetNextStruct(file)
if not data:
break
entities.extend(ProcessStruct(data))
return entities
def GuardName(name):
name = '_'.join(name.split('.'))
name = '_'.join(name.split('/'))
guard = '_'+name.upper()+'_'
return guard
def HeaderPreamble(name):
guard = GuardName(name)
pre = (
'/*\n'
' * Automatically generated from %s\n'
' */\n\n'
'#ifndef %s\n'
'#define %s\n\n' ) % (
name, guard, guard)
# insert stdint.h - let's hope everyone has it
pre += (
'#include <event-config.h>\n'
'#ifdef _EVENT_HAVE_STDINT_H\n'
'#include <stdint.h>\n'
'#endif\n' )
for statement in headerdirect:
pre += '%s\n' % statement
if headerdirect:
pre += '\n'
pre += (
'#define EVTAG_HAS(msg, member) ((msg)->member##_set == 1)\n'
'#ifdef __GNUC__\n'
'#define EVTAG_ASSIGN(msg, member, args...) '
'(*(msg)->base->member##_assign)(msg, ## args)\n'
'#define EVTAG_GET(msg, member, args...) '
'(*(msg)->base->member##_get)(msg, ## args)\n'
'#else\n'
'#define EVTAG_ASSIGN(msg, member, ...) '
'(*(msg)->base->member##_assign)(msg, ## __VA_ARGS__)\n'
'#define EVTAG_GET(msg, member, ...) '
'(*(msg)->base->member##_get)(msg, ## __VA_ARGS__)\n'
'#endif\n'
'#define EVTAG_ADD(msg, member) (*(msg)->base->member##_add)(msg)\n'
'#define EVTAG_LEN(msg, member) ((msg)->member##_length)\n'
)
return pre
def HeaderPostamble(name):
guard = GuardName(name)
return '#endif /* %s */' % guard
def BodyPreamble(name):
global _NAME
global _VERSION
header_file = '.'.join(name.split('.')[:-1]) + '.gen.h'
pre = ( '/*\n'
' * Automatically generated from %s\n'
' * by %s/%s. DO NOT EDIT THIS FILE.\n'
' */\n\n' ) % (name, _NAME, _VERSION)
pre += ( '#include <sys/types.h>\n'
'#ifdef _EVENT_HAVE_SYS_TIME_H\n'
'#include <sys/time.h>\n'
'#endif\n'
'#include <stdlib.h>\n'
'#include <string.h>\n'
'#include <assert.h>\n'
'#define EVENT_NO_STRUCT\n'
'#include <event.h>\n\n'
'#ifdef _EVENT___func__\n'
'#define __func__ _EVENT___func__\n'
'#endif\n' )
for statement in cppdirect:
pre += '%s\n' % statement
pre += '\n#include "%s"\n\n' % header_file
pre += 'void event_err(int eval, const char *fmt, ...);\n'
pre += 'void event_warn(const char *fmt, ...);\n'
pre += 'void event_errx(int eval, const char *fmt, ...);\n'
pre += 'void event_warnx(const char *fmt, ...);\n\n'
return pre
def main(argv):
if len(argv) < 2 or not argv[1]:
print >>sys.stderr, 'Need RPC description file as first argument.'
sys.exit(1)
filename = argv[1]
ext = filename.split('.')[-1]
if ext != 'rpc':
print >>sys.stderr, 'Unrecognized file extension: %s' % ext
sys.exit(1)
print >>sys.stderr, 'Reading \"%s\"' % filename
fp = open(filename, 'r')
entities = Parse(fp)
fp.close()
header_file = '.'.join(filename.split('.')[:-1]) + '.gen.h'
impl_file = '.'.join(filename.split('.')[:-1]) + '.gen.c'
print >>sys.stderr, '... creating "%s"' % header_file
header_fp = open(header_file, 'w')
print >>header_fp, HeaderPreamble(filename)
# Create forward declarations: allows other structs to reference
# each other
for entry in entities:
entry.PrintForwardDeclaration(header_fp)
print >>header_fp, ''
for entry in entities:
entry.PrintTags(header_fp)
entry.PrintDeclaration(header_fp)
print >>header_fp, HeaderPostamble(filename)
header_fp.close()
print >>sys.stderr, '... creating "%s"' % impl_file
impl_fp = open(impl_file, 'w')
print >>impl_fp, BodyPreamble(filename)
for entry in entities:
entry.PrintCode(impl_fp)
impl_fp.close()
if __name__ == '__main__':
main(sys.argv)
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
##
## Copyright (C) 2012 Async Open Source <http://www.async.com.br>
## All rights reserved
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., or visit: http://www.gnu.org/.
##
## Author(s): Stoq Team <stoq-devel@async.com.br>
##
import mock
from stoqlib.api import api
from stoqlib.gui.editors.preferenceseditor import PreferencesEditor
from stoqlib.gui.test.uitestutils import GUITest
class TestPreferencesEditor(GUITest):
@mock.patch('stoqlib.gui.editors.preferenceseditor.gio.app_info_get_default_for_type')
def test_show(self, app_info):
# stoq.gui.application sets this default style, but if we run this test
# isolated, it will fail
api.user_settings.set('toolbar-style', 'both-horizontal')
app_info.return_value = None
editor = PreferencesEditor(self.store)
editor.language.select_item_by_data(None)
self.check_editor(editor, 'editor-preferences-show')
|
unknown
|
codeparrot/codeparrot-clean
| ||
## Input
```javascript
// @lowerContextAccess
function App() {
const {
joe: {foo},
bar,
} = useContext(MyContext);
return <Bar foo={foo} bar={bar} />;
}
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime"; // @lowerContextAccess
function App() {
const $ = _c(3);
const { joe: t0, bar } = useContext(MyContext);
const { foo } = t0;
let t1;
if ($[0] !== bar || $[1] !== foo) {
t1 = <Bar foo={foo} bar={bar} />;
$[0] = bar;
$[1] = foo;
$[2] = t1;
} else {
t1 = $[2];
}
return t1;
}
```
|
unknown
|
github
|
https://github.com/facebook/react
|
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo.lower-context-access-nested-destructuring.expect.md
|
"""Use the HTMLParser library to parse HTML files that aren't too bad."""
__all__ = [
'HTMLParserTreeBuilder',
]
from html.parser import HTMLParser
try:
from html.parser import HTMLParseError
except ImportError as e:
# HTMLParseError is removed in Python 3.5. Since it can never be
# thrown in 3.5, we can just define our own class as a placeholder.
class HTMLParseError(Exception):
pass
import sys
import warnings
# Starting in Python 3.2, the HTMLParser constructor takes a 'strict'
# argument, which we'd like to set to False. Unfortunately,
# http://bugs.python.org/issue13273 makes strict=True a better bet
# before Python 3.2.3.
#
# At the end of this file, we monkeypatch HTMLParser so that
# strict=True works well on Python 3.2.2.
major, minor, release = sys.version_info[:3]
CONSTRUCTOR_TAKES_STRICT = major == 3 and minor == 2 and release >= 3
CONSTRUCTOR_STRICT_IS_DEPRECATED = major == 3 and minor == 3
CONSTRUCTOR_TAKES_CONVERT_CHARREFS = major == 3 and minor >= 4
from bs4.element import (
CData,
Comment,
Declaration,
Doctype,
ProcessingInstruction,
)
from bs4.dammit import EntitySubstitution, UnicodeDammit
from bs4.builder import (
HTML,
HTMLTreeBuilder,
STRICT,
)
HTMLPARSER = 'html.parser'
class BeautifulSoupHTMLParser(HTMLParser):
def handle_starttag(self, name, attrs):
# XXX namespace
attr_dict = {}
for key, value in attrs:
# Change None attribute values to the empty string
# for consistency with the other tree builders.
if value is None:
value = ''
attr_dict[key] = value
attrvalue = '""'
self.soup.handle_starttag(name, None, None, attr_dict)
def handle_endtag(self, name):
self.soup.handle_endtag(name)
def handle_data(self, data):
self.soup.handle_data(data)
def handle_charref(self, name):
# XXX workaround for a bug in HTMLParser. Remove this once
# it's fixed in all supported versions.
# http://bugs.python.org/issue13633
if name.startswith('x'):
real_name = int(name.lstrip('x'), 16)
elif name.startswith('X'):
real_name = int(name.lstrip('X'), 16)
else:
real_name = int(name)
try:
data = chr(real_name)
except (ValueError, OverflowError) as e:
data = "\N{REPLACEMENT CHARACTER}"
self.handle_data(data)
def handle_entityref(self, name):
character = EntitySubstitution.HTML_ENTITY_TO_CHARACTER.get(name)
if character is not None:
data = character
else:
data = "&%s;" % name
self.handle_data(data)
def handle_comment(self, data):
self.soup.endData()
self.soup.handle_data(data)
self.soup.endData(Comment)
def handle_decl(self, data):
self.soup.endData()
if data.startswith("DOCTYPE "):
data = data[len("DOCTYPE "):]
elif data == 'DOCTYPE':
# i.e. "<!DOCTYPE>"
data = ''
self.soup.handle_data(data)
self.soup.endData(Doctype)
def unknown_decl(self, data):
if data.upper().startswith('CDATA['):
cls = CData
data = data[len('CDATA['):]
else:
cls = Declaration
self.soup.endData()
self.soup.handle_data(data)
self.soup.endData(cls)
def handle_pi(self, data):
self.soup.endData()
self.soup.handle_data(data)
self.soup.endData(ProcessingInstruction)
class HTMLParserTreeBuilder(HTMLTreeBuilder):
is_xml = False
picklable = True
NAME = HTMLPARSER
features = [NAME, HTML, STRICT]
def __init__(self, *args, **kwargs):
if CONSTRUCTOR_TAKES_STRICT and not CONSTRUCTOR_STRICT_IS_DEPRECATED:
kwargs['strict'] = False
if CONSTRUCTOR_TAKES_CONVERT_CHARREFS:
kwargs['convert_charrefs'] = False
self.parser_args = (args, kwargs)
def prepare_markup(self, markup, user_specified_encoding=None,
document_declared_encoding=None, exclude_encodings=None):
"""
:return: A 4-tuple (markup, original encoding, encoding
declared within markup, whether any characters had to be
replaced with REPLACEMENT CHARACTER).
"""
if isinstance(markup, str):
yield (markup, None, None, False)
return
try_encodings = [user_specified_encoding, document_declared_encoding]
dammit = UnicodeDammit(markup, try_encodings, is_html=True,
exclude_encodings=exclude_encodings)
yield (dammit.markup, dammit.original_encoding,
dammit.declared_html_encoding,
dammit.contains_replacement_characters)
def feed(self, markup):
args, kwargs = self.parser_args
parser = BeautifulSoupHTMLParser(*args, **kwargs)
parser.soup = self.soup
try:
parser.feed(markup)
except HTMLParseError as e:
warnings.warn(RuntimeWarning(
"Python's built-in HTMLParser cannot parse the given document. This is not a bug in Beautiful Soup. The best solution is to install an external parser (lxml or html5lib), and use Beautiful Soup with that parser. See http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser for help."))
raise e
# Patch 3.2 versions of HTMLParser earlier than 3.2.3 to use some
# 3.2.3 code. This ensures they don't treat markup like <p></p> as a
# string.
#
# XXX This code can be removed once most Python 3 users are on 3.2.3.
if major == 3 and minor == 2 and not CONSTRUCTOR_TAKES_STRICT:
import re
attrfind_tolerant = re.compile(
r'\s*((?<=[\'"\s])[^\s/>][^\s/=>]*)(\s*=+\s*'
r'(\'[^\']*\'|"[^"]*"|(?![\'"])[^>\s]*))?')
HTMLParserTreeBuilder.attrfind_tolerant = attrfind_tolerant
locatestarttagend = re.compile(r"""
<[a-zA-Z][-.a-zA-Z0-9:_]* # tag name
(?:\s+ # whitespace before attribute name
(?:[a-zA-Z_][-.:a-zA-Z0-9_]* # attribute name
(?:\s*=\s* # value indicator
(?:'[^']*' # LITA-enclosed value
|\"[^\"]*\" # LIT-enclosed value
|[^'\">\s]+ # bare value
)
)?
)
)*
\s* # trailing whitespace
""", re.VERBOSE)
BeautifulSoupHTMLParser.locatestarttagend = locatestarttagend
from html.parser import tagfind, attrfind
def parse_starttag(self, i):
self.__starttag_text = None
endpos = self.check_for_whole_start_tag(i)
if endpos < 0:
return endpos
rawdata = self.rawdata
self.__starttag_text = rawdata[i:endpos]
# Now parse the data between i+1 and j into a tag and attrs
attrs = []
match = tagfind.match(rawdata, i+1)
assert match, 'unexpected call to parse_starttag()'
k = match.end()
self.lasttag = tag = rawdata[i+1:k].lower()
while k < endpos:
if self.strict:
m = attrfind.match(rawdata, k)
else:
m = attrfind_tolerant.match(rawdata, k)
if not m:
break
attrname, rest, attrvalue = m.group(1, 2, 3)
if not rest:
attrvalue = None
elif attrvalue[:1] == '\'' == attrvalue[-1:] or \
attrvalue[:1] == '"' == attrvalue[-1:]:
attrvalue = attrvalue[1:-1]
if attrvalue:
attrvalue = self.unescape(attrvalue)
attrs.append((attrname.lower(), attrvalue))
k = m.end()
end = rawdata[k:endpos].strip()
if end not in (">", "/>"):
lineno, offset = self.getpos()
if "\n" in self.__starttag_text:
lineno = lineno + self.__starttag_text.count("\n")
offset = len(self.__starttag_text) \
- self.__starttag_text.rfind("\n")
else:
offset = offset + len(self.__starttag_text)
if self.strict:
self.error("junk characters in start tag: %r"
% (rawdata[k:endpos][:20],))
self.handle_data(rawdata[i:endpos])
return endpos
if end.endswith('/>'):
# XHTML-style empty tag: <span attr="value" />
self.handle_startendtag(tag, attrs)
else:
self.handle_starttag(tag, attrs)
if tag in self.CDATA_CONTENT_ELEMENTS:
self.set_cdata_mode(tag)
return endpos
def set_cdata_mode(self, elem):
self.cdata_elem = elem.lower()
self.interesting = re.compile(r'</\s*%s\s*>' % self.cdata_elem, re.I)
BeautifulSoupHTMLParser.parse_starttag = parse_starttag
BeautifulSoupHTMLParser.set_cdata_mode = set_cdata_mode
CONSTRUCTOR_TAKES_STRICT = True
|
unknown
|
codeparrot/codeparrot-clean
| ||
"""
Views and functions for serving static files. These are only to be used during
development, and SHOULD NOT be used in a production setting.
"""
import os
import posixpath
try:
from urllib.parse import unquote
except ImportError: # Python 2
from urllib import unquote
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.http import Http404
from django.views import static
from django.contrib.staticfiles import finders
def serve(request, path, document_root=None, insecure=False, **kwargs):
"""
Serve static files below a given point in the directory structure or
from locations inferred from the staticfiles finders.
To use, put a URL pattern such as::
(r'^(?P<path>.*)$', 'django.contrib.staticfiles.views.serve')
in your URLconf.
It uses the django.views.static view to serve the found files.
"""
if not settings.DEBUG and not insecure:
raise ImproperlyConfigured("The staticfiles view can only be used in "
"debug mode or if the --insecure "
"option of 'runserver' is used")
normalized_path = posixpath.normpath(unquote(path)).lstrip('/')
absolute_path = finders.find(normalized_path)
if not absolute_path:
if path.endswith('/') or path == '':
raise Http404("Directory indexes are not allowed here.")
raise Http404("'%s' could not be found" % path)
document_root, path = os.path.split(absolute_path)
return static.serve(request, path, document_root=document_root, **kwargs)
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/env python
#
# Copyright (C) 2009 Google 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.
from types import ListType, DictionaryType
"""Contains a client to communicate with the Contacts servers.
For documentation on the Contacts API, see:
http://code.google.com/apis/contatcs/
"""
__author__ = 'vinces1979@gmail.com (Vince Spicer)'
import gdata.client
import gdata.contacts.data
import atom.client
import atom.data
import atom.http_core
import gdata.gauth
DEFAULT_BATCH_URL = ('https://www.google.com/m8/feeds/contacts/default/full'
'/batch')
DEFAULT_PROFILES_BATCH_URL = ('https://www.google.com/m8/feeds/profiles/domain/'
'%s/full/batch')
class ContactsClient(gdata.client.GDClient):
api_version = '3'
auth_service = 'cp'
server = "www.google.com"
contact_list = "default"
auth_scopes = gdata.gauth.AUTH_SCOPES['cp']
ssl = True
def __init__(self, domain=None, auth_token=None, **kwargs):
"""Constructs a new client for the Email Settings API.
Args:
domain: string The Google Apps domain (if any).
kwargs: The other parameters to pass to the gdata.client.GDClient
constructor.
"""
gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs)
self.domain = domain
def get_feed_uri(self, kind='contacts', contact_list=None, projection='full',
scheme="https"):
"""Builds a feed URI.
Args:
kind: The type of feed to return, typically 'groups' or 'contacts'.
Default value: 'contacts'.
contact_list: The contact list to return a feed for.
Default value: self.contact_list.
projection: The projection to apply to the feed contents, for example
'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
scheme: The URL scheme such as 'http' or 'https', None to return a
relative URI without hostname.
Returns:
A feed URI using the given kind, contact list, and projection.
Example: '/m8/feeds/contacts/default/full'.
"""
contact_list = contact_list or self.contact_list
if kind == 'profiles':
contact_list = 'domain/%s' % self.domain
prefix = scheme and '%s://%s' % (scheme, self.server) or ''
return '%s/m8/feeds/%s/%s/%s' % (prefix, kind, contact_list, projection)
GetFeedUri = get_feed_uri
def get_contact(self, uri, desired_class=gdata.contacts.data.ContactEntry,
auth_token=None, **kwargs):
return self.get_entry(uri, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetContact = get_contact
def create_contact(self, new_contact, insert_uri=None, auth_token=None, **kwargs):
"""Adds an new contact to Google Contacts.
Args:
new_contact: atom.Entry or subclass A new contact which is to be added to
Google Contacts.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = insert_uri or self.GetFeedUri()
return self.Post(new_contact, insert_uri,
auth_token=auth_token, **kwargs)
CreateContact = create_contact
def add_contact(self, new_contact, insert_uri=None, auth_token=None,
billing_information=None, birthday=None, calendar_link=None, **kwargs):
"""Adds an new contact to Google Contacts.
Args:
new_contact: atom.Entry or subclass A new contact which is to be added to
Google Contacts.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
contact = gdata.contacts.data.ContactEntry()
if billing_information is not None:
if not isinstance(billing_information, gdata.contacts.data.BillingInformation):
billing_information = gdata.contacts.data.BillingInformation(text=billing_information)
contact.billing_information = billing_information
if birthday is not None:
if not isinstance(birthday, gdata.contacts.data.Birthday):
birthday = gdata.contacts.data.Birthday(when=birthday)
contact.birthday = birthday
if calendar_link is not None:
if type(calendar_link) is not ListType:
calendar_link = [calendar_link]
for link in calendar_link:
if not isinstance(link, gdata.contacts.data.CalendarLink):
if type(link) is not DictionaryType:
raise TypeError, "calendar_link Requires dictionary not %s" % type(link)
link = gdata.contacts.data.CalendarLink(
rel=link.get("rel", None),
label=link.get("label", None),
primary=link.get("primary", None),
href=link.get("href", None),
)
contact.calendar_link.append(link)
insert_uri = insert_uri or self.GetFeedUri()
return self.Post(contact, insert_uri,
auth_token=auth_token, **kwargs)
AddContact = add_contact
def get_contacts(self, uri=None, desired_class=gdata.contacts.data.ContactsFeed,
auth_token=None, **kwargs):
"""Obtains a feed with the contacts belonging to the current user.
Args:
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.SpreadsheetsFeed.
"""
uri = uri or self.GetFeedUri()
return self.get_feed(uri, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetContacts = get_contacts
def get_group(self, uri=None, desired_class=gdata.contacts.data.GroupEntry,
auth_token=None, **kwargs):
""" Get a single groups details
Args:
uri: the group uri or id
"""
return self.get_entry(uri, desired_class=desired_class, auth_token=auth_token, **kwargs)
GetGroup = get_group
def get_groups(self, uri=None, desired_class=gdata.contacts.data.GroupsFeed,
auth_token=None, **kwargs):
uri = uri or self.GetFeedUri('groups')
return self.get_feed(uri, desired_class=desired_class, auth_token=auth_token, **kwargs)
GetGroups = get_groups
def create_group(self, new_group, insert_uri=None, url_params=None,
desired_class=None, **kwargs):
insert_uri = insert_uri or self.GetFeedUri('groups')
return self.Post(new_group, insert_uri, url_params=url_params,
desired_class=desired_class, **kwargs)
CreateGroup = create_group
def update_group(self, edit_uri, updated_group, url_params=None,
escape_params=True, desired_class=None, auth_token=None, **kwargs):
return self.Put(updated_group, self._CleanUri(edit_uri),
url_params=url_params,
escape_params=escape_params,
desired_class=desired_class,
auth_token=auth_token, **kwargs)
UpdateGroup = update_group
def delete_group(self, group_object, auth_token=None, force=False, **kws):
return self.Delete(group_object, auth_token=auth_token, force=force, **kws)
DeleteGroup = delete_group
def change_photo(self, media, contact_entry_or_url, content_type=None,
content_length=None, auth_token=None, **kwargs):
"""Change the photo for the contact by uploading a new photo.
Performs a PUT against the photo edit URL to send the binary data for the
photo.
Args:
media: filename, file-like-object, or a gdata.data.MediaSource object to send.
contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this
method will search for an edit photo link URL and
perform a PUT to the URL.
content_type: str (optional) the mime type for the photo data. This is
necessary if media is a file or file name, but if media
is a MediaSource object then the media object can contain
the mime type. If media_type is set, it will override the
mime type in the media object.
content_length: int or str (optional) Specifying the content length is
only required if media is a file-like object. If media
is a filename, the length is determined using
os.path.getsize. If media is a MediaSource object, it is
assumed that it already contains the content length.
"""
ifmatch_header = None
if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
uri = photo_link.href
ifmatch_header = atom.client.CustomHeaders(
**{'if-match': photo_link.etag})
else:
uri = contact_entry_or_url
if isinstance(media, gdata.data.MediaSource):
payload = media
# If the media object is a file-like object, then use it as the file
# handle in the in the MediaSource.
elif hasattr(media, 'read'):
payload = gdata.data.MediaSource(file_handle=media,
content_type=content_type, content_length=content_length)
# Assume that the media object is a file name.
else:
payload = gdata.data.MediaSource(content_type=content_type,
content_length=content_length, file_path=media)
return self.Put(uri=uri, data=payload, auth_token=auth_token,
ifmatch_header=ifmatch_header, **kwargs)
ChangePhoto = change_photo
def get_photo(self, contact_entry_or_url, auth_token=None, **kwargs):
"""Retrives the binary data for the contact's profile photo as a string.
Args:
contact_entry_or_url: a gdata.contacts.ContactEntry object or a string
containing the photo link's URL. If the contact entry does not
contain a photo link, the image will not be fetched and this method
will return None.
"""
# TODO: add the ability to write out the binary image data to a file,
# reading and writing a chunk at a time to avoid potentially using up
# large amounts of memory.
url = None
if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
if photo_link:
url = photo_link.href
else:
url = contact_entry_or_url
if url:
return self.Get(url, auth_token=auth_token, **kwargs).read()
else:
return None
GetPhoto = get_photo
def delete_photo(self, contact_entry_or_url, auth_token=None, **kwargs):
"""Delete the contact's profile photo.
Args:
contact_entry_or_url: a gdata.contacts.ContactEntry object or a string
containing the photo link's URL.
"""
uri = None
ifmatch_header = None
if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
if photo_link.etag:
uri = photo_link.href
ifmatch_header = atom.client.CustomHeaders(
**{'if-match': photo_link.etag})
else:
# No etag means no photo has been assigned to this contact.
return
else:
uri = contact_entry_or_url
if uri:
self.Delete(entry_or_uri=uri, auth_token=auth_token,
ifmatch_header=ifmatch_header, **kwargs)
DeletePhoto = delete_photo
def get_profiles_feed(self, uri=None, auth_token=None, **kwargs):
"""Retrieves a feed containing all domain's profiles.
Args:
uri: string (optional) the URL to retrieve the profiles feed,
for example /m8/feeds/profiles/default/full
Returns:
On success, a ProfilesFeed containing the profiles.
On failure, raises a RequestError.
"""
uri = uri or self.GetFeedUri('profiles')
return self.get_feed(uri, auth_token=auth_token,
desired_class=gdata.contacts.data.ProfilesFeed, **kwargs)
GetProfilesFeed = get_profiles_feed
def get_profile(self, uri, auth_token=None, **kwargs):
"""Retrieves a domain's profile for the user.
Args:
uri: string the URL to retrieve the profiles feed,
for example /m8/feeds/profiles/default/full/username
Returns:
On success, a ProfileEntry containing the profile for the user.
On failure, raises a RequestError
"""
return self.get_entry(uri,
desired_class=gdata.contacts.data.ProfileEntry,
auth_token=auth_token, **kwargs)
GetProfile = get_profile
def update_profile(self, updated_profile, auth_token=None, force=False, **kwargs):
"""Updates an existing profile.
Args:
updated_profile: atom.Entry or subclass containing
the Atom Entry which will replace the profile which is
stored at the edit_url.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of ContactsClient.
force: boolean stating whether an update should be forced. Defaults to
False. Normally, if a change has been made since the passed in
entry was obtained, the server will not overwrite the entry since
the changes were based on an obsolete version of the entry.
Setting force to True will cause the update to silently
overwrite whatever version is present.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, raises a RequestError.
"""
return self.Update(updated_profile, auth_token=auth_token, force=force, **kwargs)
UpdateProfile = update_profile
def execute_batch(self, batch_feed, url=DEFAULT_BATCH_URL, desired_class=None,
auth_token=None, **kwargs):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.contacts.ContactFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: str The batch URL to which these operations should be applied.
converter: Function (optional) The function used to convert the server's
response to an object.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a ContactsFeed.
"""
return self.Post(batch_feed, url, desired_class=desired_class,
auth_token=None, **kwargs)
ExecuteBatch = execute_batch
def execute_batch_profiles(self, batch_feed, url=None,
desired_class=gdata.contacts.data.ProfilesFeed,
auth_token=None, **kwargs):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.profiles.ProfilesFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: string The batch URL to which these operations should be applied.
converter: Function (optional) The function used to convert the server's
response to an object. The default value is
gdata.profiles.ProfilesFeedFromString.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a ProfilesFeed.
"""
url = url or (DEFAULT_PROFILES_BATCH_URL % self.domain)
return self.Post(batch_feed, url, desired_class=desired_class,
auth_token=auth_token, **kwargs)
ExecuteBatchProfiles = execute_batch_profiles
def _CleanUri(self, uri):
"""Sanitizes a feed URI.
Args:
uri: The URI to sanitize, can be relative or absolute.
Returns:
The given URI without its http://server prefix, if any.
Keeps the leading slash of the URI.
"""
url_prefix = 'http://%s' % self.server
if uri.startswith(url_prefix):
uri = uri[len(url_prefix):]
return uri
class ContactsQuery(gdata.client.Query):
"""
Create a custom Contacts Query
Full specs can be found at: U{Contacts query parameters reference
<http://code.google.com/apis/contacts/docs/3.0/reference.html#Parameters>}
"""
def __init__(self, feed=None, group=None, orderby=None, showdeleted=None,
sortorder=None, requirealldeleted=None, **kwargs):
"""
@param max_results: The maximum number of entries to return. If you want
to receive all of the contacts, rather than only the default maximum, you
can specify a very large number for max-results.
@param start-index: The 1-based index of the first result to be retrieved.
@param updated-min: The lower bound on entry update dates.
@param group: Constrains the results to only the contacts belonging to the
group specified. Value of this parameter specifies group ID
@param orderby: Sorting criterion. The only supported value is
lastmodified.
@param showdeleted: Include deleted contacts in the returned contacts feed
@pram sortorder: Sorting order direction. Can be either ascending or
descending.
@param requirealldeleted: Only relevant if showdeleted and updated-min
are also provided. It dictates the behavior of the server in case it
detects that placeholders of some entries deleted since the point in
time specified as updated-min may have been lost.
"""
gdata.client.Query.__init__(self, **kwargs)
self.group = group
self.orderby = orderby
self.sortorder = sortorder
self.showdeleted = showdeleted
def modify_request(self, http_request):
if self.group:
gdata.client._add_query_param('group', self.group, http_request)
if self.orderby:
gdata.client._add_query_param('orderby', self.orderby, http_request)
if self.sortorder:
gdata.client._add_query_param('sortorder', self.sortorder, http_request)
if self.showdeleted:
gdata.client._add_query_param('showdeleted', self.showdeleted, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
class ProfilesQuery(gdata.client.Query):
"""
Create a custom Profiles Query
Full specs can be found at: U{Profiless query parameters reference
<http://code.google.com/apis/apps/profiles/reference.html#Parameters>}
"""
def __init__(self, feed=None, start_key=None, **kwargs):
"""
@param start_key: Opaque key of the first element to retrieve. Present in
the next link of an earlier request, if further pages of response are
available.
"""
gdata.client.Query.__init__(self, **kwargs)
self.feed = feed or 'https://www.google.com/m8/feeds/profiles/default/full'
self.start_key = start_key
def modify_request(self, http_request):
if self.start_key:
gdata.client._add_query_param('start-key', self.start_key, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.fir.components
import org.jetbrains.kotlin.analysis.api.components.KaClassTypeBuilder
import org.jetbrains.kotlin.analysis.api.components.KaTypeParameterTypeBuilder
import org.jetbrains.kotlin.analysis.api.fir.KaFirSession
import org.jetbrains.kotlin.analysis.api.fir.utils.firSymbol
import org.jetbrains.kotlin.analysis.api.impl.base.components.KaBaseClassTypeBuilder
import org.jetbrains.kotlin.analysis.api.impl.base.components.KaBaseTypeCreator
import org.jetbrains.kotlin.analysis.api.impl.base.components.KaBaseTypeParameterTypeBuilder
import org.jetbrains.kotlin.analysis.api.lifetime.withValidityAssertion
import org.jetbrains.kotlin.analysis.api.symbols.KaClassLikeSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KaTypeParameterSymbol
import org.jetbrains.kotlin.analysis.api.types.KaType
import org.jetbrains.kotlin.analysis.api.types.KaTypeParameterType
import org.jetbrains.kotlin.fir.resolve.diagnostics.ConeUnresolvedSymbolError
import org.jetbrains.kotlin.fir.resolve.providers.symbolProvider
import org.jetbrains.kotlin.fir.scopes.impl.toConeType
import org.jetbrains.kotlin.fir.types.*
import org.jetbrains.kotlin.name.ClassId
internal class KaFirTypeCreator(
override val analysisSessionProvider: () -> KaFirSession,
) : KaBaseTypeCreator<KaFirSession>(), KaFirSessionComponent {
override fun buildClassType(classId: ClassId, init: KaClassTypeBuilder.() -> Unit): KaType = withValidityAssertion {
return buildClassType(KaBaseClassTypeBuilder.ByClassId(classId, token).apply(init))
}
override fun buildClassType(symbol: KaClassLikeSymbol, init: KaClassTypeBuilder.() -> Unit): KaType = withValidityAssertion {
return buildClassType(KaBaseClassTypeBuilder.BySymbol(symbol, token).apply(init))
}
private fun buildClassType(builder: KaBaseClassTypeBuilder): KaType {
val lookupTag = when (builder) {
is KaBaseClassTypeBuilder.ByClassId -> {
val classSymbol = rootModuleSession.symbolProvider.getClassLikeSymbolByClassId(builder.classId)
?: return ConeErrorType(ConeUnresolvedSymbolError(builder.classId)).asKaType()
classSymbol.toLookupTag()
}
is KaBaseClassTypeBuilder.BySymbol -> {
val symbol = builder.symbol
symbol.classId?.toLookupTag() ?: symbol.firSymbol.toLookupTag()
}
}
val typeContext = rootModuleSession.typeContext
val coneType = typeContext.createSimpleType(
lookupTag,
builder.arguments.map { it.coneTypeProjection },
builder.isMarkedNullable
) as ConeClassLikeType
return coneType.asKaType()
}
override fun buildTypeParameterType(symbol: KaTypeParameterSymbol, init: KaTypeParameterTypeBuilder.() -> Unit): KaTypeParameterType {
withValidityAssertion {
val builder = KaBaseTypeParameterTypeBuilder.BySymbol(symbol, token).apply(init)
val symbol = builder.symbol
val coneType = symbol.firSymbol.toConeType()
.withNullability(nullable = builder.isMarkedNullable, typeContext = analysisSession.firSession.typeContext)
return coneType.asKaType() as KaTypeParameterType
}
}
}
|
kotlin
|
github
|
https://github.com/JetBrains/kotlin
|
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/components/KaFirTypeCreator.kt
|
#!/usr/bin/python
#
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = """
---
module: sros_config
version_added: "2.2"
author: "Peter Sprygada (@privateip)"
short_description: Manage Nokia SR OS device configuration
description:
- Nokia SR OS configurations use a simple block indent file syntax
for segmenting configuration into sections. This module provides
an implementation for working with SR OS configuration sections in
a deterministic way.
extends_documentation_fragment: sros
options:
lines:
description:
- The ordered set of commands that should be configured in the
section. The commands must be the exact same commands as found
in the device running-config. Be sure to note the configuration
command syntax as some commands are automatically modified by the
device config parser.
required: false
default: null
aliases: ['commands']
parents:
description:
- The ordered set of parents that uniquely identify the section
the commands should be checked against. If the parents argument
is omitted, the commands are checked against the set of top
level or global commands.
required: false
default: null
src:
description:
- Specifies the source path to the file that contains the configuration
or configuration template to load. The path to the source file can
either be the full path on the Ansible control host or a relative
path from the playbook or role root directory. This argument is mutually
exclusive with I(lines).
required: false
default: null
version_added: "2.2"
before:
description:
- The ordered set of commands to push on to the command stack if
a change needs to be made. This allows the playbook designer
the opportunity to perform configuration commands prior to pushing
any changes without affecting how the set of commands are matched
against the system.
required: false
default: null
after:
description:
- The ordered set of commands to append to the end of the command
stack if a change needs to be made. Just like with I(before) this
allows the playbook designer to append a set of commands to be
executed after the command set.
required: false
default: null
match:
description:
- Instructs the module on the way to perform the matching of
the set of commands against the current device config. If
match is set to I(line), commands are matched line by line. If
match is set to I(strict), command lines are matched with respect
to position. If match is set to I(exact), command lines
must be an equal match. Finally, if match is set to I(none), the
module will not attempt to compare the source configuration with
the running configuration on the remote device.
required: false
default: line
choices: ['line', 'strict', 'exact', 'none']
replace:
description:
- Instructs the module on the way to perform the configuration
on the device. If the replace argument is set to I(line) then
the modified lines are pushed to the device in configuration
mode. If the replace argument is set to I(block) then the entire
command block is pushed to the device in configuration mode if any
line is not correct.
required: false
default: line
choices: ['line', 'block']
force:
description:
- The force argument instructs the module to not consider the
current devices running-config. When set to true, this will
cause the module to push the contents of I(src) into the device
without first checking if already configured.
- Note this argument should be considered deprecated. To achieve
the equivalent, set the C(match=none) which is idempotent. This argument
will be removed in a future release.
required: false
default: false
choices: [ "true", "false" ]
version_added: "2.2"
backup:
description:
- This argument will cause the module to create a full backup of
the current C(running-config) from the remote device before any
changes are made. The backup file is written to the C(backup)
folder in the playbook root directory. If the directory does not
exist, it is created.
required: false
default: no
choices: ['yes', 'no']
version_added: "2.2"
config:
description:
- The C(config) argument allows the playbook designer to supply
the base configuration to be used to validate configuration
changes necessary. If this argument is provided, the module
will not download the running-config from the remote node.
required: false
default: null
version_added: "2.2"
defaults:
description:
- This argument specifies whether or not to collect all defaults
when getting the remote device running config. When enabled,
the module will get the current config by issuing the command
C(show running-config all).
required: false
default: no
choices: ['yes', 'no']
aliases: ['detail']
version_added: "2.2"
save:
description:
- The C(save) argument instructs the module to save the running-
config to the startup-config at the conclusion of the module
running. If check mode is specified, this argument is ignored.
required: false
default: no
choices: ['yes', 'no']
version_added: "2.2"
"""
EXAMPLES = """
# Note: examples below use the following provider dict to handle
# transport and authentication to the node.
---
vars:
cli:
host: "{{ inventory_hostname }}"
username: admin
password: admin
transport: cli
---
- name: enable rollback location
sros_config:
lines: configure system rollback rollback-location "cf3:/ansible"
provider: "{{ cli }}"
- name: set system name to {{ inventory_hostname }} using one line
sros_config:
lines:
- configure system name "{{ inventory_hostname }}"
provider: "{{ cli }}"
- name: set system name to {{ inventory_hostname }} using parents
sros_config:
lines:
- 'name "{{ inventory_hostname }}"'
parents:
- configure
- system
provider: "{{ cli }}"
backup: yes
- name: load config from file
sros_config:
src: "{{ inventory_hostname }}.cfg"
provider: "{{ cli }}"
save: yes
"""
RETURN = """
updates:
description: The set of commands that will be pushed to the remote device
returned: always
type: list
sample: ['config system name "sros01"']
commands:
description: The set of commands that will be pushed to the remote device
returned: always
type: list
sample: ['config system name "sros01"']
backup_path:
description: The full path to the backup file
returned: when backup is yes
type: string
sample: /playbooks/ansible/backup/sros_config.2016-07-16@22:28:34
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.netcfg import NetworkConfig, dumps
from ansible.module_utils.sros import sros_argument_spec, check_args, load_config, run_commands, get_config
def sanitize_config(lines):
commands = list()
for line in lines:
for index, entry in enumerate(commands):
if line.startswith(entry):
del commands[index]
break
commands.append(line)
return commands
def get_active_config(module):
contents = module.params['config']
if not contents:
flags = []
if module.params['defaults']:
flags = ['detail']
return get_config(module, flags)
return contents
def get_candidate(module):
candidate = NetworkConfig(indent=4)
if module.params['src']:
candidate.load(module.params['src'])
elif module.params['lines']:
parents = module.params['parents'] or list()
candidate.add(module.params['lines'], parents=parents)
return candidate
def run(module, result):
match = module.params['match']
candidate = get_candidate(module)
if match != 'none':
config_text = get_active_config(module)
config = NetworkConfig(indent=4, contents=config_text)
configobjs = candidate.difference(config)
else:
configobjs = candidate.items
if configobjs:
commands = dumps(configobjs, 'commands')
commands = sanitize_config(commands.split('\n'))
result['commands'] = commands
result['updates'] = commands
# send the configuration commands to the device and merge
# them with the current running config
if not module.check_mode:
load_config(module, commands)
result['changed'] = True
def main():
""" main entry point for module execution
"""
argument_spec = dict(
src=dict(type='path'),
lines=dict(aliases=['commands'], type='list'),
parents=dict(type='list'),
match=dict(default='line', choices=['line', 'none']),
config=dict(),
defaults=dict(type='bool', default=False, aliases=['detail']),
backup=dict(type='bool', default=False),
save=dict(type='bool', default=False),
)
argument_spec.update(sros_argument_spec)
mutually_exclusive = [('lines', 'src')]
module = AnsibleModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)
result = dict(changed=False, warnings=list())
warnings = list()
check_args(module, warnings)
if warnings:
result['warnings'] = warnings
if module.params['backup']:
result['__backup__'] = get_config(module)
run(module, result)
if module.params['save']:
if not module.check_mode:
run_commands(module, ['admin save'])
result['changed'] = True
module.exit_json(**result)
if __name__ == '__main__':
main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package remote
|
go
|
github
|
https://github.com/hashicorp/terraform
|
internal/communicator/remote/command_test.go
|
import os
from typing import List, Optional
from pyllars.cppparser.parser.clang_translator import NodeType
from .generator import Generator
class CXXRecordDeclGenerator(Generator):
def generate(self):
self._node.normalize()
if 'implicit' in self._node.qualifiers:
return None, None
name = self._node.name or "anonymous_%s" % self._node.node_id
typename_qualifier = "typename" if 'union' not in self._node.qualifiers else ""
def find_typename(node: NodeType.Node, recurse: bool=False):
if node is None:
return None
if self._node.name:
typename = f"{typename_qualifier} ::{self._node.full_cpp_name}"
elif not self._node.parent:
typename = None
else:
index = self._node.parent.children.index(self._node)
if index < 0:
raise Exception("invalid code structure encountered")
if len(self._node.parent.children) > index + 1 and isinstance(self._node.parent.children[index + 1],
NodeType.FieldDecl):
field = self._node.parent.children[index + 1]
field_name = field.full_cpp_name
typename = f"decltype(::{field_name})" if field.name else None
elif recurse and node.parent and not isinstance(node.parent, NodeType.NamespaceDecl):
return find_typename(node.parent, recurse)
else:
typename = None
return typename
typename = find_typename(self._node)
if not typename:
return None, None
header_stream = open(os.path.join(self.my_root_dir, name+'.hpp'), 'w',
encoding='utf-8')
body_stream = open(os.path.join(self.my_root_dir, self._source_path_root, name+'.cpp'), 'w',
encoding='utf-8')
try:
parent = self._node.parent
# generate body
body_stream.write(f"#include <pyllars/pyllars_class.hpp>\n")
body_stream.write(f"#include <{self.source_path}>\n")
if self._node.name:
body_stream.write(f"#include \"{self._node.name}.hpp\"\n\n")
body_stream.write("namespace {\n")
if isinstance(parent, NodeType.NamespaceDecl):
if parent:
body_stream.write(f"""
extern const char parent_fullnsname[] = "{parent.full_cpp_name}";
using Parent = pyllars::NSInfo<parent_fullnsname>;
""")
else:
body_stream.write("using Parent = pyllars:GlobalNS;\n")
else:
body_stream.write(f"using Parent = {find_typename(self._node.parent, True) or 'pyllars::GlobalNS'};\n")
if self._node.bases:
bases = ", " + ", ".join([c.full_name for c in self._node.bases])
else:
bases = ""
body_stream.write("}\n\n")
body_stream.write(f"template class pyllars::PyllarsClass<{typename}, Parent{bases}>;\n")
body_stream.write(f"""
namespace __pyllars_internal{{
template<>
const char* const TypeInfo<{typename}>::type_name = \"{self._node.name if self._node.name else "<<anonymous type>>"}\";
}}
""")
finally:
header_stream.close()
body_stream.close()
return header_stream.name, body_stream.name
class DefinitionDataGenerator(Generator):
def generate(self):
return None, None
class DefaultConstructorGenerator(Generator):
def generate(self):
parent = self._node.parent.parent
class_name = self._node.parent.parent.name
if not class_name:
return None, None
if 'default_is_constexpr' in self._node.classifiers:
return None, None
while parent and not parent.name and isinstance(parent, NodeType.CXXRecordDecl):
parent = parent.parent
if not parent:
return None, None
body_stream = open(
os.path.join(self.my_root_dir, self._source_path_root, class_name + ' default_constructor.cpp'), 'w',
encoding='utf-8')
try:
# generate body
body_stream.write(f"""\n#include \"{self.source_path}\"
#include <pyllars/pyllars_classconstructor.hpp>
""")
body_stream.write("namespace {\n")
body_stream.write(" static const char* const empty_list[] = {nullptr};\n")
body_stream.write("}\n")
body_stream.write(f"template class pyllars::PyllarsClassConstructor<empty_list, "
f"{self._node.parent.parent.full_cpp_name}>;")
finally:
body_stream.close()
return None, body_stream.name
class CopyConstructorGenerator(Generator):
def generate(self):
class_name = self._node.parent.parent.name
if not class_name:
return None, None
if 'user_declared' in self._node.classifiers or not self._node.classifiers:
return None, None
class_full_cpp_name = self._node.parent.parent.full_cpp_name
parent = self._node.parent.parent
while parent and not parent.name and isinstance(parent, NodeType.CXXRecordDecl):
parent = parent.parent
if not parent:
return None, None
body_stream = open(
os.path.join(self.my_root_dir, self._source_path_root, class_name + ' default_copy_constructor.cpp'), 'w',
encoding='utf-8')
try:
parent_name = parent.name
parent_header_path = os.path.join("..", parent_name)
# generate body
body_stream.write(f"""\n#include \"{self.source_path}\"
#include \"{parent_header_path}.hpp\"
#include <pyllars/pyllars_classconstructor.hpp>
""")
body_stream.write("using namespace pyllars;\nnamespace{\n")
body_stream.write(" const char* const kwlist[] = {\"object\", nullptr};")
body_stream.write("}\n\n")
body_stream.write(f"template class PyllarsClassConstructor<kwlist, {class_full_cpp_name}, const {class_full_cpp_name}&>;")
finally:
body_stream.close()
return None, body_stream.name
class MoveConstructorGenerator(Generator):
def generate(self):
class_name = self._node.parent.parent.name
if not class_name:
return None, None
if 'user_declared' in self._node.classifiers or not self._node.classifiers:
return None, None
class_full_cpp_name = self._node.parent.parent.full_cpp_name
parent = self._node.parent.parent
while parent and not parent.name and isinstance(parent, NodeType.CXXRecordDecl):
parent = parent.parent
if not parent:
return None, None
body_stream = open(
os.path.join(self.my_root_dir, self._source_path_root, class_name + ' default_move_constructor.cpp'), 'w',
encoding='utf-8')
try:
parent_name = parent.name
parent_header_path = os.path.join("..", parent_name)
# generate body
body_stream.write(f"""\n#include \"{self.source_path}\"
#include \"{parent_header_path}.hpp\"
#include <pyllars/pyllars_classconstructor.hpp>
""")
body_stream.write("using namespace pyllars;\nnamespace{\n")
body_stream.write(" const char* const kwlist[] = {\"object\", nullptr};")
body_stream.write("}\n\n")
body_stream.write(
f"template class PyllarsClassConstructor<kwlist, {class_full_cpp_name}, const {class_full_cpp_name}&&>;")
finally:
body_stream.close()
return None, body_stream.name
class CopyAssignmentGenerator(Generator):
def generate(self):
class_name = self._node.parent.parent.name
if not class_name:
return None, None
if 'user_declared' in self._node.classifiers or not self._node.classifiers:
return None, None
class_full_cpp_name = self._node.parent.parent.full_cpp_name
parent = self._node.parent.parent
while parent and not parent.name and isinstance(parent, NodeType.CXXRecordDecl):
parent = parent.parent
if not parent:
return None, None
body_stream = open(
os.path.join(self.my_root_dir, self._source_path_root, class_name + ' default_copy_assignment.cpp'), 'w',
encoding='utf-8')
try:
parent_name = parent.name
parent_header_path = os.path.join("..", parent_name)
# generate body
body_stream.write(f"""\n#include \"{self.source_path}\"
#include \"{parent_header_path}.hpp\"
#include <cstddef>
#include <type_traits>
#include <pyllars/pyllars_classmethod.hpp>
""")
body_stream.write(f"""
using namespace pyllars;
namespace {{
//From: DefaultConstructorDeclGenerator.generate
/**
* clang does not properly delete default assignment operator, so must use compile-time check
* instead to prevent compiler error from generated code that shouldn't be
*/
template<const char* const name, const char* const kwlist[], typename T>
static int template_set_up(){{
if constexpr (std::is_copy_assignable<T>::value){{
typedef T& (T::*method_t)(const T&);
PyllarsClassMethod<name, kwlist, method_t, &T::operator= >();
}}
return 0;
}}
typedef const char* const kwlist_t[2];
constexpr kwlist_t kwlist = {{"assign_to", nullptr}};
constexpr cstring this_name = "this";
const int status = template_set_up<this_name, kwlist, {class_full_cpp_name}>();
}}
""")
finally:
body_stream.close()
return None, body_stream.name
class MoveAssignmentGenerator(Generator):
def generate(self):
class_name = self._node.parent.parent.name
if not class_name:
return None, None
if 'user_declared' in self._node.classifiers or not self._node.classifiers:
return None, None
class_full_cpp_name = self._node.parent.parent.full_cpp_name
parent = self._node.parent.parent
while parent and not parent.name and isinstance(parent, NodeType.CXXRecordDecl):
parent = parent.parent
if not parent:
return None, None
body_stream = open(
os.path.join(self.my_root_dir, self._source_path_root, class_name + ' default_copy_assignment.cpp'), 'w',
encoding='utf-8')
try:
parent_name = parent.name
parent_header_path = os.path.join("..", parent_name)
# generate body
body_stream.write(f"""\n#include \"{self.source_path}\"
#include \"{parent_header_path}.hpp\"
#include <cstddef>
#include <type_traits>
#include <pyllars/pyllars_classmethod.hpp>
""")
body_stream.write(f"""
using namespace pyllars;
namespace {{
//From: DefaultConstructorDeclGenerator.generate
/**
* clang does not properly delete default assignment operator, so must use compile-time check
* instead to prevent compiler error from generated code that shouldn't be
*/
template<const char* const name, const char* const kwlist[], typename T>
static int template_set_up(){{
if constexpr (std::is_copy_assignable<T>::value){{
typedef T& (T::*method_t)(const T&&);
PyllarsClassMethod<name, kwlist, method_t, &T::operator= >();
}}
return 0;
}}
typedef const char* const kwlist_t[2];
constexpr kwlist_t kwlist = {{"assign_to", nullptr}};
constexpr cstring this_name = "this";
const int status = template_set_up<this_name, kwlist, {class_full_cpp_name}>();
}}
""")
finally:
body_stream.close()
return None, body_stream.name
class CXXConstructorDeclGenerator(Generator):
def _scoped_type_name(self, typ):
parts = typ.strip().split(' ')
def full_name(t):
if "::" in t:
first, rest = t.split("::", maxsplit=1)
else:
first, rest = t, ""
# search upward for enclosing definition
parent = self._node
while parent:
if hasattr(parent, 'name') and parent.name == first:
return "::" + ("::".join([parent.full_cpp_name, rest]) if rest else parent.full_cpp_name)
parent = parent.parent
# possibly an internally defined class or type:
for child in self._node.parent.children:
if hasattr(child, 'name') and child.name == t:
return '::' + child.full_cpp_name
return t
for index, typ in enumerate(parts):
if not typ in self.KEYWORDS:
parts[index] = full_name(typ)
return ' '.join(parts)
def _full_signature(self):
qualifiers = self._node.signature.rsplit(')', maxsplit=1)[-1]
params = [self._scoped_type_name(p.type_text) for p in self._node.children if isinstance(p, NodeType.ParmVarDecl)]
if '...' in self._node.signature:
params.append("...")
params = ", ".join(params)
class_qualifier = f"(::{self._node.parent.full_cpp_name}::*)"
return f"{class_qualifier}({params}) {qualifiers}"
def generate(self):
class_name = self._node.parent.name
parent = self._node.parent
body_stream = open(
os.path.join(self.my_root_dir, self._source_path_root, class_name + '::' + self._node.name.replace("/", " div") + self._node.signature + '.cpp'), 'w',
encoding='utf-8')
body_stream.write(f"""\n#include \"{self.source_path}\"\n\n""")
#grand_parent = parent
#while grand_parent and grand_parent.name:
# if isinstance(grand_parent, NodeType.NamespaceDecl):
# body_stream.write(f"using namespace {grand_parent.full_cpp_name};\n")
# grand_parent = grand_parent.parent
try:
#parent_name = parent.name
# generate body
body_stream.write(f"""\n#include \"{self.source_path}\"
#include <pyllars/pyllars_classconstructor.hpp>
\n""")
name = self._node.name
signature = self._full_signature()
kwlist = []
args = []
for c in reversed([c for c in self._node.children if isinstance(c, NodeType.ParmVarDecl)]):
if not c.name:
break
kwlist.insert(0, f"\"{c.name}\"")
args.append(c.type_text)
args = (", " + ", ".join(args)) if args else ""
kwlist_items = ", ".join(kwlist + ["nullptr"])
body_stream.write("namespace{\n")
body_stream.write(f" static const char* const kwlist[] = {{{kwlist_items}}};\n")
body_stream.write(f" constexpr cstring name = \"{name}\";\n")
body_stream.write("}\n\n")
body_stream.write(f"template class pyllars::PyllarsClassConstructor<kwlist, {self._node.parent.full_cpp_name} {args}>;")
finally:
body_stream.close()
return None, body_stream.name
class CXXMethodDeclGenerator(Generator):
def _scoped_type_name(self, typ):
parts = typ.strip().split(' ')
def full_name(t):
if "::" in t:
first, rest = t.split("::", maxsplit=1)
else:
first, rest = t, ""
# search upward for enclosing definition
parent = self._node
while parent:
if hasattr(parent, 'name') and parent.name == first:
return "::" + ("::".join([parent.full_cpp_name, rest]) if rest else parent.full_cpp_name)
parent = parent.parent
# possibly an internally defined class or type:
for child in self._node.parent.children:
if hasattr(child, 'name') and child.name == t:
return '::' + child.full_cpp_name
return t
for index, typ in enumerate(parts):
if not typ in self.KEYWORDS:
parts[index] = full_name(typ)
return ' '.join(parts)
def _full_signature(self):
is_static = 'static' in self._node.qualifiers
ret_type = self._scoped_type_name(self._node.signature.split('(')[0])
qualifiers = self._node.signature.rsplit(')', maxsplit=1)[-1]
params = [self._scoped_type_name(p.type_text) for p in self._node.children if isinstance(p, NodeType.ParmVarDecl)]
if '...' in self._node.signature:
params.append("...")
params = ", ".join(params)
class_qualifier = f"(::{self._node.parent.full_cpp_name}::*)" if not is_static else "(*)"
return f"{ret_type} {class_qualifier}({params}) {qualifiers}"
def generate(self):
class_name = self._node.parent.name
parent = self._node.parent
while parent and not parent.name and isinstance(parent, NodeType.CXXRecordDecl):
parent = parent.parent
if not parent:
return None, None
body_stream = open(
os.path.join(self.my_root_dir, self._source_path_root, class_name + '::' + self._node.name.replace("/", " div") + self._node.signature + '.cpp'), 'w',
encoding='utf-8')
body_stream.write(f"""\n#include \"{self.source_path}\"\n\n""")
grand_parent = parent
while grand_parent and grand_parent.name:
if isinstance(grand_parent, NodeType.NamespaceDecl):
body_stream.write(f"using namespace {grand_parent.full_cpp_name};\n")
grand_parent = grand_parent.parent
if self._node.name == "operator=":
return self.generate_assignment(body_stream)
if self._node.name.startswith("operator"):
return self.generate_operator(body_stream)
try:
parent_name = parent.name
# generate body
if 'static' in self._node.qualifiers:
method_qualifier = "Static"
class_param = f"{self._node.parent.full_cpp_name}, "
body_stream.write(f"""\n#include \"{self.source_path}\"
#include <pyllars/pyllars_classstaticmethod.hpp>
""")
else:
method_qualifier = ""
class_param = ""
body_stream.write(f"""\n#include \"{self.source_path}\"
#include <pyllars/pyllars_classmethod.hpp>
\n""")
name = self._node.name
signature = self._full_signature()
kwlist = []
for c in reversed([c for c in self._node.children if isinstance(c, NodeType.ParmVarDecl)]):
if not c.name:
break
kwlist.insert(0, f"\"{c.name}\"")
kwlist_items = ", ".join(kwlist + ["nullptr"])
body_stream.write("namespace{\n")
body_stream.write(f" static const char* const kwlist[] = {{{kwlist_items}}};\n")
body_stream.write(f" constexpr cstring name = \"{name}\";\n")
body_stream.write("}\n\n")
body_stream.write(f"template class pyllars::PyllarsClass{method_qualifier}Method<name, kwlist, {class_param}{signature}, &{self._node.full_cpp_name}>;")
finally:
body_stream.close()
return None, body_stream.name
def generate_assignment(self, body_stream):
if 'default_delete' in self._node.qualifiers:
return None, None
class_name = self._node.parent.name
class_full_cpp_name = self._node.parent.full_cpp_name
try:
parent = self._node.parent
while parent and not parent.name and isinstance(parent, NodeType.CXXRecordDecl):
parent = parent.parent
if not parent:
return None, None
parent_name = parent.name
parent_header_path = os.path.join("..", parent_name)
# generate body
body_stream.write(f"""\n#include \"{self.source_path}\"
#include \"{parent_header_path}.hpp\"
#include <{self.source_path}>
#include <pyllars/pyllars_classmethod.hpp>
""")
name = "this"
signature = self._full_signature()
kwlist = []
for c in reversed([c for c in self._node.children if isinstance(c, NodeType.ParmVarDecl)]):
if not c.name:
break
kwlist.insert(0, f"\"{c.name}\"")
if len(kwlist) == 1:
kwlist = ["assign_to"]
kwlist_items = ", ".join(kwlist + ["nullptr"])
body_stream.write("namespace{\n")
body_stream.write(f" static const char* const kwlist[] = {{{kwlist_items}}};\n")
body_stream.write(f" constexpr cstring name = \"{name}\";\n")
body_stream.write("}\n\n")
body_stream.write(f"template class pyllars::PyllarsClassMethod<name, kwlist, {signature}, &::{class_full_cpp_name}::operator= >;")
finally:
body_stream.close()
return None, body_stream.name
def generate_operator(self, body_stream):
unary_mapping = {
'~' : 'pyllars::OpUnaryEnum::INV',
'+' : 'pyllars::OpUnaryEnum::POS',
'-' : 'pyllars::OpUnaryEnum::NEG',
}
binary_mapping = {
'+': 'pyllars::OpBinaryEnum::ADD',
'-': 'pyllars::OpBinaryEnum::SUB',
'*': 'pyllars::OpBinaryEnum::MUL',
'/': 'pyllars::OpBinaryEnum::DIV',
'&': 'pyllars::OpBinaryEnum::AND',
'|': 'pyllars::OpBinaryEnum::OR',
'^': 'pyllars::OpBinaryEnum::XOR',
'<<': 'pyllars::OpBinaryEnum::LSHIFT',
'>>': 'pyllars::OpBinaryEnum::RSHIFT',
'%': 'pyllars::OpBinaryEnum::MOD',
'+=': 'pyllars::OpBinaryEnum::IADD',
'-=': 'pyllars::OpBinaryEnum::ISUB',
'*=': 'pyllars::OpBinaryEnum::IMUL',
'/=': 'pyllars::OpBinaryEnum::IDIV',
'&=': 'pyllars::OpBinaryEnum::IAND',
'|=': 'pyllars::OpBinaryEnum::IOR',
'^=': 'pyllars::OpBinaryEnum::IXOR',
'<<=': 'pyllars::OpBinaryEnum::ILSHIFT',
'>>=': 'pyllars::OpBinaryEnum::IRSHIFT',
'%=': 'pyllars::OpBinaryEnum::IMOD',
'[]': 'Map'
}
if 'default_delete' in self._node.qualifiers:
return None, None
operator_kind = self._node.name.replace("operator", '')
params = [p for p in self._node.children if isinstance(p, NodeType.ParmVarDecl)]
if len(params) > 1:
raise Exception("Unexpected number of operator params")
cpp_op_name = unary_mapping.get(operator_kind) if len(params) == 0 else binary_mapping.get(operator_kind)
if cpp_op_name is None:
raise Exception(f"Unknown operator: {operator_kind}")
class_name = self._node.parent.name
class_full_cpp_name = self._node.parent.full_cpp_name
try:
parent = self._node.parent
while parent and not parent.name and isinstance(parent, NodeType.CXXRecordDecl):
parent = parent.parent
if not parent:
return None, None
parent_name = parent.name
parent_header_path = os.path.join("..", parent_name)
# generate body
body_stream.write(f"""\n#include \"{self.source_path}\"
#include \"{parent_header_path}.hpp\"
#include <{self.source_path}>\n""")
if cpp_op_name == 'Map':
body_stream.write("#include <pyllars/pyllars_classmapoperator.hpp>\n\n")
body_stream.write(f"""template class pyllars::PyllarsClassMapOperator<{self._full_signature()},
&{class_full_cpp_name}::{self._node.name}>;""")
else:
body_stream.write("#include <pyllars/pyllars_classoperator.hpp>\n\n")
body_stream.write(f"""template class pyllars::PyllarsClassOperator<{self._full_signature()},
&{class_full_cpp_name}::{self._node.name}, {cpp_op_name}>;""")
finally:
body_stream.close()
return None, body_stream.name
def _parent_wrapper_name(node: NodeType.Node, recursed: Optional[NodeType.Node] = None):
if False and not node.name:
if node.parent is None:
return None, None, None
return _parent_wrapper_name(node.parent, recursed)
parent = node.parent
if recursed:
node = recursed
if parent.parent:
index = parent.parent.children.index(parent)
if index < 0:
raise Exception("Invalid structure in hierarchy")
is_named_attribute = len(parent.parent.children) -1 > index and isinstance(parent.parent.children[index + 1], NodeType.FieldDecl)
else:
is_named_attribute = False
if parent.name:
if recursed:
return f"__pyllars_internal::PythonAnonymousClassWrapper< ::{parent.full_cpp_name} >",\
f"::{parent.full_cpp_name}", \
f"decltype(::{parent.full_cpp_name}::{node.name})",\
f"::{parent.full_cpp_name}::{node.name}"
else:
return f"__pyllars_internal::PythonClassWrapper< ::{parent.full_cpp_name} >", \
f"::{parent.full_cpp_name}", \
f"decltype(::{parent.full_cpp_name}::{node.name})",\
f"::{parent.full_cpp_name}::{node.name}"
elif is_named_attribute:
# parent is anonymous type with a named field declaration, so this element is referenced to direct parent (field)
parent_field_name = parent.parent.children[index + 1].name
if parent_field_name:
return f"__pyllars_internal::PythonClassWrapper<decltype(::{parent.parent.full_cpp_name}::{parent_field_name})>", \
f"decltype(::{parent.parent.full_cpp_name}::{parent_field_name})", \
f"decltype(::{parent.parent.full_cpp_name}::{parent_field_name}.{node.name})", \
f"decltype(::{parent.parent.full_cpp_name}::{parent_field_name})::{node.name}"
elif parent.parent.name:
return f"__pyllars_internal::PythonClassWrapper<::{parent.parent.full_cpp_name}>", \
f"::{parent.parent.full_cpp_name}", \
f"decltype(::{parent.parent.full_cpp_name}::{node.name})", \
f"::{parent.parent.full_cpp_name}::{node.name}"
else:
return _parent_wrapper_name(parent, node)
elif recursed:
return _parent_wrapper_name(parent, node)
index = parent.parent.children.index(parent)
if index < 0:
raise Exception("Invalid structure in hierarchy")
if is_named_attribute:
# parent is anonymous type with a named field declaration, so this element is referenced to direct parent (field)
parent_field_name = parent.parent.children[index + 1].name
if parent_field_name:
return f"__pyllars_internal::PythonClassWrapper<decltype(::{parent.parent.full_cpp_name}::{parent_field_name})>", \
f"{parent.parent.full_cpp_name}", \
f"decltype(::{parent.parent.full_cpp_name}::{parent_field_name})",\
f"::{parent.parent.full_cpp_name}::{parent_field_name}"
elif parent.parent.name:
return f"__pyllars_internal::PythonClassWrapper<decltype(::{parent.parent.full_cpp_name})>", \
f"::{parent.parent.full_cpp_name}",\
f"decltype(::{parent.parent.full_cpp_name}::{node.name})",\
f"::{parent.parent.full_cpp_name}::{node.name}"
else:
return _parent_wrapper_name(parent, node)
else:
# parent is anonymous type without associated field, so element belongs to parent's parent when referenced in code
if parent.parent.name:
return f"__pyllars_internal::PythonAnonymousClassWrapper< ::{parent.parent.full_cpp_name} >", \
f"::{parent.parent.full_cpp_name}", \
f"decltype(::{parent.parent.full_cpp_name}::{node.name})", \
f"::{parent.parent.full_cpp_name}::{node.name}"
else:
return _parent_wrapper_name(parent, node)
class FieldDeclGenerator(Generator):
def _scoped_type_name(self, typ):
parts = typ.strip().split(' ')
def full_name(t):
if "::" in t:
first, rest = t.split("::", maxsplit=1)
else:
first, rest = t, ""
# search upward for enclosing definition
parent = self._node
while parent:
if hasattr(parent, 'name') and parent.name == first:
return "::" + ("::".join([parent.full_cpp_name, rest]) if rest else parent.full_cpp_name)
parent = parent.parent
# possibly an internally defined class or type:
for child in self._node.parent.children:
if hasattr(child, 'name') and child.name == t:
return '::' + child.full_cpp_name
return t
for index, typ in enumerate(parts):
if not typ in self.KEYWORDS:
parts[index] = full_name(typ)
return ' '.join(parts)
def generate(self):
if 'public' not in self._node.qualifiers and\
(self._node.parent is None or not hasattr(self._node.parent, 'qualifiers')\
or 'struct' not in self._node.parent.qualifiers):
return None, None
if isinstance(self._node, NodeType.IndirectFieldDecl):
return None, None
if not self._node.name:
return None, None
parent = self._node.parent
while parent and not parent.name:
parent = parent.parent
if not parent:
return None, None
bitfield_specs = [c for c in self._node.children if isinstance(c, NodeType.IntegerLiteral)]
if not isinstance(self, VarDeclGenerator) and bitfield_specs:
return self.generate_bitfield(bitfield_specs)
body_stream = open(
os.path.join(self.my_root_dir, self._source_path_root, (parent.name or f"anon_{parent.node_id}") + '::' + (self._node.name or "anon_" + self._node.node_id) + '.cpp'), 'w',
encoding='utf-8')
try:
parent_name = parent.name
parent_header_path = os.path.join("..", parent_name)
# generate body
if 'static' in self._node.qualifiers:
member_qualifier = "Static"
else:
member_qualifier = ""
body_stream.write(f"""\n#include \"{self.source_path}\"
#include \"{parent_header_path}.hpp\"
#include <pyllars/pyllars_class{member_qualifier.lower()}member.hpp>
""")
if not self._node.name:
return None, None
wrapper, parent_type_name, attribute_type_name, attribute_full_cpp_name = _parent_wrapper_name(self._node)
body_stream.write("using namespace pyllars;\n\nnamespace{\n")
body_stream.write(f" constexpr cstring name = \"{self._node.name}\";\n")
body_stream.write("}\n\n")
body_stream.write(f"template class pyllars::PyllarsClass{member_qualifier}Member<name, {parent.full_cpp_name}, {attribute_type_name}, &{attribute_full_cpp_name}>;")
finally:
body_stream.close()
return None, body_stream.name
def generate_bitfield(self, specs: List["NodeType.IntegerLiteral"]):
if len(specs) > 1:
raise Exception("multiple size specs provided for bit feild")
size = specs[0].value
is_const = 'const' in self._node.type_text.split()
name = self._node.name or f"anon_{self._node.node_id}"
wrapper, parent_type_name, attribute_type_name, attribute_full_cpp_name = _parent_wrapper_name(self._node)
body_stream = open(
os.path.join(self.my_root_dir, self._source_path_root, (self._node.parent.name or f"anon_{self._node.parent.node_id}") + '::' +
(self._node.name or "anon_{self._node.node_id}") + '.cpp'), 'w',
encoding='utf-8')
try:
parent = self._node.parent
while parent and not parent.name and isinstance(parent, NodeType.CXXRecordDecl):
parent = parent.parent
if not parent:
return None, None
parent_name = parent.name
parent_header_path = os.path.join("..", parent_name)
# generate body
body_stream.write(f"""\n#include \"{self.source_path}\"
#include \"{parent_header_path}.hpp\"
#include <{self.source_path}>
#include <pyllars/pyllars_classbitfield.hpp>
""")
name = self._node.name
if not name:
return None, None
typename = self._scoped_type_name(self._node.type_text)
const_typename = 'const ' + typename if 'const' not in typename.split() else typename
setter = "" if is_const else f"static std::function<{typename}({parent_type_name}&, {const_typename}&)> setter = []({parent_type_name} & obj, {const_typename}& value)->{typename}{{obj.{name} = value; return value;}};"
body_stream.write(f"""
namespace{{
extern const char name[] = "{name}";
static std::function<{typename}(const {parent_type_name}&)> getter = [](const {parent_type_name} & obj)->{typename}{{return obj.{name};}};
constexpr std::function<{typename}(const {parent_type_name}&)>* getter_p = &getter;
""")
if setter:
body_stream.write(f"""
{setter}
constexpr std::function<{typename}({parent_type_name}&, {const_typename}&)>* setter_p = &setter;
""")
body_stream.write("}\n\n")
body_stream.write(f"""template class pyllars::PyllarsClassBitField<name, {parent_type_name}, {typename}, {size}, getter_p, {"setter_p" if setter else "nullptr"}>;""")
finally:
body_stream.close()
return None, body_stream.name
class VarDeclGenerator(FieldDeclGenerator):
pass
class IndirectFieldDeclGenerator(FieldDeclGenerator):
pass
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2009 Sharoon Thomas
# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.com>)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
##############################################################################
import base64
import datetime
import dateutil.relativedelta as relativedelta
import logging
import lxml
import urlparse
import openerp
from openerp import SUPERUSER_ID
from openerp.osv import osv, fields
from openerp import tools
from openerp.tools.translate import _
from urllib import urlencode, quote as quote
_logger = logging.getLogger(__name__)
try:
# We use a jinja2 sandboxed environment to render mako templates.
# Note that the rendering does not cover all the mako syntax, in particular
# arbitrary Python statements are not accepted, and not all expressions are
# allowed: only "public" attributes (not starting with '_') of objects may
# be accessed.
# This is done on purpose: it prevents incidental or malicious execution of
# Python code that may break the security of the server.
from jinja2.sandbox import SandboxedEnvironment
mako_template_env = SandboxedEnvironment(
block_start_string="<%",
block_end_string="%>",
variable_start_string="${",
variable_end_string="}",
comment_start_string="<%doc>",
comment_end_string="</%doc>",
line_statement_prefix="%",
line_comment_prefix="##",
trim_blocks=True, # do not output newline after blocks
autoescape=True, # XML/HTML automatic escaping
)
mako_template_env.globals.update({
'str': str,
'quote': quote,
'urlencode': urlencode,
'datetime': datetime,
'len': len,
'abs': abs,
'min': min,
'max': max,
'sum': sum,
'filter': filter,
'reduce': reduce,
'map': map,
'round': round,
# dateutil.relativedelta is an old-style class and cannot be directly
# instanciated wihtin a jinja2 expression, so a lambda "proxy" is
# is needed, apparently.
'relativedelta': lambda *a, **kw : relativedelta.relativedelta(*a, **kw),
})
except ImportError:
_logger.warning("jinja2 not available, templating features will not work!")
class email_template(osv.osv):
"Templates for sending email"
_name = "email.template"
_description = 'Email Templates'
_order = 'name'
def default_get(self, cr, uid, fields, context=None):
res = super(email_template, self).default_get(cr, uid, fields, context)
if res.get('model'):
res['model_id'] = self.pool['ir.model'].search(cr, uid, [('model', '=', res.pop('model'))], context=context)[0]
return res
def _replace_local_links(self, cr, uid, html, context=None):
""" Post-processing of html content to replace local links to absolute
links, using web.base.url as base url. """
if not html:
return html
# form a tree
root = lxml.html.fromstring(html)
if not len(root) and root.text is None and root.tail is None:
html = '<div>%s</div>' % html
root = lxml.html.fromstring(html)
base_url = self.pool['ir.config_parameter'].get_param(cr, uid, 'web.base.url')
(base_scheme, base_netloc, bpath, bparams, bquery, bfragment) = urlparse.urlparse(base_url)
def _process_link(url):
new_url = url
(scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url)
if not scheme and not netloc:
new_url = urlparse.urlunparse((base_scheme, base_netloc, path, params, query, fragment))
return new_url
# check all nodes, replace :
# - img src -> check URL
# - a href -> check URL
for node in root.iter():
if node.tag == 'a':
node.set('href', _process_link(node.get('href')))
elif node.tag == 'img' and not node.get('src', 'data').startswith('data'):
node.set('src', _process_link(node.get('src')))
html = lxml.html.tostring(root, pretty_print=False, method='html')
# this is ugly, but lxml/etree tostring want to put everything in a 'div' that breaks the editor -> remove that
if html.startswith('<div>') and html.endswith('</div>'):
html = html[5:-6]
return html
def render_post_process(self, cr, uid, html, context=None):
html = self._replace_local_links(cr, uid, html, context=context)
return html
def render_template_batch(self, cr, uid, template, model, res_ids, context=None, post_process=False):
"""Render the given template text, replace mako expressions ``${expr}``
with the result of evaluating these expressions with
an evaluation context containing:
* ``user``: browse_record of the current user
* ``object``: browse_record of the document record this mail is
related to
* ``context``: the context passed to the mail composition wizard
:param str template: the template text to render
:param str model: model name of the document record this mail is related to.
:param int res_ids: list of ids of document records those mails are related to.
"""
if context is None:
context = {}
results = dict.fromkeys(res_ids, u"")
# try to load the template
try:
template = mako_template_env.from_string(tools.ustr(template))
except Exception:
_logger.exception("Failed to load template %r", template)
return results
# prepare template variables
user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
records = self.pool[model].browse(cr, uid, res_ids, context=context) or [None]
variables = {
'user': user,
'ctx': context, # context kw would clash with mako internals
}
for record in records:
res_id = record.id if record else None
variables['object'] = record
try:
render_result = template.render(variables)
except Exception:
_logger.exception("Failed to render template %r using values %r" % (template, variables))
render_result = u""
if render_result == u"False":
render_result = u""
results[res_id] = render_result
if post_process:
for res_id, result in results.iteritems():
results[res_id] = self.render_post_process(cr, uid, result, context=context)
return results
def get_email_template_batch(self, cr, uid, template_id=False, res_ids=None, context=None):
if context is None:
context = {}
if res_ids is None:
res_ids = [None]
results = dict.fromkeys(res_ids, False)
if not template_id:
return results
template = self.browse(cr, uid, template_id, context)
langs = self.render_template_batch(cr, uid, template.lang, template.model, res_ids, context)
for res_id, lang in langs.iteritems():
if lang:
# Use translated template if necessary
ctx = context.copy()
ctx['lang'] = lang
template = self.browse(cr, uid, template.id, ctx)
else:
template = self.browse(cr, uid, int(template_id), context)
results[res_id] = template
return results
def onchange_model_id(self, cr, uid, ids, model_id, context=None):
mod_name = False
if model_id:
mod_name = self.pool.get('ir.model').browse(cr, uid, model_id, context).model
return {'value': {'model': mod_name}}
_columns = {
'name': fields.char('Name'),
'model_id': fields.many2one('ir.model', 'Applies to', help="The kind of document with with this template can be used"),
'model': fields.related('model_id', 'model', type='char', string='Related Document Model',
size=128, select=True, store=True, readonly=True),
'lang': fields.char('Language',
help="Optional translation language (ISO code) to select when sending out an email. "
"If not set, the english version will be used. "
"This should usually be a placeholder expression "
"that provides the appropriate language code, e.g. "
"${object.partner_id.lang.code}.",
placeholder="${object.partner_id.lang.code}"),
'user_signature': fields.boolean('Add Signature',
help="If checked, the user's signature will be appended to the text version "
"of the message"),
'subject': fields.char('Subject', translate=True, help="Subject (placeholders may be used here)",),
'email_from': fields.char('From',
help="Sender address (placeholders may be used here). If not set, the default "
"value will be the author's email alias if configured, or email address."),
'use_default_to': fields.boolean(
'Default recipients',
help="Default recipients of the record:\n"
"- partner (using id on a partner or the partner_id field) OR\n"
"- email (using email_from or email field)"),
'email_to': fields.char('To (Emails)', help="Comma-separated recipient addresses (placeholders may be used here)"),
'partner_to': fields.char('To (Partners)',
help="Comma-separated ids of recipient partners (placeholders may be used here)",
oldname='email_recipients'),
'email_cc': fields.char('Cc', help="Carbon copy recipients (placeholders may be used here)"),
'reply_to': fields.char('Reply-To', help="Preferred response address (placeholders may be used here)"),
'mail_server_id': fields.many2one('ir.mail_server', 'Outgoing Mail Server', readonly=False,
help="Optional preferred server for outgoing mails. If not set, the highest "
"priority one will be used."),
'body_html': fields.html('Body', translate=True, sanitize=False, help="Rich-text/HTML version of the message (placeholders may be used here)"),
'report_name': fields.char('Report Filename', translate=True,
help="Name to use for the generated report file (may contain placeholders)\n"
"The extension can be omitted and will then come from the report type."),
'report_template': fields.many2one('ir.actions.report.xml', 'Optional report to print and attach'),
'ref_ir_act_window': fields.many2one('ir.actions.act_window', 'Sidebar action', readonly=True,
help="Sidebar action to make this template available on records "
"of the related document model"),
'ref_ir_value': fields.many2one('ir.values', 'Sidebar Button', readonly=True,
help="Sidebar button to open the sidebar action"),
'attachment_ids': fields.many2many('ir.attachment', 'email_template_attachment_rel', 'email_template_id',
'attachment_id', 'Attachments',
help="You may attach files to this template, to be added to all "
"emails created from this template"),
'auto_delete': fields.boolean('Auto Delete', help="Permanently delete this email after sending it, to save space"),
# Fake fields used to implement the placeholder assistant
'model_object_field': fields.many2one('ir.model.fields', string="Field",
help="Select target field from the related document model.\n"
"If it is a relationship field you will be able to select "
"a target field at the destination of the relationship."),
'sub_object': fields.many2one('ir.model', 'Sub-model', readonly=True,
help="When a relationship field is selected as first field, "
"this field shows the document model the relationship goes to."),
'sub_model_object_field': fields.many2one('ir.model.fields', 'Sub-field',
help="When a relationship field is selected as first field, "
"this field lets you select the target field within the "
"destination document model (sub-model)."),
'null_value': fields.char('Default Value', help="Optional value to use if the target field is empty"),
'copyvalue': fields.char('Placeholder Expression', help="Final placeholder expression, to be copy-pasted in the desired template field."),
}
_defaults = {
'auto_delete': True,
}
def create_action(self, cr, uid, ids, context=None):
action_obj = self.pool.get('ir.actions.act_window')
data_obj = self.pool.get('ir.model.data')
for template in self.browse(cr, uid, ids, context=context):
src_obj = template.model_id.model
model_data_id = data_obj._get_id(cr, uid, 'mail', 'email_compose_message_wizard_form')
res_id = data_obj.browse(cr, uid, model_data_id, context=context).res_id
button_name = _('Send Mail (%s)') % template.name
act_id = action_obj.create(cr, SUPERUSER_ID, {
'name': button_name,
'type': 'ir.actions.act_window',
'res_model': 'mail.compose.message',
'src_model': src_obj,
'view_type': 'form',
'context': "{'default_composition_mode': 'mass_mail', 'default_template_id' : %d, 'default_use_template': True}" % (template.id),
'view_mode':'form,tree',
'view_id': res_id,
'target': 'new',
'auto_refresh':1
}, context)
ir_values_id = self.pool.get('ir.values').create(cr, SUPERUSER_ID, {
'name': button_name,
'model': src_obj,
'key2': 'client_action_multi',
'value': "ir.actions.act_window,%s" % act_id,
'object': True,
}, context)
template.write({
'ref_ir_act_window': act_id,
'ref_ir_value': ir_values_id,
})
return True
def unlink_action(self, cr, uid, ids, context=None):
for template in self.browse(cr, uid, ids, context=context):
try:
if template.ref_ir_act_window:
self.pool.get('ir.actions.act_window').unlink(cr, SUPERUSER_ID, template.ref_ir_act_window.id, context)
if template.ref_ir_value:
ir_values_obj = self.pool.get('ir.values')
ir_values_obj.unlink(cr, SUPERUSER_ID, template.ref_ir_value.id, context)
except Exception:
raise osv.except_osv(_("Warning"), _("Deletion of the action record failed."))
return True
def unlink(self, cr, uid, ids, context=None):
self.unlink_action(cr, uid, ids, context=context)
return super(email_template, self).unlink(cr, uid, ids, context=context)
def copy(self, cr, uid, id, default=None, context=None):
template = self.browse(cr, uid, id, context=context)
if default is None:
default = {}
default = default.copy()
default.update(
name=_("%s (copy)") % (template.name),
ref_ir_act_window=False,
ref_ir_value=False)
return super(email_template, self).copy(cr, uid, id, default, context)
def build_expression(self, field_name, sub_field_name, null_value):
"""Returns a placeholder expression for use in a template field,
based on the values provided in the placeholder assistant.
:param field_name: main field name
:param sub_field_name: sub field name (M2O)
:param null_value: default value if the target value is empty
:return: final placeholder expression
"""
expression = ''
if field_name:
expression = "${object." + field_name
if sub_field_name:
expression += "." + sub_field_name
if null_value:
expression += " or '''%s'''" % null_value
expression += "}"
return expression
def onchange_sub_model_object_value_field(self, cr, uid, ids, model_object_field, sub_model_object_field=False, null_value=None, context=None):
result = {
'sub_object': False,
'copyvalue': False,
'sub_model_object_field': False,
'null_value': False
}
if model_object_field:
fields_obj = self.pool.get('ir.model.fields')
field_value = fields_obj.browse(cr, uid, model_object_field, context)
if field_value.ttype in ['many2one', 'one2many', 'many2many']:
res_ids = self.pool.get('ir.model').search(cr, uid, [('model', '=', field_value.relation)], context=context)
sub_field_value = False
if sub_model_object_field:
sub_field_value = fields_obj.browse(cr, uid, sub_model_object_field, context)
if res_ids:
result.update({
'sub_object': res_ids[0],
'copyvalue': self.build_expression(field_value.name, sub_field_value and sub_field_value.name or False, null_value or False),
'sub_model_object_field': sub_model_object_field or False,
'null_value': null_value or False
})
else:
result.update({
'copyvalue': self.build_expression(field_value.name, False, null_value or False),
'null_value': null_value or False
})
return {'value': result}
def generate_recipients_batch(self, cr, uid, results, template_id, res_ids, context=None):
"""Generates the recipients of the template. Default values can ben generated
instead of the template values if requested by template or context.
Emails (email_to, email_cc) can be transformed into partners if requested
in the context. """
if context is None:
context = {}
template = self.browse(cr, uid, template_id, context=context)
if template.use_default_to or context.get('tpl_force_default_to'):
ctx = dict(context, thread_model=template.model)
default_recipients = self.pool['mail.thread'].message_get_default_recipients(cr, uid, res_ids, context=ctx)
for res_id, recipients in default_recipients.iteritems():
results[res_id].pop('partner_to', None)
results[res_id].update(recipients)
for res_id, values in results.iteritems():
partner_ids = values.get('partner_ids', list())
if context and context.get('tpl_partners_only'):
mails = tools.email_split(values.pop('email_to', '')) + tools.email_split(values.pop('email_cc', ''))
for mail in mails:
partner_id = self.pool.get('res.partner').find_or_create(cr, uid, mail, context=context)
partner_ids.append(partner_id)
partner_to = values.pop('partner_to', '')
if partner_to:
# placeholders could generate '', 3, 2 due to some empty field values
tpl_partner_ids = [int(pid) for pid in partner_to.split(',') if pid]
partner_ids += self.pool['res.partner'].exists(cr, SUPERUSER_ID, tpl_partner_ids, context=context)
results[res_id]['partner_ids'] = partner_ids
return results
def generate_email_batch(self, cr, uid, template_id, res_ids, context=None, fields=None):
"""Generates an email from the template for given the given model based on
records given by res_ids.
:param template_id: id of the template to render.
:param res_id: id of the record to use for rendering the template (model
is taken from template definition)
:returns: a dict containing all relevant fields for creating a new
mail.mail entry, with one extra key ``attachments``, in the
format [(report_name, data)] where data is base64 encoded.
"""
if context is None:
context = {}
if fields is None:
fields = ['subject', 'body_html', 'email_from', 'email_to', 'partner_to', 'email_cc', 'reply_to']
report_xml_pool = self.pool.get('ir.actions.report.xml')
res_ids_to_templates = self.get_email_template_batch(cr, uid, template_id, res_ids, context)
# templates: res_id -> template; template -> res_ids
templates_to_res_ids = {}
for res_id, template in res_ids_to_templates.iteritems():
templates_to_res_ids.setdefault(template, []).append(res_id)
results = dict()
for template, template_res_ids in templates_to_res_ids.iteritems():
# generate fields value for all res_ids linked to the current template
for field in fields:
generated_field_values = self.render_template_batch(
cr, uid, getattr(template, field), template.model, template_res_ids,
post_process=(field == 'body_html'),
context=context)
for res_id, field_value in generated_field_values.iteritems():
results.setdefault(res_id, dict())[field] = field_value
# compute recipients
results = self.generate_recipients_batch(cr, uid, results, template.id, template_res_ids, context=context)
# update values for all res_ids
for res_id in template_res_ids:
values = results[res_id]
# body: add user signature, sanitize
if 'body_html' in fields and template.user_signature:
signature = self.pool.get('res.users').browse(cr, uid, uid, context).signature
values['body_html'] = tools.append_content_to_html(values['body_html'], signature)
if values.get('body_html'):
values['body'] = tools.html_sanitize(values['body_html'])
# technical settings
values.update(
mail_server_id=template.mail_server_id.id or False,
auto_delete=template.auto_delete,
model=template.model,
res_id=res_id or False,
attachment_ids=[attach.id for attach in template.attachment_ids],
)
# Add report in attachments: generate once for all template_res_ids
if template.report_template:
for res_id in template_res_ids:
attachments = []
report_name = self.render_template(cr, uid, template.report_name, template.model, res_id, context=context)
report = report_xml_pool.browse(cr, uid, template.report_template.id, context)
report_service = report.report_name
# Ensure report is rendered using template's language
ctx = context.copy()
if template.lang:
ctx['lang'] = self.render_template_batch(cr, uid, template.lang, template.model, [res_id], context)[res_id] # take 0 ?
if report.report_type in ['qweb-html', 'qweb-pdf']:
result, format = self.pool['report'].get_pdf(cr, uid, [res_id], report_service, context=ctx), 'pdf'
else:
result, format = openerp.report.render_report(cr, uid, [res_id], report_service, {'model': template.model}, ctx)
# TODO in trunk, change return format to binary to match message_post expected format
result = base64.b64encode(result)
if not report_name:
report_name = 'report.' + report_service
ext = "." + format
if not report_name.endswith(ext):
report_name += ext
attachments.append((report_name, result))
results[res_id]['attachments'] = attachments
return results
def send_mail(self, cr, uid, template_id, res_id, force_send=False, raise_exception=False, context=None):
"""Generates a new mail message for the given template and record,
and schedules it for delivery through the ``mail`` module's scheduler.
:param int template_id: id of the template to render
:param int res_id: id of the record to render the template with
(model is taken from the template)
:param bool force_send: if True, the generated mail.message is
immediately sent after being created, as if the scheduler
was executed for this message only.
:returns: id of the mail.message that was created
"""
if context is None:
context = {}
mail_mail = self.pool.get('mail.mail')
ir_attachment = self.pool.get('ir.attachment')
# create a mail_mail based on values, without attachments
values = self.generate_email(cr, uid, template_id, res_id, context=context)
if not values.get('email_from'):
raise osv.except_osv(_('Warning!'), _("Sender email is missing or empty after template rendering. Specify one to deliver your message"))
values['recipient_ids'] = [(4, pid) for pid in values.get('partner_ids', list())]
attachment_ids = values.pop('attachment_ids', [])
attachments = values.pop('attachments', [])
msg_id = mail_mail.create(cr, uid, values, context=context)
mail = mail_mail.browse(cr, uid, msg_id, context=context)
# manage attachments
for attachment in attachments:
attachment_data = {
'name': attachment[0],
'datas_fname': attachment[0],
'datas': attachment[1],
'res_model': 'mail.message',
'res_id': mail.mail_message_id.id,
}
context.pop('default_type', None)
attachment_ids.append(ir_attachment.create(cr, uid, attachment_data, context=context))
if attachment_ids:
values['attachment_ids'] = [(6, 0, attachment_ids)]
mail_mail.write(cr, uid, msg_id, {'attachment_ids': [(6, 0, attachment_ids)]}, context=context)
if force_send:
mail_mail.send(cr, uid, [msg_id], raise_exception=raise_exception, context=context)
return msg_id
# Compatibility method
def render_template(self, cr, uid, template, model, res_id, context=None):
return self.render_template_batch(cr, uid, template, model, [res_id], context)[res_id]
def get_email_template(self, cr, uid, template_id=False, record_id=None, context=None):
return self.get_email_template_batch(cr, uid, template_id, [record_id], context)[record_id]
def generate_email(self, cr, uid, template_id, res_id, context=None):
return self.generate_email_batch(cr, uid, template_id, [res_id], context)[res_id]
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
"""
requests.exceptions
~~~~~~~~~~~~~~~~~~~
This module contains the set of Requests' exceptions.
"""
from .packages.urllib3.exceptions import HTTPError as BaseHTTPError
class RequestException(IOError):
"""There was an ambiguous exception that occurred while handling your
request."""
def __init__(self, *args, **kwargs):
"""
Initialize RequestException with `request` and `response` objects.
"""
response = kwargs.pop('response', None)
self.response = response
self.request = kwargs.pop('request', None)
if (response is not None and not self.request and
hasattr(response, 'request')):
self.request = self.response.request
super(RequestException, self).__init__(*args, **kwargs)
class HTTPError(RequestException):
"""An HTTP error occurred."""
class ConnectionError(RequestException):
"""A Connection error occurred."""
class ProxyError(ConnectionError):
"""A proxy error occurred."""
class SSLError(ConnectionError):
"""An SSL error occurred."""
class Timeout(RequestException):
"""The request timed out.
Catching this error will catch both
:exc:`~requests.exceptions.ConnectTimeout` and
:exc:`~requests.exceptions.ReadTimeout` errors.
"""
class ConnectTimeout(ConnectionError, Timeout):
"""The request timed out while trying to connect to the remote server.
Requests that produced this error are safe to retry.
"""
class ReadTimeout(Timeout):
"""The server did not send any data in the allotted amount of time."""
class URLRequired(RequestException):
"""A valid URL is required to make a request."""
class TooManyRedirects(RequestException):
"""Too many redirects."""
class MissingSchema(RequestException, ValueError):
"""The URL schema (e.g. http or https) is missing."""
class InvalidSchema(RequestException, ValueError):
"""See defaults.py for valid schemas."""
class InvalidURL(RequestException, ValueError):
""" The URL provided was somehow invalid. """
class ChunkedEncodingError(RequestException):
"""The server declared chunked encoding but sent an invalid chunk."""
class ContentDecodingError(RequestException, BaseHTTPError):
"""Failed to decode response content"""
class StreamConsumedError(RequestException, TypeError):
"""The content for this response was already consumed"""
class RetryError(RequestException):
"""Custom retries logic failed"""
# Warnings
class RequestsWarning(Warning):
"""Base warning for Requests."""
pass
class FileModeWarning(RequestsWarning, DeprecationWarning):
"""
A file was opened in text mode, but Requests determined its binary length.
"""
pass
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
import translate.storage.base
import django.core.validators
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
from django.utils.timezone import utc
import pootle.core.mixins.treeitem
import pootle.core.storage
import pootle_store.fields
import pootle_store.models
from pootle.core.utils.db import set_mysql_collation_for_column
def make_store_paths_cs(apps, schema_editor):
cursor = schema_editor.connection.cursor()
set_mysql_collation_for_column(
apps,
cursor,
'pootle_store.Store',
'pootle_path',
'utf8_bin',
'varchar(255)',
)
set_mysql_collation_for_column(
apps,
cursor,
'pootle_store.Store',
'name',
'utf8_bin',
'varchar(255)',
)
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('pootle_app', '0001_initial'),
# Avoids circular dependency
# ('pootle_translationproject', '0003_realpath_can_be_none'),
# ('pootle_project', '0001_initial'),
# ('pootle_translationproject', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Store',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('file', pootle_store.fields.TranslationStoreField(db_index=True, editable=False, max_length=255, storage=pootle.core.storage.PootleFileSystemStorage(), upload_to=b'')),
('pootle_path', models.CharField(db_index=True, max_length=255, unique=True, verbose_name='Path')),
('name', models.CharField(editable=False, max_length=128, validators=[pootle_store.models.validate_no_slashes])),
('file_mtime', models.DateTimeField(default=datetime.datetime(1, 1, 1, 0, 0, tzinfo=utc))),
('state', models.IntegerField(db_index=True, default=0, editable=False)),
('creation_time', models.DateTimeField(auto_now_add=True, db_index=True, null=True)),
('last_sync_revision', models.IntegerField(blank=True, db_index=True, null=True)),
('obsolete', models.BooleanField(default=False)),
('parent', models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='child_stores', to='pootle_app.Directory')),
# ('translation_project', models.ForeignKey(editable=False, on_delete=django.db.models.deletion.CASCADE, related_name='stores', to='pootle_translationproject.TranslationProject')),
],
options={
'ordering': ['pootle_path'],
},
bases=(models.Model, pootle.core.mixins.treeitem.CachedTreeItem, translate.storage.base.TranslationStore),
),
migrations.CreateModel(
name='Unit',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('index', models.IntegerField(db_index=True)),
('unitid', models.TextField(editable=False)),
('unitid_hash', models.CharField(db_index=True, editable=False, max_length=32)),
('source_f', pootle_store.fields.MultiStringField(null=True)),
('source_hash', models.CharField(db_index=True, editable=False, max_length=32)),
('source_wordcount', models.SmallIntegerField(default=0, editable=False)),
('source_length', models.SmallIntegerField(db_index=True, default=0, editable=False)),
('target_f', pootle_store.fields.MultiStringField(blank=True, null=True)),
('target_wordcount', models.SmallIntegerField(default=0, editable=False)),
('target_length', models.SmallIntegerField(db_index=True, default=0, editable=False)),
('developer_comment', models.TextField(blank=True, null=True)),
('translator_comment', models.TextField(blank=True, null=True)),
('locations', models.TextField(editable=False, null=True)),
('context', models.TextField(editable=False, null=True)),
('state', models.IntegerField(db_index=True, default=0)),
('revision', models.IntegerField(blank=True, db_index=True, default=0)),
('creation_time', models.DateTimeField(auto_now_add=True, db_index=True, null=True)),
('mtime', models.DateTimeField(auto_now=True, db_index=True)),
('submitted_on', models.DateTimeField(db_index=True, null=True)),
('commented_on', models.DateTimeField(db_index=True, null=True)),
('reviewed_on', models.DateTimeField(db_index=True, null=True)),
('commented_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='commented', to=settings.AUTH_USER_MODEL)),
('reviewed_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='reviewed', to=settings.AUTH_USER_MODEL)),
('store', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pootle_store.Store')),
('submitted_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='submitted', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['store', 'index'],
},
bases=(models.Model, translate.storage.base.TranslationUnit),
),
migrations.CreateModel(
name='Suggestion',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('target_f', pootle_store.fields.MultiStringField()),
('target_hash', models.CharField(db_index=True, max_length=32)),
('translator_comment_f', models.TextField(blank=True, null=True)),
('state', models.CharField(choices=[(b'pending', 'Pending'), (b'accepted', 'Accepted'), (b'rejected', 'Rejected')], db_index=True, default=b'pending', max_length=16)),
('creation_time', models.DateTimeField(db_index=True, null=True)),
('review_time', models.DateTimeField(db_index=True, null=True)),
('unit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pootle_store.Unit')),
('reviewer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='reviews', to=settings.AUTH_USER_MODEL)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='suggestions', to=settings.AUTH_USER_MODEL)),
],
bases=(models.Model, translate.storage.base.TranslationUnit),
),
migrations.CreateModel(
name='QualityCheck',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(db_index=True, max_length=64)),
('category', models.IntegerField(default=0)),
('message', models.TextField()),
('false_positive', models.BooleanField(db_index=True, default=False)),
('unit', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pootle_store.Unit')),
],
),
migrations.AlterUniqueTogether(
name='store',
unique_together=set([('parent', 'name')]),
),
migrations.RunPython(
code=make_store_paths_cs,
),
migrations.AlterUniqueTogether(
name='unit',
unique_together=set([('store', 'unitid_hash')]),
),
migrations.AlterIndexTogether(
name='unit',
index_together=set([('store', 'revision'), ('store', 'index'), ('store', 'mtime')]),
),
migrations.AlterModelOptions(
name='unit',
options={'get_latest_by': 'mtime'},
),
]
|
unknown
|
codeparrot/codeparrot-clean
| ||
from test import TestCase, generate_random_vector
import struct
import redis.exceptions
class DimensionValidation(TestCase):
def getname(self):
return "[regression] Dimension Validation with Projection"
def estimated_runtime(self):
return 0.5
def test(self):
# Test scenario 1: Create a set with projection
original_dim = 100
reduced_dim = 50
# Create the initial vector and set with projection
vec1 = generate_random_vector(original_dim)
vec1_bytes = struct.pack(f'{original_dim}f', *vec1)
# Add first vector with projection
result = self.redis.execute_command('VADD', self.test_key,
'REDUCE', reduced_dim,
'FP32', vec1_bytes, f'{self.test_key}:item:1')
assert result == 1, "First VADD with REDUCE should return 1"
# Check VINFO returns the correct projection information
info = self.redis.execute_command('VINFO', self.test_key)
info_map = {k.decode('utf-8'): v for k, v in zip(info[::2], info[1::2])}
assert 'vector-dim' in info_map, "VINFO should contain vector-dim"
assert info_map['vector-dim'] == reduced_dim, f"Expected reduced dimension {reduced_dim}, got {info['vector-dim']}"
assert 'projection-input-dim' in info_map, "VINFO should contain projection-input-dim"
assert info_map['projection-input-dim'] == original_dim, f"Expected original dimension {original_dim}, got {info['projection-input-dim']}"
# Test scenario 2: Try adding a mismatched vector - should fail
wrong_dim = 80
wrong_vec = generate_random_vector(wrong_dim)
wrong_vec_bytes = struct.pack(f'{wrong_dim}f', *wrong_vec)
# This should fail with dimension mismatch error
try:
self.redis.execute_command('VADD', self.test_key,
'REDUCE', reduced_dim,
'FP32', wrong_vec_bytes, f'{self.test_key}:item:2')
assert False, "VADD with wrong dimension should fail"
except redis.exceptions.ResponseError as e:
assert "Input dimension mismatch for projection" in str(e), f"Expected dimension mismatch error, got: {e}"
# Test scenario 3: Add a correctly-sized vector
vec2 = generate_random_vector(original_dim)
vec2_bytes = struct.pack(f'{original_dim}f', *vec2)
# This should succeed
result = self.redis.execute_command('VADD', self.test_key,
'REDUCE', reduced_dim,
'FP32', vec2_bytes, f'{self.test_key}:item:3')
assert result == 1, "VADD with correct dimensions should succeed"
# Check VSIM also validates input dimensions
wrong_query = generate_random_vector(wrong_dim)
try:
self.redis.execute_command('VSIM', self.test_key,
'VALUES', wrong_dim, *[str(x) for x in wrong_query],
'COUNT', 10)
assert False, "VSIM with wrong dimension should fail"
except redis.exceptions.ResponseError as e:
assert "Input dimension mismatch for projection" in str(e), f"Expected dimension mismatch error in VSIM, got: {e}"
|
python
|
github
|
https://github.com/redis/redis
|
modules/vector-sets/tests/dimension_validation.py
|
import doctest
import unittest
import itertools
from test import support
from test.support import threading_helper, script_helper
from itertools import *
import weakref
from decimal import Decimal
from fractions import Fraction
import operator
import random
import copy
import pickle
from functools import reduce
import sys
import struct
import threading
import gc
maxsize = support.MAX_Py_ssize_t
minsize = -maxsize-1
def lzip(*args):
return list(zip(*args))
def onearg(x):
'Test function of one argument'
return 2*x
def errfunc(*args):
'Test function that raises an error'
raise ValueError
def gen3():
'Non-restartable source sequence'
for i in (0, 1, 2):
yield i
def isEven(x):
'Test predicate'
return x%2==0
def isOdd(x):
'Test predicate'
return x%2==1
def tupleize(*args):
return args
def irange(n):
for i in range(n):
yield i
class StopNow:
'Class emulating an empty iterable.'
def __iter__(self):
return self
def __next__(self):
raise StopIteration
def take(n, seq):
'Convenience function for partially consuming a long of infinite iterable'
return list(islice(seq, n))
def prod(iterable):
return reduce(operator.mul, iterable, 1)
def fact(n):
'Factorial'
return prod(range(1, n+1))
# root level methods for pickling ability
def testR(r):
return r[0]
def testR2(r):
return r[2]
def underten(x):
return x<10
picklecopiers = [lambda s, proto=proto: pickle.loads(pickle.dumps(s, proto))
for proto in range(pickle.HIGHEST_PROTOCOL + 1)]
class TestBasicOps(unittest.TestCase):
def pickletest(self, protocol, it, stop=4, take=1, compare=None):
"""Test that an iterator is the same after pickling, also when part-consumed"""
def expand(it, i=0):
# Recursively expand iterables, within sensible bounds
if i > 10:
raise RuntimeError("infinite recursion encountered")
if isinstance(it, str):
return it
try:
l = list(islice(it, stop))
except TypeError:
return it # can't expand it
return [expand(e, i+1) for e in l]
# Test the initial copy against the original
dump = pickle.dumps(it, protocol)
i2 = pickle.loads(dump)
self.assertEqual(type(it), type(i2))
a, b = expand(it), expand(i2)
self.assertEqual(a, b)
if compare:
c = expand(compare)
self.assertEqual(a, c)
# Take from the copy, and create another copy and compare them.
i3 = pickle.loads(dump)
took = 0
try:
for i in range(take):
next(i3)
took += 1
except StopIteration:
pass #in case there is less data than 'take'
dump = pickle.dumps(i3, protocol)
i4 = pickle.loads(dump)
a, b = expand(i3), expand(i4)
self.assertEqual(a, b)
if compare:
c = expand(compare[took:])
self.assertEqual(a, c);
def test_accumulate(self):
self.assertEqual(list(accumulate(range(10))), # one positional arg
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
self.assertEqual(list(accumulate(iterable=range(10))), # kw arg
[0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
for typ in int, complex, Decimal, Fraction: # multiple types
self.assertEqual(
list(accumulate(map(typ, range(10)))),
list(map(typ, [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])))
self.assertEqual(list(accumulate('abc')), ['a', 'ab', 'abc']) # works with non-numeric
self.assertEqual(list(accumulate([])), []) # empty iterable
self.assertEqual(list(accumulate([7])), [7]) # iterable of length one
self.assertRaises(TypeError, accumulate, range(10), 5, 6) # too many args
self.assertRaises(TypeError, accumulate) # too few args
self.assertRaises(TypeError, accumulate, x=range(10)) # unexpected kwd arg
self.assertRaises(TypeError, list, accumulate([1, []])) # args that don't add
s = [2, 8, 9, 5, 7, 0, 3, 4, 1, 6]
self.assertEqual(list(accumulate(s, min)),
[2, 2, 2, 2, 2, 0, 0, 0, 0, 0])
self.assertEqual(list(accumulate(s, max)),
[2, 8, 9, 9, 9, 9, 9, 9, 9, 9])
self.assertEqual(list(accumulate(s, operator.mul)),
[2, 16, 144, 720, 5040, 0, 0, 0, 0, 0])
with self.assertRaises(TypeError):
list(accumulate(s, chr)) # unary-operation
self.assertEqual(list(accumulate([10, 5, 1], initial=None)), [10, 15, 16])
self.assertEqual(list(accumulate([10, 5, 1], initial=100)), [100, 110, 115, 116])
self.assertEqual(list(accumulate([], initial=100)), [100])
with self.assertRaises(TypeError):
list(accumulate([10, 20], 100))
def test_batched(self):
self.assertEqual(list(batched('ABCDEFG', 3)),
[('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)])
self.assertEqual(list(batched('ABCDEFG', 2)),
[('A', 'B'), ('C', 'D'), ('E', 'F'), ('G',)])
self.assertEqual(list(batched('ABCDEFG', 1)),
[('A',), ('B',), ('C',), ('D',), ('E',), ('F',), ('G',)])
self.assertEqual(list(batched('ABCDEF', 2, strict=True)),
[('A', 'B'), ('C', 'D'), ('E', 'F')])
with self.assertRaises(ValueError): # Incomplete batch when strict
list(batched('ABCDEFG', 3, strict=True))
with self.assertRaises(TypeError): # Too few arguments
list(batched('ABCDEFG'))
with self.assertRaises(TypeError):
list(batched('ABCDEFG', 3, None)) # Too many arguments
with self.assertRaises(TypeError):
list(batched(None, 3)) # Non-iterable input
with self.assertRaises(TypeError):
list(batched('ABCDEFG', 'hello')) # n is a string
with self.assertRaises(ValueError):
list(batched('ABCDEFG', 0)) # n is zero
with self.assertRaises(ValueError):
list(batched('ABCDEFG', -1)) # n is negative
data = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for n in range(1, 6):
for i in range(len(data)):
s = data[:i]
batches = list(batched(s, n))
with self.subTest(s=s, n=n, batches=batches):
# Order is preserved and no data is lost
self.assertEqual(''.join(chain(*batches)), s)
# Each batch is an exact tuple
self.assertTrue(all(type(batch) is tuple for batch in batches))
# All but the last batch is of size n
if batches:
last_batch = batches.pop()
self.assertTrue(all(len(batch) == n for batch in batches))
self.assertTrue(len(last_batch) <= n)
batches.append(last_batch)
def test_chain(self):
def chain2(*iterables):
'Pure python version in the docs'
for it in iterables:
for element in it:
yield element
for c in (chain, chain2):
self.assertEqual(list(c('abc', 'def')), list('abcdef'))
self.assertEqual(list(c('abc')), list('abc'))
self.assertEqual(list(c('')), [])
self.assertEqual(take(4, c('abc', 'def')), list('abcd'))
self.assertRaises(TypeError, list,c(2, 3))
def test_chain_from_iterable(self):
self.assertEqual(list(chain.from_iterable(['abc', 'def'])), list('abcdef'))
self.assertEqual(list(chain.from_iterable(['abc'])), list('abc'))
self.assertEqual(list(chain.from_iterable([''])), [])
self.assertEqual(take(4, chain.from_iterable(['abc', 'def'])), list('abcd'))
self.assertRaises(TypeError, list, chain.from_iterable([2, 3]))
self.assertEqual(list(islice(chain.from_iterable(repeat(range(5))), 2)), [0, 1])
def test_combinations(self):
self.assertRaises(TypeError, combinations, 'abc') # missing r argument
self.assertRaises(TypeError, combinations, 'abc', 2, 1) # too many arguments
self.assertRaises(TypeError, combinations, None) # pool is not iterable
self.assertRaises(ValueError, combinations, 'abc', -2) # r is negative
def combinations1(iterable, r):
'Pure python version shown in the docs'
pool = tuple(iterable)
n = len(pool)
if r > n:
return
indices = list(range(r))
yield tuple(pool[i] for i in indices)
while 1:
for i in reversed(range(r)):
if indices[i] != i + n - r:
break
else:
return
indices[i] += 1
for j in range(i+1, r):
indices[j] = indices[j-1] + 1
yield tuple(pool[i] for i in indices)
def combinations2(iterable, r):
'Pure python version shown in the docs'
pool = tuple(iterable)
n = len(pool)
for indices in permutations(range(n), r):
if sorted(indices) == list(indices):
yield tuple(pool[i] for i in indices)
def combinations3(iterable, r):
'Pure python version from cwr()'
pool = tuple(iterable)
n = len(pool)
for indices in combinations_with_replacement(range(n), r):
if len(set(indices)) == r:
yield tuple(pool[i] for i in indices)
for n in range(7):
values = [5*x-12 for x in range(n)]
for r in range(n+2):
result = list(combinations(values, r))
self.assertEqual(len(result), 0 if r>n else fact(n) / fact(r) / fact(n-r)) # right number of combs
self.assertEqual(len(result), len(set(result))) # no repeats
self.assertEqual(result, sorted(result)) # lexicographic order
for c in result:
self.assertEqual(len(c), r) # r-length combinations
self.assertEqual(len(set(c)), r) # no duplicate elements
self.assertEqual(list(c), sorted(c)) # keep original ordering
self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
self.assertEqual(list(c),
[e for e in values if e in c]) # comb is a subsequence of the input iterable
self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version
@support.bigaddrspacetest
def test_combinations_overflow(self):
with self.assertRaises((OverflowError, MemoryError)):
combinations("AA", 2**29)
# Test implementation detail: tuple re-use
@support.impl_detail("tuple reuse is specific to CPython")
def test_combinations_tuple_reuse(self):
self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
self.assertNotEqual(len(set(map(id, list(combinations('abcde', 3))))), 1)
def test_combinations_with_replacement(self):
cwr = combinations_with_replacement
self.assertRaises(TypeError, cwr, 'abc') # missing r argument
self.assertRaises(TypeError, cwr, 'abc', 2, 1) # too many arguments
self.assertRaises(TypeError, cwr, None) # pool is not iterable
self.assertRaises(ValueError, cwr, 'abc', -2) # r is negative
def cwr1(iterable, r):
'Pure python version shown in the docs'
# number items returned: (n+r-1)! / r! / (n-1)! when n>0
pool = tuple(iterable)
n = len(pool)
if not n and r:
return
indices = [0] * r
yield tuple(pool[i] for i in indices)
while 1:
for i in reversed(range(r)):
if indices[i] != n - 1:
break
else:
return
indices[i:] = [indices[i] + 1] * (r - i)
yield tuple(pool[i] for i in indices)
def cwr2(iterable, r):
'Pure python version shown in the docs'
pool = tuple(iterable)
n = len(pool)
for indices in product(range(n), repeat=r):
if sorted(indices) == list(indices):
yield tuple(pool[i] for i in indices)
def numcombs(n, r):
if not n:
return 0 if r else 1
return fact(n+r-1) / fact(r)/ fact(n-1)
for n in range(7):
values = [5*x-12 for x in range(n)]
for r in range(n+2):
result = list(cwr(values, r))
self.assertEqual(len(result), numcombs(n, r)) # right number of combs
self.assertEqual(len(result), len(set(result))) # no repeats
self.assertEqual(result, sorted(result)) # lexicographic order
regular_combs = list(combinations(values, r)) # compare to combs without replacement
if n == 0 or r <= 1:
self.assertEqual(result, regular_combs) # cases that should be identical
else:
self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs
for c in result:
self.assertEqual(len(c), r) # r-length combinations
noruns = [k for k,v in groupby(c)] # combo without consecutive repeats
self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive
self.assertEqual(list(c), sorted(c)) # keep original ordering
self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
self.assertEqual(noruns,
[e for e in values if e in c]) # comb is a subsequence of the input iterable
self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version
self.assertEqual(result, list(cwr2(values, r))) # matches second pure python version
@support.bigaddrspacetest
def test_combinations_with_replacement_overflow(self):
with self.assertRaises((OverflowError, MemoryError)):
combinations_with_replacement("AA", 2**30)
# Test implementation detail: tuple re-use
@support.impl_detail("tuple reuse is specific to CPython")
def test_combinations_with_replacement_tuple_reuse(self):
cwr = combinations_with_replacement
self.assertEqual(len(set(map(id, cwr('abcde', 3)))), 1)
self.assertNotEqual(len(set(map(id, list(cwr('abcde', 3))))), 1)
def test_permutations(self):
self.assertRaises(TypeError, permutations) # too few arguments
self.assertRaises(TypeError, permutations, 'abc', 2, 1) # too many arguments
self.assertRaises(TypeError, permutations, None) # pool is not iterable
self.assertRaises(ValueError, permutations, 'abc', -2) # r is negative
self.assertEqual(list(permutations('abc', 32)), []) # r > n
self.assertRaises(TypeError, permutations, 'abc', 's') # r is not an int or None
self.assertEqual(list(permutations(range(3), 2)),
[(0,1), (0,2), (1,0), (1,2), (2,0), (2,1)])
def permutations1(iterable, r=None):
'Pure python version shown in the docs'
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = list(range(n-r+1, n+1))[::-1]
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
def permutations2(iterable, r=None):
'Pure python version shown in the docs'
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
for indices in product(range(n), repeat=r):
if len(set(indices)) == r:
yield tuple(pool[i] for i in indices)
for n in range(7):
values = [5*x-12 for x in range(n)]
for r in range(n+2):
result = list(permutations(values, r))
self.assertEqual(len(result), 0 if r>n else fact(n) / fact(n-r)) # right number of perms
self.assertEqual(len(result), len(set(result))) # no repeats
self.assertEqual(result, sorted(result)) # lexicographic order
for p in result:
self.assertEqual(len(p), r) # r-length permutations
self.assertEqual(len(set(p)), r) # no duplicate elements
self.assertTrue(all(e in values for e in p)) # elements taken from input iterable
self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
if r == n:
self.assertEqual(result, list(permutations(values, None))) # test r as None
self.assertEqual(result, list(permutations(values))) # test default r
@support.bigaddrspacetest
def test_permutations_overflow(self):
with self.assertRaises((OverflowError, MemoryError)):
permutations("A", 2**30)
@support.impl_detail("tuple reuse is specific to CPython")
def test_permutations_tuple_reuse(self):
self.assertEqual(len(set(map(id, permutations('abcde', 3)))), 1)
self.assertNotEqual(len(set(map(id, list(permutations('abcde', 3))))), 1)
def test_combinatorics(self):
# Test relationships between product(), permutations(),
# combinations() and combinations_with_replacement().
for n in range(6):
s = 'ABCDEFG'[:n]
for r in range(8):
prod = list(product(s, repeat=r))
cwr = list(combinations_with_replacement(s, r))
perm = list(permutations(s, r))
comb = list(combinations(s, r))
# Check size
self.assertEqual(len(prod), n**r)
self.assertEqual(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r))
self.assertEqual(len(perm), 0 if r>n else fact(n) / fact(n-r))
self.assertEqual(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r))
# Check lexicographic order without repeated tuples
self.assertEqual(prod, sorted(set(prod)))
self.assertEqual(cwr, sorted(set(cwr)))
self.assertEqual(perm, sorted(set(perm)))
self.assertEqual(comb, sorted(set(comb)))
# Check interrelationships
self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted
self.assertEqual(perm, [t for t in prod if len(set(t))==r]) # perm: prods with no dups
self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) # comb: perms that are sorted
self.assertEqual(comb, [t for t in cwr if len(set(t))==r]) # comb: cwrs without dups
self.assertEqual(comb, list(filter(set(cwr).__contains__, perm))) # comb: perm that is a cwr
self.assertEqual(comb, list(filter(set(perm).__contains__, cwr))) # comb: cwr that is a perm
self.assertEqual(comb, sorted(set(cwr) & set(perm))) # comb: both a cwr and a perm
def test_compress(self):
self.assertEqual(list(compress(data='ABCDEF', selectors=[1,0,1,0,1,1])), list('ACEF'))
self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
self.assertEqual(list(compress('ABCDEF', [0,0,0,0,0,0])), list(''))
self.assertEqual(list(compress('ABCDEF', [1,1,1,1,1,1])), list('ABCDEF'))
self.assertEqual(list(compress('ABCDEF', [1,0,1])), list('AC'))
self.assertEqual(list(compress('ABC', [0,1,1,1,1,1])), list('BC'))
n = 10000
data = chain.from_iterable(repeat(range(6), n))
selectors = chain.from_iterable(repeat((0, 1)))
self.assertEqual(list(compress(data, selectors)), [1,3,5] * n)
self.assertRaises(TypeError, compress, None, range(6)) # 1st arg not iterable
self.assertRaises(TypeError, compress, range(6), None) # 2nd arg not iterable
self.assertRaises(TypeError, compress, range(6)) # too few args
self.assertRaises(TypeError, compress, range(6), None) # too many args
def test_count(self):
self.assertEqual(lzip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
self.assertEqual(lzip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)])
self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)])
self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
self.assertRaises(TypeError, count, 2, 3, 4)
self.assertRaises(TypeError, count, 'a')
self.assertEqual(take(3, count(maxsize)),
[maxsize, maxsize + 1, maxsize + 2])
self.assertEqual(take(10, count(maxsize-5)),
list(range(maxsize-5, maxsize+5)))
self.assertEqual(take(10, count(-maxsize-5)),
list(range(-maxsize-5, -maxsize+5)))
self.assertEqual(take(3, count(3.25)), [3.25, 4.25, 5.25])
self.assertEqual(take(3, count(3.25-4j)), [3.25-4j, 4.25-4j, 5.25-4j])
self.assertEqual(take(3, count(Decimal('1.1'))),
[Decimal('1.1'), Decimal('2.1'), Decimal('3.1')])
self.assertEqual(take(3, count(Fraction(2, 3))),
[Fraction(2, 3), Fraction(5, 3), Fraction(8, 3)])
BIGINT = 1<<1000
self.assertEqual(take(3, count(BIGINT)), [BIGINT, BIGINT+1, BIGINT+2])
c = count(3)
self.assertEqual(repr(c), 'count(3)')
next(c)
self.assertEqual(repr(c), 'count(4)')
c = count(-9)
self.assertEqual(repr(c), 'count(-9)')
next(c)
self.assertEqual(next(c), -8)
self.assertEqual(repr(count(10.25)), 'count(10.25)')
self.assertEqual(repr(count(10.0)), 'count(10.0)')
self.assertEqual(repr(count(maxsize)), f'count({maxsize})')
c = count(maxsize - 1)
self.assertEqual(repr(c), f'count({maxsize - 1})')
next(c) # c is now at masize
self.assertEqual(repr(c), f'count({maxsize})')
next(c)
self.assertEqual(repr(c), f'count({maxsize + 1})')
self.assertEqual(type(next(count(10.0))), float)
for i in (-sys.maxsize-5, -sys.maxsize+5 ,-10, -1, 0, 10, sys.maxsize-5, sys.maxsize+5):
# Test repr
r1 = repr(count(i))
r2 = 'count(%r)'.__mod__(i)
self.assertEqual(r1, r2)
#check proper internal error handling for large "step' sizes
count(1, maxsize+5); sys.exc_info()
def test_count_with_step(self):
self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
self.assertEqual(lzip('abc',count(start=2,step=3)),
[('a', 2), ('b', 5), ('c', 8)])
self.assertEqual(lzip('abc',count(step=-1)),
[('a', 0), ('b', -1), ('c', -2)])
self.assertRaises(TypeError, count, 'a', 'b')
self.assertEqual(lzip('abc',count(2,0)), [('a', 2), ('b', 2), ('c', 2)])
self.assertEqual(lzip('abc',count(2,1)), [('a', 2), ('b', 3), ('c', 4)])
self.assertEqual(lzip('abc',count(2,3)), [('a', 2), ('b', 5), ('c', 8)])
self.assertEqual(take(20, count(maxsize-15, 3)), take(20, range(maxsize-15, maxsize+100, 3)))
self.assertEqual(take(20, count(-maxsize-15, 3)), take(20, range(-maxsize-15,-maxsize+100, 3)))
self.assertEqual(take(3, count(10, maxsize+5)),
list(range(10, 10+3*(maxsize+5), maxsize+5)))
self.assertEqual(take(3, count(maxsize, 2)),
[maxsize, maxsize + 2, maxsize + 4])
self.assertEqual(take(3, count(maxsize, maxsize)),
[maxsize, 2 * maxsize, 3 * maxsize])
self.assertEqual(take(3, count(-maxsize, maxsize)),
[-maxsize, 0, maxsize])
self.assertEqual(take(3, count(2, 1.25)), [2, 3.25, 4.5])
self.assertEqual(take(3, count(2, 3.25-4j)), [2, 5.25-4j, 8.5-8j])
self.assertEqual(take(3, count(Decimal('1.1'), Decimal('.1'))),
[Decimal('1.1'), Decimal('1.2'), Decimal('1.3')])
self.assertEqual(take(3, count(Fraction(2,3), Fraction(1,7))),
[Fraction(2,3), Fraction(17,21), Fraction(20,21)])
BIGINT = 1<<1000
self.assertEqual(take(3, count(step=BIGINT)), [0, BIGINT, 2*BIGINT])
self.assertEqual(repr(take(3, count(10, 2.5))), repr([10, 12.5, 15.0]))
c = count(3, 5)
self.assertEqual(repr(c), 'count(3, 5)')
next(c)
self.assertEqual(repr(c), 'count(8, 5)')
c = count(-9, 0)
self.assertEqual(repr(c), 'count(-9, 0)')
next(c)
self.assertEqual(repr(c), 'count(-9, 0)')
c = count(-9, -3)
self.assertEqual(repr(c), 'count(-9, -3)')
next(c)
self.assertEqual(repr(c), 'count(-12, -3)')
self.assertEqual(repr(c), 'count(-12, -3)')
self.assertEqual(repr(count(10.5, 1.25)), 'count(10.5, 1.25)')
self.assertEqual(repr(count(10.5, 1)), 'count(10.5)') # suppress step=1 when it's an int
self.assertEqual(repr(count(10.5, 1.00)), 'count(10.5, 1.0)') # do show float values lilke 1.0
self.assertEqual(repr(count(10, 1.00)), 'count(10, 1.0)')
c = count(10, 1.0)
self.assertEqual(type(next(c)), int)
self.assertEqual(type(next(c)), float)
c = count(maxsize -2, 2)
self.assertEqual(repr(c), f'count({maxsize - 2}, 2)')
next(c) # c is now at masize
self.assertEqual(repr(c), f'count({maxsize}, 2)')
next(c)
self.assertEqual(repr(c), f'count({maxsize + 2}, 2)')
c = count(maxsize + 1, -1)
self.assertEqual(repr(c), f'count({maxsize + 1}, -1)')
next(c) # c is now at masize
self.assertEqual(repr(c), f'count({maxsize}, -1)')
next(c)
self.assertEqual(repr(c), f'count({maxsize - 1}, -1)')
@threading_helper.requires_working_threading()
def test_count_threading(self, step=1):
# this test verifies multithreading consistency, which is
# mostly for testing builds without GIL, but nice to test anyway
count_to = 10_000
num_threads = 10
c = count(step=step)
def counting_thread():
for i in range(count_to):
next(c)
threads = []
for i in range(num_threads):
thread = threading.Thread(target=counting_thread)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
self.assertEqual(next(c), count_to * num_threads * step)
def test_count_with_step_threading(self):
self.test_count_threading(step=5)
def test_cycle(self):
self.assertEqual(take(10, cycle('abc')), list('abcabcabca'))
self.assertEqual(list(cycle('')), [])
self.assertRaises(TypeError, cycle)
self.assertRaises(TypeError, cycle, 5)
self.assertEqual(list(islice(cycle(gen3()),10)), [0,1,2,0,1,2,0,1,2,0])
def test_groupby(self):
# Check whether it accepts arguments correctly
self.assertEqual([], list(groupby([])))
self.assertEqual([], list(groupby([], key=id)))
self.assertRaises(TypeError, list, groupby('abc', []))
self.assertRaises(TypeError, groupby, None)
self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
# Check normal input
s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
(2,15,22), (3,16,23), (3,17,23)]
dup = []
for k, g in groupby(s, lambda r:r[0]):
for elem in g:
self.assertEqual(k, elem[0])
dup.append(elem)
self.assertEqual(s, dup)
# Check nested case
dup = []
for k, g in groupby(s, testR):
for ik, ig in groupby(g, testR2):
for elem in ig:
self.assertEqual(k, elem[0])
self.assertEqual(ik, elem[2])
dup.append(elem)
self.assertEqual(s, dup)
# Check case where inner iterator is not used
keys = [k for k, g in groupby(s, testR)]
expectedkeys = set([r[0] for r in s])
self.assertEqual(set(keys), expectedkeys)
self.assertEqual(len(keys), len(expectedkeys))
# Check case where inner iterator is used after advancing the groupby
# iterator
s = list(zip('AABBBAAAA', range(9)))
it = groupby(s, testR)
_, g1 = next(it)
_, g2 = next(it)
_, g3 = next(it)
self.assertEqual(list(g1), [])
self.assertEqual(list(g2), [])
self.assertEqual(next(g3), ('A', 5))
list(it) # exhaust the groupby iterator
self.assertEqual(list(g3), [])
# Exercise pipes and filters style
s = 'abracadabra'
# sort s | uniq
r = [k for k, g in groupby(sorted(s))]
self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
# sort s | uniq -d
r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
self.assertEqual(r, ['a', 'b', 'r'])
# sort s | uniq -c
r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
# sort s | uniq -c | sort -rn | head -3
r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
# iter.__next__ failure
class ExpectedError(Exception):
pass
def delayed_raise(n=0):
for i in range(n):
yield 'yo'
raise ExpectedError
def gulp(iterable, keyp=None, func=list):
return [func(g) for k, g in groupby(iterable, keyp)]
# iter.__next__ failure on outer object
self.assertRaises(ExpectedError, gulp, delayed_raise(0))
# iter.__next__ failure on inner object
self.assertRaises(ExpectedError, gulp, delayed_raise(1))
# __eq__ failure
class DummyCmp:
def __eq__(self, dst):
raise ExpectedError
s = [DummyCmp(), DummyCmp(), None]
# __eq__ failure on outer object
self.assertRaises(ExpectedError, gulp, s, func=id)
# __eq__ failure on inner object
self.assertRaises(ExpectedError, gulp, s)
# keyfunc failure
def keyfunc(obj):
if keyfunc.skip > 0:
keyfunc.skip -= 1
return obj
else:
raise ExpectedError
# keyfunc failure on outer object
keyfunc.skip = 0
self.assertRaises(ExpectedError, gulp, [None], keyfunc)
keyfunc.skip = 1
self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
def test_groupby_reentrant_eq_does_not_crash(self):
# regression test for gh-143543
class Key:
def __init__(self, do_advance):
self.do_advance = do_advance
def __eq__(self, other):
if self.do_advance:
self.do_advance = False
next(g)
return NotImplemented
return False
def keys():
yield Key(True)
yield Key(False)
g = itertools.groupby([None, None], keys().send)
next(g)
next(g) # must pass with address sanitizer
def test_filter(self):
self.assertEqual(list(filter(isEven, range(6))), [0,2,4])
self.assertEqual(list(filter(None, [0,1,0,2,0])), [1,2])
self.assertEqual(list(filter(bool, [0,1,0,2,0])), [1,2])
self.assertEqual(take(4, filter(isEven, count())), [0,2,4,6])
self.assertRaises(TypeError, filter)
self.assertRaises(TypeError, filter, lambda x:x)
self.assertRaises(TypeError, filter, lambda x:x, range(6), 7)
self.assertRaises(TypeError, filter, isEven, 3)
self.assertRaises(TypeError, next, filter(range(6), range(6)))
# check copy, deepcopy, pickle
ans = [0,2,4]
c = filter(isEven, range(6))
self.assertEqual(list(copy.copy(c)), ans)
c = filter(isEven, range(6))
self.assertEqual(list(copy.deepcopy(c)), ans)
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
c = filter(isEven, range(6))
self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans)
next(c)
self.assertEqual(list(pickle.loads(pickle.dumps(c, proto))), ans[1:])
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
c = filter(isEven, range(6))
self.pickletest(proto, c)
def test_filterfalse(self):
self.assertEqual(list(filterfalse(isEven, range(6))), [1,3,5])
self.assertEqual(list(filterfalse(None, [0,1,0,2,0])), [0,0,0])
self.assertEqual(list(filterfalse(bool, [0,1,0,2,0])), [0,0,0])
self.assertEqual(take(4, filterfalse(isEven, count())), [1,3,5,7])
self.assertRaises(TypeError, filterfalse)
self.assertRaises(TypeError, filterfalse, lambda x:x)
self.assertRaises(TypeError, filterfalse, lambda x:x, range(6), 7)
self.assertRaises(TypeError, filterfalse, isEven, 3)
self.assertRaises(TypeError, next, filterfalse(range(6), range(6)))
def test_zip(self):
# XXX This is rather silly now that builtin zip() calls zip()...
ans = [(x,y) for x, y in zip('abc',count())]
self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)])
self.assertEqual(list(zip('abc', range(6))), lzip('abc', range(6)))
self.assertEqual(list(zip('abcdef', range(3))), lzip('abcdef', range(3)))
self.assertEqual(take(3,zip('abcdef', count())), lzip('abcdef', range(3)))
self.assertEqual(list(zip('abcdef')), lzip('abcdef'))
self.assertEqual(list(zip()), lzip())
self.assertRaises(TypeError, zip, 3)
self.assertRaises(TypeError, zip, range(3), 3)
self.assertEqual([tuple(list(pair)) for pair in zip('abc', 'def')],
lzip('abc', 'def'))
self.assertEqual([pair for pair in zip('abc', 'def')],
lzip('abc', 'def'))
@support.impl_detail("tuple reuse is specific to CPython")
def test_zip_tuple_reuse(self):
ids = list(map(id, zip('abc', 'def')))
self.assertEqual(min(ids), max(ids))
ids = list(map(id, list(zip('abc', 'def'))))
self.assertEqual(len(dict.fromkeys(ids)), len(ids))
def test_ziplongest(self):
for args in [
['abc', range(6)],
[range(6), 'abc'],
[range(1000), range(2000,2100), range(3000,3050)],
[range(1000), range(0), range(3000,3050), range(1200), range(1500)],
[range(1000), range(0), range(3000,3050), range(1200), range(1500), range(0)],
]:
target = [tuple([arg[i] if i < len(arg) else None for arg in args])
for i in range(max(map(len, args)))]
self.assertEqual(list(zip_longest(*args)), target)
self.assertEqual(list(zip_longest(*args, **{})), target)
target = [tuple((e is None and 'X' or e) for e in t) for t in target] # Replace None fills with 'X'
self.assertEqual(list(zip_longest(*args, **dict(fillvalue='X'))), target)
self.assertEqual(take(3,zip_longest('abcdef', count())), list(zip('abcdef', range(3)))) # take 3 from infinite input
self.assertEqual(list(zip_longest()), list(zip()))
self.assertEqual(list(zip_longest([])), list(zip([])))
self.assertEqual(list(zip_longest('abcdef')), list(zip('abcdef')))
self.assertEqual(list(zip_longest('abc', 'defg', **{})),
list(zip(list('abc')+[None], 'defg'))) # empty keyword dict
self.assertRaises(TypeError, zip_longest, 3)
self.assertRaises(TypeError, zip_longest, range(3), 3)
for stmt in [
"zip_longest('abc', fv=1)",
"zip_longest('abc', fillvalue=1, bogus_keyword=None)",
]:
try:
eval(stmt, globals(), locals())
except TypeError:
pass
else:
self.fail('Did not raise Type in: ' + stmt)
self.assertEqual([tuple(list(pair)) for pair in zip_longest('abc', 'def')],
list(zip('abc', 'def')))
self.assertEqual([pair for pair in zip_longest('abc', 'def')],
list(zip('abc', 'def')))
@support.impl_detail("tuple reuse is specific to CPython")
def test_zip_longest_tuple_reuse(self):
ids = list(map(id, zip_longest('abc', 'def')))
self.assertEqual(min(ids), max(ids))
ids = list(map(id, list(zip_longest('abc', 'def'))))
self.assertEqual(len(dict.fromkeys(ids)), len(ids))
def test_zip_longest_bad_iterable(self):
exception = TypeError()
class BadIterable:
def __iter__(self):
raise exception
with self.assertRaises(TypeError) as cm:
zip_longest(BadIterable())
self.assertIs(cm.exception, exception)
def test_bug_7244(self):
class Repeater:
# this class is similar to itertools.repeat
def __init__(self, o, t, e):
self.o = o
self.t = int(t)
self.e = e
def __iter__(self): # its iterator is itself
return self
def __next__(self):
if self.t > 0:
self.t -= 1
return self.o
else:
raise self.e
# Formerly this code in would fail in debug mode
# with Undetected Error and Stop Iteration
r1 = Repeater(1, 3, StopIteration)
r2 = Repeater(2, 4, StopIteration)
def run(r1, r2):
result = []
for i, j in zip_longest(r1, r2, fillvalue=0):
with support.captured_output('stdout'):
print((i, j))
result.append((i, j))
return result
self.assertEqual(run(r1, r2), [(1,2), (1,2), (1,2), (0,2)])
# Formerly, the RuntimeError would be lost
# and StopIteration would stop as expected
r1 = Repeater(1, 3, RuntimeError)
r2 = Repeater(2, 4, StopIteration)
it = zip_longest(r1, r2, fillvalue=0)
self.assertEqual(next(it), (1, 2))
self.assertEqual(next(it), (1, 2))
self.assertEqual(next(it), (1, 2))
self.assertRaises(RuntimeError, next, it)
def test_pairwise(self):
self.assertEqual(list(pairwise('')), [])
self.assertEqual(list(pairwise('a')), [])
self.assertEqual(list(pairwise('ab')),
[('a', 'b')]),
self.assertEqual(list(pairwise('abcde')),
[('a', 'b'), ('b', 'c'), ('c', 'd'), ('d', 'e')])
self.assertEqual(list(pairwise(range(10_000))),
list(zip(range(10_000), range(1, 10_000))))
with self.assertRaises(TypeError):
pairwise() # too few arguments
with self.assertRaises(TypeError):
pairwise('abc', 10) # too many arguments
with self.assertRaises(TypeError):
pairwise(iterable='abc') # keyword arguments
with self.assertRaises(TypeError):
pairwise(None) # non-iterable argument
def test_pairwise_reenter(self):
def check(reenter_at, expected):
class I:
count = 0
def __iter__(self):
return self
def __next__(self):
self.count +=1
if self.count in reenter_at:
return next(it)
return [self.count] # new object
it = pairwise(I())
for item in expected:
self.assertEqual(next(it), item)
check({1}, [
(([2], [3]), [4]),
([4], [5]),
])
check({2}, [
([1], ([1], [3])),
(([1], [3]), [4]),
([4], [5]),
])
check({3}, [
([1], [2]),
([2], ([2], [4])),
(([2], [4]), [5]),
([5], [6]),
])
check({1, 2}, [
((([3], [4]), [5]), [6]),
([6], [7]),
])
check({1, 3}, [
(([2], ([2], [4])), [5]),
([5], [6]),
])
check({1, 4}, [
(([2], [3]), (([2], [3]), [5])),
((([2], [3]), [5]), [6]),
([6], [7]),
])
check({2, 3}, [
([1], ([1], ([1], [4]))),
(([1], ([1], [4])), [5]),
([5], [6]),
])
def test_pairwise_reenter2(self):
def check(maxcount, expected):
class I:
count = 0
def __iter__(self):
return self
def __next__(self):
if self.count >= maxcount:
raise StopIteration
self.count +=1
if self.count == 1:
return next(it, None)
return [self.count] # new object
it = pairwise(I())
self.assertEqual(list(it), expected)
check(1, [])
check(2, [])
check(3, [])
check(4, [(([2], [3]), [4])])
def test_product(self):
for args, result in [
([], [()]), # zero iterables
(['ab'], [('a',), ('b',)]), # one iterable
([range(2), range(3)], [(0,0), (0,1), (0,2), (1,0), (1,1), (1,2)]), # two iterables
([range(0), range(2), range(3)], []), # first iterable with zero length
([range(2), range(0), range(3)], []), # middle iterable with zero length
([range(2), range(3), range(0)], []), # last iterable with zero length
]:
self.assertEqual(list(product(*args)), result)
for r in range(4):
self.assertEqual(list(product(*(args*r))),
list(product(*args, **dict(repeat=r))))
self.assertEqual(len(list(product(*[range(7)]*6))), 7**6)
self.assertRaises(TypeError, product, range(6), None)
def product1(*args, **kwds):
pools = list(map(tuple, args)) * kwds.get('repeat', 1)
n = len(pools)
if n == 0:
yield ()
return
if any(len(pool) == 0 for pool in pools):
return
indices = [0] * n
yield tuple(pool[i] for pool, i in zip(pools, indices))
while 1:
for i in reversed(range(n)): # right to left
if indices[i] == len(pools[i]) - 1:
continue
indices[i] += 1
for j in range(i+1, n):
indices[j] = 0
yield tuple(pool[i] for pool, i in zip(pools, indices))
break
else:
return
def product2(*iterables, repeat=1):
'Pure python version used in docs'
if repeat < 0:
raise ValueError('repeat argument cannot be negative')
pools = [tuple(pool) for pool in iterables] * repeat
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)
argtypes = ['', 'abc', '', range(0), range(4), dict(a=1, b=2, c=3),
set('abcdefg'), range(11), tuple(range(13))]
for i in range(100):
args = [random.choice(argtypes) for j in range(random.randrange(5))]
expected_len = prod(map(len, args))
self.assertEqual(len(list(product(*args))), expected_len)
self.assertEqual(list(product(*args)), list(product1(*args)))
self.assertEqual(list(product(*args)), list(product2(*args)))
args = map(iter, args)
self.assertEqual(len(list(product(*args))), expected_len)
@support.bigaddrspacetest
def test_product_overflow(self):
with self.assertRaises((OverflowError, MemoryError)):
product(*(['ab']*2**5), repeat=2**25)
@support.impl_detail("tuple reuse is specific to CPython")
def test_product_tuple_reuse(self):
self.assertEqual(len(set(map(id, product('abc', 'def')))), 1)
self.assertNotEqual(len(set(map(id, list(product('abc', 'def'))))), 1)
def test_repeat(self):
self.assertEqual(list(repeat(object='a', times=3)), ['a', 'a', 'a'])
self.assertEqual(lzip(range(3),repeat('a')),
[(0, 'a'), (1, 'a'), (2, 'a')])
self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a'])
self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a'])
self.assertEqual(list(repeat('a', 0)), [])
self.assertEqual(list(repeat('a', -3)), [])
self.assertRaises(TypeError, repeat)
self.assertRaises(TypeError, repeat, None, 3, 4)
self.assertRaises(TypeError, repeat, None, 'a')
r = repeat(1+0j)
self.assertEqual(repr(r), 'repeat((1+0j))')
r = repeat(1+0j, 5)
self.assertEqual(repr(r), 'repeat((1+0j), 5)')
list(r)
self.assertEqual(repr(r), 'repeat((1+0j), 0)')
def test_repeat_with_negative_times(self):
self.assertEqual(repr(repeat('a', -1)), "repeat('a', 0)")
self.assertEqual(repr(repeat('a', -2)), "repeat('a', 0)")
self.assertEqual(repr(repeat('a', times=-1)), "repeat('a', 0)")
self.assertEqual(repr(repeat('a', times=-2)), "repeat('a', 0)")
def test_map(self):
self.assertEqual(list(map(operator.pow, range(3), range(1,7))),
[0**1, 1**2, 2**3])
self.assertEqual(list(map(tupleize, 'abc', range(5))),
[('a',0),('b',1),('c',2)])
self.assertEqual(list(map(tupleize, 'abc', count())),
[('a',0),('b',1),('c',2)])
self.assertEqual(take(2,map(tupleize, 'abc', count())),
[('a',0),('b',1)])
self.assertEqual(list(map(operator.pow, [])), [])
self.assertRaises(TypeError, map)
self.assertRaises(TypeError, list, map(None, range(3), range(3)))
self.assertRaises(TypeError, map, operator.neg)
self.assertRaises(TypeError, next, map(10, range(5)))
self.assertRaises(ValueError, next, map(errfunc, [4], [5]))
self.assertRaises(TypeError, next, map(onearg, [4], [5]))
def test_starmap(self):
self.assertEqual(list(starmap(operator.pow, zip(range(3), range(1,7)))),
[0**1, 1**2, 2**3])
self.assertEqual(take(3, starmap(operator.pow, zip(count(), count(1)))),
[0**1, 1**2, 2**3])
self.assertEqual(list(starmap(operator.pow, [])), [])
self.assertEqual(list(starmap(operator.pow, [iter([4,5])])), [4**5])
self.assertRaises(TypeError, list, starmap(operator.pow, [None]))
self.assertRaises(TypeError, starmap)
self.assertRaises(TypeError, starmap, operator.pow, [(4,5)], 'extra')
self.assertRaises(TypeError, next, starmap(10, [(4,5)]))
self.assertRaises(ValueError, next, starmap(errfunc, [(4,5)]))
self.assertRaises(TypeError, next, starmap(onearg, [(4,5)]))
def test_islice(self):
for args in [ # islice(args) should agree with range(args)
(10, 20, 3),
(10, 3, 20),
(10, 20),
(10, 10),
(10, 3),
(20,)
]:
self.assertEqual(list(islice(range(100), *args)),
list(range(*args)))
for args, tgtargs in [ # Stop when seqn is exhausted
((10, 110, 3), ((10, 100, 3))),
((10, 110), ((10, 100))),
((110,), (100,))
]:
self.assertEqual(list(islice(range(100), *args)),
list(range(*tgtargs)))
# Test stop=None
self.assertEqual(list(islice(range(10), None)), list(range(10)))
self.assertEqual(list(islice(range(10), None, None)), list(range(10)))
self.assertEqual(list(islice(range(10), None, None, None)), list(range(10)))
self.assertEqual(list(islice(range(10), 2, None)), list(range(2, 10)))
self.assertEqual(list(islice(range(10), 1, None, 2)), list(range(1, 10, 2)))
# Test number of items consumed SF #1171417
it = iter(range(10))
self.assertEqual(list(islice(it, 3)), list(range(3)))
self.assertEqual(list(it), list(range(3, 10)))
it = iter(range(10))
self.assertEqual(list(islice(it, 3, 3)), [])
self.assertEqual(list(it), list(range(3, 10)))
# Test invalid arguments
ra = range(10)
self.assertRaises(TypeError, islice, ra)
self.assertRaises(TypeError, islice, ra, 1, 2, 3, 4)
self.assertRaises(ValueError, islice, ra, -5, 10, 1)
self.assertRaises(ValueError, islice, ra, 1, -5, -1)
self.assertRaises(ValueError, islice, ra, 1, 10, -1)
self.assertRaises(ValueError, islice, ra, 1, 10, 0)
self.assertRaises(ValueError, islice, ra, 'a')
self.assertRaises(ValueError, islice, ra, 'a', 1)
self.assertRaises(ValueError, islice, ra, 1, 'a')
self.assertRaises(ValueError, islice, ra, 'a', 1, 1)
self.assertRaises(ValueError, islice, ra, 1, 'a', 1)
self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
# Issue #10323: Less islice in a predictable state
c = count()
self.assertEqual(list(islice(c, 1, 3, 50)), [1])
self.assertEqual(next(c), 3)
# Issue #21321: check source iterator is not referenced
# from islice() after the latter has been exhausted
it = (x for x in (1, 2))
wr = weakref.ref(it)
it = islice(it, 1)
self.assertIsNotNone(wr())
list(it) # exhaust the iterator
support.gc_collect()
self.assertIsNone(wr())
# Issue #30537: islice can accept integer-like objects as
# arguments
class IntLike(object):
def __init__(self, val):
self.val = val
def __index__(self):
return self.val
self.assertEqual(list(islice(range(100), IntLike(10))), list(range(10)))
self.assertEqual(list(islice(range(100), IntLike(10), IntLike(50))),
list(range(10, 50)))
self.assertEqual(list(islice(range(100), IntLike(10), IntLike(50), IntLike(5))),
list(range(10,50,5)))
def test_takewhile(self):
data = [1, 3, 5, 20, 2, 4, 6, 8]
self.assertEqual(list(takewhile(underten, data)), [1, 3, 5])
self.assertEqual(list(takewhile(underten, [])), [])
self.assertRaises(TypeError, takewhile)
self.assertRaises(TypeError, takewhile, operator.pow)
self.assertRaises(TypeError, takewhile, operator.pow, [(4,5)], 'extra')
self.assertRaises(TypeError, next, takewhile(10, [(4,5)]))
self.assertRaises(ValueError, next, takewhile(errfunc, [(4,5)]))
t = takewhile(bool, [1, 1, 1, 0, 0, 0])
self.assertEqual(list(t), [1, 1, 1])
self.assertRaises(StopIteration, next, t)
def test_dropwhile(self):
data = [1, 3, 5, 20, 2, 4, 6, 8]
self.assertEqual(list(dropwhile(underten, data)), [20, 2, 4, 6, 8])
self.assertEqual(list(dropwhile(underten, [])), [])
self.assertRaises(TypeError, dropwhile)
self.assertRaises(TypeError, dropwhile, operator.pow)
self.assertRaises(TypeError, dropwhile, operator.pow, [(4,5)], 'extra')
self.assertRaises(TypeError, next, dropwhile(10, [(4,5)]))
self.assertRaises(ValueError, next, dropwhile(errfunc, [(4,5)]))
def test_tee(self):
n = 200
a, b = tee([]) # test empty iterator
self.assertEqual(list(a), [])
self.assertEqual(list(b), [])
a, b = tee(irange(n)) # test 100% interleaved
self.assertEqual(lzip(a,b), lzip(range(n), range(n)))
a, b = tee(irange(n)) # test 0% interleaved
self.assertEqual(list(a), list(range(n)))
self.assertEqual(list(b), list(range(n)))
a, b = tee(irange(n)) # test dealloc of leading iterator
for i in range(100):
self.assertEqual(next(a), i)
del a
self.assertEqual(list(b), list(range(n)))
a, b = tee(irange(n)) # test dealloc of trailing iterator
for i in range(100):
self.assertEqual(next(a), i)
del b
self.assertEqual(list(a), list(range(100, n)))
for j in range(5): # test randomly interleaved
order = [0]*n + [1]*n
random.shuffle(order)
lists = ([], [])
its = tee(irange(n))
for i in order:
value = next(its[i])
lists[i].append(value)
self.assertEqual(lists[0], list(range(n)))
self.assertEqual(lists[1], list(range(n)))
# test argument format checking
self.assertRaises(TypeError, tee)
self.assertRaises(TypeError, tee, 3)
self.assertRaises(TypeError, tee, [1,2], 'x')
self.assertRaises(TypeError, tee, [1,2], 3, 'x')
# tee object should be instantiable
a, b = tee('abc')
c = type(a)('def')
self.assertEqual(list(c), list('def'))
# test long-lagged and multi-way split
a, b, c = tee(range(2000), 3)
for i in range(100):
self.assertEqual(next(a), i)
self.assertEqual(list(b), list(range(2000)))
self.assertEqual([next(c), next(c)], list(range(2)))
self.assertEqual(list(a), list(range(100,2000)))
self.assertEqual(list(c), list(range(2,2000)))
# test values of n
self.assertRaises(TypeError, tee, 'abc', 'invalid')
self.assertRaises(ValueError, tee, [], -1)
for n in range(5):
result = tee('abc', n)
self.assertEqual(type(result), tuple)
self.assertEqual(len(result), n)
self.assertEqual([list(x) for x in result], [list('abc')]*n)
# tee objects are independent (see bug gh-123884)
a, b = tee('abc')
c, d = tee(a)
e, f = tee(c)
self.assertTrue(len({a, b, c, d, e, f}) == 6)
# test tee_new
t1, t2 = tee('abc')
tnew = type(t1)
self.assertRaises(TypeError, tnew)
self.assertRaises(TypeError, tnew, 10)
t3 = tnew(t1)
self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
# test that tee objects are weak referenceable
a, b = tee(range(10))
p = weakref.proxy(a)
self.assertEqual(getattr(p, '__class__'), type(b))
del a
support.gc_collect() # For PyPy or other GCs.
self.assertRaises(ReferenceError, getattr, p, '__class__')
ans = list('abc')
long_ans = list(range(10000))
# check copy
a, b = tee('abc')
self.assertEqual(list(copy.copy(a)), ans)
self.assertEqual(list(copy.copy(b)), ans)
a, b = tee(list(range(10000)))
self.assertEqual(list(copy.copy(a)), long_ans)
self.assertEqual(list(copy.copy(b)), long_ans)
# check partially consumed copy
a, b = tee('abc')
take(2, a)
take(1, b)
self.assertEqual(list(copy.copy(a)), ans[2:])
self.assertEqual(list(copy.copy(b)), ans[1:])
self.assertEqual(list(a), ans[2:])
self.assertEqual(list(b), ans[1:])
a, b = tee(range(10000))
take(100, a)
take(60, b)
self.assertEqual(list(copy.copy(a)), long_ans[100:])
self.assertEqual(list(copy.copy(b)), long_ans[60:])
self.assertEqual(list(a), long_ans[100:])
self.assertEqual(list(b), long_ans[60:])
def test_tee_dealloc_segfault(self):
# gh-115874: segfaults when accessing module state in tp_dealloc.
script = (
"import typing, copyreg, itertools; "
"copyreg.buggy_tee = itertools.tee(())"
)
script_helper.assert_python_ok("-c", script)
# Issue 13454: Crash when deleting backward iterator from tee()
def test_tee_del_backward(self):
forward, backward = tee(repeat(None, 20000000))
try:
any(forward) # exhaust the iterator
del backward
except:
del forward, backward
raise
def test_tee_reenter(self):
class I:
first = True
def __iter__(self):
return self
def __next__(self):
first = self.first
self.first = False
if first:
return next(b)
a, b = tee(I())
with self.assertRaisesRegex(RuntimeError, "tee"):
next(a)
@threading_helper.requires_working_threading()
def test_tee_concurrent(self):
start = threading.Event()
finish = threading.Event()
class I:
def __iter__(self):
return self
def __next__(self):
start.set()
finish.wait()
a, b = tee(I())
thread = threading.Thread(target=next, args=[a])
thread.start()
try:
start.wait()
with self.assertRaisesRegex(RuntimeError, "tee"):
next(b)
finally:
finish.set()
thread.join()
def test_StopIteration(self):
self.assertRaises(StopIteration, next, zip())
for f in (chain, cycle, zip, groupby):
self.assertRaises(StopIteration, next, f([]))
self.assertRaises(StopIteration, next, f(StopNow()))
self.assertRaises(StopIteration, next, islice([], None))
self.assertRaises(StopIteration, next, islice(StopNow(), None))
p, q = tee([])
self.assertRaises(StopIteration, next, p)
self.assertRaises(StopIteration, next, q)
p, q = tee(StopNow())
self.assertRaises(StopIteration, next, p)
self.assertRaises(StopIteration, next, q)
self.assertRaises(StopIteration, next, repeat(None, 0))
for f in (filter, filterfalse, map, takewhile, dropwhile, starmap):
self.assertRaises(StopIteration, next, f(lambda x:x, []))
self.assertRaises(StopIteration, next, f(lambda x:x, StopNow()))
@support.cpython_only
def test_combinations_result_gc(self):
# bpo-42536: combinations's tuple-reuse speed trick breaks the GC's
# assumptions about what can be untracked. Make sure we re-track result
# tuples whenever we reuse them.
it = combinations([None, []], 1)
next(it)
gc.collect()
# That GC collection probably untracked the recycled internal result
# tuple, which has the value (None,). Make sure it's re-tracked when
# it's mutated and returned from __next__:
self.assertTrue(gc.is_tracked(next(it)))
@support.cpython_only
def test_combinations_with_replacement_result_gc(self):
# Ditto for combinations_with_replacement.
it = combinations_with_replacement([None, []], 1)
next(it)
gc.collect()
self.assertTrue(gc.is_tracked(next(it)))
@support.cpython_only
def test_permutations_result_gc(self):
# Ditto for permutations.
it = permutations([None, []], 1)
next(it)
gc.collect()
self.assertTrue(gc.is_tracked(next(it)))
@support.cpython_only
def test_product_result_gc(self):
# Ditto for product.
it = product([None, []])
next(it)
gc.collect()
self.assertTrue(gc.is_tracked(next(it)))
@support.cpython_only
def test_zip_longest_result_gc(self):
# Ditto for zip_longest.
it = zip_longest([[]])
gc.collect()
self.assertTrue(gc.is_tracked(next(it)))
@support.cpython_only
def test_pairwise_result_gc(self):
# Ditto for pairwise.
it = pairwise([None, None])
gc.collect()
self.assertTrue(gc.is_tracked(next(it)))
@support.cpython_only
def test_immutable_types(self):
from itertools import _grouper, _tee, _tee_dataobject
dataset = (
accumulate,
batched,
chain,
combinations,
combinations_with_replacement,
compress,
count,
cycle,
dropwhile,
filterfalse,
groupby,
_grouper,
islice,
pairwise,
permutations,
product,
repeat,
starmap,
takewhile,
_tee,
_tee_dataobject,
zip_longest,
)
for tp in dataset:
with self.subTest(tp=tp):
with self.assertRaisesRegex(TypeError, "immutable"):
tp.foobar = 1
class TestExamples(unittest.TestCase):
def test_accumulate(self):
self.assertEqual(list(accumulate([1,2,3,4,5])), [1, 3, 6, 10, 15])
def test_chain(self):
self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
def test_chain_from_iterable(self):
self.assertEqual(''.join(chain.from_iterable(['ABC', 'DEF'])), 'ABCDEF')
def test_combinations(self):
self.assertEqual(list(combinations('ABCD', 2)),
[('A','B'), ('A','C'), ('A','D'), ('B','C'), ('B','D'), ('C','D')])
self.assertEqual(list(combinations(range(4), 3)),
[(0,1,2), (0,1,3), (0,2,3), (1,2,3)])
def test_combinations_with_replacement(self):
self.assertEqual(list(combinations_with_replacement('ABC', 2)),
[('A','A'), ('A','B'), ('A','C'), ('B','B'), ('B','C'), ('C','C')])
def test_compress(self):
self.assertEqual(list(compress('ABCDEF', [1,0,1,0,1,1])), list('ACEF'))
def test_count(self):
self.assertEqual(list(islice(count(10), 5)), [10, 11, 12, 13, 14])
def test_cycle(self):
self.assertEqual(list(islice(cycle('ABCD'), 12)), list('ABCDABCDABCD'))
def test_dropwhile(self):
self.assertEqual(list(dropwhile(lambda x: x<5, [1,4,6,4,1])), [6,4,1])
def test_groupby(self):
self.assertEqual([k for k, g in groupby('AAAABBBCCDAABBB')],
list('ABCDAB'))
self.assertEqual([(list(g)) for k, g in groupby('AAAABBBCCD')],
[list('AAAA'), list('BBB'), list('CC'), list('D')])
def test_filter(self):
self.assertEqual(list(filter(lambda x: x%2, range(10))), [1,3,5,7,9])
def test_filterfalse(self):
self.assertEqual(list(filterfalse(lambda x: x%2, range(10))), [0,2,4,6,8])
def test_map(self):
self.assertEqual(list(map(pow, (2,3,10), (5,2,3))), [32, 9, 1000])
def test_islice(self):
self.assertEqual(list(islice('ABCDEFG', 2)), list('AB'))
self.assertEqual(list(islice('ABCDEFG', 2, 4)), list('CD'))
self.assertEqual(list(islice('ABCDEFG', 2, None)), list('CDEFG'))
self.assertEqual(list(islice('ABCDEFG', 0, None, 2)), list('ACEG'))
def test_zip(self):
self.assertEqual(list(zip('ABCD', 'xy')), [('A', 'x'), ('B', 'y')])
def test_zip_longest(self):
self.assertEqual(list(zip_longest('ABCD', 'xy', fillvalue='-')),
[('A', 'x'), ('B', 'y'), ('C', '-'), ('D', '-')])
def test_permutations(self):
self.assertEqual(list(permutations('ABCD', 2)),
list(map(tuple, 'AB AC AD BA BC BD CA CB CD DA DB DC'.split())))
self.assertEqual(list(permutations(range(3))),
[(0,1,2), (0,2,1), (1,0,2), (1,2,0), (2,0,1), (2,1,0)])
def test_product(self):
self.assertEqual(list(product('ABCD', 'xy')),
list(map(tuple, 'Ax Ay Bx By Cx Cy Dx Dy'.split())))
self.assertEqual(list(product(range(2), repeat=3)),
[(0,0,0), (0,0,1), (0,1,0), (0,1,1),
(1,0,0), (1,0,1), (1,1,0), (1,1,1)])
def test_repeat(self):
self.assertEqual(list(repeat(10, 3)), [10, 10, 10])
def test_stapmap(self):
self.assertEqual(list(starmap(pow, [(2,5), (3,2), (10,3)])),
[32, 9, 1000])
def test_takewhile(self):
self.assertEqual(list(takewhile(lambda x: x<5, [1,4,6,4,1])), [1,4])
class TestPurePythonRoughEquivalents(unittest.TestCase):
def test_batched_recipe(self):
def batched_recipe(iterable, n):
"Batch data into tuples of length n. The last batch may be shorter."
# batched('ABCDEFG', 3) --> ABC DEF G
if n < 1:
raise ValueError('n must be at least one')
it = iter(iterable)
while batch := tuple(islice(it, n)):
yield batch
for iterable, n in product(
['', 'a', 'ab', 'abc', 'abcd', 'abcde', 'abcdef', 'abcdefg', None],
[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, None]):
with self.subTest(iterable=iterable, n=n):
try:
e1, r1 = None, list(batched(iterable, n))
except Exception as e:
e1, r1 = type(e), None
try:
e2, r2 = None, list(batched_recipe(iterable, n))
except Exception as e:
e2, r2 = type(e), None
self.assertEqual(r1, r2)
self.assertEqual(e1, e2)
def test_groupby_recipe(self):
# Begin groupby() recipe #######################################
def groupby(iterable, key=None):
# [k for k, g in groupby('AAAABBBCCDAABBB')] → A B C D A B
# [list(g) for k, g in groupby('AAAABBBCCD')] → AAAA BBB CC D
keyfunc = (lambda x: x) if key is None else key
iterator = iter(iterable)
exhausted = False
def _grouper(target_key):
nonlocal curr_value, curr_key, exhausted
yield curr_value
for curr_value in iterator:
curr_key = keyfunc(curr_value)
if curr_key != target_key:
return
yield curr_value
exhausted = True
try:
curr_value = next(iterator)
except StopIteration:
return
curr_key = keyfunc(curr_value)
while not exhausted:
target_key = curr_key
curr_group = _grouper(target_key)
yield curr_key, curr_group
if curr_key == target_key:
for _ in curr_group:
pass
# End groupby() recipe #########################################
# Check whether it accepts arguments correctly
self.assertEqual([], list(groupby([])))
self.assertEqual([], list(groupby([], key=id)))
self.assertRaises(TypeError, list, groupby('abc', []))
if False:
# Test not applicable to the recipe
self.assertRaises(TypeError, list, groupby('abc', None))
self.assertRaises(TypeError, groupby, 'abc', lambda x:x, 10)
# Check normal input
s = [(0, 10, 20), (0, 11,21), (0,12,21), (1,13,21), (1,14,22),
(2,15,22), (3,16,23), (3,17,23)]
dup = []
for k, g in groupby(s, lambda r:r[0]):
for elem in g:
self.assertEqual(k, elem[0])
dup.append(elem)
self.assertEqual(s, dup)
# Check nested case
dup = []
for k, g in groupby(s, testR):
for ik, ig in groupby(g, testR2):
for elem in ig:
self.assertEqual(k, elem[0])
self.assertEqual(ik, elem[2])
dup.append(elem)
self.assertEqual(s, dup)
# Check case where inner iterator is not used
keys = [k for k, g in groupby(s, testR)]
expectedkeys = set([r[0] for r in s])
self.assertEqual(set(keys), expectedkeys)
self.assertEqual(len(keys), len(expectedkeys))
# Check case where inner iterator is used after advancing the groupby
# iterator
s = list(zip('AABBBAAAA', range(9)))
it = groupby(s, testR)
_, g1 = next(it)
_, g2 = next(it)
_, g3 = next(it)
self.assertEqual(list(g1), [])
self.assertEqual(list(g2), [])
self.assertEqual(next(g3), ('A', 5))
list(it) # exhaust the groupby iterator
self.assertEqual(list(g3), [])
# Exercise pipes and filters style
s = 'abracadabra'
# sort s | uniq
r = [k for k, g in groupby(sorted(s))]
self.assertEqual(r, ['a', 'b', 'c', 'd', 'r'])
# sort s | uniq -d
r = [k for k, g in groupby(sorted(s)) if list(islice(g,1,2))]
self.assertEqual(r, ['a', 'b', 'r'])
# sort s | uniq -c
r = [(len(list(g)), k) for k, g in groupby(sorted(s))]
self.assertEqual(r, [(5, 'a'), (2, 'b'), (1, 'c'), (1, 'd'), (2, 'r')])
# sort s | uniq -c | sort -rn | head -3
r = sorted([(len(list(g)) , k) for k, g in groupby(sorted(s))], reverse=True)[:3]
self.assertEqual(r, [(5, 'a'), (2, 'r'), (2, 'b')])
# iter.__next__ failure
class ExpectedError(Exception):
pass
def delayed_raise(n=0):
for i in range(n):
yield 'yo'
raise ExpectedError
def gulp(iterable, keyp=None, func=list):
return [func(g) for k, g in groupby(iterable, keyp)]
# iter.__next__ failure on outer object
self.assertRaises(ExpectedError, gulp, delayed_raise(0))
# iter.__next__ failure on inner object
self.assertRaises(ExpectedError, gulp, delayed_raise(1))
# __eq__ failure
class DummyCmp:
def __eq__(self, dst):
raise ExpectedError
s = [DummyCmp(), DummyCmp(), None]
# __eq__ failure on outer object
self.assertRaises(ExpectedError, gulp, s, func=id)
# __eq__ failure on inner object
self.assertRaises(ExpectedError, gulp, s)
# keyfunc failure
def keyfunc(obj):
if keyfunc.skip > 0:
keyfunc.skip -= 1
return obj
else:
raise ExpectedError
# keyfunc failure on outer object
keyfunc.skip = 0
self.assertRaises(ExpectedError, gulp, [None], keyfunc)
keyfunc.skip = 1
self.assertRaises(ExpectedError, gulp, [None, None], keyfunc)
@staticmethod
def islice(iterable, *args):
# islice('ABCDEFG', 2) → A B
# islice('ABCDEFG', 2, 4) → C D
# islice('ABCDEFG', 2, None) → C D E F G
# islice('ABCDEFG', 0, None, 2) → A C E G
s = slice(*args)
start = 0 if s.start is None else s.start
stop = s.stop
step = 1 if s.step is None else s.step
if start < 0 or (stop is not None and stop < 0) or step <= 0:
raise ValueError
indices = count() if stop is None else range(max(start, stop))
next_i = start
for i, element in zip(indices, iterable):
if i == next_i:
yield element
next_i += step
def test_islice_recipe(self):
self.assertEqual(list(self.islice('ABCDEFG', 2)), list('AB'))
self.assertEqual(list(self.islice('ABCDEFG', 2, 4)), list('CD'))
self.assertEqual(list(self.islice('ABCDEFG', 2, None)), list('CDEFG'))
self.assertEqual(list(self.islice('ABCDEFG', 0, None, 2)), list('ACEG'))
# Test items consumed.
it = iter(range(10))
self.assertEqual(list(self.islice(it, 3)), list(range(3)))
self.assertEqual(list(it), list(range(3, 10)))
it = iter(range(10))
self.assertEqual(list(self.islice(it, 3, 3)), [])
self.assertEqual(list(it), list(range(3, 10)))
# Test that slice finishes in predictable state.
c = count()
self.assertEqual(list(self.islice(c, 1, 3, 50)), [1])
self.assertEqual(next(c), 3)
def test_tee_recipe(self):
# Begin tee() recipe ###########################################
def tee(iterable, n=2):
if n < 0:
raise ValueError
if n == 0:
return ()
iterator = _tee(iterable)
result = [iterator]
for _ in range(n - 1):
result.append(_tee(iterator))
return tuple(result)
class _tee:
def __init__(self, iterable):
it = iter(iterable)
if isinstance(it, _tee):
self.iterator = it.iterator
self.link = it.link
else:
self.iterator = it
self.link = [None, None]
def __iter__(self):
return self
def __next__(self):
link = self.link
if link[1] is None:
link[0] = next(self.iterator)
link[1] = [None, None]
value, self.link = link
return value
# End tee() recipe #############################################
n = 200
a, b = tee([]) # test empty iterator
self.assertEqual(list(a), [])
self.assertEqual(list(b), [])
a, b = tee(irange(n)) # test 100% interleaved
self.assertEqual(lzip(a,b), lzip(range(n), range(n)))
a, b = tee(irange(n)) # test 0% interleaved
self.assertEqual(list(a), list(range(n)))
self.assertEqual(list(b), list(range(n)))
a, b = tee(irange(n)) # test dealloc of leading iterator
for i in range(100):
self.assertEqual(next(a), i)
del a
self.assertEqual(list(b), list(range(n)))
a, b = tee(irange(n)) # test dealloc of trailing iterator
for i in range(100):
self.assertEqual(next(a), i)
del b
self.assertEqual(list(a), list(range(100, n)))
for j in range(5): # test randomly interleaved
order = [0]*n + [1]*n
random.shuffle(order)
lists = ([], [])
its = tee(irange(n))
for i in order:
value = next(its[i])
lists[i].append(value)
self.assertEqual(lists[0], list(range(n)))
self.assertEqual(lists[1], list(range(n)))
# test argument format checking
self.assertRaises(TypeError, tee)
self.assertRaises(TypeError, tee, 3)
self.assertRaises(TypeError, tee, [1,2], 'x')
self.assertRaises(TypeError, tee, [1,2], 3, 'x')
# tee object should be instantiable
a, b = tee('abc')
c = type(a)('def')
self.assertEqual(list(c), list('def'))
# test long-lagged and multi-way split
a, b, c = tee(range(2000), 3)
for i in range(100):
self.assertEqual(next(a), i)
self.assertEqual(list(b), list(range(2000)))
self.assertEqual([next(c), next(c)], list(range(2)))
self.assertEqual(list(a), list(range(100,2000)))
self.assertEqual(list(c), list(range(2,2000)))
# test invalid values of n
self.assertRaises(TypeError, tee, 'abc', 'invalid')
self.assertRaises(ValueError, tee, [], -1)
for n in range(5):
result = tee('abc', n)
self.assertEqual(type(result), tuple)
self.assertEqual(len(result), n)
self.assertEqual([list(x) for x in result], [list('abc')]*n)
# tee objects are independent (see bug gh-123884)
a, b = tee('abc')
c, d = tee(a)
e, f = tee(c)
self.assertTrue(len({a, b, c, d, e, f}) == 6)
# test tee_new
t1, t2 = tee('abc')
tnew = type(t1)
self.assertRaises(TypeError, tnew)
self.assertRaises(TypeError, tnew, 10)
t3 = tnew(t1)
self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
# test that tee objects are weak referencable
a, b = tee(range(10))
p = weakref.proxy(a)
self.assertEqual(getattr(p, '__class__'), type(b))
del a
gc.collect() # For PyPy or other GCs.
self.assertRaises(ReferenceError, getattr, p, '__class__')
ans = list('abc')
long_ans = list(range(10000))
# Tests not applicable to the tee() recipe
if False:
# check copy
a, b = tee('abc')
self.assertEqual(list(copy.copy(a)), ans)
self.assertEqual(list(copy.copy(b)), ans)
a, b = tee(list(range(10000)))
self.assertEqual(list(copy.copy(a)), long_ans)
self.assertEqual(list(copy.copy(b)), long_ans)
# check partially consumed copy
a, b = tee('abc')
take(2, a)
take(1, b)
self.assertEqual(list(copy.copy(a)), ans[2:])
self.assertEqual(list(copy.copy(b)), ans[1:])
self.assertEqual(list(a), ans[2:])
self.assertEqual(list(b), ans[1:])
a, b = tee(range(10000))
take(100, a)
take(60, b)
self.assertEqual(list(copy.copy(a)), long_ans[100:])
self.assertEqual(list(copy.copy(b)), long_ans[60:])
self.assertEqual(list(a), long_ans[100:])
self.assertEqual(list(b), long_ans[60:])
# Issue 13454: Crash when deleting backward iterator from tee()
forward, backward = tee(repeat(None, 2000)) # 20000000
try:
any(forward) # exhaust the iterator
del backward
except:
del forward, backward
raise
class TestGC(unittest.TestCase):
def makecycle(self, iterator, container):
container.append(iterator)
next(iterator)
del container, iterator
def test_accumulate(self):
a = []
self.makecycle(accumulate([1,2,a,3]), a)
def test_batched(self):
a = []
self.makecycle(batched([1,2,a,3], 2), a)
def test_chain(self):
a = []
self.makecycle(chain(a), a)
def test_chain_from_iterable(self):
a = []
self.makecycle(chain.from_iterable([a]), a)
def test_combinations(self):
a = []
self.makecycle(combinations([1,2,a,3], 3), a)
def test_combinations_with_replacement(self):
a = []
self.makecycle(combinations_with_replacement([1,2,a,3], 3), a)
def test_compress(self):
a = []
self.makecycle(compress('ABCDEF', [1,0,1,0,1,0]), a)
def test_count(self):
a = []
Int = type('Int', (int,), dict(x=a))
self.makecycle(count(Int(0), Int(1)), a)
def test_cycle(self):
a = []
self.makecycle(cycle([a]*2), a)
def test_dropwhile(self):
a = []
self.makecycle(dropwhile(bool, [0, a, a]), a)
def test_groupby(self):
a = []
self.makecycle(groupby([a]*2, lambda x:x), a)
def test_issue2246(self):
# Issue 2246 -- the _grouper iterator was not included in GC
n = 10
keyfunc = lambda x: x
for i, j in groupby(range(n), key=keyfunc):
keyfunc.__dict__.setdefault('x',[]).append(j)
def test_filter(self):
a = []
self.makecycle(filter(lambda x:True, [a]*2), a)
def test_filterfalse(self):
a = []
self.makecycle(filterfalse(lambda x:False, a), a)
def test_zip(self):
a = []
self.makecycle(zip([a]*2, [a]*3), a)
def test_zip_longest(self):
a = []
self.makecycle(zip_longest([a]*2, [a]*3), a)
b = [a, None]
self.makecycle(zip_longest([a]*2, [a]*3, fillvalue=b), a)
def test_map(self):
a = []
self.makecycle(map(lambda x:x, [a]*2), a)
def test_islice(self):
a = []
self.makecycle(islice([a]*2, None), a)
def test_pairwise(self):
a = []
self.makecycle(pairwise([a]*5), a)
def test_permutations(self):
a = []
self.makecycle(permutations([1,2,a,3], 3), a)
def test_product(self):
a = []
self.makecycle(product([1,2,a,3], repeat=3), a)
def test_repeat(self):
a = []
self.makecycle(repeat(a), a)
def test_starmap(self):
a = []
self.makecycle(starmap(lambda *t: t, [(a,a)]*2), a)
def test_takewhile(self):
a = []
self.makecycle(takewhile(bool, [1, 0, a, a]), a)
def R(seqn):
'Regular generator'
for i in seqn:
yield i
class G:
'Sequence using __getitem__'
def __init__(self, seqn):
self.seqn = seqn
def __getitem__(self, i):
return self.seqn[i]
class I:
'Sequence using iterator protocol'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class Ig:
'Sequence using iterator protocol defined with a generator'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
for val in self.seqn:
yield val
class X:
'Missing __getitem__ and __iter__'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __next__(self):
if self.i >= len(self.seqn): raise StopIteration
v = self.seqn[self.i]
self.i += 1
return v
class N:
'Iterator missing __next__()'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
class E:
'Test propagation of exceptions'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def __next__(self):
3 // 0
class E2:
'Test propagation of exceptions after two iterations'
def __init__(self, seqn):
self.seqn = seqn
self.i = 0
def __iter__(self):
return self
def __next__(self):
if self.i == 2:
raise ZeroDivisionError
v = self.seqn[self.i]
self.i += 1
return v
class S:
'Test immediate stop'
def __init__(self, seqn):
pass
def __iter__(self):
return self
def __next__(self):
raise StopIteration
def L(seqn):
'Test multiple tiers of iterators'
return chain(map(lambda x:x, R(Ig(G(seqn)))))
class TestVariousIteratorArgs(unittest.TestCase):
def test_accumulate(self):
s = [1,2,3,4,5]
r = [1,3,6,10,15]
n = len(s)
for g in (G, I, Ig, L, R):
self.assertEqual(list(accumulate(g(s))), r)
self.assertEqual(list(accumulate(S(s))), [])
self.assertRaises(TypeError, accumulate, X(s))
self.assertRaises(TypeError, accumulate, N(s))
self.assertRaises(ZeroDivisionError, list, accumulate(E(s)))
def test_batched(self):
s = 'abcde'
r = [('a', 'b'), ('c', 'd'), ('e',)]
n = 2
for g in (G, I, Ig, L, R):
with self.subTest(g=g):
self.assertEqual(list(batched(g(s), n)), r)
self.assertEqual(list(batched(S(s), 2)), [])
self.assertRaises(TypeError, batched, X(s), 2)
self.assertRaises(TypeError, batched, N(s), 2)
self.assertRaises(ZeroDivisionError, list, batched(E(s), 2))
self.assertRaises(ZeroDivisionError, list, batched(E2(s), 4))
def test_chain(self):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(chain(g(s))), list(g(s)))
self.assertEqual(list(chain(g(s), g(s))), list(g(s))+list(g(s)))
self.assertRaises(TypeError, list, chain(X(s)))
self.assertRaises(TypeError, list, chain(N(s)))
self.assertRaises(ZeroDivisionError, list, chain(E(s)))
def test_compress(self):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
n = len(s)
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(compress(g(s), repeat(1))), list(g(s)))
self.assertRaises(TypeError, compress, X(s), repeat(1))
self.assertRaises(TypeError, compress, N(s), repeat(1))
self.assertRaises(ZeroDivisionError, list, compress(E(s), repeat(1)))
def test_product(self):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
self.assertRaises(TypeError, product, X(s))
self.assertRaises(TypeError, product, N(s))
self.assertRaises(ZeroDivisionError, product, E(s))
def test_cycle(self):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
tgtlen = len(s) * 3
expected = list(g(s))*3
actual = list(islice(cycle(g(s)), tgtlen))
self.assertEqual(actual, expected)
self.assertRaises(TypeError, cycle, X(s))
self.assertRaises(TypeError, cycle, N(s))
self.assertRaises(ZeroDivisionError, list, cycle(E(s)))
def test_groupby(self):
for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual([k for k, sb in groupby(g(s))], list(g(s)))
self.assertRaises(TypeError, groupby, X(s))
self.assertRaises(TypeError, groupby, N(s))
self.assertRaises(ZeroDivisionError, list, groupby(E(s)))
def test_filter(self):
for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(filter(isEven, g(s))),
[x for x in g(s) if isEven(x)])
self.assertRaises(TypeError, filter, isEven, X(s))
self.assertRaises(TypeError, filter, isEven, N(s))
self.assertRaises(ZeroDivisionError, list, filter(isEven, E(s)))
def test_filterfalse(self):
for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(filterfalse(isEven, g(s))),
[x for x in g(s) if isOdd(x)])
self.assertRaises(TypeError, filterfalse, isEven, X(s))
self.assertRaises(TypeError, filterfalse, isEven, N(s))
self.assertRaises(ZeroDivisionError, list, filterfalse(isEven, E(s)))
def test_zip(self):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(zip(g(s))), lzip(g(s)))
self.assertEqual(list(zip(g(s), g(s))), lzip(g(s), g(s)))
self.assertRaises(TypeError, zip, X(s))
self.assertRaises(TypeError, zip, N(s))
self.assertRaises(ZeroDivisionError, list, zip(E(s)))
def test_ziplongest(self):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(zip_longest(g(s))), list(zip(g(s))))
self.assertEqual(list(zip_longest(g(s), g(s))), list(zip(g(s), g(s))))
self.assertRaises(TypeError, zip_longest, X(s))
self.assertRaises(TypeError, zip_longest, N(s))
self.assertRaises(ZeroDivisionError, list, zip_longest(E(s)))
def test_map(self):
for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(map(onearg, g(s))),
[onearg(x) for x in g(s)])
self.assertEqual(list(map(operator.pow, g(s), g(s))),
[x**x for x in g(s)])
self.assertRaises(TypeError, map, onearg, X(s))
self.assertRaises(TypeError, map, onearg, N(s))
self.assertRaises(ZeroDivisionError, list, map(onearg, E(s)))
def test_islice(self):
for s in ("12345", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
self.assertEqual(list(islice(g(s),1,None,2)), list(g(s))[1::2])
self.assertRaises(TypeError, islice, X(s), 10)
self.assertRaises(TypeError, islice, N(s), 10)
self.assertRaises(ZeroDivisionError, list, islice(E(s), 10))
def test_pairwise(self):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
seq = list(g(s))
expected = list(zip(seq, seq[1:]))
actual = list(pairwise(g(s)))
self.assertEqual(actual, expected)
self.assertRaises(TypeError, pairwise, X(s))
self.assertRaises(TypeError, pairwise, N(s))
self.assertRaises(ZeroDivisionError, list, pairwise(E(s)))
def test_starmap(self):
for s in (range(10), range(0), range(100), (7,11), range(20,50,5)):
for g in (G, I, Ig, S, L, R):
ss = lzip(s, s)
self.assertEqual(list(starmap(operator.pow, g(ss))),
[x**x for x in g(s)])
self.assertRaises(TypeError, starmap, operator.pow, X(ss))
self.assertRaises(TypeError, starmap, operator.pow, N(ss))
self.assertRaises(ZeroDivisionError, list, starmap(operator.pow, E(ss)))
def test_takewhile(self):
for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
tgt = []
for elem in g(s):
if not isEven(elem): break
tgt.append(elem)
self.assertEqual(list(takewhile(isEven, g(s))), tgt)
self.assertRaises(TypeError, takewhile, isEven, X(s))
self.assertRaises(TypeError, takewhile, isEven, N(s))
self.assertRaises(ZeroDivisionError, list, takewhile(isEven, E(s)))
def test_dropwhile(self):
for s in (range(10), range(0), range(1000), (7,11), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
tgt = []
for elem in g(s):
if not tgt and isOdd(elem): continue
tgt.append(elem)
self.assertEqual(list(dropwhile(isOdd, g(s))), tgt)
self.assertRaises(TypeError, dropwhile, isOdd, X(s))
self.assertRaises(TypeError, dropwhile, isOdd, N(s))
self.assertRaises(ZeroDivisionError, list, dropwhile(isOdd, E(s)))
def test_tee(self):
for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
for g in (G, I, Ig, S, L, R):
it1, it2 = tee(g(s))
self.assertEqual(list(it1), list(g(s)))
self.assertEqual(list(it2), list(g(s)))
self.assertRaises(TypeError, tee, X(s))
self.assertRaises(TypeError, tee, N(s))
self.assertRaises(ZeroDivisionError, list, tee(E(s))[0])
class LengthTransparency(unittest.TestCase):
def test_repeat(self):
self.assertEqual(operator.length_hint(repeat(None, 50)), 50)
self.assertEqual(operator.length_hint(repeat(None, 0)), 0)
self.assertEqual(operator.length_hint(repeat(None), 12), 12)
def test_repeat_with_negative_times(self):
self.assertEqual(operator.length_hint(repeat(None, -1)), 0)
self.assertEqual(operator.length_hint(repeat(None, -2)), 0)
self.assertEqual(operator.length_hint(repeat(None, times=-1)), 0)
self.assertEqual(operator.length_hint(repeat(None, times=-2)), 0)
class RegressionTests(unittest.TestCase):
def test_sf_793826(self):
# Fix Armin Rigo's successful efforts to wreak havoc
def mutatingtuple(tuple1, f, tuple2):
# this builds a tuple t which is a copy of tuple1,
# then calls f(t), then mutates t to be equal to tuple2
# (needs len(tuple1) == len(tuple2)).
def g(value, first=[1]):
if first:
del first[:]
f(next(z))
return value
items = list(tuple2)
items[1:1] = list(tuple1)
gen = map(g, items)
z = zip(*[gen]*len(tuple1))
next(z)
def f(t):
global T
T = t
first[:] = list(T)
first = []
mutatingtuple((1,2,3), f, (4,5,6))
second = list(T)
self.assertEqual(first, second)
def test_sf_950057(self):
# Make sure that chain() and cycle() catch exceptions immediately
# rather than when shifting between input sources
def gen1():
hist.append(0)
yield 1
hist.append(1)
raise AssertionError
hist.append(2)
def gen2(x):
hist.append(3)
yield 2
hist.append(4)
hist = []
self.assertRaises(AssertionError, list, chain(gen1(), gen2(False)))
self.assertEqual(hist, [0,1])
hist = []
self.assertRaises(AssertionError, list, chain(gen1(), gen2(True)))
self.assertEqual(hist, [0,1])
hist = []
self.assertRaises(AssertionError, list, cycle(gen1()))
self.assertEqual(hist, [0,1])
@support.skip_if_pgo_task
@support.requires_resource('cpu')
def test_long_chain_of_empty_iterables(self):
# Make sure itertools.chain doesn't run into recursion limits when
# dealing with long chains of empty iterables. Even with a high
# number this would probably only fail in Py_DEBUG mode.
it = chain.from_iterable(() for unused in range(10000000))
with self.assertRaises(StopIteration):
next(it)
def test_issue30347_1(self):
def f(n):
if n == 5:
list(b)
return n != 6
for (k, b) in groupby(range(10), f):
list(b) # shouldn't crash
def test_issue30347_2(self):
class K:
def __init__(self, v):
pass
def __eq__(self, other):
nonlocal i
i += 1
if i == 1:
next(g, None)
return True
i = 0
g = next(groupby(range(10), K))[1]
for j in range(2):
next(g, None) # shouldn't crash
class SubclassWithKwargsTest(unittest.TestCase):
def test_keywords_in_subclass(self):
# count is not subclassable...
testcases = [
(repeat, (1, 2), [1, 1]),
(zip, ([1, 2], 'ab'), [(1, 'a'), (2, 'b')]),
(filter, (None, [0, 1]), [1]),
(filterfalse, (None, [0, 1]), [0]),
(chain, ([1, 2], [3, 4]), [1, 2, 3]),
(map, (str, [1, 2]), ['1', '2']),
(starmap, (operator.pow, ((2, 3), (3, 2))), [8, 9]),
(islice, ([1, 2, 3, 4], 1, 3), [2, 3]),
(takewhile, (isEven, [2, 3, 4]), [2]),
(dropwhile, (isEven, [2, 3, 4]), [3, 4]),
(cycle, ([1, 2],), [1, 2, 1]),
(compress, ('ABC', [1, 0, 1]), ['A', 'C']),
]
for cls, args, result in testcases:
with self.subTest(cls):
class subclass(cls):
pass
u = subclass(*args)
self.assertIs(type(u), subclass)
self.assertEqual(list(islice(u, 0, 3)), result)
with self.assertRaises(TypeError):
subclass(*args, newarg=3)
for cls, args, result in testcases:
# Constructors of repeat, zip, map, compress accept keyword arguments.
# Their subclasses need overriding __new__ to support new
# keyword arguments.
if cls in [repeat, zip, map, compress]:
continue
with self.subTest(cls):
class subclass_with_init(cls):
def __init__(self, *args, newarg=None):
self.newarg = newarg
u = subclass_with_init(*args, newarg=3)
self.assertIs(type(u), subclass_with_init)
self.assertEqual(list(islice(u, 0, 3)), result)
self.assertEqual(u.newarg, 3)
for cls, args, result in testcases:
with self.subTest(cls):
class subclass_with_new(cls):
def __new__(cls, *args, newarg=None):
self = super().__new__(cls, *args)
self.newarg = newarg
return self
u = subclass_with_new(*args, newarg=3)
self.assertIs(type(u), subclass_with_new)
self.assertEqual(list(islice(u, 0, 3)), result)
self.assertEqual(u.newarg, 3)
@support.cpython_only
class SizeofTest(unittest.TestCase):
def setUp(self):
self.ssize_t = struct.calcsize('n')
check_sizeof = support.check_sizeof
def test_product_sizeof(self):
basesize = support.calcobjsize('3Pi')
check = self.check_sizeof
check(product('ab', '12'), basesize + 2 * self.ssize_t)
check(product(*(('abc',) * 10)), basesize + 10 * self.ssize_t)
def test_combinations_sizeof(self):
basesize = support.calcobjsize('3Pni')
check = self.check_sizeof
check(combinations('abcd', 3), basesize + 3 * self.ssize_t)
check(combinations(range(10), 4), basesize + 4 * self.ssize_t)
def test_combinations_with_replacement_sizeof(self):
cwr = combinations_with_replacement
basesize = support.calcobjsize('3Pni')
check = self.check_sizeof
check(cwr('abcd', 3), basesize + 3 * self.ssize_t)
check(cwr(range(10), 4), basesize + 4 * self.ssize_t)
def test_permutations_sizeof(self):
basesize = support.calcobjsize('4Pni')
check = self.check_sizeof
check(permutations('abcd'),
basesize + 4 * self.ssize_t + 4 * self.ssize_t)
check(permutations('abcd', 3),
basesize + 4 * self.ssize_t + 3 * self.ssize_t)
check(permutations('abcde', 3),
basesize + 5 * self.ssize_t + 3 * self.ssize_t)
check(permutations(range(10), 4),
basesize + 10 * self.ssize_t + 4 * self.ssize_t)
def load_tests(loader, tests, pattern):
tests.addTest(doctest.DocTestSuite(itertools))
return tests
if __name__ == "__main__":
unittest.main()
|
python
|
github
|
https://github.com/python/cpython
|
Lib/test/test_itertools.py
|
# Copyright 2009-2010 Gregory P. Ward
# Copyright 2009-2010 Intelerad Medical Systems Incorporated
# Copyright 2010-2011 Fog Creek Software
# Copyright 2010-2011 Unity Technologies
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
'''setup for largefiles extension: uisetup'''
from mercurial import archival, cmdutil, commands, extensions, filemerge, hg, \
httppeer, localrepo, merge, scmutil, sshpeer, wireproto, revset
from mercurial.i18n import _
from mercurial.hgweb import hgweb_mod, webcommands
from mercurial.subrepo import hgsubrepo
import overrides
import proto
def uisetup(ui):
# Disable auto-status for some commands which assume that all
# files in the result are under Mercurial's control
entry = extensions.wrapcommand(commands.table, 'add',
overrides.overrideadd)
addopt = [('', 'large', None, _('add as largefile')),
('', 'normal', None, _('add as normal file')),
('', 'lfsize', '', _('add all files above this size '
'(in megabytes) as largefiles '
'(default: 10)'))]
entry[1].extend(addopt)
# The scmutil function is called both by the (trivial) addremove command,
# and in the process of handling commit -A (issue3542)
entry = extensions.wrapfunction(scmutil, 'addremove',
overrides.scmutiladdremove)
entry = extensions.wrapcommand(commands.table, 'remove',
overrides.overrideremove)
entry = extensions.wrapcommand(commands.table, 'forget',
overrides.overrideforget)
# Subrepos call status function
entry = extensions.wrapcommand(commands.table, 'status',
overrides.overridestatus)
entry = extensions.wrapfunction(hgsubrepo, 'status',
overrides.overridestatusfn)
entry = extensions.wrapcommand(commands.table, 'log',
overrides.overridelog)
entry = extensions.wrapcommand(commands.table, 'rollback',
overrides.overriderollback)
entry = extensions.wrapcommand(commands.table, 'verify',
overrides.overrideverify)
verifyopt = [('', 'large', None,
_('verify that all largefiles in current revision exists')),
('', 'lfa', None,
_('verify largefiles in all revisions, not just current')),
('', 'lfc', None,
_('verify local largefile contents, not just existence'))]
entry[1].extend(verifyopt)
entry = extensions.wrapcommand(commands.table, 'debugstate',
overrides.overridedebugstate)
debugstateopt = [('', 'large', None, _('display largefiles dirstate'))]
entry[1].extend(debugstateopt)
entry = extensions.wrapcommand(commands.table, 'outgoing',
overrides.overrideoutgoing)
outgoingopt = [('', 'large', None, _('display outgoing largefiles'))]
entry[1].extend(outgoingopt)
entry = extensions.wrapcommand(commands.table, 'summary',
overrides.overridesummary)
summaryopt = [('', 'large', None, _('display outgoing largefiles'))]
entry[1].extend(summaryopt)
entry = extensions.wrapcommand(commands.table, 'update',
overrides.overrideupdate)
entry = extensions.wrapcommand(commands.table, 'pull',
overrides.overridepull)
pullopt = [('', 'all-largefiles', None,
_('download all pulled versions of largefiles (DEPRECATED)')),
('', 'lfrev', [],
_('download largefiles for these revisions'), _('REV'))]
entry[1].extend(pullopt)
revset.symbols['pulled'] = overrides.pulledrevsetsymbol
entry = extensions.wrapcommand(commands.table, 'clone',
overrides.overrideclone)
cloneopt = [('', 'all-largefiles', None,
_('download all versions of all largefiles'))]
entry[1].extend(cloneopt)
entry = extensions.wrapfunction(hg, 'clone', overrides.hgclone)
entry = extensions.wrapcommand(commands.table, 'cat',
overrides.overridecat)
entry = extensions.wrapfunction(merge, '_checkunknownfile',
overrides.overridecheckunknownfile)
entry = extensions.wrapfunction(merge, 'manifestmerge',
overrides.overridemanifestmerge)
entry = extensions.wrapfunction(filemerge, 'filemerge',
overrides.overridefilemerge)
entry = extensions.wrapfunction(cmdutil, 'copy',
overrides.overridecopy)
# Summary calls dirty on the subrepos
entry = extensions.wrapfunction(hgsubrepo, 'dirty',
overrides.overridedirty)
# Backout calls revert so we need to override both the command and the
# function
entry = extensions.wrapcommand(commands.table, 'revert',
overrides.overriderevert)
entry = extensions.wrapfunction(commands, 'revert',
overrides.overriderevert)
extensions.wrapfunction(hg, 'updaterepo', overrides.hgupdaterepo)
extensions.wrapfunction(hg, 'merge', overrides.hgmerge)
extensions.wrapfunction(archival, 'archive', overrides.overridearchive)
extensions.wrapfunction(hgsubrepo, 'archive', overrides.hgsubrepoarchive)
extensions.wrapfunction(cmdutil, 'bailifchanged',
overrides.overridebailifchanged)
# create the new wireproto commands ...
wireproto.commands['putlfile'] = (proto.putlfile, 'sha')
wireproto.commands['getlfile'] = (proto.getlfile, 'sha')
wireproto.commands['statlfile'] = (proto.statlfile, 'sha')
# ... and wrap some existing ones
wireproto.commands['capabilities'] = (proto.capabilities, '')
wireproto.commands['heads'] = (proto.heads, '')
wireproto.commands['lheads'] = (wireproto.heads, '')
# make putlfile behave the same as push and {get,stat}lfile behave
# the same as pull w.r.t. permissions checks
hgweb_mod.perms['putlfile'] = 'push'
hgweb_mod.perms['getlfile'] = 'pull'
hgweb_mod.perms['statlfile'] = 'pull'
extensions.wrapfunction(webcommands, 'decodepath', overrides.decodepath)
# the hello wireproto command uses wireproto.capabilities, so it won't see
# our largefiles capability unless we replace the actual function as well.
proto.capabilitiesorig = wireproto.capabilities
wireproto.capabilities = proto.capabilities
# can't do this in reposetup because it needs to have happened before
# wirerepo.__init__ is called
proto.ssholdcallstream = sshpeer.sshpeer._callstream
proto.httpoldcallstream = httppeer.httppeer._callstream
sshpeer.sshpeer._callstream = proto.sshrepocallstream
httppeer.httppeer._callstream = proto.httprepocallstream
# don't die on seeing a repo with the largefiles requirement
localrepo.localrepository.supported |= set(['largefiles'])
# override some extensions' stuff as well
for name, module in extensions.extensions():
if name == 'fetch':
extensions.wrapcommand(getattr(module, 'cmdtable'), 'fetch',
overrides.overridefetch)
if name == 'purge':
extensions.wrapcommand(getattr(module, 'cmdtable'), 'purge',
overrides.overridepurge)
if name == 'rebase':
extensions.wrapcommand(getattr(module, 'cmdtable'), 'rebase',
overrides.overriderebase)
if name == 'transplant':
extensions.wrapcommand(getattr(module, 'cmdtable'), 'transplant',
overrides.overridetransplant)
if name == 'convert':
convcmd = getattr(module, 'convcmd')
hgsink = getattr(convcmd, 'mercurial_sink')
extensions.wrapfunction(hgsink, 'before',
overrides.mercurialsinkbefore)
extensions.wrapfunction(hgsink, 'after',
overrides.mercurialsinkafter)
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
* Copyright 2014-2025 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.request
import io.ktor.client.engine.*
import io.ktor.utils.io.InternalAPI
@InternalAPI
public class UnixSocketSettings(public val path: String)
@OptIn(InternalAPI::class)
public data object UnixSocketCapability : HttpClientEngineCapability<UnixSocketSettings>
|
kotlin
|
github
|
https://github.com/ktorio/ktor
|
ktor-client/ktor-client-core/common/src/io/ktor/client/request/UnixSockets.kt
|
"""Adapt an HTTP server."""
import time
class ServerAdapter(object):
"""Adapter for an HTTP server.
If you need to start more than one HTTP server (to serve on multiple
ports, or protocols, etc.), you can manually register each one and then
start them all with bus.start:
s1 = ServerAdapter(bus, MyWSGIServer(host='0.0.0.0', port=80))
s2 = ServerAdapter(bus, another.HTTPServer(host='127.0.0.1', SSL=True))
s1.subscribe()
s2.subscribe()
bus.start()
"""
def __init__(self, bus, httpserver=None, bind_addr=None):
self.bus = bus
self.httpserver = httpserver
self.bind_addr = bind_addr
self.interrupt = None
self.running = False
def subscribe(self):
self.bus.subscribe('start', self.start)
self.bus.subscribe('stop', self.stop)
def unsubscribe(self):
self.bus.unsubscribe('start', self.start)
self.bus.unsubscribe('stop', self.stop)
def start(self):
"""Start the HTTP server."""
if self.bind_addr is None:
on_what = "unknown interface (dynamic?)"
elif isinstance(self.bind_addr, tuple):
host, port = self.bind_addr
on_what = "%s:%s" % (host, port)
else:
on_what = "socket file: %s" % self.bind_addr
if self.running:
self.bus.log("Already serving on %s" % on_what)
return
self.interrupt = None
if not self.httpserver:
raise ValueError("No HTTP server has been created.")
# Start the httpserver in a new thread.
if isinstance(self.bind_addr, tuple):
wait_for_free_port(*self.bind_addr)
import threading
t = threading.Thread(target=self._start_http_thread)
t.setName("HTTPServer " + t.getName())
t.start()
self.wait()
self.running = True
self.bus.log("Serving on %s" % on_what)
start.priority = 75
def _start_http_thread(self):
"""HTTP servers MUST be running in new threads, so that the
main thread persists to receive KeyboardInterrupt's. If an
exception is raised in the httpserver's thread then it's
trapped here, and the bus (and therefore our httpserver)
are shut down.
"""
try:
self.httpserver.start()
except KeyboardInterrupt, exc:
self.bus.log("<Ctrl-C> hit: shutting down HTTP server")
self.interrupt = exc
self.bus.exit()
except SystemExit, exc:
self.bus.log("SystemExit raised: shutting down HTTP server")
self.interrupt = exc
self.bus.exit()
raise
except:
import sys
self.interrupt = sys.exc_info()[1]
self.bus.log("Error in HTTP server: shutting down",
traceback=True, level=40)
self.bus.exit()
raise
def wait(self):
"""Wait until the HTTP server is ready to receive requests."""
while not getattr(self.httpserver, "ready", False):
if self.interrupt:
raise self.interrupt
time.sleep(.1)
# Wait for port to be occupied
if isinstance(self.bind_addr, tuple):
host, port = self.bind_addr
wait_for_occupied_port(host, port)
def stop(self):
"""Stop the HTTP server."""
if self.running:
# stop() MUST block until the server is *truly* stopped.
self.httpserver.stop()
# Wait for the socket to be truly freed.
if isinstance(self.bind_addr, tuple):
wait_for_free_port(*self.bind_addr)
self.running = False
self.bus.log("HTTP Server %s shut down" % self.httpserver)
else:
self.bus.log("HTTP Server %s already shut down" % self.httpserver)
stop.priority = 25
def restart(self):
"""Restart the HTTP server."""
self.stop()
self.start()
class FlupFCGIServer(object):
"""Adapter for a flup.server.fcgi.WSGIServer."""
def __init__(self, *args, **kwargs):
if kwargs.get('bindAddress', None) is None:
import socket
if not hasattr(socket.socket, 'fromfd'):
raise ValueError(
'Dynamic FCGI server not available on this platform. '
'You must use a static or external one by providing a '
'legal bindAddress.')
self.args = args
self.kwargs = kwargs
self.ready = False
def start(self):
"""Start the FCGI server."""
# We have to instantiate the server class here because its __init__
# starts a threadpool. If we do it too early, daemonize won't work.
from flup.server.fcgi import WSGIServer
self.fcgiserver = WSGIServer(*self.args, **self.kwargs)
# TODO: report this bug upstream to flup.
# If we don't set _oldSIGs on Windows, we get:
# File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
# line 108, in run
# self._restoreSignalHandlers()
# File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
# line 156, in _restoreSignalHandlers
# for signum,handler in self._oldSIGs:
# AttributeError: 'WSGIServer' object has no attribute '_oldSIGs'
self.fcgiserver._installSignalHandlers = lambda: None
self.fcgiserver._oldSIGs = []
self.ready = True
self.fcgiserver.run()
def stop(self):
"""Stop the HTTP server."""
# Forcibly stop the fcgi server main event loop.
self.fcgiserver._keepGoing = False
# Force all worker threads to die off.
self.fcgiserver._threadPool.maxSpare = self.fcgiserver._threadPool._idleCount
self.ready = False
class FlupSCGIServer(object):
"""Adapter for a flup.server.scgi.WSGIServer."""
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.ready = False
def start(self):
"""Start the SCGI server."""
# We have to instantiate the server class here because its __init__
# starts a threadpool. If we do it too early, daemonize won't work.
from flup.server.scgi import WSGIServer
self.scgiserver = WSGIServer(*self.args, **self.kwargs)
# TODO: report this bug upstream to flup.
# If we don't set _oldSIGs on Windows, we get:
# File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
# line 108, in run
# self._restoreSignalHandlers()
# File "C:\Python24\Lib\site-packages\flup\server\threadedserver.py",
# line 156, in _restoreSignalHandlers
# for signum,handler in self._oldSIGs:
# AttributeError: 'WSGIServer' object has no attribute '_oldSIGs'
self.scgiserver._installSignalHandlers = lambda: None
self.scgiserver._oldSIGs = []
self.ready = True
self.scgiserver.run()
def stop(self):
"""Stop the HTTP server."""
self.ready = False
# Forcibly stop the scgi server main event loop.
self.scgiserver._keepGoing = False
# Force all worker threads to die off.
self.scgiserver._threadPool.maxSpare = 0
def client_host(server_host):
"""Return the host on which a client can connect to the given listener."""
if server_host == '0.0.0.0':
# 0.0.0.0 is INADDR_ANY, which should answer on localhost.
return '127.0.0.1'
if server_host == '::':
# :: is IN6ADDR_ANY, which should answer on localhost.
return '::1'
return server_host
def check_port(host, port, timeout=1.0):
"""Raise an error if the given port is not free on the given host."""
if not host:
raise ValueError("Host values of '' or None are not allowed.")
host = client_host(host)
port = int(port)
import socket
# AF_INET or AF_INET6 socket
# Get the correct address family for our host (allows IPv6 addresses)
try:
info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM)
except socket.gaierror:
if ':' in host:
info = [(socket.AF_INET6, socket.SOCK_STREAM, 0, "", (host, port, 0, 0))]
else:
info = [(socket.AF_INET, socket.SOCK_STREAM, 0, "", (host, port))]
for res in info:
af, socktype, proto, canonname, sa = res
s = None
try:
s = socket.socket(af, socktype, proto)
# See http://groups.google.com/group/cherrypy-users/
# browse_frm/thread/bbfe5eb39c904fe0
s.settimeout(timeout)
s.connect((host, port))
s.close()
raise IOError("Port %s is in use on %s; perhaps the previous "
"httpserver did not shut down properly." %
(repr(port), repr(host)))
except socket.error:
if s:
s.close()
def wait_for_free_port(host, port):
"""Wait for the specified port to become free (drop requests)."""
if not host:
raise ValueError("Host values of '' or None are not allowed.")
for trial in range(50):
try:
# we are expecting a free port, so reduce the timeout
check_port(host, port, timeout=0.1)
except IOError:
# Give the old server thread time to free the port.
time.sleep(0.1)
else:
return
raise IOError("Port %r not free on %r" % (port, host))
def wait_for_occupied_port(host, port):
"""Wait for the specified port to become active (receive requests)."""
if not host:
raise ValueError("Host values of '' or None are not allowed.")
for trial in range(50):
try:
check_port(host, port)
except IOError:
return
else:
time.sleep(.1)
raise IOError("Port %r not bound on %r" % (port, host))
|
unknown
|
codeparrot/codeparrot-clean
| ||
from Cython.Compiler.Visitor import CythonTransform
from Cython.Compiler.ModuleNode import ModuleNode
from Cython.Compiler.Errors import CompileError
from Cython.Compiler.UtilityCode import CythonUtilityCode
from Cython.Compiler.Code import UtilityCode, TempitaUtilityCode
from Cython.Compiler import Options
from Cython.Compiler import Interpreter
from Cython.Compiler import PyrexTypes
from Cython.Compiler import Naming
from Cython.Compiler import Symtab
def dedent(text, reindent=0):
from textwrap import dedent
text = dedent(text)
if reindent > 0:
indent = " " * reindent
text = '\n'.join([indent + x for x in text.split('\n')])
return text
class IntroduceBufferAuxiliaryVars(CythonTransform):
#
# Entry point
#
buffers_exists = False
using_memoryview = False
def __call__(self, node):
assert isinstance(node, ModuleNode)
self.max_ndim = 0
result = super(IntroduceBufferAuxiliaryVars, self).__call__(node)
if self.buffers_exists:
use_bufstruct_declare_code(node.scope)
use_py2_buffer_functions(node.scope)
node.scope.use_utility_code(empty_bufstruct_utility)
return result
#
# Basic operations for transforms
#
def handle_scope(self, node, scope):
# For all buffers, insert extra variables in the scope.
# The variables are also accessible from the buffer_info
# on the buffer entry
bufvars = [entry for name, entry
in scope.entries.iteritems()
if entry.type.is_buffer]
if len(bufvars) > 0:
bufvars.sort(key=lambda entry: entry.name)
self.buffers_exists = True
memviewslicevars = [entry for name, entry
in scope.entries.iteritems()
if entry.type.is_memoryviewslice]
if len(memviewslicevars) > 0:
self.buffers_exists = True
for (name, entry) in scope.entries.iteritems():
if name == 'memoryview' and isinstance(entry.utility_code_definition, CythonUtilityCode):
self.using_memoryview = True
break
if isinstance(node, ModuleNode) and len(bufvars) > 0:
# for now...note that pos is wrong
raise CompileError(node.pos, "Buffer vars not allowed in module scope")
for entry in bufvars:
if entry.type.dtype.is_ptr:
raise CompileError(node.pos, "Buffers with pointer types not yet supported.")
name = entry.name
buftype = entry.type
if buftype.ndim > Options.buffer_max_dims:
raise CompileError(node.pos,
"Buffer ndims exceeds Options.buffer_max_dims = %d" % Options.buffer_max_dims)
if buftype.ndim > self.max_ndim:
self.max_ndim = buftype.ndim
# Declare auxiliary vars
def decvar(type, prefix):
cname = scope.mangle(prefix, name)
aux_var = scope.declare_var(name=None, cname=cname,
type=type, pos=node.pos)
if entry.is_arg:
aux_var.used = True # otherwise, NameNode will mark whether it is used
return aux_var
auxvars = ((PyrexTypes.c_pyx_buffer_nd_type, Naming.pybuffernd_prefix),
(PyrexTypes.c_pyx_buffer_type, Naming.pybufferstruct_prefix))
pybuffernd, rcbuffer = [decvar(type, prefix) for (type, prefix) in auxvars]
entry.buffer_aux = Symtab.BufferAux(pybuffernd, rcbuffer)
scope.buffer_entries = bufvars
self.scope = scope
def visit_ModuleNode(self, node):
self.handle_scope(node, node.scope)
self.visitchildren(node)
return node
def visit_FuncDefNode(self, node):
self.handle_scope(node, node.local_scope)
self.visitchildren(node)
return node
#
# Analysis
#
buffer_options = ("dtype", "ndim", "mode", "negative_indices", "cast") # ordered!
buffer_defaults = {"ndim": 1, "mode": "full", "negative_indices": True, "cast": False}
buffer_positional_options_count = 1 # anything beyond this needs keyword argument
ERR_BUF_OPTION_UNKNOWN = '"%s" is not a buffer option'
ERR_BUF_TOO_MANY = 'Too many buffer options'
ERR_BUF_DUP = '"%s" buffer option already supplied'
ERR_BUF_MISSING = '"%s" missing'
ERR_BUF_MODE = 'Only allowed buffer modes are: "c", "fortran", "full", "strided" (as a compile-time string)'
ERR_BUF_NDIM = 'ndim must be a non-negative integer'
ERR_BUF_DTYPE = 'dtype must be "object", numeric type or a struct'
ERR_BUF_BOOL = '"%s" must be a boolean'
def analyse_buffer_options(globalpos, env, posargs, dictargs, defaults=None, need_complete=True):
"""
Must be called during type analysis, as analyse is called
on the dtype argument.
posargs and dictargs should consist of a list and a dict
of tuples (value, pos). Defaults should be a dict of values.
Returns a dict containing all the options a buffer can have and
its value (with the positions stripped).
"""
if defaults is None:
defaults = buffer_defaults
posargs, dictargs = Interpreter.interpret_compiletime_options(posargs, dictargs, type_env=env, type_args = (0,'dtype'))
if len(posargs) > buffer_positional_options_count:
raise CompileError(posargs[-1][1], ERR_BUF_TOO_MANY)
options = {}
for name, (value, pos) in dictargs.iteritems():
if not name in buffer_options:
raise CompileError(pos, ERR_BUF_OPTION_UNKNOWN % name)
options[name] = value
for name, (value, pos) in zip(buffer_options, posargs):
if not name in buffer_options:
raise CompileError(pos, ERR_BUF_OPTION_UNKNOWN % name)
if name in options:
raise CompileError(pos, ERR_BUF_DUP % name)
options[name] = value
# Check that they are all there and copy defaults
for name in buffer_options:
if not name in options:
try:
options[name] = defaults[name]
except KeyError:
if need_complete:
raise CompileError(globalpos, ERR_BUF_MISSING % name)
dtype = options.get("dtype")
if dtype and dtype.is_extension_type:
raise CompileError(globalpos, ERR_BUF_DTYPE)
ndim = options.get("ndim")
if ndim and (not isinstance(ndim, int) or ndim < 0):
raise CompileError(globalpos, ERR_BUF_NDIM)
mode = options.get("mode")
if mode and not (mode in ('full', 'strided', 'c', 'fortran')):
raise CompileError(globalpos, ERR_BUF_MODE)
def assert_bool(name):
x = options.get(name)
if not isinstance(x, bool):
raise CompileError(globalpos, ERR_BUF_BOOL % name)
assert_bool('negative_indices')
assert_bool('cast')
return options
#
# Code generation
#
class BufferEntry(object):
def __init__(self, entry):
self.entry = entry
self.type = entry.type
self.cname = entry.buffer_aux.buflocal_nd_var.cname
self.buf_ptr = "%s.rcbuffer->pybuffer.buf" % self.cname
self.buf_ptr_type = self.entry.type.buffer_ptr_type
def get_buf_suboffsetvars(self):
return self._for_all_ndim("%s.diminfo[%d].suboffsets")
def get_buf_stridevars(self):
return self._for_all_ndim("%s.diminfo[%d].strides")
def get_buf_shapevars(self):
return self._for_all_ndim("%s.diminfo[%d].shape")
def _for_all_ndim(self, s):
return [s % (self.cname, i) for i in range(self.type.ndim)]
def generate_buffer_lookup_code(self, code, index_cnames):
# Create buffer lookup and return it
# This is done via utility macros/inline functions, which vary
# according to the access mode used.
params = []
nd = self.type.ndim
mode = self.type.mode
if mode == 'full':
for i, s, o in zip(index_cnames,
self.get_buf_stridevars(),
self.get_buf_suboffsetvars()):
params.append(i)
params.append(s)
params.append(o)
funcname = "__Pyx_BufPtrFull%dd" % nd
funcgen = buf_lookup_full_code
else:
if mode == 'strided':
funcname = "__Pyx_BufPtrStrided%dd" % nd
funcgen = buf_lookup_strided_code
elif mode == 'c':
funcname = "__Pyx_BufPtrCContig%dd" % nd
funcgen = buf_lookup_c_code
elif mode == 'fortran':
funcname = "__Pyx_BufPtrFortranContig%dd" % nd
funcgen = buf_lookup_fortran_code
else:
assert False
for i, s in zip(index_cnames, self.get_buf_stridevars()):
params.append(i)
params.append(s)
# Make sure the utility code is available
if funcname not in code.globalstate.utility_codes:
code.globalstate.utility_codes.add(funcname)
protocode = code.globalstate['utility_code_proto']
defcode = code.globalstate['utility_code_def']
funcgen(protocode, defcode, name=funcname, nd=nd)
buf_ptr_type_code = self.buf_ptr_type.declaration_code("")
ptrcode = "%s(%s, %s, %s)" % (funcname, buf_ptr_type_code, self.buf_ptr,
", ".join(params))
return ptrcode
def get_flags(buffer_aux, buffer_type):
flags = 'PyBUF_FORMAT'
mode = buffer_type.mode
if mode == 'full':
flags += '| PyBUF_INDIRECT'
elif mode == 'strided':
flags += '| PyBUF_STRIDES'
elif mode == 'c':
flags += '| PyBUF_C_CONTIGUOUS'
elif mode == 'fortran':
flags += '| PyBUF_F_CONTIGUOUS'
else:
assert False
if buffer_aux.writable_needed: flags += "| PyBUF_WRITABLE"
return flags
def used_buffer_aux_vars(entry):
buffer_aux = entry.buffer_aux
buffer_aux.buflocal_nd_var.used = True
buffer_aux.rcbuf_var.used = True
def put_unpack_buffer_aux_into_scope(buf_entry, code):
# Generate code to copy the needed struct info into local
# variables.
buffer_aux, mode = buf_entry.buffer_aux, buf_entry.type.mode
pybuffernd_struct = buffer_aux.buflocal_nd_var.cname
fldnames = ['strides', 'shape']
if mode == 'full':
fldnames.append('suboffsets')
ln = []
for i in range(buf_entry.type.ndim):
for fldname in fldnames:
ln.append("%s.diminfo[%d].%s = %s.rcbuffer->pybuffer.%s[%d];" % \
(pybuffernd_struct, i, fldname,
pybuffernd_struct, fldname, i))
code.putln(' '.join(ln))
def put_init_vars(entry, code):
bufaux = entry.buffer_aux
pybuffernd_struct = bufaux.buflocal_nd_var.cname
pybuffer_struct = bufaux.rcbuf_var.cname
# init pybuffer_struct
code.putln("%s.pybuffer.buf = NULL;" % pybuffer_struct)
code.putln("%s.refcount = 0;" % pybuffer_struct)
# init the buffer object
# code.put_init_var_to_py_none(entry)
# init the pybuffernd_struct
code.putln("%s.data = NULL;" % pybuffernd_struct)
code.putln("%s.rcbuffer = &%s;" % (pybuffernd_struct, pybuffer_struct))
def put_acquire_arg_buffer(entry, code, pos):
code.globalstate.use_utility_code(acquire_utility_code)
buffer_aux = entry.buffer_aux
getbuffer = get_getbuffer_call(code, entry.cname, buffer_aux, entry.type)
# Acquire any new buffer
code.putln("{")
code.putln("__Pyx_BufFmt_StackElem __pyx_stack[%d];" % entry.type.dtype.struct_nesting_depth())
code.putln(code.error_goto_if("%s == -1" % getbuffer, pos))
code.putln("}")
# An exception raised in arg parsing cannot be catched, so no
# need to care about the buffer then.
put_unpack_buffer_aux_into_scope(entry, code)
def put_release_buffer_code(code, entry):
code.globalstate.use_utility_code(acquire_utility_code)
code.putln("__Pyx_SafeReleaseBuffer(&%s.rcbuffer->pybuffer);" % entry.buffer_aux.buflocal_nd_var.cname)
def get_getbuffer_call(code, obj_cname, buffer_aux, buffer_type):
ndim = buffer_type.ndim
cast = int(buffer_type.cast)
flags = get_flags(buffer_aux, buffer_type)
pybuffernd_struct = buffer_aux.buflocal_nd_var.cname
dtype_typeinfo = get_type_information_cname(code, buffer_type.dtype)
return ("__Pyx_GetBufferAndValidate(&%(pybuffernd_struct)s.rcbuffer->pybuffer, "
"(PyObject*)%(obj_cname)s, &%(dtype_typeinfo)s, %(flags)s, %(ndim)d, "
"%(cast)d, __pyx_stack)" % locals())
def put_assign_to_buffer(lhs_cname, rhs_cname, buf_entry,
is_initialized, pos, code):
"""
Generate code for reassigning a buffer variables. This only deals with getting
the buffer auxiliary structure and variables set up correctly, the assignment
itself and refcounting is the responsibility of the caller.
However, the assignment operation may throw an exception so that the reassignment
never happens.
Depending on the circumstances there are two possible outcomes:
- Old buffer released, new acquired, rhs assigned to lhs
- Old buffer released, new acquired which fails, reaqcuire old lhs buffer
(which may or may not succeed).
"""
buffer_aux, buffer_type = buf_entry.buffer_aux, buf_entry.type
code.globalstate.use_utility_code(acquire_utility_code)
pybuffernd_struct = buffer_aux.buflocal_nd_var.cname
flags = get_flags(buffer_aux, buffer_type)
code.putln("{") # Set up necesarry stack for getbuffer
code.putln("__Pyx_BufFmt_StackElem __pyx_stack[%d];" % buffer_type.dtype.struct_nesting_depth())
getbuffer = get_getbuffer_call(code, "%s", buffer_aux, buffer_type) # fill in object below
if is_initialized:
# Release any existing buffer
code.putln('__Pyx_SafeReleaseBuffer(&%s.rcbuffer->pybuffer);' % pybuffernd_struct)
# Acquire
retcode_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
code.putln("%s = %s;" % (retcode_cname, getbuffer % rhs_cname))
code.putln('if (%s) {' % (code.unlikely("%s < 0" % retcode_cname)))
# If acquisition failed, attempt to reacquire the old buffer
# before raising the exception. A failure of reacquisition
# will cause the reacquisition exception to be reported, one
# can consider working around this later.
type, value, tb = [code.funcstate.allocate_temp(PyrexTypes.py_object_type, manage_ref=False)
for i in range(3)]
code.putln('PyErr_Fetch(&%s, &%s, &%s);' % (type, value, tb))
code.putln('if (%s) {' % code.unlikely("%s == -1" % (getbuffer % lhs_cname)))
code.putln('Py_XDECREF(%s); Py_XDECREF(%s); Py_XDECREF(%s);' % (type, value, tb)) # Do not refnanny these!
code.globalstate.use_utility_code(raise_buffer_fallback_code)
code.putln('__Pyx_RaiseBufferFallbackError();')
code.putln('} else {')
code.putln('PyErr_Restore(%s, %s, %s);' % (type, value, tb))
for t in (type, value, tb):
code.funcstate.release_temp(t)
code.putln('}')
code.putln('}')
# Unpack indices
put_unpack_buffer_aux_into_scope(buf_entry, code)
code.putln(code.error_goto_if_neg(retcode_cname, pos))
code.funcstate.release_temp(retcode_cname)
else:
# Our entry had no previous value, so set to None when acquisition fails.
# In this case, auxiliary vars should be set up right in initialization to a zero-buffer,
# so it suffices to set the buf field to NULL.
code.putln('if (%s) {' % code.unlikely("%s == -1" % (getbuffer % rhs_cname)))
code.putln('%s = %s; __Pyx_INCREF(Py_None); %s.rcbuffer->pybuffer.buf = NULL;' %
(lhs_cname,
PyrexTypes.typecast(buffer_type, PyrexTypes.py_object_type, "Py_None"),
pybuffernd_struct))
code.putln(code.error_goto(pos))
code.put('} else {')
# Unpack indices
put_unpack_buffer_aux_into_scope(buf_entry, code)
code.putln('}')
code.putln("}") # Release stack
def put_buffer_lookup_code(entry, index_signeds, index_cnames, directives,
pos, code, negative_indices, in_nogil_context):
"""
Generates code to process indices and calculate an offset into
a buffer. Returns a C string which gives a pointer which can be
read from or written to at will (it is an expression so caller should
store it in a temporary if it is used more than once).
As the bounds checking can have any number of combinations of unsigned
arguments, smart optimizations etc. we insert it directly in the function
body. The lookup however is delegated to a inline function that is instantiated
once per ndim (lookup with suboffsets tend to get quite complicated).
entry is a BufferEntry
"""
negative_indices = directives['wraparound'] and negative_indices
if directives['boundscheck']:
# Check bounds and fix negative indices.
# We allocate a temporary which is initialized to -1, meaning OK (!).
# If an error occurs, the temp is set to the dimension index the
# error is occuring at.
tmp_cname = code.funcstate.allocate_temp(PyrexTypes.c_int_type, manage_ref=False)
code.putln("%s = -1;" % tmp_cname)
for dim, (signed, cname, shape) in enumerate(zip(index_signeds, index_cnames,
entry.get_buf_shapevars())):
if signed != 0:
# not unsigned, deal with negative index
code.putln("if (%s < 0) {" % cname)
if negative_indices:
code.putln("%s += %s;" % (cname, shape))
code.putln("if (%s) %s = %d;" % (
code.unlikely("%s < 0" % cname), tmp_cname, dim))
else:
code.putln("%s = %d;" % (tmp_cname, dim))
code.put("} else ")
# check bounds in positive direction
if signed != 0:
cast = ""
else:
cast = "(size_t)"
code.putln("if (%s) %s = %d;" % (
code.unlikely("%s >= %s%s" % (cname, cast, shape)),
tmp_cname, dim))
if in_nogil_context:
code.globalstate.use_utility_code(raise_indexerror_nogil)
func = '__Pyx_RaiseBufferIndexErrorNogil'
else:
code.globalstate.use_utility_code(raise_indexerror_code)
func = '__Pyx_RaiseBufferIndexError'
code.putln("if (%s) {" % code.unlikely("%s != -1" % tmp_cname))
code.putln('%s(%s);' % (func, tmp_cname))
code.putln(code.error_goto(pos))
code.putln('}')
code.funcstate.release_temp(tmp_cname)
elif negative_indices:
# Only fix negative indices.
for signed, cname, shape in zip(index_signeds, index_cnames,
entry.get_buf_shapevars()):
if signed != 0:
code.putln("if (%s < 0) %s += %s;" % (cname, cname, shape))
return entry.generate_buffer_lookup_code(code, index_cnames)
def use_bufstruct_declare_code(env):
env.use_utility_code(buffer_struct_declare_code)
def get_empty_bufstruct_code(max_ndim):
code = dedent("""
static Py_ssize_t __Pyx_zeros[] = {%s};
static Py_ssize_t __Pyx_minusones[] = {%s};
""") % (", ".join(["0"] * max_ndim), ", ".join(["-1"] * max_ndim))
return UtilityCode(proto=code)
empty_bufstruct_utility = get_empty_bufstruct_code(Options.buffer_max_dims)
def buf_lookup_full_code(proto, defin, name, nd):
"""
Generates a buffer lookup function for the right number
of dimensions. The function gives back a void* at the right location.
"""
# _i_ndex, _s_tride, sub_o_ffset
macroargs = ", ".join(["i%d, s%d, o%d" % (i, i, i) for i in range(nd)])
proto.putln("#define %s(type, buf, %s) (type)(%s_imp(buf, %s))" % (name, macroargs, name, macroargs))
funcargs = ", ".join(["Py_ssize_t i%d, Py_ssize_t s%d, Py_ssize_t o%d" % (i, i, i) for i in range(nd)])
proto.putln("static CYTHON_INLINE void* %s_imp(void* buf, %s);" % (name, funcargs))
defin.putln(dedent("""
static CYTHON_INLINE void* %s_imp(void* buf, %s) {
char* ptr = (char*)buf;
""") % (name, funcargs) + "".join([dedent("""\
ptr += s%d * i%d;
if (o%d >= 0) ptr = *((char**)ptr) + o%d;
""") % (i, i, i, i) for i in range(nd)]
) + "\nreturn ptr;\n}")
def buf_lookup_strided_code(proto, defin, name, nd):
"""
Generates a buffer lookup function for the right number
of dimensions. The function gives back a void* at the right location.
"""
# _i_ndex, _s_tride
args = ", ".join(["i%d, s%d" % (i, i) for i in range(nd)])
offset = " + ".join(["i%d * s%d" % (i, i) for i in range(nd)])
proto.putln("#define %s(type, buf, %s) (type)((char*)buf + %s)" % (name, args, offset))
def buf_lookup_c_code(proto, defin, name, nd):
"""
Similar to strided lookup, but can assume that the last dimension
doesn't need a multiplication as long as.
Still we keep the same signature for now.
"""
if nd == 1:
proto.putln("#define %s(type, buf, i0, s0) ((type)buf + i0)" % name)
else:
args = ", ".join(["i%d, s%d" % (i, i) for i in range(nd)])
offset = " + ".join(["i%d * s%d" % (i, i) for i in range(nd - 1)])
proto.putln("#define %s(type, buf, %s) ((type)((char*)buf + %s) + i%d)" % (name, args, offset, nd - 1))
def buf_lookup_fortran_code(proto, defin, name, nd):
"""
Like C lookup, but the first index is optimized instead.
"""
if nd == 1:
proto.putln("#define %s(type, buf, i0, s0) ((type)buf + i0)" % name)
else:
args = ", ".join(["i%d, s%d" % (i, i) for i in range(nd)])
offset = " + ".join(["i%d * s%d" % (i, i) for i in range(1, nd)])
proto.putln("#define %s(type, buf, %s) ((type)((char*)buf + %s) + i%d)" % (name, args, offset, 0))
def use_py2_buffer_functions(env):
env.use_utility_code(GetAndReleaseBufferUtilityCode())
class GetAndReleaseBufferUtilityCode(object):
# Emulation of PyObject_GetBuffer and PyBuffer_Release for Python 2.
# For >= 2.6 we do double mode -- use the new buffer interface on objects
# which has the right tp_flags set, but emulation otherwise.
requires = None
is_cython_utility = False
def __init__(self):
pass
def __eq__(self, other):
return isinstance(other, GetAndReleaseBufferUtilityCode)
def __hash__(self):
return 24342342
def get_tree(self): pass
def put_code(self, output):
code = output['utility_code_def']
proto_code = output['utility_code_proto']
env = output.module_node.scope
cython_scope = env.context.cython_scope
# Search all types for __getbuffer__ overloads
types = []
visited_scopes = set()
def find_buffer_types(scope):
if scope in visited_scopes:
return
visited_scopes.add(scope)
for m in scope.cimported_modules:
find_buffer_types(m)
for e in scope.type_entries:
if isinstance(e.utility_code_definition, CythonUtilityCode):
continue
t = e.type
if t.is_extension_type:
if scope is cython_scope and not e.used:
continue
release = get = None
for x in t.scope.pyfunc_entries:
if x.name == u"__getbuffer__": get = x.func_cname
elif x.name == u"__releasebuffer__": release = x.func_cname
if get:
types.append((t.typeptr_cname, get, release))
find_buffer_types(env)
util_code = TempitaUtilityCode.load(
"GetAndReleaseBuffer", from_file="Buffer.c",
context=dict(types=types))
proto = util_code.format_code(util_code.proto)
impl = util_code.format_code(
util_code.inject_string_constants(util_code.impl, output)[1])
proto_code.putln(proto)
code.putln(impl)
def mangle_dtype_name(dtype):
# Use prefixes to seperate user defined types from builtins
# (consider "typedef float unsigned_int")
if dtype.is_pyobject:
return "object"
elif dtype.is_ptr:
return "ptr"
else:
if dtype.is_typedef or dtype.is_struct_or_union:
prefix = "nn_"
else:
prefix = ""
type_decl = dtype.declaration_code("")
type_decl = type_decl.replace(" ", "_")
return prefix + type_decl.replace("[", "_").replace("]", "_")
def get_type_information_cname(code, dtype, maxdepth=None):
"""
Output the run-time type information (__Pyx_TypeInfo) for given dtype,
and return the name of the type info struct.
Structs with two floats of the same size are encoded as complex numbers.
One can seperate between complex numbers declared as struct or with native
encoding by inspecting to see if the fields field of the type is
filled in.
"""
namesuffix = mangle_dtype_name(dtype)
name = "__Pyx_TypeInfo_%s" % namesuffix
structinfo_name = "__Pyx_StructFields_%s" % namesuffix
if dtype.is_error: return "<error>"
# It's critical that walking the type info doesn't use more stack
# depth than dtype.struct_nesting_depth() returns, so use an assertion for this
if maxdepth is None: maxdepth = dtype.struct_nesting_depth()
if maxdepth <= 0:
assert False
if name not in code.globalstate.utility_codes:
code.globalstate.utility_codes.add(name)
typecode = code.globalstate['typeinfo']
arraysizes = []
if dtype.is_array:
while dtype.is_array:
arraysizes.append(dtype.size)
dtype = dtype.base_type
complex_possible = dtype.is_struct_or_union and dtype.can_be_complex()
declcode = dtype.declaration_code("")
if dtype.is_simple_buffer_dtype():
structinfo_name = "NULL"
elif dtype.is_struct:
fields = dtype.scope.var_entries
# Must pre-call all used types in order not to recurse utility code
# writing.
assert len(fields) > 0
types = [get_type_information_cname(code, f.type, maxdepth - 1)
for f in fields]
typecode.putln("static __Pyx_StructField %s[] = {" % structinfo_name, safe=True)
for f, typeinfo in zip(fields, types):
typecode.putln(' {&%s, "%s", offsetof(%s, %s)},' %
(typeinfo, f.name, dtype.declaration_code(""), f.cname), safe=True)
typecode.putln(' {NULL, NULL, 0}', safe=True)
typecode.putln("};", safe=True)
else:
assert False
rep = str(dtype)
flags = "0"
is_unsigned = "0"
if dtype is PyrexTypes.c_char_type:
is_unsigned = "IS_UNSIGNED(%s)" % declcode
typegroup = "'H'"
elif dtype.is_int:
is_unsigned = "IS_UNSIGNED(%s)" % declcode
typegroup = "%s ? 'U' : 'I'" % is_unsigned
elif complex_possible or dtype.is_complex:
typegroup = "'C'"
elif dtype.is_float:
typegroup = "'R'"
elif dtype.is_struct:
typegroup = "'S'"
if dtype.packed:
flags = "__PYX_BUF_FLAGS_PACKED_STRUCT"
elif dtype.is_pyobject:
typegroup = "'O'"
else:
assert False, dtype
typeinfo = ('static __Pyx_TypeInfo %s = '
'{ "%s", %s, sizeof(%s), { %s }, %s, %s, %s, %s };')
tup = (name, rep, structinfo_name, declcode,
', '.join([str(x) for x in arraysizes]) or '0', len(arraysizes),
typegroup, is_unsigned, flags)
typecode.putln(typeinfo % tup, safe=True)
return name
def load_buffer_utility(util_code_name, context=None, **kwargs):
if context is None:
return UtilityCode.load(util_code_name, "Buffer.c", **kwargs)
else:
return TempitaUtilityCode.load(util_code_name, "Buffer.c", context=context, **kwargs)
context = dict(max_dims=str(Options.buffer_max_dims))
buffer_struct_declare_code = load_buffer_utility("BufferStructDeclare",
context=context)
# Utility function to set the right exception
# The caller should immediately goto_error
raise_indexerror_code = load_buffer_utility("BufferIndexError")
raise_indexerror_nogil = load_buffer_utility("BufferIndexErrorNogil")
raise_buffer_fallback_code = load_buffer_utility("BufferFallbackError")
buffer_structs_code = load_buffer_utility(
"BufferFormatStructs", proto_block='utility_code_proto_before_types')
acquire_utility_code = load_buffer_utility("BufferFormatCheck",
context=context,
requires=[buffer_structs_code])
# See utility code BufferFormatFromTypeInfo
_typeinfo_to_format_code = load_buffer_utility("TypeInfoToFormat", context={},
requires=[buffer_structs_code])
typeinfo_compare_code = load_buffer_utility("TypeInfoCompare", context={},
requires=[buffer_structs_code])
|
unknown
|
codeparrot/codeparrot-clean
| ||
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2012 OpenStack Foundation.
# 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 contextlib import nested
import mock
from oslo.config import cfg
from neutron.agent import rpc
from neutron.openstack.common import context
from neutron.tests import base
class AgentRPCPluginApi(base.BaseTestCase):
def _test_rpc_call(self, method):
agent = rpc.PluginApi('fake_topic')
ctxt = context.RequestContext('fake_user', 'fake_project')
expect_val = 'foo'
with mock.patch('oslo.messaging.RPCClient.call') as rpc_call:
rpc_call.return_value = expect_val
func_obj = getattr(agent, method)
if method == 'tunnel_sync':
actual_val = func_obj(ctxt, 'fake_tunnel_ip')
else:
actual_val = func_obj(ctxt, 'fake_device', 'fake_agent_id')
self.assertEqual(actual_val, expect_val)
def test_get_device_details(self):
self._test_rpc_call('get_device_details')
def test_update_device_down(self):
self._test_rpc_call('update_device_down')
def test_tunnel_sync(self):
self._test_rpc_call('tunnel_sync')
class AgentPluginReportState(base.BaseTestCase):
strtime = 'neutron.openstack.common.timeutils.strtime'
def test_plugin_report_state_use_call(self):
topic = 'test'
reportStateAPI = rpc.PluginReportStateAPI(topic)
expected_agent_state = {'agent': 'test'}
with nested(mock.patch.object(reportStateAPI.client, 'call'),
mock.patch(self.strtime)) as (call, time):
time.return_value = 'TESTTIME'
ctxt = context.RequestContext('fake_user', 'fake_project')
reportStateAPI.report_state(ctxt, expected_agent_state,
use_call=True)
expected_args = mock.call(
ctxt, 'report_state',
agent_state={'agent_state': expected_agent_state},
time='TESTTIME')
self.assertEqual(call.call_args, expected_args)
def test_plugin_report_state_cast(self):
topic = 'test'
reportStateAPI = rpc.PluginReportStateAPI(topic)
expected_agent_state = {'agent': 'test'}
with nested(mock.patch.object(reportStateAPI.client, 'cast'),
mock.patch(self.strtime)) as (cast, time):
time.return_value = 'TESTTIME'
ctxt = context.RequestContext('fake_user', 'fake_project')
reportStateAPI.report_state(ctxt, expected_agent_state)
expected_args = mock.call(
ctxt, 'report_state',
agent_state={'agent_state': expected_agent_state},
time='TESTTIME')
self.assertEqual(cast.call_args, expected_args)
class AgentRPCMethods(base.BaseTestCase):
def test_create_consumers(self):
endpoint = mock.Mock()
expected_get_server = [
mock.call(mock.ANY, endpoints=[endpoint]),
mock.call().start(),
]
expected_target = [
mock.call(topic='foo-topic-op', server=cfg.CONF.host),
]
get_server_call = 'neutron.common.rpc.get_server'
target_call = 'oslo.messaging.Target'
with nested(mock.patch(get_server_call),
mock.patch(target_call)) as (get_server, target):
rpc.create_servers([endpoint], 'foo', [('topic', 'op')])
target.assert_has_calls(expected_target)
get_server.assert_has_calls(expected_get_server)
def test_create_consumers_with_node_name(self):
endpoint = mock.Mock()
expected_get_server = [
mock.call(mock.ANY, endpoints=[endpoint]),
mock.call().start(),
]
expected_target = [
mock.call(topic='foo-topic-op', server='node1'),
]
get_server_call = 'neutron.common.rpc.get_server'
target_call = 'oslo.messaging.Target'
with nested(mock.patch(get_server_call),
mock.patch(target_call)) as (get_server, target):
rpc.create_servers([endpoint], 'foo', [('topic', 'op', 'node1')])
target.assert_has_calls(expected_target)
get_server.assert_has_calls(expected_get_server)
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/python
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['stableinterface'],
'supported_by': 'curated'}
DOCUMENTATION = """
---
module: ec2_vpc_dhcp_options
short_description: Manages DHCP Options, and can ensure the DHCP options for the given VPC match what's
requested
description:
- This module removes, or creates DHCP option sets, and can associate them to a VPC.
Optionally, a new DHCP Options set can be created that converges a VPC's existing
DHCP option set with values provided.
When dhcp_options_id is provided, the module will
1. remove (with state='absent')
2. ensure tags are applied (if state='present' and tags are provided
3. attach it to a VPC (if state='present' and a vpc_id is provided.
If any of the optional values are missing, they will either be treated
as a no-op (i.e., inherit what already exists for the VPC)
To remove existing options while inheriting, supply an empty value
(e.g. set ntp_servers to [] if you want to remove them from the VPC's options)
Most of the options should be self-explanatory.
author: "Joel Thompson (@joelthompson)"
version_added: 2.1
options:
domain_name:
description:
- The domain name to set in the DHCP option sets
required: false
default: None
dns_servers:
description:
- A list of hosts to set the DNS servers for the VPC to. (Should be a
list of IP addresses rather than host names.)
required: false
default: None
ntp_servers:
description:
- List of hosts to advertise as NTP servers for the VPC.
required: false
default: None
netbios_name_servers:
description:
- List of hosts to advertise as NetBIOS servers.
required: false
default: None
netbios_node_type:
description:
- NetBIOS node type to advertise in the DHCP options.
The AWS recommendation is to use 2 (when using netbios name services)
http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_DHCP_Options.html
required: false
default: None
vpc_id:
description:
- VPC ID to associate with the requested DHCP option set.
If no vpc id is provided, and no matching option set is found then a new
DHCP option set is created.
required: false
default: None
delete_old:
description:
- Whether to delete the old VPC DHCP option set when associating a new one.
This is primarily useful for debugging/development purposes when you
want to quickly roll back to the old option set. Note that this setting
will be ignored, and the old DHCP option set will be preserved, if it
is in use by any other VPC. (Otherwise, AWS will return an error.)
required: false
default: true
inherit_existing:
description:
- For any DHCP options not specified in these parameters, whether to
inherit them from the options set already applied to vpc_id, or to
reset them to be empty.
required: false
default: false
tags:
description:
- Tags to be applied to a VPC options set if a new one is created, or
if the resource_id is provided. (options must match)
required: False
default: None
aliases: [ 'resource_tags']
version_added: "2.1"
dhcp_options_id:
description:
- The resource_id of an existing DHCP options set.
If this is specified, then it will override other settings, except tags
(which will be updated to match)
required: False
default: None
version_added: "2.1"
state:
description:
- create/assign or remove the DHCP options.
If state is set to absent, then a DHCP options set matched either
by id, or tags and options will be removed if possible.
required: False
default: present
choices: [ 'absent', 'present' ]
version_added: "2.1"
extends_documentation_fragment: aws
requirements:
- boto
"""
RETURN = """
new_options:
description: The DHCP options created, associated or found
returned: when appropriate
type: dict
sample:
domain-name-servers:
- 10.0.0.1
- 10.0.1.1
netbois-name-servers:
- 10.0.0.1
- 10.0.1.1
netbios-node-type: 2
domain-name: "my.example.com"
dhcp_options_id:
description: The aws resource id of the primary DCHP options set created, found or removed
type: string
returned: when available
changed:
description: Whether the dhcp options were changed
type: bool
returned: always
"""
EXAMPLES = """
# Completely overrides the VPC DHCP options associated with VPC vpc-123456 and deletes any existing
# DHCP option set that may have been attached to that VPC.
- ec2_vpc_dhcp_options:
domain_name: "foo.example.com"
region: us-east-1
dns_servers:
- 10.0.0.1
- 10.0.1.1
ntp_servers:
- 10.0.0.2
- 10.0.1.2
netbios_name_servers:
- 10.0.0.1
- 10.0.1.1
netbios_node_type: 2
vpc_id: vpc-123456
delete_old: True
inherit_existing: False
# Ensure the DHCP option set for the VPC has 10.0.0.4 and 10.0.1.4 as the specified DNS servers, but
# keep any other existing settings. Also, keep the old DHCP option set around.
- ec2_vpc_dhcp_options:
region: us-east-1
dns_servers:
- "{{groups['dns-primary']}}"
- "{{groups['dns-secondary']}}"
vpc_id: vpc-123456
inherit_existing: True
delete_old: False
## Create a DHCP option set with 4.4.4.4 and 8.8.8.8 as the specified DNS servers, with tags
## but do not assign to a VPC
- ec2_vpc_dhcp_options:
region: us-east-1
dns_servers:
- 4.4.4.4
- 8.8.8.8
tags:
Name: google servers
Environment: Test
## Delete a DHCP options set that matches the tags and options specified
- ec2_vpc_dhcp_options:
region: us-east-1
dns_servers:
- 4.4.4.4
- 8.8.8.8
tags:
Name: google servers
Environment: Test
state: absent
## Associate a DHCP options set with a VPC by ID
- ec2_vpc_dhcp_options:
region: us-east-1
dhcp_options_id: dopt-12345678
vpc_id: vpc-123456
"""
import boto.vpc
import boto.ec2
from boto.exception import EC2ResponseError
import socket
import collections
def get_resource_tags(vpc_conn, resource_id):
return dict((t.name, t.value) for t in vpc_conn.get_all_tags(filters={'resource-id': resource_id}))
def ensure_tags(vpc_conn, resource_id, tags, add_only, check_mode):
try:
cur_tags = get_resource_tags(vpc_conn, resource_id)
if tags == cur_tags:
return {'changed': False, 'tags': cur_tags}
to_delete = dict((k, cur_tags[k]) for k in cur_tags if k not in tags)
if to_delete and not add_only:
vpc_conn.delete_tags(resource_id, to_delete, dry_run=check_mode)
to_add = dict((k, tags[k]) for k in tags if k not in cur_tags)
if to_add:
vpc_conn.create_tags(resource_id, to_add, dry_run=check_mode)
latest_tags = get_resource_tags(vpc_conn, resource_id)
return {'changed': True, 'tags': latest_tags}
except EC2ResponseError as e:
module.fail_json(msg=get_error_message(e.args[2]))
def fetch_dhcp_options_for_vpc(vpc_conn, vpc_id):
"""
Returns the DHCP options object currently associated with the requested VPC ID using the VPC
connection variable.
"""
vpcs = vpc_conn.get_all_vpcs(vpc_ids=[vpc_id])
if len(vpcs) != 1 or vpcs[0].dhcp_options_id == "default":
return None
dhcp_options = vpc_conn.get_all_dhcp_options(dhcp_options_ids=[vpcs[0].dhcp_options_id])
if len(dhcp_options) != 1:
return None
return dhcp_options[0]
def match_dhcp_options(vpc_conn, tags=None, options=None):
"""
Finds a DHCP Options object that optionally matches the tags and options provided
"""
dhcp_options = vpc_conn.get_all_dhcp_options()
for dopts in dhcp_options:
if (not tags) or get_resource_tags(vpc_conn, dopts.id) == tags:
if (not options) or dopts.options == options:
return(True, dopts)
return(False, None)
def remove_dhcp_options_by_id(vpc_conn, dhcp_options_id):
associations = vpc_conn.get_all_vpcs(filters={'dhcpOptionsId': dhcp_options_id})
if len(associations) > 0:
return False
else:
vpc_conn.delete_dhcp_options(dhcp_options_id)
return True
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
dhcp_options_id=dict(type='str', default=None),
domain_name=dict(type='str', default=None),
dns_servers=dict(type='list', default=None),
ntp_servers=dict(type='list', default=None),
netbios_name_servers=dict(type='list', default=None),
netbios_node_type=dict(type='int', default=None),
vpc_id=dict(type='str', default=None),
delete_old=dict(type='bool', default=True),
inherit_existing=dict(type='bool', default=False),
tags=dict(type='dict', default=None, aliases=['resource_tags']),
state=dict(type='str', default='present', choices=['present', 'absent'])
)
)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
params = module.params
found = False
changed = False
new_options = collections.defaultdict(lambda: None)
region, ec2_url, boto_params = get_aws_connection_info(module)
connection = connect_to_aws(boto.vpc, region, **boto_params)
existing_options = None
# First check if we were given a dhcp_options_id
if not params['dhcp_options_id']:
# No, so create new_options from the parameters
if params['dns_servers'] is not None:
new_options['domain-name-servers'] = params['dns_servers']
if params['netbios_name_servers'] is not None:
new_options['netbios-name-servers'] = params['netbios_name_servers']
if params['ntp_servers'] is not None:
new_options['ntp-servers'] = params['ntp_servers']
if params['domain_name'] is not None:
# needs to be a list for comparison with boto objects later
new_options['domain-name'] = [ params['domain_name'] ]
if params['netbios_node_type'] is not None:
# needs to be a list for comparison with boto objects later
new_options['netbios-node-type'] = [ str(params['netbios_node_type']) ]
# If we were given a vpc_id then we need to look at the options on that
if params['vpc_id']:
existing_options = fetch_dhcp_options_for_vpc(connection, params['vpc_id'])
# if we've been asked to inherit existing options, do that now
if params['inherit_existing']:
if existing_options:
for option in [ 'domain-name-servers', 'netbios-name-servers', 'ntp-servers', 'domain-name', 'netbios-node-type']:
if existing_options.options.get(option) and new_options[option] != [] and (not new_options[option] or [''] == new_options[option]):
new_options[option] = existing_options.options.get(option)
# Do the vpc's dhcp options already match what we're asked for? if so we are done
if existing_options and new_options == existing_options.options:
module.exit_json(changed=changed, new_options=new_options, dhcp_options_id=existing_options.id)
# If no vpc_id was given, or the options don't match then look for an existing set using tags
found, dhcp_option = match_dhcp_options(connection, params['tags'], new_options)
# Now let's cover the case where there are existing options that we were told about by id
# If a dhcp_options_id was supplied we don't look at options inside, just set tags (if given)
else:
supplied_options = connection.get_all_dhcp_options(filters={'dhcp-options-id':params['dhcp_options_id']})
if len(supplied_options) != 1:
if params['state'] != 'absent':
module.fail_json(msg=" a dhcp_options_id was supplied, but does not exist")
else:
found = True
dhcp_option = supplied_options[0]
if params['state'] != 'absent' and params['tags']:
ensure_tags(connection, dhcp_option.id, params['tags'], False, module.check_mode)
# Now we have the dhcp options set, let's do the necessary
# if we found options we were asked to remove then try to do so
if params['state'] == 'absent':
if not module.check_mode:
if found:
changed = remove_dhcp_options_by_id(connection, dhcp_option.id)
module.exit_json(changed=changed, new_options={})
# otherwise if we haven't found the required options we have something to do
elif not module.check_mode and not found:
# create some dhcp options if we weren't able to use existing ones
if not found:
# Convert netbios-node-type and domain-name back to strings
if new_options['netbios-node-type']:
new_options['netbios-node-type'] = new_options['netbios-node-type'][0]
if new_options['domain-name']:
new_options['domain-name'] = new_options['domain-name'][0]
# create the new dhcp options set requested
dhcp_option = connection.create_dhcp_options(
new_options['domain-name'],
new_options['domain-name-servers'],
new_options['ntp-servers'],
new_options['netbios-name-servers'],
new_options['netbios-node-type'])
changed = True
if params['tags']:
ensure_tags(connection, dhcp_option.id, params['tags'], False, module.check_mode)
# If we were given a vpc_id, then attach the options we now have to that before we finish
if params['vpc_id'] and not module.check_mode:
changed = True
connection.associate_dhcp_options(dhcp_option.id, params['vpc_id'])
# and remove old ones if that was requested
if params['delete_old'] and existing_options:
remove_dhcp_options_by_id(connection, existing_options.id)
module.exit_json(changed=changed, new_options=new_options, dhcp_options_id=dhcp_option.id)
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
if __name__ == "__main__":
main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
"""
Tool-specific initialization for Clang static analyzer
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
__revision__ = "tools/clang-analyze.py 2013-09-06 grissiom"
import os
import os.path
import SCons.Action
import SCons.Builder
import SCons.Defaults
import SCons.Tool
import SCons.Util
import rtconfig
def generate(env):
assert(rtconfig.CROSS_TOOL == 'clang-analyze')
# let gnu_tools setup a basic env(learnt from SCons/Tools/mingw.py)
gnu_tools = ['gcc', 'g++', 'gnulink', 'ar', 'gas', 'm4']
for tool in gnu_tools:
SCons.Tool.Tool(tool)(env)
# then we could stand on the shoulders of gaints
env['CC'] = 'ccc-analyzer'
env['CXX'] = 'c++-analyzer'
env['AS'] = 'true'
env['AR'] = 'true'
env['LINK'] = 'true'
env['CFLAGS'] = ['-fsyntax-only', '-Wall', '-Wno-invalid-source-encoding', '-m32']
env['LINKFLAGS'] = '-Wl,--gc-sections'
env['ARFLAGS'] = '-rc'
# only check, don't compile. ccc-analyzer use CCC_CC as the CC.
# fsyntax-only will give us some additional warning messages
env['ENV']['CCC_CC'] = 'clang'
env['ENV']['CCC_CXX'] = 'clang++'
# setup the output dir and format
env['ENV']['CCC_ANALYZER_HTML'] = './build/'
env['ENV']['CCC_ANALYZER_OUTPUT_FORMAT'] = 'html'
# Some setting from the platform also have to be overridden:
env['OBJSUFFIX'] = '.o'
env['LIBPREFIX'] = 'lib'
env['LIBSUFFIX'] = '.a'
if rtconfig.EXEC_PATH:
if not os.path.exists(rtconfig.EXEC_PATH):
print
print 'warning: rtconfig.EXEC_PATH(%s) does not exists.' % rtconfig.EXEC_PATH
print
return
env.AppendENVPath('PATH', rtconfig.EXEC_PATH)
def exists(env):
return env.Detect(['ccc-analyzer', 'c++-analyzer'])
# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ovirt_cluster_facts
short_description: Retrieve facts about one or more oVirt/RHV clusters
author: "Ondra Machacek (@machacekondra)"
version_added: "2.3"
description:
- "Retrieve facts about one or more oVirt/RHV clusters."
notes:
- "This module creates a new top-level C(ovirt_clusters) fact, which
contains a list of clusters."
options:
pattern:
description:
- "Search term which is accepted by oVirt/RHV search backend."
- "For example to search cluster X from datacenter Y use following pattern:
name=X and datacenter=Y"
extends_documentation_fragment: ovirt_facts
'''
EXAMPLES = '''
# Examples don't contain auth parameter for simplicity,
# look at ovirt_auth module to see how to reuse authentication:
# Gather facts about all clusters which names start with C<production>:
- ovirt_cluster_facts:
pattern:
name: 'production*'
- debug:
var: ovirt_clusters
'''
RETURN = '''
ovirt_clusters:
description: "List of dictionaries describing the clusters. Cluster attributes are mapped to dictionary keys,
all clusters attributes can be found at following url: http://ovirt.github.io/ovirt-engine-api-model/master/#types/cluster."
returned: On success.
type: list
'''
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
get_dict_of_struct,
ovirt_facts_full_argument_spec,
)
def main():
argument_spec = ovirt_facts_full_argument_spec(
pattern=dict(default='', required=False),
)
module = AnsibleModule(argument_spec)
check_sdk(module)
try:
auth = module.params.pop('auth')
connection = create_connection(auth)
clusters_service = connection.system_service().clusters_service()
clusters = clusters_service.list(search=module.params['pattern'])
module.exit_json(
changed=False,
ansible_facts=dict(
ovirt_clusters=[
get_dict_of_struct(
struct=c,
connection=connection,
fetch_nested=module.params.get('fetch_nested'),
attributes=module.params.get('nested_attributes'),
) for c in clusters
],
),
)
except Exception as e:
module.fail_json(msg=str(e), exception=traceback.format_exc())
finally:
connection.close(logout=auth.get('token') is None)
if __name__ == '__main__':
main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
# 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/.
import json
import uuid
from django.http import HttpResponse
from django.test.client import RequestFactory
import basket
from bedrock.base.urlresolvers import reverse
from mock import DEFAULT, Mock, patch
from nose.tools import eq_, ok_
from pyquery import PyQuery as pq
from bedrock.mozorg.tests import TestCase
from bedrock.newsletter.tests import newsletters
from bedrock.newsletter.views import (
general_error,
invalid_email_address,
newsletter_subscribe,
recovery_text,
unknown_address_text,
updated,
)
cache_mock = Mock()
cache_mock.get.return_value = None
def assert_redirect(response, url):
"""
Assert that the response indicates a redirect to the url.
"""
# This is like Django TestCase's assertRedirect, only we're not
# using Django TestCase due to our lack of a database, so we
# need to fake our own.
# Django seems to stick this into the Location header
url = "http://testserver" + url
assert url == response['Location'],\
"Response did not redirect to %s; Location=%s" % \
(url, response['Location'])
@patch('bedrock.newsletter.utils.cache', cache_mock)
class TestViews(TestCase):
def setUp(self):
self.rf = RequestFactory()
def test_hacks_newsletter_frames_allow(self):
"""
Bedrock pages get the 'x-frame-options: DENY' header by default.
The hacks newsletter page is framed, so needs to ALLOW.
"""
with self.activate('en-US'):
resp = self.client.get(reverse('mozorg.hacks_newsletter'))
ok_('x-frame-options' not in resp)
@patch('bedrock.newsletter.views.l10n_utils.render')
def test_updated_allows_good_tokens(self, mock_render):
token = unicode(uuid.uuid4())
req = self.rf.get('/', {'token': token, 'unsub': 1})
updated(req)
self.assertEqual(mock_render.call_args[0][2]['token'], token)
@patch('bedrock.newsletter.views.l10n_utils.render')
def test_updated_disallows_bad_tokens(self, mock_render):
token = 'the-dude'
req = self.rf.get('/', {'token': token, 'unsub': 1})
updated(req)
eq_(mock_render.call_args[0][2]['token'], None)
token = '\'>"><img src=x onerror=alert(1)>'
req = self.rf.get('/', {'token': token, 'unsub': 1})
updated(req)
eq_(mock_render.call_args[0][2]['token'], None)
# Always mock basket.request to be sure we never actually call basket
# during tests.
@patch('basket.base.request')
@patch('bedrock.newsletter.utils.cache', cache_mock)
class TestExistingNewsletterView(TestCase):
def setUp(self):
self.token = unicode(uuid.uuid4())
self.user = {
'newsletters': [u'mozilla-and-you'],
'token': self.token,
'email': u'user@example.com',
'lang': u'pt',
'country': u'br',
'format': u'T',
}
# By default, data matches user's existing data; change it
# in the test as desired. Also, user has accepted privacy
# checkbox.
self.data = {
u'form-MAX_NUM_FORMS': 4,
u'form-INITIAL_FORMS': 4,
u'form-TOTAL_FORMS': 4,
u'email': self.user['email'],
u'lang': self.user['lang'],
u'country': self.user['country'],
u'format': self.user['format'],
u'privacy': u'on',
u'form-0-newsletter': u'mozilla-and-you',
u'form-0-subscribed_radio': u'True',
u'form-1-newsletter': u'mobile',
u'form-1-subscribed_radio': u'False',
u'form-2-newsletter': u'firefox-tips',
u'form-2-subscribed_check': u'False',
u'form-3-newsletter': u'join-mozilla',
u'form-3-subscribed_check': u'False',
u'submit': u'Save Preferences',
}
super(TestExistingNewsletterView, self).setUp()
@patch('bedrock.newsletter.utils.get_newsletters')
def test_get_token(self, get_newsletters, mock_basket_request):
# If user gets page with valid token in their URL, they
# see their data, and no privacy checkbox is presented
get_newsletters.return_value = newsletters
url = reverse('newsletter.existing.token', args=(self.token,))
# noinspection PyUnresolvedReferences
with patch.multiple('basket',
update_user=DEFAULT,
subscribe=DEFAULT,
unsubscribe=DEFAULT,
user=DEFAULT) as basket_patches:
with patch('lib.l10n_utils.render') as render:
basket_patches['user'].return_value = self.user
render.return_value = HttpResponse('')
self.client.get(url)
request, template_name, context = render.call_args[0]
form = context['form']
self.assertNotIn('privacy', form.fields)
self.assertEqual(self.user['lang'], form.initial['lang'])
@patch('bedrock.newsletter.utils.get_newsletters')
def test_show(self, get_newsletters, mock_basket_request):
# Newsletters are only listed if the user is subscribed to them,
# or they are marked 'show' and 'active' in the settings
get_newsletters.return_value = newsletters
# Find a newsletter without 'show' and subscribe the user to it
for newsletter, data in newsletters.iteritems():
if not data.get('show', False):
self.user['newsletters'] = [newsletter]
break
url = reverse('newsletter.existing.token', args=(self.token,))
with patch.multiple('basket',
update_user=DEFAULT,
subscribe=DEFAULT,
unsubscribe=DEFAULT,
user=DEFAULT) as basket_patches:
with patch('lib.l10n_utils.render') as render:
basket_patches['user'].return_value = self.user
render.return_value = HttpResponse('')
self.client.get(url)
request, template_name, context = render.call_args[0]
forms = context['formset'].initial_forms
shown = set([form.initial['newsletter'] for form in forms])
inactive = set([newsletter for newsletter, data
in newsletters.iteritems()
if not data.get('active', False)])
to_show = set([newsletter for newsletter, data
in newsletters.iteritems()
if data.get('show', False)]) - inactive
subscribed = set(self.user['newsletters'])
# All subscribed newsletters except inactive ones are shown
self.assertEqual(set(), subscribed - inactive - shown)
# All 'show' newsletters are shown
self.assertEqual(set(), to_show - shown)
# No other newsletters are shown
self.assertEqual(set(), shown - subscribed - to_show)
def test_get_no_token(self, mock_basket_request):
# No token in URL - should redirect to recovery
url = reverse('newsletter.existing.token', args=('',))
rsp = self.client.get(url)
self.assertEqual(302, rsp.status_code)
self.assertTrue(rsp['Location'].endswith(reverse('newsletter.recovery')))
def test_get_user_not_found(self, mock_basket_request):
# Token in URL but not a valid token - should redirect to recovery
rand_token = unicode(uuid.uuid4())
url = reverse('newsletter.existing.token', args=(rand_token,))
with patch.multiple('basket',
user=DEFAULT) as basket_patches:
with patch('lib.l10n_utils.render') as render:
render.return_value = HttpResponse('')
with patch('django.contrib.messages.add_message') as add_msg:
basket_patches['user'].side_effect = basket.BasketException
rsp = self.client.get(url)
# Should have given a message
self.assertEqual(1, add_msg.call_count,
msg=repr(add_msg.call_args_list))
# Should have been redirected to recovery page
self.assertEqual(302, rsp.status_code)
self.assertTrue(rsp['Location'].endswith(reverse('newsletter.recovery')))
def test_invalid_token(self, mock_basket_request):
# "Token" in URL is not syntactically a UUID - should redirect to
# recovery *without* calling Exact Target
token = "not a token"
url = reverse('newsletter.existing.token', args=(token,))
with patch.multiple('basket', user=DEFAULT) as basket_patches:
with patch('django.contrib.messages.add_message') as add_msg:
rsp = self.client.get(url, follow=False)
self.assertEqual(0, basket_patches['user'].call_count)
self.assertEqual(1, add_msg.call_count)
self.assertEqual(302, rsp.status_code)
self.assertTrue(rsp['Location'].endswith(reverse('newsletter.recovery')))
def test_post_user_not_found(self, mock_basket_request):
# User submits form and passed token, but no user was found
# Should issue message and redirect to recovery
rand_token = unicode(uuid.uuid4())
url = reverse('newsletter.existing.token', args=(rand_token,))
with patch.multiple('basket',
update_user=DEFAULT,
subscribe=DEFAULT,
unsubscribe=DEFAULT,
user=DEFAULT) as basket_patches:
with patch('lib.l10n_utils.render') as render:
render.return_value = HttpResponse('')
with patch('django.contrib.messages.add_message') as add_msg:
basket_patches['user'].side_effect = basket.BasketException
rsp = self.client.post(url, self.data)
# Shouldn't call basket except for the attempt to find the user
self.assertEqual(0, basket_patches['update_user'].call_count)
self.assertEqual(0, basket_patches['unsubscribe'].call_count)
self.assertEqual(0, basket_patches['subscribe'].call_count)
# Should have given a message
self.assertEqual(1, add_msg.call_count,
msg=repr(add_msg.call_args_list))
# Should have been redirected to recovery page
self.assertEqual(302, rsp.status_code)
self.assertTrue(rsp['Location'].endswith(reverse('newsletter.recovery')))
@patch('bedrock.newsletter.utils.get_newsletters')
def test_subscribing(self, get_newsletters, mock_basket_request):
get_newsletters.return_value = newsletters
# They subscribe to firefox-tips
self.data['form-2-subscribed_check'] = u'True'
# in English - and that's their language too
self.user['lang'] = u'en'
self.data['lang'] = u'en'
url = reverse('newsletter.existing.token', args=(self.token,))
with patch.multiple('basket',
update_user=DEFAULT,
subscribe=DEFAULT,
unsubscribe=DEFAULT,
user=DEFAULT) as basket_patches:
with patch('django.contrib.messages.add_message') as add_msg:
with patch('lib.l10n_utils.render'):
basket_patches['user'].return_value = self.user
rsp = self.client.post(url, self.data)
# Should have given no messages
self.assertEqual(0, add_msg.call_count,
msg=repr(add_msg.call_args_list))
# Should have called update_user with subscription list
self.assertEqual(1, basket_patches['update_user'].call_count)
kwargs = basket_patches['update_user'].call_args[1]
self.assertEqual(
{'newsletters': u'mozilla-and-you,firefox-tips'},
kwargs
)
# Should not have called unsubscribe
self.assertEqual(0, basket_patches['unsubscribe'].call_count)
# Should not have called subscribe
self.assertEqual(0, basket_patches['subscribe'].call_count)
# Should redirect to the 'updated' view
url = reverse('newsletter.updated')
assert_redirect(rsp, url)
@patch('bedrock.newsletter.utils.get_newsletters')
def test_unsubscribing(self, get_newsletters, mock_basket_request):
get_newsletters.return_value = newsletters
# They unsubscribe from the one newsletter they're subscribed to
self.data['form-0-subscribed_radio'] = u'False'
url = reverse('newsletter.existing.token', args=(self.token,))
with patch.multiple('basket',
update_user=DEFAULT,
subscribe=DEFAULT,
unsubscribe=DEFAULT,
user=DEFAULT) as basket_patches:
with patch('lib.l10n_utils.render'):
basket_patches['user'].return_value = self.user
rsp = self.client.post(url, self.data)
# Should have called update_user with list of newsletters
self.assertEqual(1, basket_patches['update_user'].call_count)
kwargs = basket_patches['update_user'].call_args[1]
self.assertEqual(
{'newsletters': u''},
kwargs
)
# Should not have called subscribe
self.assertEqual(0, basket_patches['subscribe'].call_count)
# Should not have called unsubscribe
self.assertEqual(0, basket_patches['unsubscribe'].call_count)
# Should redirect to the 'updated' view
url = reverse('newsletter.updated')
assert_redirect(rsp, url)
@patch('bedrock.newsletter.utils.get_newsletters')
def test_remove_all(self, get_newsletters, mock_basket_request):
get_newsletters.return_value = newsletters
self.data['remove_all'] = 'on' # any value should do
url = reverse('newsletter.existing.token', args=(self.token,))
with patch.multiple('basket',
update_user=DEFAULT,
subscribe=DEFAULT,
unsubscribe=DEFAULT,
user=DEFAULT) as basket_patches:
with patch('lib.l10n_utils.render'):
basket_patches['user'].return_value = self.user
rsp = self.client.post(url, self.data)
# Should not have updated user details at all
self.assertEqual(0, basket_patches['update_user'].call_count)
# Should have called unsubscribe
self.assertEqual(1, basket_patches['unsubscribe'].call_count)
# and said user opts out
args, kwargs = basket_patches['unsubscribe'].call_args
self.assertEqual((self.token, self.user['email']), args)
self.assertTrue(kwargs['optout'])
# Should redirect to the 'updated' view with unsub=1 and token
url = reverse('newsletter.updated') + "?unsub=1"
url += "&token=%s" % self.token
assert_redirect(rsp, url)
@patch('bedrock.newsletter.utils.get_newsletters')
def test_change_lang_country(self, get_newsletters, mock_basket_request):
get_newsletters.return_value = newsletters
self.data['lang'] = 'en'
self.data['country'] = 'us'
url = reverse('newsletter.existing.token', args=(self.token,))
with patch.multiple('basket',
update_user=DEFAULT,
subscribe=DEFAULT,
user=DEFAULT) as basket_patches:
with patch('lib.l10n_utils.render'):
with patch('django.contrib.messages.add_message') as add_msg:
basket_patches['user'].return_value = self.user
rsp = self.client.post(url, self.data)
# We have an existing user with a change to their email data,
# but none to their subscriptions.
# 'subscribe' should not be called
self.assertEqual(0, basket_patches['subscribe'].call_count)
# update_user should be called once
self.assertEqual(1, basket_patches['update_user'].call_count)
# with the new lang and country and the newsletter list
kwargs = basket_patches['update_user'].call_args[1]
self.assertEqual(
{'lang': u'en',
'country': u'us',
'newsletters': u'mozilla-and-you'},
kwargs
)
# No messages should be emitted
self.assertEqual(0, add_msg.call_count,
msg=repr(add_msg.call_args_list))
# Should redirect to the 'updated' view
url = reverse('newsletter.updated')
assert_redirect(rsp, url)
@patch('bedrock.newsletter.utils.get_newsletters')
def test_newsletter_ordering(self, get_newsletters, mock_basket_request):
# Newsletters are listed in 'order' order, if they have an 'order'
# field
get_newsletters.return_value = newsletters
url = reverse('newsletter.existing.token', args=(self.token,))
self.user['newsletters'] = [u'mozilla-and-you', u'firefox-tips',
u'beta']
with patch.multiple('basket',
update_user=DEFAULT,
subscribe=DEFAULT,
unsubscribe=DEFAULT,
user=DEFAULT) as basket_patches:
with patch('lib.l10n_utils.render') as render:
basket_patches['user'].return_value = self.user
render.return_value = HttpResponse('')
self.client.get(url)
request, template_name, context = render.call_args[0]
forms = context['formset'].initial_forms
newsletters_in_order = [form.initial['newsletter'] for form in forms]
self.assertEqual([u'firefox-tips', u'mozilla-and-you'],
newsletters_in_order)
@patch('bedrock.newsletter.utils.get_newsletters')
def test_newsletter_no_order(self, get_newsletters, mock_basket_request):
"""Newsletter views should work if we get no order from basket."""
orderless_newsletters = {}
for key, val in newsletters.items():
nl_copy = val.copy()
del nl_copy['order']
orderless_newsletters[key] = nl_copy
get_newsletters.return_value = orderless_newsletters
url = reverse('newsletter.existing.token', args=(self.token,))
self.user['newsletters'] = [u'mozilla-and-you', u'firefox-tips',
u'beta']
with patch.multiple('basket',
update_user=DEFAULT,
subscribe=DEFAULT,
unsubscribe=DEFAULT,
user=DEFAULT) as basket_patches:
with patch('lib.l10n_utils.render') as render:
basket_patches['user'].return_value = self.user
render.return_value = HttpResponse('')
self.client.get(url)
request, template_name, context = render.call_args[0]
forms = context['formset'].initial_forms
newsletters_in_order = [form.initial['newsletter'] for form in forms]
self.assertEqual([u'mozilla-and-you', u'firefox-tips'],
newsletters_in_order)
@patch('bedrock.newsletter.utils.cache', cache_mock)
class TestConfirmView(TestCase):
def setUp(self):
self.token = unicode(uuid.uuid4())
self.url = reverse('newsletter.confirm', kwargs={'token': self.token})
def test_normal(self):
"""Confirm works with a valid token"""
with patch('basket.confirm') as confirm:
confirm.return_value = {'status': 'ok'}
with patch('lib.l10n_utils.render') as mock_render:
mock_render.return_value = HttpResponse('')
rsp = self.client.get(self.url, follow=True)
self.assertEqual(200, rsp.status_code)
confirm.assert_called_with(self.token)
context = mock_render.call_args[0][2]
self.assertTrue(context['success'])
self.assertFalse(context['generic_error'])
self.assertFalse(context['token_error'])
def test_basket_down(self):
"""If basket is down, we report the appropriate error"""
with patch('basket.confirm') as confirm:
confirm.side_effect = basket.BasketException()
with patch('lib.l10n_utils.render') as mock_render:
mock_render.return_value = HttpResponse('')
rsp = self.client.get(self.url, follow=True)
self.assertEqual(200, rsp.status_code)
confirm.assert_called_with(self.token)
context = mock_render.call_args[0][2]
self.assertFalse(context['success'])
self.assertTrue(context['generic_error'])
self.assertFalse(context['token_error'])
def test_bad_token(self):
"""If the token is bad, we report the appropriate error"""
with patch('basket.confirm') as confirm:
confirm.side_effect = basket.BasketException(status_code=403,
code=basket.errors.BASKET_UNKNOWN_TOKEN)
with patch('lib.l10n_utils.render') as mock_render:
mock_render.return_value = HttpResponse('')
rsp = self.client.get(self.url, follow=True)
self.assertEqual(200, rsp.status_code)
confirm.assert_called_with(self.token)
context = mock_render.call_args[0][2]
self.assertFalse(context['success'])
self.assertFalse(context['generic_error'])
self.assertTrue(context['token_error'])
class TestRecoveryView(TestCase):
def setUp(self):
with self.activate('en-US'):
self.url = reverse('newsletter.recovery')
def test_bad_email(self):
"""Email syntax errors are caught"""
data = {'email': 'not_an_email'}
rsp = self.client.post(self.url, data)
self.assertEqual(200, rsp.status_code)
self.assertIn('email', rsp.context['form'].errors)
@patch('basket.send_recovery_message', autospec=True)
def test_unknown_email(self, mock_basket):
"""Unknown email addresses give helpful error message"""
data = {'email': 'unknown@example.com'}
mock_basket.side_effect = basket.BasketException(status_code=404,
code=basket.errors.BASKET_UNKNOWN_EMAIL)
rsp = self.client.post(self.url, data)
self.assertTrue(mock_basket.called)
self.assertEqual(200, rsp.status_code)
form = rsp.context['form']
expected_error = unknown_address_text % \
reverse('newsletter.subscribe')
self.assertIn(expected_error, form.errors['email'])
@patch('django.contrib.messages.add_message', autospec=True)
@patch('basket.send_recovery_message', autospec=True)
def test_good_email(self, mock_basket, add_msg):
"""If basket returns success, don't report errors"""
data = {'email': 'known@example.com'}
mock_basket.return_value = {'status': 'ok'}
rsp = self.client.post(self.url, data)
self.assertTrue(mock_basket.called)
# On successful submit, we redirect
self.assertEqual(302, rsp.status_code)
rsp = self.client.get(rsp['Location'])
self.assertEqual(200, rsp.status_code)
self.assertFalse(rsp.context['form'])
# We also give them a success message
self.assertEqual(1, add_msg.call_count,
msg=repr(add_msg.call_args_list))
self.assertIn(recovery_text, add_msg.call_args[0])
class TestNewsletterSubscribe(TestCase):
def setUp(self):
self.rf = RequestFactory()
def ajax_request(self, data):
return self.request(data, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
def request(self, data=None, **kwargs):
if data:
req = self.rf.post('/', data, **kwargs)
else:
req = self.rf.get('/', **kwargs)
return newsletter_subscribe(req)
@patch('bedrock.newsletter.views.basket')
def test_returns_ajax_errors(self, basket_mock):
"""Incomplete data should return specific errors in JSON"""
data = {
'newsletters': 'flintstones',
'email': 'fred@example.com',
'fmt': 'H',
}
resp = self.ajax_request(data)
resp_data = json.loads(resp.content)
self.assertFalse(resp_data['success'])
self.assertEqual(len(resp_data['errors']), 1)
self.assertIn('privacy', resp_data['errors'][0])
self.assertFalse(basket_mock.called)
@patch('bedrock.newsletter.views.basket')
def test_returns_sanitized_ajax_errors(self, basket_mock):
"""Error messages should be HTML escaped.
Bug 1116754
"""
data = {
'newsletters': 'flintstones',
'email': 'fred@example.com',
'fmt': 'H',
'privacy': True,
'country': '<svg/onload=alert("NEFARIOUSNESS")>',
}
resp = self.ajax_request(data)
resp_data = json.loads(resp.content)
self.assertFalse(resp_data['success'])
self.assertEqual(len(resp_data['errors']), 1)
self.assertNotIn(data['country'], resp_data['errors'][0])
self.assertIn('NEFARIOUSNESS', resp_data['errors'][0])
self.assertIn('<svg', resp_data['errors'][0])
self.assertFalse(basket_mock.called)
@patch('bedrock.newsletter.views.basket')
def test_returns_ajax_success(self, basket_mock):
"""Good post should return success JSON"""
data = {
'newsletters': 'flintstones',
'email': 'fred@example.com',
'fmt': 'H',
'privacy': True,
}
resp = self.ajax_request(data)
resp_data = json.loads(resp.content)
self.assertDictEqual(resp_data, {'success': True})
basket_mock.subscribe.assert_called_with('fred@example.com', 'flintstones',
format='H')
@patch.object(basket, 'subscribe')
def test_returns_ajax_invalid_email(self, subscribe_mock):
"""Invalid email AJAX post should return proper error."""
subscribe_mock.side_effect = basket.BasketException(
code=basket.errors.BASKET_INVALID_EMAIL)
data = {
'newsletters': 'flintstones',
'email': 'fred@example.com',
'fmt': 'H',
'privacy': True,
}
resp = self.ajax_request(data)
resp_data = json.loads(resp.content)
self.assertFalse(resp_data['success'])
self.assertEqual(resp_data['errors'][0], unicode(invalid_email_address))
@patch.object(basket, 'subscribe')
def test_returns_ajax_basket_error(self, subscribe_mock):
"""Basket error AJAX post should return proper error."""
subscribe_mock.side_effect = basket.BasketException(
code=basket.errors.BASKET_NETWORK_FAILURE)
data = {
'newsletters': 'flintstones',
'email': 'fred@example.com',
'fmt': 'H',
'privacy': True,
}
resp = self.ajax_request(data)
resp_data = json.loads(resp.content)
self.assertFalse(resp_data['success'])
self.assertEqual(resp_data['errors'][0], unicode(general_error))
def test_shows_normal_form(self):
"""A normal GET should show the form."""
resp = self.request()
doc = pq(resp.content)
self.assertTrue(doc('#newsletter-form'))
self.assertTrue(doc('input[value="mozilla-and-you"]'))
@patch('bedrock.newsletter.views.basket')
def test_returns_success(self, basket_mock):
"""Good non-ajax post should return thank-you page."""
data = {
'newsletters': 'flintstones',
'email': 'fred@example.com',
'fmt': 'H',
'privacy': True,
}
resp = self.request(data)
doc = pq(resp.content)
self.assertFalse(doc('#footer_email_submit'))
self.assertFalse(doc('input[value="mozilla-and-you"]'))
self.assertTrue(doc('#email-form').hasClass('thank'))
basket_mock.subscribe.assert_called_with('fred@example.com', 'flintstones',
format='H')
@patch('bedrock.newsletter.views.basket')
def test_returns_failure(self, basket_mock):
"""Bad non-ajax post should return form with errors."""
data = {
'newsletters': 'flintstones',
'email': 'fred@example.com',
'fmt': 'H',
}
resp = self.request(data)
doc = pq(resp.content)
self.assertTrue(doc('#newsletter-form'))
self.assertFalse(doc('input[value="mozilla-and-you"]'))
self.assertTrue(doc('input[value="flintstones"]'))
self.assertFalse(doc('#email-form').hasClass('thank'))
self.assertTrue(doc('.field-privacy').hasClass('form-field-error'))
self.assertIn('privacy', doc('#footer-email-errors .errorlist li').eq(0).text())
self.assertFalse(basket_mock.subscribe.called)
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Vispy Development Team.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
from __future__ import division
from .image import ImageVisual
from ..color import Color
from .shaders import Function
grid_color = """
vec4 grid_color(vec2 pos) {
vec4 px_pos = $map_to_doc(vec4(pos, 0, 1));
px_pos /= px_pos.w;
// Compute vectors representing width, height of pixel in local coords
float s = 1.;
vec4 local_pos = $map_doc_to_local(px_pos);
vec4 dx = $map_doc_to_local(px_pos + vec4(1.0 / s, 0, 0, 0));
vec4 dy = $map_doc_to_local(px_pos + vec4(0, 1.0 / s, 0, 0));
local_pos /= local_pos.w;
dx = dx / dx.w - local_pos;
dy = dy / dy.w - local_pos;
// Pixel length along each axis, rounded to the nearest power of 10
vec2 px = s * vec2(abs(dx.x) + abs(dy.x), abs(dx.y) + abs(dy.y));
float log10 = log(10.0);
float sx = pow(10.0, floor(log(px.x) / log10)+1) * $scale.x;
float sy = pow(10.0, floor(log(px.y) / log10)+1) * $scale.y;
float max_alpha = 0.6;
float x_alpha = 0.0;
if (mod(local_pos.x, 1000 * sx) < px.x) {
x_alpha = clamp(1 * sx/px.x, 0, max_alpha);
}
else if (mod(local_pos.x, 100 * sx) < px.x) {
x_alpha = clamp(.1 * sx/px.x, 0, max_alpha);
}
else if (mod(local_pos.x, 10 * sx) < px.x) {
x_alpha = clamp(0.01 * sx/px.x, 0, max_alpha);
}
float y_alpha = 0.0;
if (mod(local_pos.y, 1000 * sy) < px.y) {
y_alpha = clamp(1 * sy/px.y, 0, max_alpha);
}
else if (mod(local_pos.y, 100 * sy) < px.y) {
y_alpha = clamp(.1 * sy/px.y, 0, max_alpha);
}
else if (mod(local_pos.y, 10 * sy) < px.y) {
y_alpha = clamp(0.01 * sy/px.y, 0, max_alpha);
}
float alpha = (((log(max(x_alpha, y_alpha))/log(10.))+2) / 3);
if (alpha == 0) {
discard;
}
return vec4($color.rgb, $color.a * alpha);
}
"""
class GridLinesVisual(ImageVisual):
""" Displays regularly spaced grid lines in any coordinate system and at
any scale.
Parameters
----------
scale : tuple
The scale factors to apply when determining the spacing of grid lines.
color : Color
The base color for grid lines. The final color may have its alpha
channel modified.
"""
def __init__(self, scale=(1, 1), color='w'):
# todo: PlaneVisual should support subdivide/impostor methods from
# image and gridlines should inherit from plane instead.
self._grid_color_fn = Function(grid_color)
self._grid_color_fn['color'] = Color(color).rgba
self._grid_color_fn['scale'] = scale
ImageVisual.__init__(self, method='impostor')
self.set_gl_state('additive', cull_face=False)
self.shared_program.frag['get_data'] = self._grid_color_fn
cfun = Function('vec4 null(vec4 x) { return x; }')
self.shared_program.frag['color_transform'] = cfun
@property
def size(self):
return (1, 1)
def _prepare_transforms(self, view):
fn = self._grid_color_fn
fn['map_to_doc'] = self.get_transform('visual', 'document')
fn['map_doc_to_local'] = self.get_transform('document', 'visual')
ImageVisual._prepare_transforms(self, view)
def _prepare_draw(self, view):
if self._need_vertex_update:
self._build_vertex_data()
if view._need_method_update:
self._update_method(view)
|
unknown
|
codeparrot/codeparrot-clean
| ||
from collections import defaultdict
from django.apps import apps
from django.db import models
from django.utils.translation import gettext_lazy as _
class ContentTypeManager(models.Manager):
use_in_migrations = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Cache shared by all the get_for_* methods to speed up
# ContentType retrieval.
self._cache = {}
def get_by_natural_key(self, app_label, model):
try:
ct = self._cache[self.db][(app_label, model)]
except KeyError:
ct = self.get(app_label=app_label, model=model)
self._add_to_cache(self.db, ct)
return ct
def _get_opts(self, model, for_concrete_model):
if for_concrete_model:
model = model._meta.concrete_model
return model._meta
def _get_from_cache(self, opts):
key = (opts.app_label, opts.model_name)
return self._cache[self.db][key]
def get_for_model(self, model, for_concrete_model=True):
"""
Return the ContentType object for a given model, creating the
ContentType if necessary. Lookups are cached so that subsequent lookups
for the same model don't hit the database.
"""
opts = self._get_opts(model, for_concrete_model)
try:
return self._get_from_cache(opts)
except KeyError:
pass
# The ContentType entry was not found in the cache, therefore we
# proceed to load or create it.
try:
# Start with get() and not get_or_create() in order to use
# the db_for_read (see #20401).
ct = self.get(app_label=opts.app_label, model=opts.model_name)
except self.model.DoesNotExist:
# Not found in the database; we proceed to create it. This time
# use get_or_create to take care of any race conditions.
ct, created = self.get_or_create(
app_label=opts.app_label,
model=opts.model_name,
)
self._add_to_cache(self.db, ct)
return ct
def get_for_models(self, *models, for_concrete_models=True):
"""
Given *models, return a dictionary mapping {model: content_type}.
"""
results = {}
# Models that aren't already in the cache.
needed_app_labels = set()
needed_models = set()
# Mapping of opts to the list of models requiring it.
needed_opts = defaultdict(list)
for model in models:
opts = self._get_opts(model, for_concrete_models)
try:
ct = self._get_from_cache(opts)
except KeyError:
needed_app_labels.add(opts.app_label)
needed_models.add(opts.model_name)
needed_opts[opts].append(model)
else:
results[model] = ct
if needed_opts:
# Lookup required content types from the DB.
cts = self.filter(
app_label__in=needed_app_labels,
model__in=needed_models
)
for ct in cts:
opts_models = needed_opts.pop(ct.model_class()._meta, [])
for model in opts_models:
results[model] = ct
self._add_to_cache(self.db, ct)
# Create content types that weren't in the cache or DB.
for opts, opts_models in needed_opts.items():
ct = self.create(
app_label=opts.app_label,
model=opts.model_name,
)
self._add_to_cache(self.db, ct)
for model in opts_models:
results[model] = ct
return results
def get_for_id(self, id):
"""
Lookup a ContentType by ID. Use the same shared cache as get_for_model
(though ContentTypes are obviously not created on-the-fly by get_by_id).
"""
try:
ct = self._cache[self.db][id]
except KeyError:
# This could raise a DoesNotExist; that's correct behavior and will
# make sure that only correct ctypes get stored in the cache dict.
ct = self.get(pk=id)
self._add_to_cache(self.db, ct)
return ct
def clear_cache(self):
"""
Clear out the content-type cache.
"""
self._cache.clear()
def _add_to_cache(self, using, ct):
"""Insert a ContentType into the cache."""
# Note it's possible for ContentType objects to be stale; model_class() will return None.
# Hence, there is no reliance on model._meta.app_label here, just using the model fields instead.
key = (ct.app_label, ct.model)
self._cache.setdefault(using, {})[key] = ct
self._cache.setdefault(using, {})[ct.id] = ct
class ContentType(models.Model):
app_label = models.CharField(max_length=100)
model = models.CharField(_('python model class name'), max_length=100)
objects = ContentTypeManager()
class Meta:
verbose_name = _('content type')
verbose_name_plural = _('content types')
db_table = 'django_content_type'
unique_together = [['app_label', 'model']]
def __str__(self):
return self.app_labeled_name
@property
def name(self):
model = self.model_class()
if not model:
return self.model
return str(model._meta.verbose_name)
@property
def app_labeled_name(self):
model = self.model_class()
if not model:
return self.model
return '%s | %s' % (model._meta.app_label, model._meta.verbose_name)
def model_class(self):
"""Return the model class for this type of content."""
try:
return apps.get_model(self.app_label, self.model)
except LookupError:
return None
def get_object_for_this_type(self, **kwargs):
"""
Return an object of this type for the keyword arguments given.
Basically, this is a proxy around this object_type's get_object() model
method. The ObjectNotExist exception, if thrown, will not be caught,
so code that calls this method should catch it.
"""
return self.model_class()._base_manager.using(self._state.db).get(**kwargs)
def get_all_objects_for_this_type(self, **kwargs):
"""
Return all objects of this type for the keyword arguments given.
"""
return self.model_class()._base_manager.using(self._state.db).filter(**kwargs)
def natural_key(self):
return (self.app_label, self.model)
|
unknown
|
codeparrot/codeparrot-clean
| ||
from __future__ import absolute_import
from ..model import Model
from ..core.properties import Any, Dict, Float, String, Int, Bool, Override
class TileSource(Model):
""" A base class for all tile source types. ``TileSource`` is
not generally useful to instantiate on its own. In general, tile sources are used as a required input for ``TileRenderer``.
Subclasses should have these properties as well:
x_origin_offset = Float
y_origin_offset = Float
initial_resolution = Float
"""
_args = ('url', 'tile_size', 'min_zoom', 'max_zoom', 'extra_url_vars')
url = String("", help="""
tile service url (example: http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png)
""")
tile_size = Int(default=256, help="""
tile size in pixels (e.g. 256)
""")
min_zoom = Int(default=0, help="""
the minimum zoom level for the tile layer. This is the most "zoomed-out" level.
""")
max_zoom = Int(default=30, help="""
the maximum zoom level for the tile layer. This is the most "zoomed-in" level.
""")
extra_url_vars = Dict(String, Any, help="""
A dictionary that maps url variable template keys to values.
These variables are useful for parts of tile urls which do not change from tile to tile (e.g. server host name, or layer name).
""")
attribution = String("", help="""
Data provider attribution content. This can include HTML content.
""")
x_origin_offset = Float(help="""
x offset in plot coordinates
""")
y_origin_offset = Float(help="""
y offset in plot coordinates
""")
initial_resolution = Float(help="""
resolution (plot_units / pixels) of minimum zoom level of tileset projection. None to auto-compute.
""")
class MercatorTileSource(TileSource):
"""``MercatorTileSource`` is not generally useful to instantiate on its own, but is the parent class of mercator tile services (e.g. ``WMTSTileSource``).
"""
_args = ('url', 'tile_size', 'min_zoom', 'max_zoom', 'x_origin_offset', 'y_origin_offset', 'extra_url_vars', 'initial_resolution')
x_origin_offset = Override(default=20037508.34)
y_origin_offset = Override(default=20037508.34)
initial_resolution = Override(default=156543.03392804097)
wrap_around = Bool(default=True, help="""
Enables continuous horizontal panning by wrapping the x-axis based on bounds of map.
Note that axis coordinates are not wrapped. To toggle axis label visibility, use ``plot.axis.visible = False``.
""")
class TMSTileSource(MercatorTileSource):
"""
The TMSTileSource contains tile config info and provides urls for tiles based on a templated url e.g. ``http://your.tms.server.host/{Z}/{X}/{Y}.png``.
The defining feature of TMS is the tile-origin in located at the bottom-left.
The TMSTileSource can also be helpful in implementing tile renderers for custom tile sets, including non-spatial datasets.
"""
pass
class WMTSTileSource(MercatorTileSource):
"""
The ``WMTSTileSource`` behaves much like ``TMSTileSource`` but has its tile-origin in the top-left.
This is the most common used tile source for web mapping applications.
Such companies as Google, MapQuest, Stamen, Esri, and OpenStreetMap provide service which use the WMTS specification
e.g. ``http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png``.
"""
pass
class QUADKEYTileSource(MercatorTileSource):
"""
The QUADKEYTileSource has the same tile origin as the WMTSTileSource but requests tiles using a `quadkey` argument instead of X, Y, Z
e.g. ``http://your.quadkey.tile.host/{Q}.png``
"""
pass
class BBoxTileSource(MercatorTileSource):
"""
The BBoxTileSource has the same default tile origin as the WMTSTileSource but requested tiles use a ``{XMIN}``, ``{YMIN}``,
``{XMAX}``, ``{YMAX}`` e.g. ``http://your.custom.tile.service?bbox={XMIN},{YMIN},{XMAX},{YMAX}``.
"""
use_latlon = Bool(default=False, help="""
Flag which indicates option to output {XMIN},{YMIN},{XMAX},{YMAX} in meters or latitude and longitude.
""")
|
unknown
|
codeparrot/codeparrot-clean
| ||
//
// Code generated by grafana-app-sdk. DO NOT EDIT.
//
package v0alpha1
import (
"encoding/json"
"io"
"github.com/grafana/grafana-app-sdk/resource"
)
// CoreRoleJSONCodec is an implementation of resource.Codec for kubernetes JSON encoding
type CoreRoleJSONCodec struct{}
// Read reads JSON-encoded bytes from `reader` and unmarshals them into `into`
func (*CoreRoleJSONCodec) Read(reader io.Reader, into resource.Object) error {
return json.NewDecoder(reader).Decode(into)
}
// Write writes JSON-encoded bytes into `writer` marshaled from `from`
func (*CoreRoleJSONCodec) Write(writer io.Writer, from resource.Object) error {
return json.NewEncoder(writer).Encode(from)
}
// Interface compliance checks
var _ resource.Codec = &CoreRoleJSONCodec{}
|
go
|
github
|
https://github.com/grafana/grafana
|
apps/iam/pkg/apis/iam/v0alpha1/corerole_codec_gen.go
|
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty
from kivy.clock import Clock
from datamgr import variables, scan
class Binding:
def __init__(self, source, source_attr, target, target_attr):
self.source = source
self.source_attr = source_attr
self.target = target
self.target_attr = target_attr
def update(self, new_value):
setattr(self.target, self.target_attr, str(new_value))
# TODO check if str(new_value) is what I will always need
class RootWidget(BoxLayout):
def __init__(self, **kwargs):
super(RootWidget, self).__init__(**kwargs)
for variable in variables.itervalues():
lbl_name = Label(text=variable.name)
lbl_text = Label(text=variable.text)
lbl_value = Label(text=str(variable.value))
self.add_widget(lbl_name)
self.add_widget(lbl_text)
self.add_widget(lbl_value)
b_text = Binding(variable, 'text', lbl_text, 'text')
b_value = Binding(variable, 'value', lbl_value, 'text')
variable.bindings.append(b_text)
variable.bindings.append(b_value)
class MyApp(App):
def build(self):
rw = RootWidget()
Clock.schedule_interval(scan, 1.0)
return rw
if __name__ == '__main__':
MyApp().run()
|
unknown
|
codeparrot/codeparrot-clean
| ||
import unittest
import _mysql
import MySQLdb
from MySQLdb.constants import FIELD_TYPE
from configdb import connection_factory
import warnings
warnings.simplefilter("ignore")
class TestDBAPISet(unittest.TestCase):
def test_set_equality(self):
self.assertTrue(MySQLdb.STRING == MySQLdb.STRING)
def test_set_inequality(self):
self.assertTrue(MySQLdb.STRING != MySQLdb.NUMBER)
def test_set_equality_membership(self):
self.assertTrue(FIELD_TYPE.VAR_STRING == MySQLdb.STRING)
def test_set_inequality_membership(self):
self.assertTrue(FIELD_TYPE.DATE != MySQLdb.STRING)
class CoreModule(unittest.TestCase):
"""Core _mysql module features."""
def test_NULL(self):
"""Should have a NULL constant."""
self.assertEqual(_mysql.NULL, 'NULL')
def test_version(self):
"""Version information sanity."""
self.assertTrue(isinstance(_mysql.__version__, str))
self.assertTrue(isinstance(_mysql.version_info, tuple))
self.assertEqual(len(_mysql.version_info), 5)
def test_client_info(self):
self.assertTrue(isinstance(_mysql.get_client_info(), str))
def test_thread_safe(self):
self.assertTrue(isinstance(_mysql.thread_safe(), int))
class CoreAPI(unittest.TestCase):
"""Test _mysql interaction internals."""
def setUp(self):
self.conn = connection_factory(use_unicode=True)
def tearDown(self):
self.conn.close()
def test_thread_id(self):
tid = self.conn.thread_id()
self.assertTrue(isinstance(tid, int),
"thread_id didn't return an int.")
self.assertRaises(TypeError, self.conn.thread_id, ('evil',),
"thread_id shouldn't accept arguments.")
def test_affected_rows(self):
self.assertEquals(self.conn.affected_rows(), 0,
"Should return 0 before we do anything.")
#def test_debug(self):
## FIXME Only actually tests if you lack SUPER
#self.assertRaises(MySQLdb.OperationalError,
#self.conn.dump_debug_info)
def test_charset_name(self):
self.assertTrue(isinstance(self.conn.character_set_name(), str),
"Should return a string.")
def test_host_info(self):
self.assertTrue(isinstance(self.conn.get_host_info(), str),
"Should return a string.")
def test_proto_info(self):
self.assertTrue(isinstance(self.conn.get_proto_info(), int),
"Should return an int.")
def test_server_info(self):
self.assertTrue(isinstance(self.conn.get_server_info(), str),
"Should return an str.")
|
unknown
|
codeparrot/codeparrot-clean
| ||
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the CockroachDB Software License
// included in the /LICENSE file.
package sql
import (
"context"
"testing"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql/parser"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessionmutator"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/redact"
"github.com/stretchr/testify/require"
)
func TestHideNonVirtualTableNameFunc(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s := cluster.MakeTestingClusterSettings()
vt, err := NewVirtualSchemaHolder(context.Background(), s)
if err != nil {
t.Fatal(err)
}
tableNameFunc := hideNonVirtualTableNameFunc(vt)
testData := []struct {
stmt string
expected string
}{
{`SELECT * FROM a.b`,
`SELECT * FROM _`},
{`SELECT * FROM pg_type`,
`SELECT * FROM _`},
{`SELECT * FROM pg_catalog.pg_type`,
`SELECT * FROM pg_catalog.pg_type`},
}
for _, test := range testData {
stmt, err := parser.ParseOne(test.stmt)
if err != nil {
t.Fatal(err)
}
f := tree.NewFmtCtx(
tree.FmtSimple,
tree.FmtReformatTableNames(tableNameFunc),
)
f.FormatNode(stmt.AST)
actual := f.CloseAndGetString()
require.Equal(t, test.expected, actual)
}
}
func TestMaybeHashAppName(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
secret := "secret"
for _, tc := range []struct {
name string
appName string
expected string
}{
{
"basic app name is hashed",
"my_app",
"a4bc27b7",
},
{
"internal app name is not hashed",
"$ internal_app",
"$ internal_app",
},
{
"delegated app name is hashed",
"$$ my_app",
"$$ 9a7e689f",
},
{
"delegated and reportable app name is not hashed",
"$$ $ internal_app",
"$$ $ internal_app",
},
} {
t.Run(tc.name, func(t *testing.T) {
out := MaybeHashAppName(tc.appName, secret)
require.Equal(t, tc.expected, out)
})
}
}
// TestSessionDefaultsSafeFormat tests the redacted output of SessionDefaults.
func TestSessionDefaultsSafeFormat(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
session := sessionmutator.SessionDefaults(make(map[string]string))
session["database"] = "test"
session["statement_timeout"] = "250ms"
session["disallow_full_table_scans"] = "true"
require.Contains(t, redact.Sprint(session), "database=‹test›")
require.Contains(t, redact.Sprint(session).Redact(), "statement_timeout=‹×›")
}
|
go
|
github
|
https://github.com/cockroachdb/cockroach
|
pkg/sql/exec_util_test.go
|
/*
Copyright 2015 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package container
import (
"errors"
"fmt"
"testing"
"time"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
)
func TestPodSyncResult(t *testing.T) {
okResults := []*SyncResult{
NewSyncResult(StartContainer, "container_0"),
NewSyncResult(SetupNetwork, "pod"),
}
errResults := []*SyncResult{
NewSyncResult(KillContainer, "container_1"),
NewSyncResult(TeardownNetwork, "pod"),
}
errResults[0].Fail(errors.New("error_0"), "message_0")
errResults[1].Fail(errors.New("error_1"), "message_1")
// If the PodSyncResult doesn't contain error result, it should not be error
result := PodSyncResult{}
result.AddSyncResult(okResults...)
if result.Error() != nil {
t.Errorf("PodSyncResult should not be error: %v", result)
}
// If the PodSyncResult contains error result, it should be error
result = PodSyncResult{}
result.AddSyncResult(okResults...)
result.AddSyncResult(errResults...)
if result.Error() == nil {
t.Errorf("PodSyncResult should be error: %v", result)
}
// If the PodSyncResult is failed, it should be error
result = PodSyncResult{}
result.AddSyncResult(okResults...)
result.Fail(errors.New("error"))
if result.Error() == nil {
t.Errorf("PodSyncResult should be error: %v", result)
}
// If the PodSyncResult is added an error PodSyncResult, it should be error
errResult := PodSyncResult{}
errResult.AddSyncResult(errResults...)
result = PodSyncResult{}
result.AddSyncResult(okResults...)
result.AddPodSyncResult(errResult)
if result.Error() == nil {
t.Errorf("PodSyncResult should be error: %v", result)
}
}
// myCustomError is a custom error type for testing.
type myCustomError struct {
msg string
}
func (e *myCustomError) Error() string {
return e.msg
}
func TestPodSyncResultPreservesOriginalErrorType(t *testing.T) {
t.Run("with custom error in SyncResult", func(t *testing.T) {
customErr := &myCustomError{msg: "a special error"}
syncResult := NewSyncResult(KillContainer, "container_1")
syncResult.Fail(customErr, "a special message")
result := &PodSyncResult{
SyncResults: []*SyncResult{syncResult},
}
aggErr := result.Error()
if aggErr == nil {
t.Fatal("expected an aggregate error, but got nil")
}
var ae utilerrors.Aggregate
if !errors.As(aggErr, &ae) {
t.Fatalf("expected an aggregate error, but got %q", aggErr)
}
errs := ae.Errors()
foundCustomErr := false
for _, err := range errs {
var ce *myCustomError
if errors.As(err, &ce) && ce == customErr {
foundCustomErr = true
}
}
if !foundCustomErr {
t.Errorf("expected custom error not found in aggregate error. got %q, want %q", aggErr, customErr)
}
})
t.Run("with custom error in SyncError", func(t *testing.T) {
customErr := &myCustomError{msg: "a special sync error"}
result := &PodSyncResult{}
result.Fail(customErr)
aggErr := result.Error()
if aggErr == nil {
t.Fatal("expected an aggregate error for SyncError, but got nil")
}
var ae utilerrors.Aggregate
if !errors.As(aggErr, &ae) {
t.Fatalf("expected an aggregate error, but got %q", aggErr)
}
errs := ae.Errors()
foundCustomErr := false
for _, err := range errs {
var ce *myCustomError
if errors.As(err, &ce) && ce == customErr {
foundCustomErr = true
}
}
if !foundCustomErr {
t.Errorf("expected custom error not found in aggregate error. got %q, want %q", aggErr, customErr)
}
})
}
func TestMinBackoffExpiration(t *testing.T) {
now := time.Now()
testCases := []struct {
name string
err error
expectedBackoff time.Time
expectedFound bool
}{
{
name: "nil error",
err: nil,
expectedBackoff: time.Time{},
expectedFound: false,
},
{
name: "simple error",
err: errors.New("generic error"),
expectedBackoff: time.Time{},
expectedFound: false,
},
{
name: "BackoffError",
err: NewBackoffError(errors.New("backoff"), now.Add(5*time.Second)),
expectedBackoff: now.Add(5 * time.Second),
expectedFound: true,
},
{
name: "wrapped BackoffError",
err: fmt.Errorf("wrapped: %w", NewBackoffError(errors.New("backoff"), now.Add(3*time.Second))),
expectedBackoff: now.Add(3 * time.Second),
expectedFound: true,
},
{
name: "aggregate with no BackoffError",
err: utilerrors.NewAggregate([]error{errors.New("err1"), errors.New("err2")}),
expectedBackoff: time.Time{},
expectedFound: false,
},
{
name: "aggregate with one BackoffError",
err: utilerrors.NewAggregate([]error{
errors.New("err1"),
NewBackoffError(errors.New("backoff"), now.Add(7*time.Second)),
}),
expectedBackoff: now.Add(7 * time.Second),
expectedFound: true,
},
{
name: "aggregate with multiple BackoffErrors, returns minimum",
err: utilerrors.NewAggregate([]error{
NewBackoffError(errors.New("backoff1"), now.Add(10*time.Second)),
NewBackoffError(errors.New("backoff2"), now.Add(3*time.Second)),
errors.New("err1"),
NewBackoffError(errors.New("backoff3"), now.Add(5*time.Second)),
}),
expectedBackoff: now.Add(3 * time.Second),
expectedFound: true,
},
{
name: "wrapped aggregate with BackoffError",
err: fmt.Errorf("wrapped: %w", utilerrors.NewAggregate([]error{
NewBackoffError(errors.New("backoff1"), now.Add(10*time.Second)),
NewBackoffError(errors.New("backoff2"), now.Add(3*time.Second)),
})),
expectedBackoff: now.Add(3 * time.Second),
expectedFound: true,
},
{
name: "nested aggregate with BackoffError",
err: utilerrors.NewAggregate([]error{
errors.New("err1"),
utilerrors.NewAggregate([]error{
NewBackoffError(errors.New("backoff nested"), now.Add(2*time.Second)),
}),
NewBackoffError(errors.New("backoff outer"), now.Add(4*time.Second)),
}),
expectedBackoff: now.Add(2 * time.Second),
expectedFound: true,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
backoff, found := MinBackoffExpiration(tc.err)
if found != tc.expectedFound {
t.Errorf("expected found=%t, got %t", tc.expectedFound, found)
}
if !backoff.Equal(tc.expectedBackoff) {
t.Errorf("expected backoff=%v, got %v", tc.expectedBackoff, backoff)
}
})
}
}
|
go
|
github
|
https://github.com/kubernetes/kubernetes
|
pkg/kubelet/container/sync_result_test.go
|
#!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = """
module: na_ontap_net_port
short_description: NetApp ONTAP network ports.
extends_documentation_fragment:
- netapp.na_ontap
version_added: '2.6'
author: NetApp Ansible Team (@carchi8py) <ng-ansibleteam@netapp.com>
description:
- Modify a ONTAP network port.
options:
state:
description:
- Whether the specified net port should exist or not.
choices: ['present']
default: present
node:
description:
- Specifies the name of node.
required: true
port:
description:
- Specifies the name of port.
required: true
mtu:
description:
- Specifies the maximum transmission unit (MTU) reported by the port.
autonegotiate_admin:
description:
- Enables or disables Ethernet auto-negotiation of speed,
duplex and flow control.
duplex_admin:
description:
- Specifies the user preferred duplex setting of the port.
- Valid values auto, half, full
speed_admin:
description:
- Specifies the user preferred speed setting of the port.
flowcontrol_admin:
description:
- Specifies the user preferred flow control setting of the port.
ipspace:
description:
- Specifies the port's associated IPspace name.
- The 'Cluster' ipspace is reserved for cluster ports.
"""
EXAMPLES = """
- name: Modify Net Port
na_ontap_net_port:
state=present
username={{ netapp_username }}
password={{ netapp_password }}
hostname={{ netapp_hostname }}
node={{ Vsim server name }}
port=e0d
autonegotiate_admin=true
"""
RETURN = """
"""
from ansible.module_utils.basic import AnsibleModule
import ansible.module_utils.netapp as netapp_utils
HAS_NETAPP_LIB = netapp_utils.has_netapp_lib()
class NetAppOntapNetPort(object):
"""
Modify a Net port
"""
def __init__(self):
"""
Initialize the Ontap Net Port Class
"""
self.argument_spec = netapp_utils.na_ontap_host_argument_spec()
self.argument_spec.update(dict(
state=dict(required=False, choices=['present'], default='present'),
node=dict(required=True, type="str"),
port=dict(required=True, type="str"),
mtu=dict(required=False, type="str", default=None),
autonegotiate_admin=dict(required=False, type="str", default=None),
duplex_admin=dict(required=False, type="str", default=None),
speed_admin=dict(required=False, type="str", default=None),
flowcontrol_admin=dict(required=False, type="str", default=None),
ipspace=dict(required=False, type="str", default=None),
))
self.module = AnsibleModule(
argument_spec=self.argument_spec,
supports_check_mode=True
)
p = self.module.params
# set up state variables
self.state = p['state']
self.node = p['node']
self.port = p['port']
# the following option are optional, but at least one need to be set
self.mtu = p['mtu']
self.autonegotiate_admin = p["autonegotiate_admin"]
self.duplex_admin = p["duplex_admin"]
self.speed_admin = p["speed_admin"]
self.flowcontrol_admin = p["flowcontrol_admin"]
if HAS_NETAPP_LIB is False:
self.module.fail_json(
msg="the python NetApp-Lib module is required")
else:
self.server = netapp_utils.setup_na_ontap_zapi(module=self.module)
return
def get_net_port(self):
"""
Return details about the net port
:return: Details about the net port. None if not found.
:rtype: dict
"""
net_port_info = netapp_utils.zapi.NaElement('net-port-get-iter')
net_port_attributes = netapp_utils.zapi.NaElement('net-port-info')
net_port_attributes.add_new_child('node', self.node)
net_port_attributes.add_new_child('port', self.port)
query = netapp_utils.zapi.NaElement('query')
query.add_child_elem(net_port_attributes)
net_port_info.add_child_elem(query)
result = self.server.invoke_successfully(net_port_info, True)
return_value = None
if result.get_child_by_name('num-records') and \
int(result.get_child_content('num-records')) >= 1:
net_port_attributes = result.get_child_by_name('attributes-list').\
get_child_by_name('net-port-info')
return_value = {
'node': net_port_attributes.get_child_content('node'),
'port': net_port_attributes.get_child_content('port'),
'mtu': net_port_attributes.get_child_content('mtu'),
'autonegotiate_admin': net_port_attributes.get_child_content(
'is-administrative-auto-negotiate'),
'duplex_admin': net_port_attributes.get_child_content(
'administrative-duplex'),
'speed_admin': net_port_attributes.get_child_content(
'administrative-speed'),
'flowcontrol_admin': net_port_attributes.get_child_content(
'administrative-flowcontrol'),
}
return return_value
def modify_net_port(self):
"""
Modify a port
"""
port_obj = netapp_utils.zapi.NaElement('net-port-modify')
port_obj.add_new_child("node", self.node)
port_obj.add_new_child("port", self.port)
# The following options are optional.
# We will only call them if they are not set to None
if self.mtu:
port_obj.add_new_child("mtu", self.mtu)
if self.autonegotiate_admin:
port_obj.add_new_child(
"is-administrative-auto-negotiate", self.autonegotiate_admin)
if self.duplex_admin:
port_obj.add_new_child("administrative-duplex", self.duplex_admin)
if self.speed_admin:
port_obj.add_new_child("administrative-speed", self.speed_admin)
if self.flowcontrol_admin:
port_obj.add_new_child(
"administrative-flowcontrol", self.flowcontrol_admin)
self.server.invoke_successfully(port_obj, True)
def apply(self):
"""
Run Module based on play book
"""
changed = False
net_port_exists = False
results = netapp_utils.get_cserver(self.server)
cserver = netapp_utils.setup_na_ontap_zapi(
module=self.module, vserver=results)
netapp_utils.ems_log_event("na_ontap_net_port", cserver)
net_port_details = self.get_net_port()
if net_port_details:
net_port_exists = True
if self.state == 'present':
if (self.mtu and self.mtu != net_port_details['mtu']) or \
(self.autonegotiate_admin and
self.autonegotiate_admin != net_port_details['autonegotiate_admin']) or \
(self.duplex_admin and
self.duplex_admin != net_port_details['duplex_admin']) or \
(self.speed_admin and
self.speed_admin != net_port_details['speed_admin']) or \
(self.flowcontrol_admin and
self.flowcontrol_admin != net_port_details['flowcontrol_admin']):
changed = True
if changed:
if self.module.check_mode:
pass
else:
if self.state == 'present':
if net_port_exists:
self.modify_net_port()
self.module.exit_json(changed=changed)
def main():
"""
Create the NetApp Ontap Net Port Object and modify it
"""
obj = NetAppOntapNetPort()
obj.apply()
if __name__ == '__main__':
main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
# loop_count is not utilized since `i` is involved in the script
benchmark:
vm_poly_method_ov: |
class C1
def m
1
end
end
class C2
def m
2
end
end
o1 = C1.new
o2 = C2.new
i = 0
while i<6_000_000
o = (i % 2 == 0) ? o1 : o2
# o.m; o.m; o.m; o.m; o.m; o.m; o.m; o.m
i += 1
end
loop_count: 1
|
unknown
|
github
|
https://github.com/ruby/ruby
|
benchmark/vm_poly_method_ov.yml
|
#ifndef FT_GLOBAL_INCLUDED
#define FT_GLOBAL_INCLUDED
/* Copyright (c) 2000, 2025, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is designed to work with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have either included with
the program or referenced in the documentation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* Written by Sergei A. Golubchik, who has a shared copyright to this code */
/**
@file include/ft_global.h
Some definitions for full-text indices.
*/
/* #include "myisam.h" */
#include <sys/types.h>
#include "my_base.h"
#include "my_inttypes.h"
#include "mysql/strings/m_ctype.h"
#define HA_FT_MAXBYTELEN 336
#define HA_FT_MAXCHARLEN (HA_FT_MAXBYTELEN / 4)
#define DEFAULT_FTB_SYNTAX "+ -><()~*:\"\"&|"
struct FT_INFO;
struct _ft_vft {
int (*read_next)(FT_INFO *, char *);
float (*find_relevance)(FT_INFO *, uchar *, uint);
void (*close_search)(FT_INFO *);
float (*get_relevance)(FT_INFO *);
void (*reinit_search)(FT_INFO *);
};
struct FT_INFO_EXT;
struct _ft_vft_ext {
uint (*get_version)(); // Extended API version
ulonglong (*get_flags)();
ulonglong (*get_docid)(FT_INFO_EXT *);
ulonglong (*count_matches)(FT_INFO_EXT *);
};
/* Flags for extended FT API */
#define FTS_ORDERED_RESULT (1LL << 1)
#define FTS_DOCID_IN_RESULT (1LL << 2)
#define FTS_DOC_ID_COL_NAME "FTS_DOC_ID"
#define FTS_NGRAM_PARSER_NAME "ngram"
struct FT_INFO {
struct _ft_vft *please; /* INTERCAL style :-) */
};
#ifndef FT_CORE
struct FT_INFO_EXT {
struct _ft_vft *please; /* INTERCAL style :-) */
struct _ft_vft_ext *could_you;
};
#endif
extern const char *ft_stopword_file;
extern const char *ft_precompiled_stopwords[];
extern ulong ft_min_word_len;
extern ulong ft_max_word_len;
extern ulong ft_query_expansion_limit;
extern const char *ft_boolean_syntax;
extern struct st_mysql_ftparser ft_default_parser;
int ft_init_stopwords(void);
void ft_free_stopwords(void);
/**
Operation types, used in FT_HINTS.
*/
enum ft_operation {
FT_OP_UNDEFINED, /** Operation undefined, use of hints is impossible */
FT_OP_NO, /** No operation, single MATCH function */
FT_OP_GT, /** 'Greater than' operation */
FT_OP_GE /** 'Greater than or equal to' operation */
};
#define FT_NL 0 /** Normal mode */
#define FT_BOOL 1 /** Boolean mode */
#define FT_SORTED 2 /** perform internal sorting by rank */
#define FT_EXPAND 4 /** query expansion */
#define FT_NO_RANKING 8 /** skip rank calculation */
/**
Info about FULLTEXT index hints,
passed to the storage engine.
*/
struct ft_hints {
/** FULLTEXT flags, see FT_NL, etc */
uint flags;
/** Operation type */
enum ft_operation op_type;
/** Operation value */
double op_value;
/** LIMIT value, HA_POS_ERROR if not set */
ha_rows limit;
};
FT_INFO *ft_init_search(uint, void *, uint, uchar *, uint, const CHARSET_INFO *,
uchar *);
bool ft_boolean_check_syntax_string(const uchar *);
#endif /* FT_GLOBAL_INCLUDED */
|
c
|
github
|
https://github.com/mysql/mysql-server
|
include/ft_global.h
|
# Standard imports
import unittest
import datetime as pydt
import logging
import uuid
# Our imports
import emission.core.get_database as edb
import emission.storage.pipeline_queries as epq
import emission.core.wrapper.pipelinestate as ewps
class TestPipelineQueries(unittest.TestCase):
def setUp(self):
self.testUUID = uuid.uuid4()
edb.get_pipeline_state_db().remove()
def tearDown(self):
edb.get_pipeline_state_db().remove()
def testStartProcessing(self):
curr_state = epq.get_current_state(self.testUUID, ewps.PipelineStages.USERCACHE)
self.assertIsNone(curr_state)
curr_query = epq.get_time_range_for_stage(self.testUUID, ewps.PipelineStages.USERCACHE)
self.assertEquals(curr_query.timeType, "write_ts")
self.assertIsNone(curr_query.startTs)
self.assertIsNotNone(curr_query.endTs)
new_state = epq.get_current_state(self.testUUID, ewps.PipelineStages.USERCACHE)
self.assertIsNotNone(new_state)
self.assertIsNotNone(new_state.curr_run_ts)
self.assertIsNone(new_state.last_ts_run)
new_state_diff_user = epq.get_current_state(uuid.uuid4(), ewps.PipelineStages.USERCACHE)
self.assertIsNone(new_state_diff_user)
def testStopProcessing(self):
self.testStartProcessing()
TEST_DONE_TS = 999999
epq.mark_stage_done(self.testUUID, ewps.PipelineStages.USERCACHE, TEST_DONE_TS)
final_state = epq.get_current_state(self.testUUID, ewps.PipelineStages.USERCACHE)
self.assertIsNotNone(final_state)
self.assertIsNone(final_state.curr_run_ts)
self.assertIsNotNone(final_state.last_ts_run)
self.assertIsNotNone(final_state.last_processed_ts)
self.assertIsNotNone(final_state.last_processed_ts, TEST_DONE_TS)
def testFailProcessing(self):
self.testStartProcessing()
epq.mark_stage_failed(self.testUUID, ewps.PipelineStages.USERCACHE)
final_state = epq.get_current_state(self.testUUID, ewps.PipelineStages.USERCACHE)
self.assertIsNotNone(final_state)
self.assertIsNone(final_state.curr_run_ts)
self.assertIsNone(final_state.last_ts_run)
def testStartProcessingTwice(self):
self.testStopProcessing()
next_query = epq.get_time_range_for_stage(self.testUUID, ewps.PipelineStages.USERCACHE)
logging.debug("next_query = %s" % next_query)
self.assertEquals(next_query.timeType, "write_ts")
self.assertIsNotNone(next_query.startTs)
self.assertIsNotNone(next_query.endTs)
new_state = epq.get_current_state(self.testUUID, ewps.PipelineStages.USERCACHE)
self.assertIsNotNone(new_state)
self.assertIsNotNone(new_state.curr_run_ts)
self.assertIsNotNone(new_state.last_ts_run)
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
unittest.main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
# Opus/UrbanSim urban simulation software.
# Copyright (C) 2005-2009 University of Washington
# See opus_core/LICENSE
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt, QVariant # these are used so frequently so a shorter name is nicer
class SubmodelStructureEditorModel(QtCore.QAbstractTableModel):
'''
Table model for displaying and editing submodel structures.
Handles <equation> and <nest> (multiple levels of nests are possible).
'''
def __init__(self, project, parent_widget = None):
QtCore.QAbstractTableModel.__init__(self, parent_widget)
# the internal data structure
self._structure = {}
self.HEA
# header constants (values appear as title for columns)
self.HEADER_ID = 'ignore'
self.HEADER_NAME = 'name'
self.HEADER_NUM_SAMPLES = 'number of samples'
self._headers = [self.HEADER_ID, self.HEADER_NAME, self.HEADER_NUM_SAMPLES]
def get_nested_structure(self):
''' convert the internal datastructure to the format used in nested logit models
'nested_structure' argument '''
pass
def structure_from_submodel(self, submodel_node):
''' convert the submodel structure to the internal datastructure '''
pass
# PyQt API
def rowCount(self, parent_index = QtCore.QModelIndex()):
node = parent_index.node
return len(node.findall('nest')) + len(node.findall('equation'))
def columnCount(self, parent = QtCore.QModelIndex()):
return len(self._headers)
def flags(self, index):
if not index.isValid():
return QVariant()
header = self._headers[index.column()]
if header == self.HEADER_VARIABLE:
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable
elif header in [self.HEADER_IGNORE, self.HEADER_FIXED]:
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEditable
elif header ==self.HEADER_DEFINITION:
flags = Qt.ItemIsSelectable
else:
flags = Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsEditable
return flags
def insertRow(self, row, parent_index = QtCore.QModelIndex(), variable_spec_node = None):
self.beginInsertRows(parent_index, row, row)
self._variable_nodes.append(variable_spec_node)
return_val = QtCore.QAbstractItemModel.insertRow(self, row, parent_index)
self.endInsertRows()
self.emit(QtCore.SIGNAL('layoutChanged()'))
return return_val
def removeRow(self, row, parent_index = QtCore.QModelIndex()):
self.beginRemoveRows(parent_index, row, row)
self._variable_nodes.pop(row)
return_val = QtCore.QAbstractItemModel.removeRow(self, row, parent_index)
self.endRemoveRows()
self.emit(QtCore.SIGNAL('layoutChanged()'))
return return_val
def data(self, index, role):
if not index.isValid():
return QVariant()
row = index.row()
header = self._headers[index.column()]
node = self._variable_nodes[row]
# look up the definition once for easy access by multiple roles
if header == self.HEADER_DEFINITION:
dataset, name = get_variable_dataset_and_name(node)
if name == 'constant':
definition = '<built-in constant>'
elif (name, dataset) in self._names_to_definition_nodes:
definition_node = self._names_to_definition_nodes[(name, dataset)]
if definition_node is not None:
definition = definition_node.text or '<empty definition>'
else:
definition = '<unknown definition>'
if role == Qt.DisplayRole:
var_name = get_variable_name(self._variable_nodes[row])
if header == self.HEADER_VARIABLE:
return QVariant(var_name)
if header == self.HEADER_DEFINITION:
return QVariant(definition)
if header == self.HEADER_COEFF_NAME:
if 'coefficient_name' in node.attrib:
return QVariant(node.get('coefficient_name'))
return QVariant(var_name)
if header == self.HEADER_STARTING_VAL:
return QVariant(node.get('starting_value') or '')
if role == Qt.CheckStateRole:
if header == self.HEADER_IGNORE:
return QVariant(Qt.Checked if node.get('ignore') == 'True' else Qt.Unchecked)
if header == self.HEADER_FIXED:
return QVariant(Qt.Checked if node.get('keep_fixed') == 'True' else Qt.Unchecked)
if role == Qt.FontRole:
font = QtGui.QFont()
if header == self.HEADER_VARIABLE:
if node.get('ignore') != 'True':
font.setBold(True)
return QVariant(font)
elif header == self.HEADER_COEFF_NAME and node.get('coefficient_name'):
font.setBold(True)
return QVariant(font)
if role == Qt.ForegroundRole:
# color default values of coefficient name as light gray
if header == self.HEADER_COEFF_NAME:
if 'coefficient_name' not in node.attrib:
return QVariant(QtGui.QColor(Qt.gray))
if role == Qt.ToolTipRole:
if header == self.HEADER_DEFINITION: # defs easily get cramped so show in tool tip as well
return QVariant(definition)
return QVariant()
def setData(self, index, value, role):
if not index.isValid():
return QVariant()
row = index.row()
header = self._headers[index.column()]
node = self._variable_nodes[row]
if role == Qt.CheckStateRole:
val, flag = value.toInt()
is_checked = val == Qt.Checked and flag
if header == self.HEADER_FIXED:
self._set_or_remove_attrib(node, 'keep_fixed', 'True' if is_checked else '')
elif header == self.HEADER_IGNORE:
self._set_or_remove_attrib(node, 'ignore', 'True' if is_checked else '')
if role == Qt.EditRole:
if header == self.HEADER_STARTING_VAL:
# if the user enters an empty string, delete the starting value
# otherwise only change it on a successful conversion to a double
if value.toString() == '' and 'starting_value' in node.attrib:
del node.attrib['starting_value']
else:
value, flag = value.toDouble()
if flag:
node.set('starting_value', str(value))
elif header == self.HEADER_COEFF_NAME:
self._set_or_remove_attrib(node, 'coefficient_name', str(value.toString()))
return True
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self._headers[col])
return QVariant()
def sort_variables_by_name(self):
''' sort all the variables by their variable name '''
compare_by_var_name = lambda x, y: cmp(get_variable_name(x), get_variable_name(y))
self._variable_nodes.sort(compare_by_var_name)
if __name__ == '__main__':
from lxml import etree #@UnresolvedImport
from opus_gui.models_manager.models.variable_selector_table_item import VariableSelectorTableItem
xml = '''
<opus_project>
<general>
<expression_library type="dictionary">
<variable source="Python class" type="variable_definition" use="both" name="zone.ln_distance_to_highway">ln(urbansim_parcel.zone.distance_to_highway)</variable>
<variable source="expression" type="variable_definition" use="model variable" name="parcel.land_price">urbansim.land_price * 5</variable>
<variable source="expression" type="variable_definition" use="model variable" name="zone.ignore_me">urbansim.ignore_with_reeeeeeeeeeeeeeeeeeeeeeaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaallllllllllllllllllllllllllllllllyyyyyyyyyyy_loooooooooooooooooooooooooooooooong_name</variable>
<variable source="expression" type="variable_definition" use="model variable" name="dataset1.variable">urbansim.dataset1.somevariable_def</variable>
<variable source="expression" type="variable_definition" use="model variable" name="dataset2.variable">10 - ln(urbansim.dataset2.somevariable_def)</variable>
<variable source="Python class" type="variable_definition" use="both" name="zone.population_per_acre">urbansim_parcel.zone.population_per_acre</variable>
<variable source="expression" type="variable_definition" use="model variable" name="constant">constant</variable>
<variable source="expression" type="variable_definition" use="model variable" name="building.people_in_building">10 * urbansim.building.people_in_building</variable>
<variable source="expression" type="variable_definition" use="model variable" name=".add me">urbansim.zone.ln_constraint</variable>
</expression_library>
</general>
<variable_list type="selectable_list">
<variable_spec name=".ln_distance_to_highway" keep_fixed="True" starting_value="42.0" coefficient_name="dth" type="variable" />
<variable_spec name=".land_price" keep_fixed="False" type="variable" />
<variable_spec name=".ignore_me" type="variable" ignore="True"/>
<variable_spec name="constant" type="variable" />
<variable_spec name="dataset2.variable" type="variable" />
</variable_list>
</opus_project>
'''
app = QtGui.QApplication([], True)
p = MockupOpusProject(xml)
f = QtGui.QFrame()
l = QtGui.QVBoxLayout()
f.setLayout(l)
tv = QtGui.QTableView()
m = VariableSelectorTableModel(p)
v_defs = p.findall('expression_library/variable')
m.init_for_variable_node_list(p.find('variable_list'))
tv.setModel(m)
l.addWidget(QtGui.QLabel('Hello'))
l.addWidget(tv)
pb = QtGui.QPushButton('reload')
lbl = QtGui.QLabel()
def update_text():
text = ''
for v in m._variable_nodes:
text = text + etree.tostring(v, pretty_print=True)
lbl.setText(text)
def add_variable():
node = p.find('variables/variable', name='add me')
m.add_selection_for_variable_node(node)
pb.connect(pb, QtCore.SIGNAL('released()'), update_text)
pb2 = QtGui.QPushButton('add')
pb2.connect(pb2, QtCore.SIGNAL('released()'), add_variable)
l.addWidget(pb)
l.addWidget(pb2)
l.addWidget(lbl)
f.show()
f.resize(QtCore.QSize(640, 480))
i = VariableSelectorTableItem(tv)
tv.setItemDelegate(i)
tv.setSelectionBehavior(tv.SelectRows)
tv.resizeColumnToContents(0)
tv.resizeColumnToContents(1)
tv.resizeRowsToContents()
tv.resizeColumnToContents(4)
tv.horizontalHeader().setStretchLastSection(True)
tv.verticalHeader().hide()
update_text()
app.exec_()
|
unknown
|
codeparrot/codeparrot-clean
| ||
"""
Copyright (C) 2016 Quinn D Granfor <spootdev@gmail.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2, as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License version 2 for more details.
You should have received a copy of the GNU General Public License
version 2 along with this program; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.
"""
import os
import signal
import subprocess
import sys
from common import common_logging_elasticsearch_httpx
sys.path.append('.')
from common import common_network_mediakraken
class TestSubprogramBroadcast:
"""
Test broadcast
"""
def __init__(self):
"""
Class init
"""
self.proc_broadcast = None
@classmethod
def setup_class(self):
# fire up broadcast server
self.proc_broadcast = subprocess.Popen(['python3', './subprogram_broadcast.py'],
shell=False)
common_logging_elasticsearch_httpx.com_es_httpx_post(message_type='info', message_text=
{'stuff': "PID: %s" % self.proc_broadcast.pid})
@classmethod
def teardown_class(self):
os.kill(self.proc_broadcast.pid, signal.SIGTERM)
def test_sub_broadcast(self):
"""
Test function
"""
common_network_mediakraken.com_net_mediakraken_find_server()
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: UTF-8 -*-
# Copyright (C) 2007 Sylvain Taverne <taverne.sylvain@gmail.com>
# Copyright (C) 2007, 2009 J. David Ibáñez <jdavid.ibp@gmail.com>
# Copyright (C) 2008 Romain Gauthier <romain.gauthier@itaapy.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import from itools
from odf import ODFFile, ODTFile, ODPFile, ODSFile
from oo import SXWFile, SXCFile, SXIFile
import schema
__all__ = [
# Opend Document Format
'ODFFile',
'ODTFile',
'ODPFile',
'ODSFile',
# Open Office 1.0
'SXWFile',
'SXCFile',
'SXIFile',
]
|
unknown
|
codeparrot/codeparrot-clean
| ||
"""Tests for letsencrypt.plugins.webroot."""
import errno
import os
import shutil
import stat
import tempfile
import unittest
import mock
from acme import challenges
from acme import jose
from letsencrypt import achallenges
from letsencrypt import errors
from letsencrypt.tests import acme_util
from letsencrypt.tests import test_util
KEY = jose.JWKRSA.load(test_util.load_vector("rsa512_key.pem"))
class AuthenticatorTest(unittest.TestCase):
"""Tests for letsencrypt.plugins.webroot.Authenticator."""
achall = achallenges.KeyAuthorizationAnnotatedChallenge(
challb=acme_util.HTTP01_P, domain="thing.com", account_key=KEY)
def setUp(self):
from letsencrypt.plugins.webroot import Authenticator
self.path = tempfile.mkdtemp()
self.validation_path = os.path.join(
self.path, ".well-known", "acme-challenge",
"ZXZhR3hmQURzNnBTUmIyTEF2OUlaZjE3RHQzanV4R0orUEN0OTJ3citvQQ")
self.config = mock.MagicMock(webroot_path=self.path,
webroot_map={"thing.com": self.path})
self.auth = Authenticator(self.config, "webroot")
def tearDown(self):
shutil.rmtree(self.path)
def test_more_info(self):
more_info = self.auth.more_info()
self.assertTrue(isinstance(more_info, str))
self.assertTrue(self.path in more_info)
def test_add_parser_arguments(self):
add = mock.MagicMock()
self.auth.add_parser_arguments(add)
self.assertEqual(0, add.call_count) # args moved to cli.py!
def test_prepare_bad_root(self):
self.config.webroot_path = os.path.join(self.path, "null")
self.config.webroot_map["thing.com"] = self.config.webroot_path
self.assertRaises(errors.PluginError, self.auth.prepare)
def test_prepare_missing_root(self):
self.config.webroot_path = None
self.config.webroot_map = {}
self.assertRaises(errors.PluginError, self.auth.prepare)
def test_prepare_full_root_exists(self):
# prepare() has already been called once in setUp()
self.auth.prepare() # shouldn't raise any exceptions
def test_prepare_reraises_other_errors(self):
self.auth.full_path = os.path.join(self.path, "null")
permission_canary = os.path.join(self.path, "rnd")
with open(permission_canary, "w") as f:
f.write("thingimy")
os.chmod(self.path, 0o000)
try:
open(permission_canary, "r")
print "Warning, running tests as root skips permissions tests..."
except IOError:
# ok, permissions work, test away...
self.assertRaises(errors.PluginError, self.auth.prepare)
os.chmod(self.path, 0o700)
@mock.patch("letsencrypt.plugins.webroot.os.chown")
def test_failed_chown_eacces(self, mock_chown):
mock_chown.side_effect = OSError(errno.EACCES, "msg")
self.auth.prepare() # exception caught and logged
@mock.patch("letsencrypt.plugins.webroot.os.chown")
def test_failed_chown_not_eacces(self, mock_chown):
mock_chown.side_effect = OSError()
self.assertRaises(errors.PluginError, self.auth.prepare)
def test_prepare_permissions(self):
self.auth.prepare()
# Remove exec bit from permission check, so that it
# matches the file
self.auth.perform([self.achall])
path_permissions = stat.S_IMODE(os.stat(self.validation_path).st_mode)
self.assertEqual(path_permissions, 0o644)
# Check permissions of the directories
for dirpath, dirnames, _ in os.walk(self.path):
for directory in dirnames:
full_path = os.path.join(dirpath, directory)
dir_permissions = stat.S_IMODE(os.stat(full_path).st_mode)
self.assertEqual(dir_permissions, 0o755)
parent_gid = os.stat(self.path).st_gid
parent_uid = os.stat(self.path).st_uid
self.assertEqual(os.stat(self.validation_path).st_gid, parent_gid)
self.assertEqual(os.stat(self.validation_path).st_uid, parent_uid)
def test_perform_missing_path(self):
self.auth.prepare()
missing_achall = achallenges.KeyAuthorizationAnnotatedChallenge(
challb=acme_util.HTTP01_P, domain="thing2.com", account_key=KEY)
self.assertRaises(
errors.PluginError, self.auth.perform, [missing_achall])
self.auth.full_roots[self.achall.domain] = 'null'
self.assertRaises(
errors.PluginError, self.auth.perform, [self.achall])
def test_perform_cleanup(self):
self.auth.prepare()
responses = self.auth.perform([self.achall])
self.assertEqual(1, len(responses))
self.assertTrue(os.path.exists(self.validation_path))
with open(self.validation_path) as validation_f:
validation = validation_f.read()
self.assertTrue(
challenges.KeyAuthorizationChallengeResponse(
key_authorization=validation).verify(
self.achall.chall, KEY.public_key()))
self.auth.cleanup([self.achall])
self.assertFalse(os.path.exists(self.validation_path))
if __name__ == "__main__":
unittest.main() # pragma: no cover
|
unknown
|
codeparrot/codeparrot-clean
| ||
/* Copyright 2015 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_UTIL_H_
#define TENSORFLOW_CORE_UTIL_UTIL_H_
#include <string>
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/platform/cpu_info.h"
namespace tensorflow {
// If op_name has '/' in it, then return everything before the first '/'.
// Otherwise return empty string.
absl::string_view NodeNamePrefix(absl::string_view op_name);
// If op_name has '/' in it, then return everything before the last '/'.
// Otherwise return empty string.
absl::string_view NodeNameFullPrefix(absl::string_view op_name);
class MovingAverage {
public:
explicit MovingAverage(int window);
~MovingAverage();
void Clear();
double GetAverage() const;
void AddValue(double v);
private:
const int window_; // Max size of interval
double sum_; // Sum over interval
double* data_; // Actual data values
int head_; // Offset of the newest statistic in data_
int count_; // # of valid data elements in window
};
// Returns a string printing bytes in ptr[0..n). The output looks
// like "00 01 ef cd cd ef".
std::string PrintMemory(const char* ptr, size_t n);
// Given a flattened index into a tensor, computes a string s so that
// StrAppend("tensor", s) is a Python indexing expression. E.g.,
// "tensor", "tensor[i]", "tensor[i, j]", etc.
std::string SliceDebugString(const TensorShape& shape, int64_t flat);
// Check if MKL is enabled in runtime
bool IsMKLEnabled();
// Flag a warning if input type is unsupported on CPU when oneDNN is enabled
void DataTypeUnsupportedWarning(const DataType& dt);
// Check if input type is supported on CPU when oneDNN is enabled
bool IsDataTypeSupportedByOneDNNOnThisCPU(const DataType& dt);
// Check if input type supports AMX on CPU when oneDNN is enabled
bool IsAMXDataTypeSupportedByOneDNNOnThisCPU(const DataType& dt);
bool IsAVXConvertSupportedByOneDNNOnThisCPU();
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_UTIL_H_
|
c
|
github
|
https://github.com/tensorflow/tensorflow
|
tensorflow/core/util/util.h
|
#include "test/jemalloc_test.h"
/*
* If we're e.g. in debug mode, we *never* enter the fast path, and so shouldn't
* be asserting that we're on one.
*/
static bool originally_fast;
static int data_cleanup_count;
void
data_cleanup(int *data) {
if (data_cleanup_count == 0) {
expect_x_eq(*data, MALLOC_TSD_TEST_DATA_INIT,
"Argument passed into cleanup function should match tsd "
"value");
}
++data_cleanup_count;
/*
* Allocate during cleanup for two rounds, in order to assure that
* jemalloc's internal tsd reinitialization happens.
*/
bool reincarnate = false;
switch (*data) {
case MALLOC_TSD_TEST_DATA_INIT:
*data = 1;
reincarnate = true;
break;
case 1:
*data = 2;
reincarnate = true;
break;
case 2:
return;
default:
not_reached();
}
if (reincarnate) {
void *p = mallocx(1, 0);
expect_ptr_not_null(p, "Unexpeced mallocx() failure");
dallocx(p, 0);
}
}
static void *
thd_start(void *arg) {
int d = (int)(uintptr_t)arg;
void *p;
/*
* Test free before tsd init -- the free fast path (which does not
* explicitly check for NULL) has to tolerate this case, and fall back
* to free_default.
*/
free(NULL);
tsd_t *tsd = tsd_fetch();
expect_x_eq(tsd_test_data_get(tsd), MALLOC_TSD_TEST_DATA_INIT,
"Initial tsd get should return initialization value");
p = malloc(1);
expect_ptr_not_null(p, "Unexpected malloc() failure");
tsd_test_data_set(tsd, d);
expect_x_eq(tsd_test_data_get(tsd), d,
"After tsd set, tsd get should return value that was set");
d = 0;
expect_x_eq(tsd_test_data_get(tsd), (int)(uintptr_t)arg,
"Resetting local data should have no effect on tsd");
tsd_test_callback_set(tsd, &data_cleanup);
free(p);
return NULL;
}
TEST_BEGIN(test_tsd_main_thread) {
thd_start((void *)(uintptr_t)0xa5f3e329);
}
TEST_END
TEST_BEGIN(test_tsd_sub_thread) {
thd_t thd;
data_cleanup_count = 0;
thd_create(&thd, thd_start, (void *)MALLOC_TSD_TEST_DATA_INIT);
thd_join(thd, NULL);
/*
* We reincarnate twice in the data cleanup, so it should execute at
* least 3 times.
*/
expect_x_ge(data_cleanup_count, 3,
"Cleanup function should have executed multiple times.");
}
TEST_END
static void *
thd_start_reincarnated(void *arg) {
tsd_t *tsd = tsd_fetch();
assert(tsd);
void *p = malloc(1);
expect_ptr_not_null(p, "Unexpected malloc() failure");
/* Manually trigger reincarnation. */
expect_ptr_not_null(tsd_arena_get(tsd),
"Should have tsd arena set.");
tsd_cleanup((void *)tsd);
expect_ptr_null(*tsd_arenap_get_unsafe(tsd),
"TSD arena should have been cleared.");
expect_u_eq(tsd_state_get(tsd), tsd_state_purgatory,
"TSD state should be purgatory\n");
free(p);
expect_u_eq(tsd_state_get(tsd), tsd_state_reincarnated,
"TSD state should be reincarnated\n");
p = mallocx(1, MALLOCX_TCACHE_NONE);
expect_ptr_not_null(p, "Unexpected malloc() failure");
expect_ptr_null(*tsd_arenap_get_unsafe(tsd),
"Should not have tsd arena set after reincarnation.");
free(p);
tsd_cleanup((void *)tsd);
expect_ptr_null(*tsd_arenap_get_unsafe(tsd),
"TSD arena should have been cleared after 2nd cleanup.");
return NULL;
}
TEST_BEGIN(test_tsd_reincarnation) {
thd_t thd;
thd_create(&thd, thd_start_reincarnated, NULL);
thd_join(thd, NULL);
}
TEST_END
typedef struct {
atomic_u32_t phase;
atomic_b_t error;
} global_slow_data_t;
static void *
thd_start_global_slow(void *arg) {
/* PHASE 0 */
global_slow_data_t *data = (global_slow_data_t *)arg;
free(mallocx(1, 0));
tsd_t *tsd = tsd_fetch();
/*
* No global slowness has happened yet; there was an error if we were
* originally fast but aren't now.
*/
atomic_store_b(&data->error, originally_fast && !tsd_fast(tsd),
ATOMIC_SEQ_CST);
atomic_store_u32(&data->phase, 1, ATOMIC_SEQ_CST);
/* PHASE 2 */
while (atomic_load_u32(&data->phase, ATOMIC_SEQ_CST) != 2) {
}
free(mallocx(1, 0));
atomic_store_b(&data->error, tsd_fast(tsd), ATOMIC_SEQ_CST);
atomic_store_u32(&data->phase, 3, ATOMIC_SEQ_CST);
/* PHASE 4 */
while (atomic_load_u32(&data->phase, ATOMIC_SEQ_CST) != 4) {
}
free(mallocx(1, 0));
atomic_store_b(&data->error, tsd_fast(tsd), ATOMIC_SEQ_CST);
atomic_store_u32(&data->phase, 5, ATOMIC_SEQ_CST);
/* PHASE 6 */
while (atomic_load_u32(&data->phase, ATOMIC_SEQ_CST) != 6) {
}
free(mallocx(1, 0));
/* Only one decrement so far. */
atomic_store_b(&data->error, tsd_fast(tsd), ATOMIC_SEQ_CST);
atomic_store_u32(&data->phase, 7, ATOMIC_SEQ_CST);
/* PHASE 8 */
while (atomic_load_u32(&data->phase, ATOMIC_SEQ_CST) != 8) {
}
free(mallocx(1, 0));
/*
* Both decrements happened; we should be fast again (if we ever
* were)
*/
atomic_store_b(&data->error, originally_fast && !tsd_fast(tsd),
ATOMIC_SEQ_CST);
atomic_store_u32(&data->phase, 9, ATOMIC_SEQ_CST);
return NULL;
}
TEST_BEGIN(test_tsd_global_slow) {
global_slow_data_t data = {ATOMIC_INIT(0), ATOMIC_INIT(false)};
/*
* Note that the "mallocx" here (vs. malloc) is important, since the
* compiler is allowed to optimize away free(malloc(1)) but not
* free(mallocx(1)).
*/
free(mallocx(1, 0));
tsd_t *tsd = tsd_fetch();
originally_fast = tsd_fast(tsd);
thd_t thd;
thd_create(&thd, thd_start_global_slow, (void *)&data.phase);
/* PHASE 1 */
while (atomic_load_u32(&data.phase, ATOMIC_SEQ_CST) != 1) {
/*
* We don't have a portable condvar/semaphore mechanism.
* Spin-wait.
*/
}
expect_false(atomic_load_b(&data.error, ATOMIC_SEQ_CST), "");
tsd_global_slow_inc(tsd_tsdn(tsd));
free(mallocx(1, 0));
expect_false(tsd_fast(tsd), "");
atomic_store_u32(&data.phase, 2, ATOMIC_SEQ_CST);
/* PHASE 3 */
while (atomic_load_u32(&data.phase, ATOMIC_SEQ_CST) != 3) {
}
expect_false(atomic_load_b(&data.error, ATOMIC_SEQ_CST), "");
/* Increase again, so that we can test multiple fast/slow changes. */
tsd_global_slow_inc(tsd_tsdn(tsd));
atomic_store_u32(&data.phase, 4, ATOMIC_SEQ_CST);
free(mallocx(1, 0));
expect_false(tsd_fast(tsd), "");
/* PHASE 5 */
while (atomic_load_u32(&data.phase, ATOMIC_SEQ_CST) != 5) {
}
expect_false(atomic_load_b(&data.error, ATOMIC_SEQ_CST), "");
tsd_global_slow_dec(tsd_tsdn(tsd));
atomic_store_u32(&data.phase, 6, ATOMIC_SEQ_CST);
/* We only decreased once; things should still be slow. */
free(mallocx(1, 0));
expect_false(tsd_fast(tsd), "");
/* PHASE 7 */
while (atomic_load_u32(&data.phase, ATOMIC_SEQ_CST) != 7) {
}
expect_false(atomic_load_b(&data.error, ATOMIC_SEQ_CST), "");
tsd_global_slow_dec(tsd_tsdn(tsd));
atomic_store_u32(&data.phase, 8, ATOMIC_SEQ_CST);
/* We incremented and then decremented twice; we should be fast now. */
free(mallocx(1, 0));
expect_true(!originally_fast || tsd_fast(tsd), "");
/* PHASE 9 */
while (atomic_load_u32(&data.phase, ATOMIC_SEQ_CST) != 9) {
}
expect_false(atomic_load_b(&data.error, ATOMIC_SEQ_CST), "");
thd_join(thd, NULL);
}
TEST_END
int
main(void) {
/* Ensure tsd bootstrapped. */
if (nallocx(1, 0) == 0) {
malloc_printf("Initialization error");
return test_status_fail;
}
return test_no_reentrancy(
test_tsd_main_thread,
test_tsd_sub_thread,
test_tsd_reincarnation,
test_tsd_global_slow);
}
|
c
|
github
|
https://github.com/redis/redis
|
deps/jemalloc/test/unit/tsd.c
|
"""
PyRSS2Gen - A Python library for generating RSS 2.0 feeds.
(This is the BSD license, based on the template at
http://www.opensource.org/licenses/bsd-license.php )
Copyright (c) 2003, Dalke Scientific Software, LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of the Dalke Scientific Softare, LLC, Andrew
Dalke, nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
__name__ = "PyRSS2Gen"
__version__ = (1, 1, 0)
__author__ = "Andrew Dalke <dalke@dalkescientific.com>"
_generator_name = __name__ + "-" + ".".join(map(str, __version__))
import datetime
import sys
if sys.version_info[0] == 3:
# Python 3
basestring = str
from io import StringIO
else:
# Python 2
try:
from cStringIO import StringIO
except ImportError:
# Very old (or memory constrained) systems might
# have left out the compiled C version. Fall back
# to the pure Python one. Haven't seen this sort
# of system since the early 2000s.
from StringIO import StringIO
# Could make this the base class; will need to add 'publish'
class WriteXmlMixin:
def write_xml(self, outfile, encoding="iso-8859-1"):
from xml.sax import saxutils
handler = saxutils.XMLGenerator(outfile, encoding)
handler.startDocument()
self.publish(handler)
handler.endDocument()
def to_xml(self, encoding="iso-8859-1"):
f = StringIO()
self.write_xml(f, encoding)
return f.getvalue()
def _element(handler, name, obj, d={}):
if isinstance(obj, basestring) or obj is None:
# special-case handling to make the API easier
# to use for the common case.
handler.startElement(name, d)
if obj is not None:
handler.characters(obj)
handler.endElement(name)
else:
# It better know how to emit the correct XML.
obj.publish(handler)
def _opt_element(handler, name, obj):
if obj is None:
return
_element(handler, name, obj)
def _format_date(dt):
"""convert a datetime into an RFC 822 formatted date
Input date must be in GMT.
"""
# Looks like:
# Sat, 07 Sep 2002 00:00:01 GMT
# Can't use strftime because that's locale dependent
#
# Isn't there a standard way to do this for Python? The
# rfc822 and email.Utils modules assume a timestamp. The
# following is based on the rfc822 module.
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()],
dt.day,
["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][dt.month - 1],
dt.year, dt.hour, dt.minute, dt.second)
##
# A couple simple wrapper objects for the fields which
# take a simple value other than a string.
class IntElement:
"""implements the 'publish' API for integers
Takes the tag name and the integer value to publish.
(Could be used for anything which uses str() to be published
to text for XML.)
"""
element_attrs = {}
def __init__(self, name, val):
self.name = name
self.val = val
def publish(self, handler):
handler.startElement(self.name, self.element_attrs)
handler.characters(str(self.val))
handler.endElement(self.name)
class DateElement:
"""implements the 'publish' API for a datetime.datetime
Takes the tag name and the datetime to publish.
Converts the datetime to RFC 2822 timestamp (4-digit year).
"""
def __init__(self, name, dt):
self.name = name
self.dt = dt
def publish(self, handler):
_element(handler, self.name, _format_date(self.dt))
####
class Category:
"""Publish a category element"""
def __init__(self, category, domain=None):
self.category = category
self.domain = domain
def publish(self, handler):
d = {}
if self.domain is not None:
d["domain"] = self.domain
_element(handler, "category", self.category, d)
class Cloud:
"""Publish a cloud"""
def __init__(self, domain, port, path,
registerProcedure, protocol):
self.domain = domain
self.port = port
self.path = path
self.registerProcedure = registerProcedure
self.protocol = protocol
def publish(self, handler):
_element(handler, "cloud", None, {
"domain": self.domain,
"port": str(self.port),
"path": self.path,
"registerProcedure": self.registerProcedure,
"protocol": self.protocol})
class Image:
"""Publish a channel Image"""
element_attrs = {}
def __init__(self, url, title, link,
width=None, height=None, description=None):
self.url = url
self.title = title
self.link = link
self.width = width
self.height = height
self.description = description
def publish(self, handler):
handler.startElement("image", self.element_attrs)
_element(handler, "url", self.url)
_element(handler, "title", self.title)
_element(handler, "link", self.link)
width = self.width
if isinstance(width, int):
width = IntElement("width", width)
_opt_element(handler, "width", width)
height = self.height
if isinstance(height, int):
height = IntElement("height", height)
_opt_element(handler, "height", height)
_opt_element(handler, "description", self.description)
handler.endElement("image")
class Guid:
"""Publish a guid
Defaults to being a permalink, which is the assumption if it's
omitted. Hence strings are always permalinks.
"""
def __init__(self, guid, isPermaLink=1):
self.guid = guid
self.isPermaLink = isPermaLink
def publish(self, handler):
d = {}
if self.isPermaLink:
d["isPermaLink"] = "true"
else:
d["isPermaLink"] = "false"
_element(handler, "guid", self.guid, d)
class TextInput:
"""Publish a textInput
Apparently this is rarely used.
"""
element_attrs = {}
def __init__(self, title, description, name, link):
self.title = title
self.description = description
self.name = name
self.link = link
def publish(self, handler):
handler.startElement("textInput", self.element_attrs)
_element(handler, "title", self.title)
_element(handler, "description", self.description)
_element(handler, "name", self.name)
_element(handler, "link", self.link)
handler.endElement("textInput")
class Enclosure:
"""Publish an enclosure"""
def __init__(self, url, length, type):
self.url = url
self.length = length
self.type = type
def publish(self, handler):
_element(handler, "enclosure", None,
{"url": self.url,
"length": str(self.length),
"type": self.type,
})
class Source:
"""Publish the item's original source, used by aggregators"""
def __init__(self, name, url):
self.name = name
self.url = url
def publish(self, handler):
_element(handler, "source", self.name, {"url": self.url})
class SkipHours:
"""Publish the skipHours
This takes a list of hours, as integers.
"""
element_attrs = {}
def __init__(self, hours):
self.hours = hours
def publish(self, handler):
if self.hours:
handler.startElement("skipHours", self.element_attrs)
for hour in self.hours:
_element(handler, "hour", str(hour))
handler.endElement("skipHours")
class SkipDays:
"""Publish the skipDays
This takes a list of days as strings.
"""
element_attrs = {}
def __init__(self, days):
self.days = days
def publish(self, handler):
if self.days:
handler.startElement("skipDays", self.element_attrs)
for day in self.days:
_element(handler, "day", day)
handler.endElement("skipDays")
class RSS2(WriteXmlMixin):
"""The main RSS class.
Stores the channel attributes, with the "category" elements under
".categories" and the RSS items under ".items".
"""
rss_attrs = {"version": "2.0"}
element_attrs = {}
def __init__(self,
title,
link,
description,
language=None,
copyright=None,
managingEditor=None,
webMaster=None,
pubDate=None, # a datetime, *in* *GMT*
lastBuildDate=None, # a datetime
categories=None, # list of strings or Category
generator=_generator_name,
docs="http://blogs.law.harvard.edu/tech/rss",
cloud=None, # a Cloud
ttl=None, # integer number of minutes
image=None, # an Image
rating=None, # a string; I don't know how it's used
textInput=None, # a TextInput
skipHours=None, # a SkipHours with a list of integers
skipDays=None, # a SkipDays with a list of strings
items=None, # list of RSSItems
):
self.title = title
self.link = link
self.description = description
self.language = language
self.copyright = copyright
self.managingEditor = managingEditor
self.webMaster = webMaster
self.pubDate = pubDate
self.lastBuildDate = lastBuildDate
if categories is None:
categories = []
self.categories = categories
self.generator = generator
self.docs = docs
self.cloud = cloud
self.ttl = ttl
self.image = image
self.rating = rating
self.textInput = textInput
self.skipHours = skipHours
self.skipDays = skipDays
if items is None:
items = []
self.items = items
def publish(self, handler):
handler.startElement("rss", self.rss_attrs)
handler.startElement("channel", self.element_attrs)
_element(handler, "title", self.title)
_element(handler, "link", self.link)
_element(handler, "description", self.description)
self.publish_extensions(handler)
_opt_element(handler, "language", self.language)
_opt_element(handler, "copyright", self.copyright)
_opt_element(handler, "managingEditor", self.managingEditor)
_opt_element(handler, "webMaster", self.webMaster)
pubDate = self.pubDate
if isinstance(pubDate, datetime.datetime):
pubDate = DateElement("pubDate", pubDate)
_opt_element(handler, "pubDate", pubDate)
lastBuildDate = self.lastBuildDate
if isinstance(lastBuildDate, datetime.datetime):
lastBuildDate = DateElement("lastBuildDate", lastBuildDate)
_opt_element(handler, "lastBuildDate", lastBuildDate)
for category in self.categories:
if isinstance(category, basestring):
category = Category(category)
category.publish(handler)
_opt_element(handler, "generator", self.generator)
_opt_element(handler, "docs", self.docs)
if self.cloud is not None:
self.cloud.publish(handler)
ttl = self.ttl
if isinstance(self.ttl, int):
ttl = IntElement("ttl", ttl)
_opt_element(handler, "ttl", ttl)
if self.image is not None:
self.image.publish(handler)
_opt_element(handler, "rating", self.rating)
if self.textInput is not None:
self.textInput.publish(handler)
if self.skipHours is not None:
self.skipHours.publish(handler)
if self.skipDays is not None:
self.skipDays.publish(handler)
for item in self.items:
item.publish(handler)
handler.endElement("channel")
handler.endElement("rss")
def publish_extensions(self, handler):
# Derived classes can hook into this to insert
# output after the three required fields.
pass
class RSSItem(WriteXmlMixin):
"""Publish an RSS Item"""
element_attrs = {}
def __init__(self,
title=None, # string
link=None, # url as string
description=None, # string
author=None, # email address as string
categories=None, # list of string or Category
comments=None, # url as string
enclosure=None, # an Enclosure
guid=None, # a unique string
pubDate=None, # a datetime
source=None, # a Source
):
if title is None and description is None:
raise TypeError(
"must define at least one of 'title' or 'description'")
self.title = title
self.link = link
self.description = description
self.author = author
if categories is None:
categories = []
self.categories = categories
self.comments = comments
self.enclosure = enclosure
self.guid = guid
self.pubDate = pubDate
self.source = source
# It sure does get tedious typing these names three times...
def publish(self, handler):
handler.startElement("item", self.element_attrs)
_opt_element(handler, "title", self.title)
_opt_element(handler, "link", self.link)
self.publish_extensions(handler)
_opt_element(handler, "description", self.description)
_opt_element(handler, "author", self.author)
for category in self.categories:
if isinstance(category, basestring):
category = Category(category)
category.publish(handler)
_opt_element(handler, "comments", self.comments)
if self.enclosure is not None:
self.enclosure.publish(handler)
_opt_element(handler, "guid", self.guid)
pubDate = self.pubDate
if isinstance(pubDate, datetime.datetime):
pubDate = DateElement("pubDate", pubDate)
_opt_element(handler, "pubDate", pubDate)
if self.source is not None:
self.source.publish(handler)
handler.endElement("item")
def publish_extensions(self, handler):
# Derived classes can hook into this to insert
# output after the title and link elements
pass
|
unknown
|
codeparrot/codeparrot-clean
| ||
#ifndef RUBY_RUBYPARSER_H
#define RUBY_RUBYPARSER_H 1
/*
* This is a header file for librubyparser interface
*/
#include <stdarg.h> /* for va_list */
#include <assert.h>
#ifdef UNIVERSAL_PARSER
#define rb_encoding const void
#define OnigCodePoint unsigned int
#include "parser_st.h"
#ifndef RUBY_RUBY_H
#include "parser_value.h"
#endif
#else
#include "ruby/encoding.h"
#endif
#ifndef FLEX_ARY_LEN
/* From internal/compilers.h */
/* A macro for defining a flexible array, like: VALUE ary[FLEX_ARY_LEN]; */
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
# define FLEX_ARY_LEN /* VALUE ary[]; */
#elif defined(__GNUC__) && !defined(__STRICT_ANSI__)
# define FLEX_ARY_LEN 0 /* VALUE ary[0]; */
#else
# define FLEX_ARY_LEN 1 /* VALUE ary[1]; */
#endif
#endif
#if defined(__GNUC__)
# if defined(__MINGW_PRINTF_FORMAT)
# define RUBYPARSER_ATTRIBUTE_FORMAT(string_index, argument_index) __attribute__((format(__MINGW_PRINTF_FORMAT, string_index, argument_index)))
# else
# define RUBYPARSER_ATTRIBUTE_FORMAT(string_index, argument_index) __attribute__((format(printf, string_index, argument_index)))
# endif
#elif defined(__clang__)
# define RUBYPARSER_ATTRIBUTE_FORMAT(string_index, argument_index) __attribute__((__format__(__printf__, string_index, argument_index)))
#else
# define RUBYPARSER_ATTRIBUTE_FORMAT(string_index, argument_index)
#endif
/*
* Parser String
*/
enum rb_parser_string_coderange_type {
/** The object's coderange is unclear yet. */
RB_PARSER_ENC_CODERANGE_UNKNOWN = 0,
RB_PARSER_ENC_CODERANGE_7BIT = 1,
RB_PARSER_ENC_CODERANGE_VALID = 2,
RB_PARSER_ENC_CODERANGE_BROKEN = 3
};
typedef struct rb_parser_string {
enum rb_parser_string_coderange_type coderange;
rb_encoding *enc;
/* Length of the string, not including terminating NUL character. */
long len;
/* Pointer to the contents of the string. */
char *ptr;
} rb_parser_string_t;
enum rb_parser_shareability {
rb_parser_shareable_none,
rb_parser_shareable_literal,
rb_parser_shareable_copy,
rb_parser_shareable_everything,
};
typedef void* rb_parser_input_data;
/*
* AST Node
*/
enum node_type {
NODE_SCOPE,
NODE_BLOCK,
NODE_IF,
NODE_UNLESS,
NODE_CASE,
NODE_CASE2,
NODE_CASE3,
NODE_WHEN,
NODE_IN,
NODE_WHILE,
NODE_UNTIL,
NODE_ITER,
NODE_FOR,
NODE_FOR_MASGN,
NODE_BREAK,
NODE_NEXT,
NODE_REDO,
NODE_RETRY,
NODE_BEGIN,
NODE_RESCUE,
NODE_RESBODY,
NODE_ENSURE,
NODE_AND,
NODE_OR,
NODE_MASGN,
NODE_LASGN,
NODE_DASGN,
NODE_GASGN,
NODE_IASGN,
NODE_CDECL,
NODE_CVASGN,
NODE_OP_ASGN1,
NODE_OP_ASGN2,
NODE_OP_ASGN_AND,
NODE_OP_ASGN_OR,
NODE_OP_CDECL,
NODE_CALL,
NODE_OPCALL,
NODE_FCALL,
NODE_VCALL,
NODE_QCALL,
NODE_SUPER,
NODE_ZSUPER,
NODE_LIST,
NODE_ZLIST,
NODE_HASH,
NODE_RETURN,
NODE_YIELD,
NODE_LVAR,
NODE_DVAR,
NODE_GVAR,
NODE_IVAR,
NODE_CONST,
NODE_CVAR,
NODE_NTH_REF,
NODE_BACK_REF,
NODE_MATCH,
NODE_MATCH2,
NODE_MATCH3,
NODE_INTEGER,
NODE_FLOAT,
NODE_RATIONAL,
NODE_IMAGINARY,
NODE_STR,
NODE_DSTR,
NODE_XSTR,
NODE_DXSTR,
NODE_EVSTR,
NODE_REGX,
NODE_DREGX,
NODE_ONCE,
NODE_ARGS,
NODE_ARGS_AUX,
NODE_OPT_ARG,
NODE_KW_ARG,
NODE_POSTARG,
NODE_ARGSCAT,
NODE_ARGSPUSH,
NODE_SPLAT,
NODE_BLOCK_PASS,
NODE_DEFN,
NODE_DEFS,
NODE_ALIAS,
NODE_VALIAS,
NODE_UNDEF,
NODE_CLASS,
NODE_MODULE,
NODE_SCLASS,
NODE_COLON2,
NODE_COLON3,
NODE_DOT2,
NODE_DOT3,
NODE_FLIP2,
NODE_FLIP3,
NODE_SELF,
NODE_NIL,
NODE_TRUE,
NODE_FALSE,
NODE_ERRINFO,
NODE_DEFINED,
NODE_POSTEXE,
NODE_SYM,
NODE_DSYM,
NODE_ATTRASGN,
NODE_LAMBDA,
NODE_ARYPTN,
NODE_HSHPTN,
NODE_FNDPTN,
NODE_ERROR,
NODE_LINE,
NODE_FILE,
NODE_ENCODING,
NODE_LAST
};
typedef struct rb_ast_id_table {
int size;
ID ids[FLEX_ARY_LEN];
} rb_ast_id_table_t;
typedef struct rb_code_position_struct {
int lineno;
int column;
} rb_code_position_t;
typedef struct rb_code_location_struct {
rb_code_position_t beg_pos;
rb_code_position_t end_pos;
} rb_code_location_t;
#define YYLTYPE rb_code_location_t
#define YYLTYPE_IS_DECLARED 1
typedef struct rb_parser_ast_token {
int id;
const char *type_name;
rb_parser_string_t *str;
rb_code_location_t loc;
} rb_parser_ast_token_t;
/*
* Array-like object for parser
*/
typedef void* rb_parser_ary_data;
enum rb_parser_ary_data_type {
PARSER_ARY_DATA_AST_TOKEN = 1,
PARSER_ARY_DATA_SCRIPT_LINE,
PARSER_ARY_DATA_NODE
};
typedef struct rb_parser_ary {
enum rb_parser_ary_data_type data_type;
rb_parser_ary_data *data;
long len; // current size
long capa; // capacity
} rb_parser_ary_t;
/* Header part of AST Node */
typedef struct RNode {
VALUE flags;
rb_code_location_t nd_loc;
int node_id;
} NODE;
typedef struct RNode_SCOPE {
NODE node;
rb_ast_id_table_t *nd_tbl;
struct RNode *nd_body;
struct RNode *nd_parent;
struct RNode_ARGS *nd_args;
} rb_node_scope_t;
typedef struct RNode_BLOCK {
NODE node;
struct RNode *nd_head;
struct RNode *nd_end;
struct RNode *nd_next;
} rb_node_block_t;
typedef struct RNode_IF {
NODE node;
struct RNode *nd_cond;
struct RNode *nd_body;
struct RNode *nd_else;
rb_code_location_t if_keyword_loc;
rb_code_location_t then_keyword_loc;
rb_code_location_t end_keyword_loc;
} rb_node_if_t;
typedef struct RNode_UNLESS {
NODE node;
struct RNode *nd_cond;
struct RNode *nd_body;
struct RNode *nd_else;
rb_code_location_t keyword_loc;
rb_code_location_t then_keyword_loc;
rb_code_location_t end_keyword_loc;
} rb_node_unless_t;
typedef struct RNode_CASE {
NODE node;
struct RNode *nd_head;
struct RNode *nd_body;
rb_code_location_t case_keyword_loc;
rb_code_location_t end_keyword_loc;
} rb_node_case_t, rb_node_case2_t, rb_node_case3_t;
typedef struct RNode_WHEN {
NODE node;
struct RNode *nd_head;
struct RNode *nd_body;
struct RNode *nd_next;
rb_code_location_t keyword_loc;
rb_code_location_t then_keyword_loc;
} rb_node_when_t;
typedef struct RNode_IN {
NODE node;
struct RNode *nd_head;
struct RNode *nd_body;
struct RNode *nd_next;
rb_code_location_t in_keyword_loc;
rb_code_location_t then_keyword_loc;
rb_code_location_t operator_loc;
} rb_node_in_t;
typedef struct RNode_LOOP {
NODE node;
struct RNode *nd_cond;
struct RNode *nd_body;
long nd_state;
rb_code_location_t keyword_loc;
rb_code_location_t closing_loc;
} rb_node_while_t, rb_node_until_t;
typedef struct RNode_ITER {
NODE node;
struct RNode *nd_body;
struct RNode *nd_iter;
} rb_node_iter_t;
typedef struct RNode_FOR {
NODE node;
struct RNode *nd_body;
struct RNode *nd_iter;
rb_code_location_t for_keyword_loc;
rb_code_location_t in_keyword_loc;
rb_code_location_t do_keyword_loc;
rb_code_location_t end_keyword_loc;
} rb_node_for_t;
typedef struct RNode_FOR_MASGN {
NODE node;
struct RNode *nd_var;
} rb_node_for_masgn_t;
typedef struct RNode_EXITS {
NODE node;
struct RNode *nd_chain;
struct RNode *nd_stts;
rb_code_location_t keyword_loc;
} rb_node_exits_t, rb_node_break_t, rb_node_next_t, rb_node_redo_t;
typedef struct RNode_RETRY {
NODE node;
} rb_node_retry_t;
typedef struct RNode_BEGIN {
NODE node;
struct RNode *nd_body;
} rb_node_begin_t;
typedef struct RNode_RESCUE {
NODE node;
struct RNode *nd_head;
struct RNode *nd_resq;
struct RNode *nd_else;
} rb_node_rescue_t;
typedef struct RNode_RESBODY {
NODE node;
struct RNode *nd_args;
struct RNode *nd_exc_var;
struct RNode *nd_body;
struct RNode *nd_next;
} rb_node_resbody_t;
typedef struct RNode_ENSURE {
NODE node;
struct RNode *nd_head;
struct RNode *nd_ensr;
} rb_node_ensure_t;
typedef struct {
NODE node;
struct RNode *nd_1st;
struct RNode *nd_2nd;
rb_code_location_t operator_loc;
} rb_node_and_t, rb_node_or_t;
typedef struct RNode_MASGN {
NODE node;
struct RNode *nd_head;
struct RNode *nd_value;
struct RNode *nd_args;
} rb_node_masgn_t;
typedef struct RNode_LASGN {
NODE node;
ID nd_vid;
struct RNode *nd_value;
} rb_node_lasgn_t;
typedef struct RNode_DASGN {
NODE node;
ID nd_vid;
struct RNode *nd_value;
} rb_node_dasgn_t;
typedef struct RNode_GASGN {
NODE node;
ID nd_vid;
struct RNode *nd_value;
} rb_node_gasgn_t;
typedef struct RNode_IASGN {
NODE node;
ID nd_vid;
struct RNode *nd_value;
} rb_node_iasgn_t;
typedef struct RNode_CDECL {
NODE node;
ID nd_vid;
struct RNode *nd_value;
struct RNode *nd_else;
enum rb_parser_shareability shareability;
} rb_node_cdecl_t;
typedef struct RNode_CVASGN {
NODE node;
ID nd_vid;
struct RNode *nd_value;
} rb_node_cvasgn_t;
typedef struct RNode_OP_ASGN1 {
NODE node;
struct RNode *nd_recv;
ID nd_mid;
struct RNode *nd_index;
struct RNode *nd_rvalue;
rb_code_location_t call_operator_loc;
rb_code_location_t opening_loc;
rb_code_location_t closing_loc;
rb_code_location_t binary_operator_loc;
} rb_node_op_asgn1_t;
typedef struct RNode_OP_ASGN2 {
NODE node;
struct RNode *nd_recv;
struct RNode *nd_value;
ID nd_vid;
ID nd_mid;
bool nd_aid;
rb_code_location_t call_operator_loc;
rb_code_location_t message_loc;
rb_code_location_t binary_operator_loc;
} rb_node_op_asgn2_t;
typedef struct RNode_OP_ASGN_AND {
NODE node;
struct RNode *nd_head;
struct RNode *nd_value;
} rb_node_op_asgn_and_t;
typedef struct RNode_OP_ASGN_OR {
NODE node;
struct RNode *nd_head;
struct RNode *nd_value;
} rb_node_op_asgn_or_t;
typedef struct RNode_OP_CDECL {
NODE node;
struct RNode *nd_head;
struct RNode *nd_value;
ID nd_aid;
enum rb_parser_shareability shareability;
} rb_node_op_cdecl_t;
typedef struct RNode_CALL {
NODE node;
struct RNode *nd_recv;
ID nd_mid;
struct RNode *nd_args;
} rb_node_call_t;
typedef struct RNode_OPCALL {
NODE node;
struct RNode *nd_recv;
ID nd_mid;
struct RNode *nd_args;
} rb_node_opcall_t;
typedef struct RNode_FCALL {
NODE node;
ID nd_mid;
struct RNode *nd_args;
} rb_node_fcall_t;
typedef struct RNode_VCALL {
NODE node;
ID nd_mid;
} rb_node_vcall_t;
typedef struct RNode_QCALL {
NODE node;
struct RNode *nd_recv;
ID nd_mid;
struct RNode *nd_args;
} rb_node_qcall_t;
typedef struct RNode_SUPER {
NODE node;
struct RNode *nd_args;
rb_code_location_t keyword_loc;
rb_code_location_t lparen_loc;
rb_code_location_t rparen_loc;
} rb_node_super_t;
typedef struct RNode_ZSUPER {
NODE node;
} rb_node_zsuper_t;
/*
Structure of LIST:
LIST +--> LIST
* head --> element | * head
* alen (length of list) | * nd_end (point to the last LIST)
* next -----------------+ * next
*/
typedef struct RNode_LIST {
NODE node;
struct RNode *nd_head; /* element */
union {
long nd_alen;
struct RNode *nd_end; /* Second list node has this structure */
} as;
struct RNode *nd_next; /* next list node */
} rb_node_list_t;
typedef struct RNode_ZLIST {
NODE node;
} rb_node_zlist_t;
typedef struct RNode_HASH {
NODE node;
struct RNode *nd_head;
long nd_brace;
} rb_node_hash_t;
typedef struct RNode_RETURN {
NODE node;
struct RNode *nd_stts;
rb_code_location_t keyword_loc;
} rb_node_return_t;
typedef struct RNode_YIELD {
NODE node;
struct RNode *nd_head;
rb_code_location_t keyword_loc;
rb_code_location_t lparen_loc;
rb_code_location_t rparen_loc;
} rb_node_yield_t;
typedef struct RNode_LVAR {
NODE node;
ID nd_vid;
} rb_node_lvar_t;
typedef struct RNode_DVAR {
NODE node;
ID nd_vid;
} rb_node_dvar_t;
typedef struct RNode_GVAR {
NODE node;
ID nd_vid;
} rb_node_gvar_t;
typedef struct RNode_IVAR {
NODE node;
ID nd_vid;
} rb_node_ivar_t;
typedef struct RNode_CONST {
NODE node;
ID nd_vid;
} rb_node_const_t;
typedef struct RNode_CVAR {
NODE node;
ID nd_vid;
} rb_node_cvar_t;
typedef struct RNode_NTH_REF {
NODE node;
long nd_nth;
} rb_node_nth_ref_t;
typedef struct RNode_BACK_REF {
NODE node;
long nd_nth;
} rb_node_back_ref_t;
typedef struct RNode_MATCH2 {
NODE node;
struct RNode *nd_recv;
struct RNode *nd_value;
struct RNode *nd_args;
} rb_node_match2_t;
typedef struct RNode_MATCH3 {
NODE node;
struct RNode *nd_recv;
struct RNode *nd_value;
} rb_node_match3_t;
typedef struct RNode_INTEGER {
NODE node;
char *val;
int minus;
int base;
} rb_node_integer_t;
typedef struct RNode_FLOAT {
NODE node;
char *val;
int minus;
} rb_node_float_t;
typedef struct RNode_RATIONAL {
NODE node;
char *val;
int minus;
int base;
int seen_point;
} rb_node_rational_t;
enum rb_numeric_type {
integer_literal,
float_literal,
rational_literal
};
typedef struct RNode_IMAGINARY {
NODE node;
char *val;
int minus;
int base;
int seen_point;
enum rb_numeric_type type;
} rb_node_imaginary_t;
typedef struct RNode_STR {
NODE node;
struct rb_parser_string *string;
} rb_node_str_t;
/* NODE_DSTR, NODE_DXSTR, NODE_DREGX, NODE_DSYM */
typedef struct RNode_DSTR {
NODE node;
struct rb_parser_string *string;
union {
long nd_alen;
long nd_cflag;
struct RNode *nd_end; /* Second dstr node has this structure. See also RNode_LIST */
} as;
struct RNode_LIST *nd_next;
} rb_node_dstr_t;
typedef rb_node_str_t rb_node_xstr_t;
typedef rb_node_dstr_t rb_node_dxstr_t;
typedef struct RNode_EVSTR {
NODE node;
struct RNode *nd_body;
rb_code_location_t opening_loc;
rb_code_location_t closing_loc;
} rb_node_evstr_t;
typedef struct RNode_REGX { /* also RNode_MATCH */
NODE node;
struct rb_parser_string *string;
int options;
rb_code_location_t opening_loc;
rb_code_location_t content_loc;
rb_code_location_t closing_loc;
} rb_node_regx_t, rb_node_match_t;
typedef rb_node_dstr_t rb_node_dregx_t;
typedef struct RNode_ONCE {
NODE node;
struct RNode *nd_body;
} rb_node_once_t;
struct rb_args_info {
NODE *pre_init;
NODE *post_init;
int pre_args_num; /* count of mandatory pre-arguments */
int post_args_num; /* count of mandatory post-arguments */
ID first_post_arg;
ID rest_arg;
ID block_arg;
struct RNode_KW_ARG *kw_args;
NODE *kw_rest_arg;
struct RNode_OPT_ARG *opt_args;
unsigned int no_kwarg: 1;
unsigned int forwarding: 1;
};
typedef struct RNode_ARGS {
NODE node;
struct rb_args_info nd_ainfo;
} rb_node_args_t;
typedef struct RNode_ARGS_AUX {
NODE node;
ID nd_pid;
int nd_plen;
struct RNode *nd_next;
} rb_node_args_aux_t;
typedef struct RNode_OPT_ARG {
NODE node;
struct RNode *nd_body;
struct RNode_OPT_ARG *nd_next;
} rb_node_opt_arg_t;
typedef struct RNode_KW_ARG {
NODE node;
struct RNode *nd_body;
struct RNode_KW_ARG *nd_next;
} rb_node_kw_arg_t;
typedef struct RNode_POSTARG {
NODE node;
struct RNode *nd_1st;
struct RNode *nd_2nd;
} rb_node_postarg_t;
typedef struct RNode_ARGSCAT {
NODE node;
struct RNode *nd_head;
struct RNode *nd_body;
} rb_node_argscat_t;
typedef struct RNode_ARGSPUSH {
NODE node;
struct RNode *nd_head;
struct RNode *nd_body;
} rb_node_argspush_t;
typedef struct RNode_SPLAT {
NODE node;
struct RNode *nd_head;
rb_code_location_t operator_loc;
} rb_node_splat_t;
typedef struct RNode_BLOCK_PASS {
NODE node;
struct RNode *nd_head;
struct RNode *nd_body;
unsigned int forwarding: 1;
rb_code_location_t operator_loc;
} rb_node_block_pass_t;
typedef struct RNode_DEFN {
NODE node;
ID nd_mid;
struct RNode *nd_defn;
} rb_node_defn_t;
typedef struct RNode_DEFS {
NODE node;
struct RNode *nd_recv;
ID nd_mid;
struct RNode *nd_defn;
} rb_node_defs_t;
typedef struct RNode_ALIAS {
NODE node;
struct RNode *nd_1st;
struct RNode *nd_2nd;
rb_code_location_t keyword_loc;
} rb_node_alias_t;
typedef struct RNode_VALIAS {
NODE node;
ID nd_alias;
ID nd_orig;
rb_code_location_t keyword_loc;
} rb_node_valias_t;
typedef struct RNode_UNDEF {
NODE node;
rb_parser_ary_t *nd_undefs;
rb_code_location_t keyword_loc;
} rb_node_undef_t;
typedef struct RNode_CLASS {
NODE node;
struct RNode *nd_cpath;
struct RNode *nd_body;
struct RNode *nd_super;
rb_code_location_t class_keyword_loc;
rb_code_location_t inheritance_operator_loc;
rb_code_location_t end_keyword_loc;
} rb_node_class_t;
typedef struct RNode_MODULE {
NODE node;
struct RNode *nd_cpath;
struct RNode *nd_body;
rb_code_location_t module_keyword_loc;
rb_code_location_t end_keyword_loc;
} rb_node_module_t;
typedef struct RNode_SCLASS {
NODE node;
struct RNode *nd_recv;
struct RNode *nd_body;
rb_code_location_t class_keyword_loc;
rb_code_location_t operator_loc;
rb_code_location_t end_keyword_loc;
} rb_node_sclass_t;
typedef struct RNode_COLON2 {
NODE node;
struct RNode *nd_head;
ID nd_mid;
rb_code_location_t delimiter_loc;
rb_code_location_t name_loc;
} rb_node_colon2_t;
typedef struct RNode_COLON3 {
NODE node;
ID nd_mid;
rb_code_location_t delimiter_loc;
rb_code_location_t name_loc;
} rb_node_colon3_t;
/* NODE_DOT2, NODE_DOT3, NODE_FLIP2, NODE_FLIP3 */
typedef struct RNode_DOTS {
NODE node;
struct RNode *nd_beg;
struct RNode *nd_end;
rb_code_location_t operator_loc;
} rb_node_dot2_t, rb_node_dot3_t, rb_node_flip2_t, rb_node_flip3_t;
typedef struct RNode_SELF {
NODE node;
long nd_state; /* Default 1. See NEW_SELF. */
} rb_node_self_t;
typedef struct RNode_NIL {
NODE node;
} rb_node_nil_t;
typedef struct RNode_TRUE {
NODE node;
} rb_node_true_t;
typedef struct RNode_FALSE {
NODE node;
} rb_node_false_t;
typedef struct RNode_ERRINFO {
NODE node;
} rb_node_errinfo_t;
typedef struct RNode_DEFINED {
NODE node;
struct RNode *nd_head;
rb_code_location_t keyword_loc;
} rb_node_defined_t;
typedef struct RNode_POSTEXE {
NODE node;
struct RNode *nd_body;
rb_code_location_t keyword_loc;
rb_code_location_t opening_loc;
rb_code_location_t closing_loc;
} rb_node_postexe_t;
typedef struct RNode_SYM {
NODE node;
struct rb_parser_string *string;
} rb_node_sym_t;
typedef rb_node_dstr_t rb_node_dsym_t;
typedef struct RNode_ATTRASGN {
NODE node;
struct RNode *nd_recv;
ID nd_mid;
struct RNode *nd_args;
} rb_node_attrasgn_t;
typedef struct RNode_LAMBDA {
NODE node;
struct RNode *nd_body;
rb_code_location_t operator_loc;
rb_code_location_t opening_loc;
rb_code_location_t closing_loc;
} rb_node_lambda_t;
typedef struct RNode_ARYPTN {
NODE node;
struct RNode *nd_pconst;
NODE *pre_args;
NODE *rest_arg;
NODE *post_args;
} rb_node_aryptn_t;
typedef struct RNode_HSHPTN {
NODE node;
struct RNode *nd_pconst;
struct RNode *nd_pkwargs;
struct RNode *nd_pkwrestarg;
} rb_node_hshptn_t;
typedef struct RNode_FNDPTN {
NODE node;
struct RNode *nd_pconst;
NODE *pre_rest_arg;
NODE *args;
NODE *post_rest_arg;
} rb_node_fndptn_t;
typedef struct RNode_LINE {
NODE node;
} rb_node_line_t;
typedef struct RNode_FILE {
NODE node;
struct rb_parser_string *path;
} rb_node_file_t;
typedef struct RNode_ENCODING {
NODE node;
rb_encoding *enc;
} rb_node_encoding_t;
typedef struct RNode_ERROR {
NODE node;
} rb_node_error_t;
#define RNODE(obj) ((NODE *)(obj))
#define RNODE_SCOPE(node) ((rb_node_scope_t *)(node))
#define RNODE_BLOCK(node) ((rb_node_block_t *)(node))
#define RNODE_IF(node) ((rb_node_if_t *)(node))
#define RNODE_UNLESS(node) ((rb_node_unless_t *)(node))
#define RNODE_CASE(node) ((rb_node_case_t *)(node))
#define RNODE_CASE2(node) ((rb_node_case2_t *)(node))
#define RNODE_CASE3(node) ((rb_node_case3_t *)(node))
#define RNODE_WHEN(node) ((rb_node_when_t *)(node))
#define RNODE_IN(node) ((rb_node_in_t *)(node))
#define RNODE_WHILE(node) ((rb_node_while_t *)(node))
#define RNODE_UNTIL(node) ((rb_node_until_t *)(node))
#define RNODE_ITER(node) ((rb_node_iter_t *)(node))
#define RNODE_FOR(node) ((rb_node_for_t *)(node))
#define RNODE_FOR_MASGN(node) ((rb_node_for_masgn_t *)(node))
#define RNODE_BREAK(node) ((rb_node_break_t *)(node))
#define RNODE_NEXT(node) ((rb_node_next_t *)(node))
#define RNODE_REDO(node) ((rb_node_redo_t *)(node))
#define RNODE_RETRY(node) ((rb_node_retry_t *)(node))
#define RNODE_BEGIN(node) ((rb_node_begin_t *)(node))
#define RNODE_RESCUE(node) ((rb_node_rescue_t *)(node))
#define RNODE_RESBODY(node) ((rb_node_resbody_t *)(node))
#define RNODE_ENSURE(node) ((rb_node_ensure_t *)(node))
#define RNODE_AND(node) ((rb_node_and_t *)(node))
#define RNODE_OR(node) ((rb_node_or_t *)(node))
#define RNODE_MASGN(node) ((rb_node_masgn_t *)(node))
#define RNODE_LASGN(node) ((rb_node_lasgn_t *)(node))
#define RNODE_DASGN(node) ((rb_node_dasgn_t *)(node))
#define RNODE_GASGN(node) ((rb_node_gasgn_t *)(node))
#define RNODE_IASGN(node) ((rb_node_iasgn_t *)(node))
#define RNODE_CDECL(node) ((rb_node_cdecl_t *)(node))
#define RNODE_CVASGN(node) ((rb_node_cvasgn_t *)(node))
#define RNODE_OP_ASGN1(node) ((rb_node_op_asgn1_t *)(node))
#define RNODE_OP_ASGN2(node) ((rb_node_op_asgn2_t *)(node))
#define RNODE_OP_ASGN_AND(node) ((rb_node_op_asgn_and_t *)(node))
#define RNODE_OP_ASGN_OR(node) ((rb_node_op_asgn_or_t *)(node))
#define RNODE_OP_CDECL(node) ((rb_node_op_cdecl_t *)(node))
#define RNODE_CALL(node) ((rb_node_call_t *)(node))
#define RNODE_OPCALL(node) ((rb_node_opcall_t *)(node))
#define RNODE_FCALL(node) ((rb_node_fcall_t *)(node))
#define RNODE_VCALL(node) ((rb_node_vcall_t *)(node))
#define RNODE_QCALL(node) ((rb_node_qcall_t *)(node))
#define RNODE_SUPER(node) ((rb_node_super_t *)(node))
#define RNODE_ZSUPER(node) ((rb_node_zsuper_t *)(node))
#define RNODE_LIST(node) ((rb_node_list_t *)(node))
#define RNODE_ZLIST(node) ((rb_node_zlist_t *)(node))
#define RNODE_HASH(node) ((rb_node_hash_t *)(node))
#define RNODE_RETURN(node) ((rb_node_return_t *)(node))
#define RNODE_YIELD(node) ((rb_node_yield_t *)(node))
#define RNODE_LVAR(node) ((rb_node_lvar_t *)(node))
#define RNODE_DVAR(node) ((rb_node_dvar_t *)(node))
#define RNODE_GVAR(node) ((rb_node_gvar_t *)(node))
#define RNODE_IVAR(node) ((rb_node_ivar_t *)(node))
#define RNODE_CONST(node) ((rb_node_const_t *)(node))
#define RNODE_CVAR(node) ((rb_node_cvar_t *)(node))
#define RNODE_NTH_REF(node) ((rb_node_nth_ref_t *)(node))
#define RNODE_BACK_REF(node) ((rb_node_back_ref_t *)(node))
#define RNODE_MATCH(node) ((rb_node_match_t *)(node))
#define RNODE_MATCH2(node) ((rb_node_match2_t *)(node))
#define RNODE_MATCH3(node) ((rb_node_match3_t *)(node))
#define RNODE_INTEGER(node) ((rb_node_integer_t *)(node))
#define RNODE_FLOAT(node) ((rb_node_float_t *)(node))
#define RNODE_RATIONAL(node) ((rb_node_rational_t *)(node))
#define RNODE_IMAGINARY(node) ((rb_node_imaginary_t *)(node))
#define RNODE_STR(node) ((rb_node_str_t *)(node))
#define RNODE_DSTR(node) ((rb_node_dstr_t *)(node))
#define RNODE_XSTR(node) ((rb_node_xstr_t *)(node))
#define RNODE_DXSTR(node) ((rb_node_dxstr_t *)(node))
#define RNODE_EVSTR(node) ((rb_node_evstr_t *)(node))
#define RNODE_REGX(node) ((rb_node_regx_t *)(node))
#define RNODE_DREGX(node) ((rb_node_dregx_t *)(node))
#define RNODE_ONCE(node) ((rb_node_once_t *)(node))
#define RNODE_ARGS(node) ((rb_node_args_t *)(node))
#define RNODE_ARGS_AUX(node) ((rb_node_args_aux_t *)(node))
#define RNODE_OPT_ARG(node) ((rb_node_opt_arg_t *)(node))
#define RNODE_KW_ARG(node) ((rb_node_kw_arg_t *)(node))
#define RNODE_POSTARG(node) ((rb_node_postarg_t *)(node))
#define RNODE_ARGSCAT(node) ((rb_node_argscat_t *)(node))
#define RNODE_ARGSPUSH(node) ((rb_node_argspush_t *)(node))
#define RNODE_SPLAT(node) ((rb_node_splat_t *)(node))
#define RNODE_BLOCK_PASS(node) ((rb_node_block_pass_t *)(node))
#define RNODE_DEFN(node) ((rb_node_defn_t *)(node))
#define RNODE_DEFS(node) ((rb_node_defs_t *)(node))
#define RNODE_ALIAS(node) ((rb_node_alias_t *)(node))
#define RNODE_VALIAS(node) ((rb_node_valias_t *)(node))
#define RNODE_UNDEF(node) ((rb_node_undef_t *)(node))
#define RNODE_CLASS(node) ((rb_node_class_t *)(node))
#define RNODE_MODULE(node) ((rb_node_module_t *)(node))
#define RNODE_SCLASS(node) ((rb_node_sclass_t *)(node))
#define RNODE_COLON2(node) ((rb_node_colon2_t *)(node))
#define RNODE_COLON3(node) ((rb_node_colon3_t *)(node))
#define RNODE_DOT2(node) ((rb_node_dot2_t *)(node))
#define RNODE_DOT3(node) ((rb_node_dot3_t *)(node))
#define RNODE_FLIP2(node) ((rb_node_flip2_t *)(node))
#define RNODE_FLIP3(node) ((rb_node_flip3_t *)(node))
#define RNODE_SELF(node) ((rb_node_self_t *)(node))
#define RNODE_NIL(node) ((rb_node_nil_t *)(node))
#define RNODE_TRUE(node) ((rb_node_true_t *)(node))
#define RNODE_FALSE(node) ((rb_node_false_t *)(node))
#define RNODE_ERRINFO(node) ((rb_node_errinfo_t *)(node))
#define RNODE_DEFINED(node) ((rb_node_defined_t *)(node))
#define RNODE_POSTEXE(node) ((rb_node_postexe_t *)(node))
#define RNODE_SYM(node) ((rb_node_sym_t *)(node))
#define RNODE_DSYM(node) ((rb_node_dsym_t *)(node))
#define RNODE_ATTRASGN(node) ((rb_node_attrasgn_t *)(node))
#define RNODE_LAMBDA(node) ((rb_node_lambda_t *)(node))
#define RNODE_ARYPTN(node) ((rb_node_aryptn_t *)(node))
#define RNODE_HSHPTN(node) ((rb_node_hshptn_t *)(node))
#define RNODE_FNDPTN(node) ((rb_node_fndptn_t *)(node))
#define RNODE_LINE(node) ((rb_node_line_t *)(node))
#define RNODE_FILE(node) ((rb_node_file_t *)(node))
#define RNODE_ENCODING(node) ((rb_node_encoding_t *)(node))
/* FL : 0..4: T_TYPES, 5: KEEP_WB, 6: PROMOTED, 7: FINALIZE, 8..10: UNUSED, 11: FREEZE */
/* NODE_FL: 0..4: UNUSED, 5: UNUSED, 6: UNUSED, 7: NODE_FL_NEWLINE,
* 8..14: nd_type,
* 15..: nd_line
*/
#define NODE_FL_NEWLINE (((VALUE)1)<<7)
#define NODE_TYPESHIFT 8
#define NODE_TYPEMASK (((VALUE)0x7f)<<NODE_TYPESHIFT)
#define nd_fl_newline(n) ((n)->flags & NODE_FL_NEWLINE)
#define nd_set_fl_newline(n) ((n)->flags |= NODE_FL_NEWLINE)
#define nd_unset_fl_newline(n) ((n)->flags &= ~NODE_FL_NEWLINE)
#define nd_type(n) ((int) ((RNODE(n)->flags & NODE_TYPEMASK)>>NODE_TYPESHIFT))
#define nd_set_type(n,t) \
rb_node_set_type(n, t)
#define nd_init_type(n,t) \
(n)->flags=(((n)->flags&~NODE_TYPEMASK)|((((unsigned long)(t))<<NODE_TYPESHIFT)&NODE_TYPEMASK))
typedef struct node_buffer_struct node_buffer_t;
#ifdef UNIVERSAL_PARSER
typedef struct rb_parser_config_struct rb_parser_config_t;
#endif
typedef struct rb_ast_body_struct {
const NODE *root;
rb_parser_ary_t *script_lines;
int line_count;
signed int frozen_string_literal:2; /* -1: not specified, 0: false, 1: true */
signed int coverage_enabled:2; /* -1: not specified, 0: false, 1: true */
} rb_ast_body_t;
typedef struct rb_ast_struct {
node_buffer_t *node_buffer;
rb_ast_body_t body;
#ifdef UNIVERSAL_PARSER
const rb_parser_config_t *config;
#endif
} rb_ast_t;
/*
* Parser Interface
*/
typedef struct parser_params rb_parser_t;
#ifndef INTERNAL_IMEMO_H
typedef struct rb_imemo_tmpbuf_struct rb_imemo_tmpbuf_t;
#endif
typedef NODE *(*rb_parser_assignable_func)(struct parser_params *p, ID id, NODE *val, const rb_code_location_t *loc);
#ifdef UNIVERSAL_PARSER
typedef struct rb_parser_config_struct {
/* Memory */
void *(*malloc)(size_t size);
void *(*calloc)(size_t number, size_t size);
void *(*realloc)(void *ptr, size_t newsiz);
void (*free)(void *ptr);
void *(*alloc_n)(size_t nelems, size_t elemsiz);
void *(*alloc)(size_t elemsiz);
void *(*realloc_n)(void *ptr, size_t newelems, size_t newsiz);
void *(*zalloc)(size_t elemsiz);
void *(*rb_memmove)(void *dest, const void *src, size_t t, size_t n);
void *(*nonempty_memcpy)(void *dest, const void *src, size_t t, size_t n);
void *(*xmalloc_mul_add)(size_t x, size_t y, size_t z);
// VALUE rb_suppress_tracing(VALUE (*func)(VALUE), VALUE arg);
VALUE (*compile_callback)(VALUE (*func)(VALUE), VALUE arg);
NODE *(*reg_named_capture_assign)(struct parser_params* p, VALUE regexp, const rb_code_location_t *loc, rb_parser_assignable_func assignable);
/* Variable */
VALUE (*attr_get)(VALUE obj, ID id);
/* Array */
VALUE (*ary_new_from_args)(long n, ...);
VALUE (*ary_unshift)(VALUE ary, VALUE item);
/* Symbol */
ID (*make_temporary_id)(size_t n);
int (*is_local_id)(ID);
int (*is_attrset_id)(ID);
int (*is_global_name_punct)(const int c);
int (*id_type)(ID id);
ID (*id_attrset)(ID);
ID (*intern)(const char *name);
ID (*intern2)(const char *name, long len);
ID (*intern3)(const char *name, long len, rb_encoding *enc);
ID (*intern_str)(VALUE str);
int (*is_notop_id)(ID);
int (*enc_symname_type)(const char *name, long len, rb_encoding *enc, unsigned int allowed_attrset);
const char *(*id2name)(ID id);
VALUE (*id2str)(ID id);
VALUE (*id2sym)(ID x);
/* String */
RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 3)
VALUE (*str_catf)(VALUE str, const char *format, ...);
VALUE (*str_cat_cstr)(VALUE str, const char *ptr);
VALUE (*str_resize)(VALUE str, long len);
VALUE (*str_new)(const char *ptr, long len);
VALUE (*str_new_cstr)(const char *ptr);
VALUE (*str_to_interned_str)(VALUE);
VALUE (*enc_str_new)(const char *ptr, long len, rb_encoding *enc);
RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 0)
VALUE (*str_vcatf)(VALUE str, const char *fmt, va_list ap);
RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 1, 2)
VALUE (*rb_sprintf)(const char *format, ...);
char *(*rstring_ptr)(VALUE str);
long (*rstring_len)(VALUE str);
/* Numeric */
VALUE (*int2num)(int v);
/* IO */
int (*stderr_tty_p)(void);
void (*write_error_str)(VALUE mesg);
VALUE (*io_write)(VALUE io, VALUE str);
VALUE (*io_flush)(VALUE io);
VALUE (*io_puts)(int argc, const VALUE *argv, VALUE out);
/* IO (Ractor) */
VALUE (*debug_output_stdout)(void);
VALUE (*debug_output_stderr)(void);
/* Encoding */
int (*is_usascii_enc)(rb_encoding *enc);
int (*enc_isalnum)(OnigCodePoint c, rb_encoding *enc);
int (*enc_precise_mbclen)(const char *p, const char *e, rb_encoding *enc);
int (*mbclen_charfound_p)(int len);
int (*mbclen_charfound_len)(int len);
const char *(*enc_name)(rb_encoding *enc);
char *(*enc_prev_char)(const char *s, const char *p, const char *e, rb_encoding *enc);
rb_encoding* (*enc_get)(VALUE obj);
int (*enc_asciicompat)(rb_encoding *enc);
rb_encoding *(*utf8_encoding)(void);
rb_encoding *(*ascii8bit_encoding)(void);
int (*enc_codelen)(int c, rb_encoding *enc);
int (*enc_mbcput)(unsigned int c, void *buf, rb_encoding *enc);
int (*enc_find_index)(const char *name);
rb_encoding *(*enc_from_index)(int idx);
int (*enc_isspace)(OnigCodePoint c, rb_encoding *enc);
int (*enc_mbminlen)(rb_encoding *enc);
bool (*enc_isascii)(OnigCodePoint c, rb_encoding *enc);
OnigCodePoint (*enc_mbc_to_codepoint)(const char *p, const char *e, rb_encoding *enc);
/* Compile */
// int rb_local_defined(ID id, const rb_iseq_t *iseq);
int (*local_defined)(ID, const void*);
// int rb_dvar_defined(ID id, const rb_iseq_t *iseq);
int (*dvar_defined)(ID, const void*);
/* Error (Exception) */
RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 6, 0)
VALUE (*syntax_error_append)(VALUE, VALUE, int, int, rb_encoding*, const char*, va_list);
RBIMPL_ATTR_FORMAT(RBIMPL_PRINTF_FORMAT, 2, 3)
void (*raise)(VALUE exc, const char *fmt, ...);
VALUE (*syntax_error_new)(void);
/* Eval */
VALUE (*errinfo)(void);
void (*set_errinfo)(VALUE err);
VALUE (*make_exception)(int argc, const VALUE *argv);
/* GC */
void (*sized_xfree)(void *x, size_t size);
void *(*sized_realloc_n)(void *ptr, size_t new_count, size_t element_size, size_t old_count);
void (*gc_guard)(VALUE);
void (*gc_mark)(VALUE);
/* Re */
VALUE (*reg_compile)(VALUE str, int options, const char *sourcefile, int sourceline);
VALUE (*reg_check_preprocess)(VALUE str);
int (*memcicmp)(const void *x, const void *y, long len);
/* Error */
void (*compile_warn)(const char *file, int line, const char *fmt, ...) RUBYPARSER_ATTRIBUTE_FORMAT(3, 4);
void (*compile_warning)(const char *file, int line, const char *fmt, ...) RUBYPARSER_ATTRIBUTE_FORMAT(3, 4);
void (*bug)(const char *fmt, ...) RUBYPARSER_ATTRIBUTE_FORMAT(1, 2);
void (*fatal)(const char *fmt, ...) RUBYPARSER_ATTRIBUTE_FORMAT(1, 2);
VALUE (*verbose)(void);
int *(*errno_ptr)(void);
/* VM */
VALUE (*make_backtrace)(void);
/* Util */
unsigned long (*scan_hex)(const char *start, size_t len, size_t *retlen);
unsigned long (*scan_oct)(const char *start, size_t len, size_t *retlen);
unsigned long (*scan_digits)(const char *str, ssize_t len, int base, size_t *retlen, int *overflow);
double (*strtod)(const char *s00, char **se);
/* Misc */
int (*rtest)(VALUE obj);
int (*nil_p)(VALUE obj);
VALUE qnil;
VALUE qfalse;
VALUE (*eArgError)(void);
int (*long2int)(long);
/* For Ripper */
int enc_coderange_7bit;
int enc_coderange_unknown;
VALUE (*static_id2sym)(ID id);
long (*str_coderange_scan_restartable)(const char *s, const char *e, rb_encoding *enc, int *cr);
} rb_parser_config_t;
#undef rb_encoding
#undef OnigCodePoint
#endif /* UNIVERSAL_PARSER */
RUBY_SYMBOL_EXPORT_BEGIN
void rb_ruby_parser_free(void *ptr);
#ifdef UNIVERSAL_PARSER
rb_parser_t *rb_ruby_parser_allocate(const rb_parser_config_t *config);
rb_parser_t *rb_ruby_parser_new(const rb_parser_config_t *config);
#endif
RUBY_SYMBOL_EXPORT_END
#endif /* RUBY_RUBYPARSER_H */
|
c
|
github
|
https://github.com/ruby/ruby
|
rubyparser.h
|
#!/usr/bin/python3
import defusedxml.ElementTree as ET
import urllib.request
import urllib.parse
import sys
import ssl
__author__ = 'Nick Levesque <nick@portcanary.com>'
class NexposeException(Exception):
'''Raise this exception when the Nexpose API returns errors.'''
pass
class Nexpose:
'''
Nexpose API wrapper.
'''
def __init__(self, hostname, port):
self.hostname = hostname
self.port = port
self.url = 'https://%s:%s/api/1.1/xml' % (self.hostname, self.port)
self.session_id = None
# Often the Nexpose Console is run with a self-signed cert.
# We allow for that here.
self.ctx = ssl.create_default_context()
self.ctx.check_hostname = False
self.ctx.verify_mode = ssl.CERT_NONE
def api_request(self, xml_string):
'''Send an API request and return the response\'s root XML element.'''
# Encode the xml so that urllib will accept it.
post_data = (xml_string).encode('utf-8')
# Prepare the request.
request = urllib.request.Request(self.url)
request.add_header("Content-type", "text/xml")
# Get a response.
response = urllib.request.urlopen(request,
post_data,
context=self.ctx).read()
xml_response = ET.fromstring(response)
# Check for errors and return response.
if xml_response.attrib.get('success') != ('0' or None):
return xml_response
else:
raise NexposeException(response)
def login(self, username, password):
'''Send a LoginRequest and capture the returned session-id.'''
xml_string = '<LoginRequest user-id=\"%s\" password=\"%s\" />'\
% (username, password)
xml_response = self.api_request(xml_string)
self.session_id = xml_response.attrib.get('session-id')
return xml_response
def logout(self):
'''Send a LogoutRequest.'''
xml_string = "<LogoutRequest session-id=\"%s\" />" % (self.session_id)
xml_response = self.api_request(xml_string)
return xml_response
def get_sites(self):
'''Return a list of dicts containing site information.'''
xml_string = '<SiteListingRequest session-id=\"%s\">\
</SiteListingRequest>' % self.session_id
xml_response = self.api_request(xml_string)
site_list = []
for SiteSummary in xml_response.iter('SiteSummary'):
site = {}
site['id'] = SiteSummary.get('id')
site['name'] = SiteSummary.get('name')
site['description'] = SiteSummary.get('description')
site['riskfactor'] = SiteSummary.get('riskfactor')
site['riskscore'] = SiteSummary.get('riskscore')
site_list.append(site)
return site_list
def get_site_hosts(self, site_id):
'''Return list of ranges and hostnames associated with a site.'''
xml_string = '<SiteConfigRequest session-id=\"%s\" site-id=\"%s\">\
</SiteConfigRequest>' % (self.session_id, site_id)
xml_response = self.api_request(xml_string)
host_list = []
site = xml_response.find('Site')
hosts = site.find('Hosts')
for host in hosts.getchildren():
if host.tag == 'range':
if host.attrib.get('to') is None:
host_list.append({'range' : host.attrib.get('from')})
else:
host_list.append({'range' : ('%s-%s' % \
(host.attrib.get('from'), host.attrib.get('to')))})
elif host.tag == 'host':
host_list.append({'host' : host.text})
return host_list
def get_site_scan_config(self, site_id):
'''Return a dict of configuration info for a site.'''
xml_string = '<SiteConfigRequest session-id=\"%s\" site-id=\"%s\">\
</SiteConfigRequest>' % (self.session_id, site_id)
xml_response = self.api_request(xml_string)
site = xml_response.find('Site')
scan_config = site.find('ScanConfig')
config = {}
config['template_id'] = scan_config.attrib.get('templateID')
config['name'] = scan_config.attrib.get('name')
config['id'] = scan_config.attrib.get('configID')
config['engine_id'] = scan_config.attrib.get('engineID')
config['config_version'] = scan_config.attrib.get('configVersion')
return config
def get_scan_summary_attributes(self, scan_id, engine_id):
'''
Send a ScanStatisticsRequest and return the ScanSummary
attributes as a dict.
'''
xml_string = '<ScanStatisticsRequest session-id = \"%s\" \
engine-id = \"%s\" scan-id = \"%s\">\
</ScanStatisticsRequest>' % \
(self.session_id, engine_id, scan_id)
xml_response = self.api_request(xml_string)
scan_summary = xml_response.find('ScanSummary')
scan_summary_attributes = {}
for key in scan_summary.attrib:
scan_summary_attributes[key] = scan_summary.attrib[key]
return scan_summary_attributes
def scan_site(self, site_id):
'''Send SiteScanRequest and return dict of scan id and engine id.'''
xml_string = '<SiteScanRequest session-id = \"%s\" site-id=\"%s\">\
</SiteScanRequest>' % (self.session_id, site_id)
xml_response = self.api_request(xml_string)
scan = xml_response.find('Scan')
scan_id = scan.attrib.get('scan-id')
engine_id = scan.attrib.get('engine-id')
return {'scan_id' : scan_id, 'engine_id' : engine_id}
def get_site_devices(self, site_id):
'''Return a list of devices in a site.'''
xml_string = '<SiteDeviceListingRequest session-id = \"%s\" \
site-id = \"%s\"></SiteDeviceListingRequest>' % \
(self.session_id, site_id)
xml_response = self.api_request(xml_string)
print(ET.tostring(xml_response, encoding='ascii', method='xml'))
def scan_site_hosts(self, site_id, host_list):
'''
Send SiteDevicesScanRequest and return dict of scan id and engine
id. host_list is a list of ranges or hostnames as get_site_hosts()
would return.
'''
hosts_string = ''
for host in host_list:
ip_range = host.get('range')
if ip_range is not None:
split_ip_range = ip_range.split('-')
if len(split_ip_range) == 1:
hosts_string += ('<range from=\"%s\"/>' % \
str(split_ip_range[0]))
elif len(split_ip_range) == 2:
hosts_string += ('<range from=\"%s\" to=\"%s\"/>' % \
(split_ip_range[0],
split_ip_range[1]))
else:
raise Exception('Invalid IP range: %s' % ip_range)
else:
hostname = host.get('host')
hostname = hostname.replace("'","")
hosts_string += ('<host>%s</host>' % hostname)
xml_string = '<SiteDevicesScanRequest session-id=\"%s\" \
site-id=\"%s\"><Devices></Devices><Hosts>%s</Hosts>\
</SiteDevicesScanRequest>' % (self.session_id,
site_id,
hosts_string)
xml_response = self.api_request(xml_string)
scan = xml_response.find('Scan')
scan_id = scan.attrib.get('scan-id')
engine_id = scan.attrib.get('engine-id')
return {'scan_id': scan_id, 'engine_id' : engine_id}
if __name__ == '__main__':
# Usage: ./nexpose.py hostname port username password
try:
nexpose = Nexpose(sys.argv[1], sys.argv[2])
nexpose.login(sys.argv[3], sys.argv[4])
print(nexpose.get_site_scan_config('1'))
except urllib.error.URLError as e:
print("URLError: Perhaps you entered the wrong URL or port? %s" % e)
exit()
try:
nexpose.logout()
except:
print('Tried to logout when we weren\'t signed in.')
pass
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
* Copyright 2012-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/
package org.springframework.boot.ant;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.jspecify.annotations.Nullable;
import org.springframework.util.StringUtils;
/**
* Quiet task that establishes a reference to its loader.
*
* @author Matt Benson
* @since 1.3.0
*/
public class ShareAntlibLoader extends Task {
private @Nullable String refid;
public ShareAntlibLoader(Project project) {
setProject(project);
}
@Override
public void execute() throws BuildException {
if (!StringUtils.hasText(this.refid)) {
throw new BuildException("@refid has no text");
}
getProject().addReference(this.refid, getClass().getClassLoader());
}
public void setRefid(@Nullable String refid) {
this.refid = refid;
}
}
|
java
|
github
|
https://github.com/spring-projects/spring-boot
|
build-plugin/spring-boot-antlib/src/main/java/org/springframework/boot/ant/ShareAntlibLoader.java
|
import json
import struct
import os
extra_info = [0 for x in range(10000)]
extra_data = open("./extra_data", "r")
for line in extra_data:
line = line.rstrip()
numeroMapa = line.split('=')[0]
data = line.split('=')[1]
extra_info[int(numeroMapa)] = data
def getExtraData (mapa):
return extra_info[mapa]
for fn in os.listdir('.'):
if not os.path.isfile(fn):
continue
if not fn.endswith(".map"):
continue
origen = open(fn, "rb")
numeroMapa = fn[4:fn.find('.')]
fileDest = "mapas_json/" + "mapa" + numeroMapa + '.json'
destino = open(fileDest,"w")
#if fileDest != "mapas_json/mapa1.json":
# continue
print fileDest
origen.read(256+17) # saco header
mapa = [[[0 for y in range(6)] for y in range(101)] for y in range(101)]
x = 1
while ( x < 101):
y = 1
while (y < 101):
flags = struct.unpack('<B', (origen.read(1)))[0] # cant layers
if (flags & 1):
bloqueado=1
else:
bloqueado=0
layer1 = struct.unpack('<H', (origen.read(2)))[0] # l1
if (flags & 2):
layer2 = struct.unpack('<H', (origen.read(2)))[0] # l1
else:
layer2=0
if (flags & 4):
layer3 = struct.unpack('<H', (origen.read(2)))[0] # l1
else:
layer3=0
if (flags & 8):
layer4 = struct.unpack('<H', (origen.read(2)))[0] # l1
else:
layer4=0
if (flags & 16):
trigger = struct.unpack('<H', (origen.read(2)))[0] # l1
if ( (trigger != 1) and (trigger != 4) ):
trigger = 0
else:
trigger=0
mapa[y][x][0] = bloqueado
mapa[y][x][1] = layer1
mapa[y][x][2] = layer2
mapa[y][x][3] = layer3
mapa[y][x][4] = layer4
mapa[y][x][5] = trigger
y = y+1
x = x+1
x = 1
# datos extra ###################### desactivado #############################
#destino.write("{")
#destino.write(getExtraData(int(numeroMapa)))
# Layers
destino.write(",")
destino.write('"layers":')
destino.write("[")
while ( x < 101):
y = 1
destino.write("[")
while (y < 101):
destino.write("{")
mapa[x][y][0] = mapa[x][y][0]
if mapa[x][y][0] != 0:
destino.write(""""0":""")
destino.write(str(mapa[x][y][0]))
#mapa[x][y][1] = mapa[x][y][1]
if mapa[x][y][1] != 0:
if mapa[x][y][0] != 0:
destino.write(",")
destino.write(""""1":""")
destino.write(str(mapa[x][y][1]))
#mapa[x][y][2] = mapa[x][y][2]
if mapa[x][y][2] != 0:
if ( (mapa[x][y][0] != 0) or (mapa[x][y][1] != 0)):
destino.write(",")
destino.write(""""2":""")
destino.write(str(mapa[x][y][2]))
#mapa[x][y][3] = mapa[x][y][3]
if mapa[x][y][3] != 0:
if ( (mapa[x][y][0] != 0 or mapa[x][y][1] != 0) or mapa[x][y][2] != 0):
destino.write(",")
destino.write(""""3":""")
destino.write(str(mapa[x][y][3]))
#mapa[x][y][4] = layer4
if mapa[x][y][4] != 0:
if ( ((mapa[x][y][0] != 0 or mapa[x][y][1] != 0) or mapa[x][y][2] != 0) or mapa[x][y][3] != 0):
destino.write(",")
destino.write(""""4":""")
destino.write(str(mapa[x][y][4]))
if mapa[x][y][5] != 0:
if ((((mapa[x][y][0] != 0 or mapa[x][y][1] != 0) or mapa[x][y][2] != 0) or mapa[x][y][3] != 0) or mapa[x][y][4] != 0):
destino.write(",")
destino.write(""""5":""")
destino.write(str(mapa[x][y][5]))
if y==100:
destino.write("}")
else:
destino.write("},")
y = y+1
if x==100:
destino.write("]")
else:
destino.write("],")
x = x+1
destino.write("]")
destino.write("}")
|
unknown
|
codeparrot/codeparrot-clean
| ||
# flake8: noqa (we don't need the "<...> imported but unused" error)
from pycqed.version import __version__
import sys
module_name = "qcodes"
if module_name in sys.modules:
# This is needed so that the `qcodes_QtPlot_monkey_patching` works for any
# subsequent `qcodes` import
raise ImportError("`pycqed` must be imported before `qcodes`! See "
"__init__.py in `pycqed` folder for more information.\n"
"NB: Any `qcodes` submodule must also be imported after pycqed.")
# We need to import this here so that any later imports of `QtPlot` from qcodes
# KEEP ABOVE any QtPlot import!!!
from pycqed.measurement import qcodes_QtPlot_monkey_patching
# from pycqed import measurement
# from pycqed import analysis
# from pycqed import instrument_drivers
# from pycqed import utilities
# # General PycQED modules
# from pycqed.measurement import measurement_control as mc
# from pycqed.measurement import sweep_functions as swf
# from pycqed.measurement import awg_sweep_functions as awg_swf
# from pycqed.measurement import detector_functions as det
# from pycqed.measurement import composite_detector_functions as cdet
# from pycqed.measurement import calibration_toolbox as cal_tools
# from pycqed.measurement import mc_parameter_wrapper as pw
# from pycqed.measurement import CBox_sweep_functions as cb_swf
# from pycqed.measurement.optimization import nelder_mead
# from pycqed.analysis import measurement_analysis as ma
# from pycqed.analysis import analysis_toolbox as a_tools
# from pycqed.utilities import general as gen
|
unknown
|
codeparrot/codeparrot-clean
| ||
import numpy as np
from scipy import fftpack
import matplotlib.pyplot as plt
from garcia_functions import *
"""
A partir de una topografia y una grilla de rigidez D obtenemos la deflexion
que genera dicha carga topografica a traves del metodo de Garcia (2014).
"""
def ploteo(x, y, z, contours=150, title=""):
plt.axes(aspect='equal')
plt.contourf(x, y, z, contours)
plt.colorbar()
plt.title(title)
plt.show()
## LEO ARCHIVO DATOS
datos = np.loadtxt("../grillas/datos.txt")
topo = np.loadtxt("../grillas/topografia.npy")
Te = np.loadtxt("../grillas/espesor-elastico-grillado.npy")
x1, x2, y1, y2, nx, ny, rho_t, rho_c, rho_m, t = datos[:]
E = 1e11
nu = 0.25
## GRILLA DE TRABAJO
x = np.linspace(x1, x2, nx)
y = np.linspace(y1, y2, ny)
x, y = np.meshgrid(x, y)
Te[np.isnan(Te)] = 0
print Te
Te_0 = 12000
w0 = deflection_calculation(x, y, topo, rho_t, rho_c, rho_m, Te_0, E, nu)
w = garcia_iteration(x, y, w0, Te, Te_0, rho_t, rho_c, rho_m, E, nu, rms_dif_tolerance=1e-13)
#~ np.savetxt("../grillas/topografia.npy", topo)
np.savetxt("../grillas/deflexion-flexural.npy", w)
ploteo(x, y, Te, title="Te")
ploteo(x, y, w0, title="w0")
ploteo(x, y, w, title="w")
|
unknown
|
codeparrot/codeparrot-clean
| ||
{
"definitions": {
"Provides": {
"description": "Modules that should be provided as shared modules to the share scope. When provided, property name is used to match modules, otherwise this is automatically inferred from share key.",
"anyOf": [
{
"type": "array",
"items": {
"description": "Modules that should be provided as shared modules to the share scope.",
"anyOf": [
{
"$ref": "#/definitions/ProvidesItem"
},
{
"$ref": "#/definitions/ProvidesObject"
}
]
}
},
{
"$ref": "#/definitions/ProvidesObject"
}
]
},
"ProvidesConfig": {
"description": "Advanced configuration for modules that should be provided as shared modules to the share scope.",
"type": "object",
"additionalProperties": false,
"properties": {
"eager": {
"description": "Include the provided module directly instead behind an async request. This allows to use this shared module in initial load too. All possible shared modules need to be eager too.",
"type": "boolean"
},
"shareKey": {
"description": "Key in the share scope under which the shared modules should be stored.",
"type": "string",
"minLength": 1
},
"shareScope": {
"description": "Share scope name.",
"type": "string",
"minLength": 1
},
"version": {
"description": "Version of the provided module. Will replace lower matching versions, but not higher.",
"anyOf": [
{
"description": "Don't provide a version.",
"enum": [false]
},
{
"description": "Version as string. Each part of the version should be separated by a dot '.'.",
"type": "string"
}
]
}
}
},
"ProvidesItem": {
"description": "Request to a module that should be provided as shared module to the share scope (will be resolved when relative).",
"type": "string",
"minLength": 1
},
"ProvidesObject": {
"description": "Modules that should be provided as shared modules to the share scope. Property names are used as share keys.",
"type": "object",
"additionalProperties": {
"description": "Modules that should be provided as shared modules to the share scope.",
"anyOf": [
{
"$ref": "#/definitions/ProvidesConfig"
},
{
"$ref": "#/definitions/ProvidesItem"
}
]
}
}
},
"title": "ProvideSharedPluginOptions",
"type": "object",
"additionalProperties": false,
"properties": {
"provides": {
"$ref": "#/definitions/Provides"
},
"shareScope": {
"description": "Share scope name used for all provided modules (defaults to 'default').",
"type": "string",
"minLength": 1
}
},
"required": ["provides"]
}
|
json
|
github
|
https://github.com/webpack/webpack
|
schemas/plugins/sharing/ProvideSharedPlugin.json
|
#!/bin/sh
# Copyright (c) 2006 Eric Wong
test_description='git svn metadata migrations from previous versions'
. ./lib-git-svn.sh
test_expect_success 'setup old-looking metadata' '
cp "$GIT_DIR"/config "$GIT_DIR"/config-old-git-svn &&
mkdir import &&
(
cd import &&
for i in trunk branches/a branches/b tags/0.1 tags/0.2 tags/0.3
do
mkdir -p $i &&
echo hello >>$i/README ||
exit 1
done &&
svn_cmd import -m test . "$svnrepo"
) &&
git svn init "$svnrepo" &&
git svn fetch &&
rm -rf "$GIT_DIR"/svn &&
git update-ref refs/heads/git-svn-HEAD refs/remotes/git-svn &&
git update-ref refs/heads/svn-HEAD refs/remotes/git-svn &&
git update-ref -d refs/remotes/git-svn refs/remotes/git-svn
'
test_expect_success 'git-svn-HEAD is a real HEAD' '
git rev-parse --verify refs/heads/git-svn-HEAD^0
'
svnrepo_escaped=$(echo $svnrepo | sed 's/ /%20/g')
test_expect_success 'initialize old-style (v0) git svn layout' '
mkdir -p "$GIT_DIR"/git-svn/info "$GIT_DIR"/svn/info &&
echo "$svnrepo" > "$GIT_DIR"/git-svn/info/url &&
echo "$svnrepo" > "$GIT_DIR"/svn/info/url &&
git svn migrate &&
! test -d "$GIT_DIR"/git-svn &&
git rev-parse --verify refs/remotes/git-svn^0 &&
git rev-parse --verify refs/remotes/svn^0 &&
test "$(git config --get svn-remote.svn.url)" = "$svnrepo_escaped" &&
test $(git config --get svn-remote.svn.fetch) = \
":refs/remotes/git-svn"
'
test_expect_success 'initialize a multi-repository repo' '
git svn init "$svnrepo" -T trunk -t tags -b branches &&
git config --get-all svn-remote.svn.fetch > fetch.out &&
grep "^trunk:refs/remotes/origin/trunk$" fetch.out &&
test -n "$(git config --get svn-remote.svn.branches \
"^branches/\*:refs/remotes/origin/\*$")" &&
test -n "$(git config --get svn-remote.svn.tags \
"^tags/\*:refs/remotes/origin/tags/\*$")" &&
git config --unset svn-remote.svn.branches \
"^branches/\*:refs/remotes/origin/\*$" &&
git config --unset svn-remote.svn.tags \
"^tags/\*:refs/remotes/origin/tags/\*$" &&
git config --add svn-remote.svn.fetch "branches/a:refs/remotes/origin/a" &&
git config --add svn-remote.svn.fetch "branches/b:refs/remotes/origin/b" &&
for i in tags/0.1 tags/0.2 tags/0.3
do
git config --add svn-remote.svn.fetch \
$i:refs/remotes/origin/$i || return 1
done &&
git config --get-all svn-remote.svn.fetch > fetch.out &&
grep "^trunk:refs/remotes/origin/trunk$" fetch.out &&
grep "^branches/a:refs/remotes/origin/a$" fetch.out &&
grep "^branches/b:refs/remotes/origin/b$" fetch.out &&
grep "^tags/0\.1:refs/remotes/origin/tags/0\.1$" fetch.out &&
grep "^tags/0\.2:refs/remotes/origin/tags/0\.2$" fetch.out &&
grep "^tags/0\.3:refs/remotes/origin/tags/0\.3$" fetch.out &&
grep "^:refs/remotes/git-svn" fetch.out
'
# refs should all be different, but the trees should all be the same:
test_expect_success 'multi-fetch works on partial urls + paths' '
refs="trunk a b tags/0.1 tags/0.2 tags/0.3" &&
git svn multi-fetch &&
for i in $refs
do
git rev-parse --verify refs/remotes/origin/$i^0 || return 1;
done >refs.out &&
test -z "$(sort <refs.out | uniq -d)" &&
for i in $refs
do
for j in $refs
do
git diff --exit-code refs/remotes/origin/$i \
refs/remotes/origin/$j ||
return 1
done
done
'
test_expect_success 'migrate --minimize on old inited layout' '
git config --unset-all svn-remote.svn.fetch &&
git config --unset-all svn-remote.svn.url &&
rm -rf "$GIT_DIR"/svn &&
for i in $(cat fetch.out)
do
path=${i%%:*} &&
ref=${i#*:} &&
if test "$ref" = "${ref#refs/remotes/}"; then continue; fi &&
if test -n "$path"; then path="/$path"; fi &&
mkdir -p "$GIT_DIR"/svn/$ref/info/ &&
echo "$svnrepo"$path >"$GIT_DIR"/svn/$ref/info/url ||
return 1
done &&
git svn migrate --minimize &&
test -z "$(git config -l | grep "^svn-remote\.git-svn\.")" &&
git config --get-all svn-remote.svn.fetch > fetch.out &&
grep "^trunk:refs/remotes/origin/trunk$" fetch.out &&
grep "^branches/a:refs/remotes/origin/a$" fetch.out &&
grep "^branches/b:refs/remotes/origin/b$" fetch.out &&
grep "^tags/0\.1:refs/remotes/origin/tags/0\.1$" fetch.out &&
grep "^tags/0\.2:refs/remotes/origin/tags/0\.2$" fetch.out &&
grep "^tags/0\.3:refs/remotes/origin/tags/0\.3$" fetch.out &&
grep "^:refs/remotes/git-svn" fetch.out
'
test_expect_success ".rev_db auto-converted to .rev_map.UUID" '
git svn fetch -i trunk &&
test -z "$(ls "$GIT_DIR"/svn/refs/remotes/origin/trunk/.rev_db.* 2>/dev/null)" &&
expect="$(ls "$GIT_DIR"/svn/refs/remotes/origin/trunk/.rev_map.*)" &&
test -n "$expect" &&
rev_db="$(echo $expect | sed -e "s,_map,_db,")" &&
convert_to_rev_db "$expect" "$rev_db" &&
rm -f "$expect" &&
test -f "$rev_db" &&
git svn fetch -i trunk &&
test -z "$(ls "$GIT_DIR"/svn/refs/remotes/origin/trunk/.rev_db.* 2>/dev/null)" &&
test ! -e "$GIT_DIR"/svn/refs/remotes/origin/trunk/.rev_db &&
test -f "$expect"
'
test_done
|
unknown
|
github
|
https://github.com/git/git
|
t/t9107-git-svn-migrate.sh
|
# 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.
# ==============================================================================
"""Functional tests for 3d convolutional operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import itertools
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import math_ops
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging
class BetaincTest(test.TestCase):
def _testBetaInc(self, a_s, b_s, x_s, dtype):
try:
from scipy import special # pylint: disable=g-import-not-at-top
np_dt = dtype.as_numpy_dtype
# Test random values
a_s = a_s.astype(np_dt) # in (0, infty)
b_s = b_s.astype(np_dt) # in (0, infty)
x_s = x_s.astype(np_dt) # in (0, 1)
tf_a_s = constant_op.constant(a_s, dtype=dtype)
tf_b_s = constant_op.constant(b_s, dtype=dtype)
tf_x_s = constant_op.constant(x_s, dtype=dtype)
tf_out_t = math_ops.betainc(tf_a_s, tf_b_s, tf_x_s)
with self.test_session():
tf_out = tf_out_t.eval()
scipy_out = special.betainc(a_s, b_s, x_s).astype(np_dt)
# the scipy version of betainc uses a double-only implementation.
# TODO(ebrevdo): identify reasons for (sometime) precision loss
# with doubles
tol = 1e-4 if dtype == dtypes.float32 else 5e-5
self.assertAllCloseAccordingToType(scipy_out, tf_out, rtol=tol, atol=0)
# Test out-of-range values (most should return nan output)
combinations = list(itertools.product([-1, 0, 0.5, 1.0, 1.5], repeat=3))
a_comb, b_comb, x_comb = np.asarray(list(zip(*combinations)), dtype=np_dt)
with self.test_session():
tf_comb = math_ops.betainc(a_comb, b_comb, x_comb).eval()
scipy_comb = special.betainc(a_comb, b_comb, x_comb).astype(np_dt)
self.assertAllCloseAccordingToType(scipy_comb, tf_comb)
# Test broadcasting between scalars and other shapes
with self.test_session():
self.assertAllCloseAccordingToType(
special.betainc(0.1, b_s, x_s).astype(np_dt),
math_ops.betainc(0.1, b_s, x_s).eval(),
rtol=tol,
atol=0)
self.assertAllCloseAccordingToType(
special.betainc(a_s, 0.1, x_s).astype(np_dt),
math_ops.betainc(a_s, 0.1, x_s).eval(),
rtol=tol,
atol=0)
self.assertAllCloseAccordingToType(
special.betainc(a_s, b_s, 0.1).astype(np_dt),
math_ops.betainc(a_s, b_s, 0.1).eval(),
rtol=tol,
atol=0)
self.assertAllCloseAccordingToType(
special.betainc(0.1, b_s, 0.1).astype(np_dt),
math_ops.betainc(0.1, b_s, 0.1).eval(),
rtol=tol,
atol=0)
self.assertAllCloseAccordingToType(
special.betainc(0.1, 0.1, 0.1).astype(np_dt),
math_ops.betainc(0.1, 0.1, 0.1).eval(),
rtol=tol,
atol=0)
with self.assertRaisesRegexp(ValueError, "must be equal"):
math_ops.betainc(0.5, [0.5], [[0.5]])
with self.test_session():
with self.assertRaisesOpError("Shapes of .* are inconsistent"):
a_p = array_ops.placeholder(dtype)
b_p = array_ops.placeholder(dtype)
x_p = array_ops.placeholder(dtype)
math_ops.betainc(a_p, b_p, x_p).eval(
feed_dict={a_p: 0.5,
b_p: [0.5],
x_p: [[0.5]]})
except ImportError as e:
tf_logging.warn("Cannot test special functions: %s" % str(e))
def testBetaIncFloat(self):
a_s = np.abs(np.random.randn(10, 10) * 30) # in (0, infty)
b_s = np.abs(np.random.randn(10, 10) * 30) # in (0, infty)
x_s = np.random.rand(10, 10) # in (0, 1)
self._testBetaInc(a_s, b_s, x_s, dtypes.float32)
def testBetaIncDouble(self):
a_s = np.abs(np.random.randn(10, 10) * 30) # in (0, infty)
b_s = np.abs(np.random.randn(10, 10) * 30) # in (0, infty)
x_s = np.random.rand(10, 10) # in (0, 1)
self._testBetaInc(a_s, b_s, x_s, dtypes.float64)
def testBetaIncDoubleVeryLargeValues(self):
a_s = np.abs(np.random.randn(10, 10) * 1e15) # in (0, infty)
b_s = np.abs(np.random.randn(10, 10) * 1e15) # in (0, infty)
x_s = np.random.rand(10, 10) # in (0, 1)
self._testBetaInc(a_s, b_s, x_s, dtypes.float64)
def testBetaIncDoubleVerySmallValues(self):
a_s = np.abs(np.random.randn(10, 10) * 1e-16) # in (0, infty)
b_s = np.abs(np.random.randn(10, 10) * 1e-16) # in (0, infty)
x_s = np.random.rand(10, 10) # in (0, 1)
self._testBetaInc(a_s, b_s, x_s, dtypes.float64)
def testBetaIncFloatVerySmallValues(self):
a_s = np.abs(np.random.randn(10, 10) * 1e-8) # in (0, infty)
b_s = np.abs(np.random.randn(10, 10) * 1e-8) # in (0, infty)
x_s = np.random.rand(10, 10) # in (0, 1)
self._testBetaInc(a_s, b_s, x_s, dtypes.float32)
def testBetaIncFpropAndBpropAreNeverNAN(self):
with self.test_session() as sess:
space = np.logspace(-8, 5).tolist()
space_x = np.linspace(1e-16, 1 - 1e-16).tolist()
ga_s, gb_s, gx_s = zip(*list(itertools.product(space, space, space_x)))
# Test grads are never nan
ga_s_t = constant_op.constant(ga_s, dtype=dtypes.float32)
gb_s_t = constant_op.constant(gb_s, dtype=dtypes.float32)
gx_s_t = constant_op.constant(gx_s, dtype=dtypes.float32)
tf_gout_t = math_ops.betainc(ga_s_t, gb_s_t, gx_s_t)
tf_gout, grads_x = sess.run(
[tf_gout_t,
gradients_impl.gradients(tf_gout_t, [ga_s_t, gb_s_t, gx_s_t])[2]])
# Equivalent to `assertAllFalse` (if it existed).
self.assertAllEqual(np.zeros_like(grads_x).astype(np.bool),
np.isnan(tf_gout))
self.assertAllEqual(np.zeros_like(grads_x).astype(np.bool),
np.isnan(grads_x))
def testBetaIncGrads(self):
err_tolerance = 1e-3
with self.test_session():
# Test gradient
ga_s = np.abs(np.random.randn(2, 2) * 30) # in (0, infty)
gb_s = np.abs(np.random.randn(2, 2) * 30) # in (0, infty)
gx_s = np.random.rand(2, 2) # in (0, 1)
tf_ga_s = constant_op.constant(ga_s, dtype=dtypes.float64)
tf_gb_s = constant_op.constant(gb_s, dtype=dtypes.float64)
tf_gx_s = constant_op.constant(gx_s, dtype=dtypes.float64)
tf_gout_t = math_ops.betainc(tf_ga_s, tf_gb_s, tf_gx_s)
err = gradient_checker.compute_gradient_error(
[tf_gx_s], [gx_s.shape], tf_gout_t, gx_s.shape)
print("betainc gradient err = %g " % err)
self.assertLess(err, err_tolerance)
# Test broadcast gradient
gx_s = np.random.rand() # in (0, 1)
tf_gx_s = constant_op.constant(gx_s, dtype=dtypes.float64)
tf_gout_t = math_ops.betainc(tf_ga_s, tf_gb_s, tf_gx_s)
err = gradient_checker.compute_gradient_error(
[tf_gx_s], [()], tf_gout_t, ga_s.shape)
print("betainc gradient err = %g " % err)
self.assertLess(err, err_tolerance)
if __name__ == "__main__":
test.main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
#
# (c) 2016 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.onyx import onyx_config
from units.modules.utils import set_module_args
from .onyx_module import TestOnyxModule, load_fixture
class TestOnyxConfigModule(TestOnyxModule):
module = onyx_config
def setUp(self):
super(TestOnyxConfigModule, self).setUp()
self.mock_get_config = patch('ansible.modules.network.onyx.onyx_config.get_config')
self.get_config = self.mock_get_config.start()
self.mock_load_config = patch('ansible.modules.network.onyx.onyx_config.load_config')
self.load_config = self.mock_load_config.start()
self.mock_run_commands = patch('ansible.modules.network.onyx.onyx_config.run_commands')
self.run_commands = self.mock_run_commands.start()
def tearDown(self):
super(TestOnyxConfigModule, self).tearDown()
self.mock_get_config.stop()
self.mock_load_config.stop()
self.mock_run_commands.stop()
def load_fixtures(self, commands=None, transport='cli'):
config_file = 'onyx_config_config.cfg'
self.get_config.return_value = load_fixture(config_file)
self.load_config.return_value = None
def test_onyx_config_unchanged(self):
src = load_fixture('onyx_config_config.cfg')
set_module_args(dict(src=src))
self.execute_module()
def test_onyx_config_src(self):
src = load_fixture('onyx_config_src.cfg')
set_module_args(dict(src=src))
commands = [
'interface mlag-port-channel 2']
self.execute_module(changed=True, commands=commands, is_updates=True)
def test_onyx_config_backup(self):
set_module_args(dict(backup=True))
result = self.execute_module()
self.assertIn('__backup__', result)
def test_onyx_config_save(self):
set_module_args(dict(save='yes'))
self.execute_module(changed=True)
self.assertEqual(self.run_commands.call_count, 1)
self.assertEqual(self.get_config.call_count, 1)
self.assertEqual(self.load_config.call_count, 0)
args = self.run_commands.call_args[0][1]
self.assertIn('configuration write', args)
def test_onyx_config_lines_wo_parents(self):
set_module_args(dict(lines=['hostname foo']))
commands = ['hostname foo']
self.execute_module(changed=True, commands=commands, is_updates=True)
def test_onyx_config_before(self):
set_module_args(dict(lines=['hostname foo'], before=['test1', 'test2']))
commands = ['test1', 'test2', 'hostname foo']
self.execute_module(changed=True, commands=commands, sort=False, is_updates=True)
def test_onyx_config_after(self):
set_module_args(dict(lines=['hostname foo'], after=['test1', 'test2']))
commands = ['hostname foo', 'test1', 'test2']
self.execute_module(changed=True, commands=commands, sort=False, is_updates=True)
def test_onyx_config_before_after(self):
set_module_args(dict(lines=['hostname foo'],
before=['test1', 'test2'],
after=['test3', 'test4']))
commands = ['test1', 'test2', 'hostname foo', 'test3', 'test4']
self.execute_module(changed=True, commands=commands, sort=False, is_updates=True)
def test_onyx_config_config(self):
config = 'hostname localhost'
set_module_args(dict(lines=['hostname router'], config=config))
commands = ['hostname router']
self.execute_module(changed=True, commands=commands, is_updates=True)
def test_onyx_config_match_none(self):
lines = ['hostname router']
set_module_args(dict(lines=lines, match='none'))
self.execute_module(changed=True, commands=lines, is_updates=True)
|
unknown
|
codeparrot/codeparrot-clean
| ||
"""
=======================================================
Check congruency of aligned reads in terms of COG
annotations
=======================================================
:Author: Nick Ilott
:Release: $Id$
:Date: |today|
:Tags: Python
"""
# load modules
from ruffus import *
import CGAT.Experiment as E
import logging as L
import CGAT.Database as Database
import CGAT.CSV as CSV
import sys
import os
import re
import shutil
import itertools
import math
import glob
import time
import gzip
import collections
import random
import numpy
import sqlite3
import CGAT.IOTools as IOTools
from rpy2.robjects import r as R
###################################################
###################################################
###################################################
# Pipeline configuration
###################################################
# load options from the config file
import CGATPipelines.Pipeline as P
P.getParameters(
["pipeline.ini"])
PARAMS = P.PARAMS
###################################################
###################################################
###################################################
@follows(mkdir("congruency.dir"))
@transform("*.tsv.gz",
regex("(\S+).tsv.gz"),
add_inputs(PARAMS.get("annotations_gene2cog")),
r"congruency.dir/\1.congruency.tsv.gz")
def buildCongruency(infiles, outfile):
'''
build a table of reads with the % congruent with
the best hit. We take the top n alignments as representing
a random sample
'''
n = PARAMS.get("sample_sample")
alignments, annotations = infiles
temp = P.getTempFilename(".")
statement = '''zcat %(alignments)s | cut -f1 | uniq | head -n %(n)i > %(temp)s;
python %(scriptsdir)s/best_hit_congruency.py
-a %(alignments)s
-m %(annotations)s
-r %(temp)s
--log=%(outfile)s.log
| gzip > %(outfile)s;
rm -rf %(temp)s'''
P.run()
#########################################
#########################################
#########################################
@jobs_limit(1, "R")
@transform(buildCongruency, suffix(".tsv.gz"), ".pdf")
def plotCongruency(infile, outfile):
'''
histogram congruency
'''
R('''library(ggplot2)''')
R('''dat <- read.csv("%s", header = T, stringsAsFactors = F, se = "\t")''' % infile)
R('''congruent_over_50 <- (length(dat$pcongruent[dat$pcongruent >= 50])/nrow(dat))*100''')
R('''ggplot(dat, aes(x = pcongruent)) + geom_histogram() + labs(title = congruent_over_50)''')
R('''ggsave("%s")''' % outfile)
#########################################
#########################################
#########################################
@follows(plotCongruency)
def full():
pass
#########################################
#########################################
#########################################
if __name__ == "__main__":
sys.exit(P.main(sys.argv))
|
unknown
|
codeparrot/codeparrot-clean
| ||
# Overrides necessary for killing the primary.
###
# Hook options.
###
- name: replica_sets_hooks
value:
executor:
hooks:
# We disable the primary termination so that stepdowns occur with a live system. This
# will caause numerous Rollback-To-Stable scenarios which is the desired scenario.
- class: ContinuousStepdown
terminate: false
kill: false
# The CheckReplDBHash hook waits until all operations have replicated to and have been applied
# on the secondaries, so we run the ValidateCollections hook after it to ensure we're
# validating the entire contents of the collection.
- class: CheckReplOplogs
- class: CheckReplPreImagesConsistency
- class: CheckReplDBHash
- class: ValidateCollections
shell_options:
global_vars:
TestData:
runningWithStepdowns: true
skipEnforceFastCountOnValidate: true
- class: CleanEveryN
n: 20
- name: replica_sets_hooks_with_legacy_validate
value:
executor:
hooks:
# We disable the primary termination so that stepdowns occur with a live system. This
# will caause numerous Rollback-To-Stable scenarios which is the desired scenario.
- class: ContinuousStepdown
terminate: false
kill: false
# The CheckReplDBHash hook waits until all operations have replicated to and have been applied
# on the secondaries, so we run the ValidateCollections hook after it to ensure we're
# validating the entire contents of the collection.
- class: CheckReplOplogs
- class: CheckReplPreImagesConsistency
- class: CheckReplDBHash
- class: ValidateCollections
use_legacy_validate: true
shell_options:
global_vars:
TestData:
runningWithStepdowns: true
skipEnforceFastCountOnValidate: true
- class: CleanEveryN
n: 20
skip_database_deletion: true
###
# Archival options.
###
- name: replica_sets_archive
value:
executor:
archive:
tests: true
hooks:
- CheckReplDBHash
- CheckReplOplogs
- CheckReplPreImagesConsistency
- ValidateCollections
|
unknown
|
github
|
https://github.com/mongodb/mongo
|
buildscripts/resmokeconfig/matrix_suites/overrides/stepdown_primary_change_streams.yml
|
"""
Copyright (C) 2014, Jaguar Land Rover
This program is licensed under the terms and conditions of the
Mozilla Public License, version 2.0. The full text of the
Mozilla Public License is at https://www.mozilla.org/MPL/2.0/
Maintainer: Rudolf Streif (rstreif@jaguarlandrover.com)
"""
"""
Software Over The Air (SOTA) services.
"""
import os, threading, base64
import time
from urlparse import urlparse
import Queue
from rvijsonrpc import RVIJSONRPCServer
import __init__
from __init__ import __RVI_LOGGER__ as rvi_logger
from __init__ import __SOTA_LOGGER__ as sota_logger
import sota.models
# globals
package_queue = Queue.Queue()
# SOTA Callback Server
class SOTACallbackServer(threading.Thread):
"""
RPC server thread responding to SOTA callbacks from the RVI framework
"""
def __init__(self, service_edge, callback_url, service_id):
self.service_edge = service_edge
self.service_id = service_id
self.callback_url = callback_url
threading.Thread.__init__(self)
url = urlparse(self.callback_url)
self.localServer = RVIJSONRPCServer(addr=((url.hostname, url.port)), logRequests=False)
self.register_services()
def register_services(self):
# register callback functions with RPC server
self.localServer.register_function(initiate_download, self.service_id + "/initiate_download")
self.localServer.register_function(cancel_download, self.service_id + "/cancel_download")
self.localServer.register_function(download_complete, self.service_id + "/download_complete")
# register services with RVI framework
result = self.service_edge.register_service(service = self.service_id+'/initiate_download',
network_address = self.callback_url)
rvi_logger.info('SOTA Service Registration: Initiate download service name: %s', result['service'])
result = self.service_edge.register_service(service = self.service_id+'/cancel_download',
network_address = self.callback_url)
rvi_logger.info('SOTA Service Registration: Cancel download service name: %s', result['service'])
result = self.service_edge.register_service(service = self.service_id+'/download_complete',
network_address = self.callback_url)
rvi_logger.info('SOTA Service Registration: Download complete service name: %s', result['service'])
def run(self):
self.localServer.serve_forever()
def shutdown(self):
self.localServer.shutdown()
# Callback functions
def initiate_download(package, destination, retry):
rvi_logger.info('SOTA Callback Server: Initiate download request: retry %s - %s to %s.', retry, package, destination)
package_queue.put([package, destination, retry])
return {u'status': 0}
def cancel_download(retry):
rvi_logger.info('SOTA Callback Server: Cancel download request: retry: %s.', retry)
retry_obj = None
update_obj = None
try:
retry_obj = sota.models.Retry.objects.filter(pk=retry)[0]
update_obj = retry_obj.ret_update
except:
rvi_logger.error('SOTA Callback Server: Cancel downlaod request: Cannot access database object: %s', retry)
return {u'status': 0}
retry_obj.set_status(sota.models.Status.REJECTED)
update_obj.set_status(sota.models.Status.REJECTED)
sota_logger.info('SOTA Callback Server: Cancel download request: %s.', retry_obj)
return {u'status': 0}
def download_complete(status, retry):
rvi_logger.info('SOTA Callback Server: Download complete: retry: %s, status: %s.', retry, status)
retry_obj = None
update_obj = None
try:
retry_obj = sota.models.Retry.objects.filter(pk=retry)[0]
update_obj = retry_obj.ret_update
except:
rvi_logger.error('SOTA Callback Server: Download complete: Cannot access database object: %s', retry)
return {u'status': 0}
if int(status) == 0:
retry_obj.set_status(sota.models.Status.SUCCESS)
update_obj.set_status(sota.models.Status.SUCCESS)
else:
retry_obj.set_status(sota.models.Status.FAILED)
update_obj.set_status(sota.models.Status.FAILED)
sota_logger.info('SOTA Callback Server: Download complete: retry: %s, status: %s.', retry_obj, status)
return {u'status': 0}
# SOTA Transmission Server
class SOTATransmissionServer(threading.Thread):
"""
File transmission server thread. When a file download request was received from
a client via initiate_download message it will be dipatched to the queue package_queue.
This thread blocks on the package_queue until an entry is posted to the queue. Then
it will start pushing the file to the client via the RVI framework.
"""
def __init__(self, service_edge, service_id='/sota', chunk_size=65536):
threading.Thread.__init__(self)
self.service_edge = service_edge
self.service_id = service_id
self.chunk_size = chunk_size
self.transaction_id = 0
def shutdown(self):
self._Thread__stop()
def run(self):
while True:
[package, destination, retry] = package_queue.get()
rvi_logger.info('SOTA Transmission Server: Sending package %s to %s', package, destination)
# accessing database objects
retry_obj = None
update_obj = None
package_obj = None
try:
retry_obj = sota.models.Retry.objects.filter(pk=retry)[0]
update_obj = retry_obj.ret_update
package_obj = update_obj.upd_package
except Exception as e:
rvi_logger.error('SOTA Transmission Server: Cannot access database object: %s, Error: %s', retry, e)
continue
try:
f = open(package_obj.pac_file.path)
except Exception as e:
sota_logger.error('SOTA Transmission Server: %s: Cannot open file: %s', retry_obj, package_obj.pac_file.path)
retry_obj.set_status(sota.models.Status.FAILED)
update_obj.set_status(sota.models.Status.FAILED)
continue
retry_obj.set_status(sota.models.Status.RUNNING)
update_obj.set_status(sota.models.Status.RUNNING)
f_stat = os.stat(package_obj.pac_file.path)
self.transaction_id += 1
self.service_edge.message(calling_service = self.service_id,
service_name = destination + "/start",
transaction_id = str(self.transaction_id),
timeout = int(retry_obj.get_timeout_epoch()),
parameters = [{ u'package': package,
u'chunk_size': self.chunk_size,
u'total_size': f_stat.st_size
}])
index = 0
while True:
msg = f.read(self.chunk_size)
if msg == "":
break
sota_logger.debug('SOTA Transmission Server: %s: Sending package: %s, chunk: %d, message size: %s', retry_obj, package, index, len(msg))
self.transaction_id += 1
self.service_edge.message(calling_service = self.service_id,
service_name = destination + "/chunk",
transaction_id = str(self.transaction_id),
timeout = int(retry_obj.get_timeout_epoch()),
parameters = [
{ u'index': index },
{ u'msg': base64.b64encode(msg) }])
time.sleep(0.05)
index += 1
f.close()
time.sleep(1.0)
sota_logger.info('SOTA Transmission Server: %s: Finishing package: %s', retry_obj, package)
self.transaction_id += 1
self.service_edge.message(calling_service = self.service_id,
service_name = destination + "/finish",
transaction_id = str(self.transaction_id),
timeout = int(retry_obj.get_timeout_epoch()),
parameters = [ { u'dummy': 0}])
|
unknown
|
codeparrot/codeparrot-clean
| ||
#-*- coding:utf-8 -*-
from rrd.store import graph_db_conn as db_conn
class EndpointCounter(object):
def __init__(self, id, endpoint_id, counter, step, type_):
self.id = str(id)
self.endpoint_id = str(endpoint_id)
self.counter = counter
self.step = step
self.type_ = type_
def __repr__(self):
return "<EndpointCounter id=%s, endpoint_id=%s, counter=%s>" %(self.id, self.endpoint_id, self.counter)
__str__ = __repr__
@classmethod
def search_in_endpoint_ids(cls, qs, endpoint_ids, start=0, limit=100):
if not endpoint_ids:
return []
holders = ["%s" for x in endpoint_ids]
placeholder = ",".join(holders)
args = endpoint_ids
for q in qs:
args.append("%"+q+"%")
args += [start, limit]
sql = '''select id, endpoint_id, counter, step, type from endpoint_counter where endpoint_id in (''' +placeholder+ ''') '''
for q in qs:
sql += ''' and counter like %s'''
sql += ''' limit %s,%s'''
cursor = db_conn.execute(sql, args)
rows = cursor.fetchall()
cursor and cursor.close()
return [cls(*row) for row in rows]
@classmethod
def gets_by_endpoint_ids(cls, endpoint_ids, start=0, limit=100):
if not endpoint_ids:
return []
holders = ["%s" for x in endpoint_ids]
placeholder = ",".join(holders)
args = endpoint_ids + [start, limit]
cursor = db_conn.execute('''select id, endpoint_id, counter, step, type from endpoint_counter where endpoint_id in ('''+placeholder+''') limit %s, %s''', args)
rows = cursor.fetchall()
cursor and cursor.close()
return [cls(*row) for row in rows]
@classmethod
def gets(cls, ids, deadline=0):
if not ids:
return []
holders = ["%s" for x in ids]
placeholder = ",".join(holders)
args = ids + [start, limit]
cursor = db_conn.execute('''select id, endpoint, ts from endpoint where id in ('''+placeholder+''') and ts > %s''', args)
rows = cursor.fetchall()
cursor and cursor.close()
return [cls(*row) for row in rows]
|
unknown
|
codeparrot/codeparrot-clean
| ||
import logging
from ..primitive.manager import PrimitiveManager
logger = logging.getLogger(__name__)
class Robot(object):
""" This class is used to regroup all motors and sensors of your robots.
Most of the time, you do not want to directly instantiate this class, but you rather want to use a factory which creates a robot instance - e.g. from a python dictionnary (see :ref:`config_file`).
This class encapsulates the different controllers (such as dynamixel ones) that automatically synchronize the virtual sensors/effectors instances held by the robot class with the real devices. By doing so, each sensor/effector can be synchronized at a different frequency.
This class also provides a generic motors accessor in order to (more or less) easily extends this class to other types of motor.
"""
def __init__(self, motor_controllers=[], sensor_controllers=[], sync=True):
"""
:param list motor_controllers: motors controllers to attach to the robot
:param list sensor_controllers: sensors controllers to attach to the robot
:param bool sync: choose if automatically starts the synchronization loops
"""
self._motors = []
self._sensors = []
self.alias = []
self._controllers = sensor_controllers + motor_controllers
for controller in motor_controllers:
for m in controller.motors:
setattr(self, m.name, m)
self._motors.extend(controller.motors)
for controller in sensor_controllers:
for s in controller.sensors:
setattr(self, s.name, s)
self._sensors.extend(controller.sensors)
self._attached_primitives = {}
self._primitive_manager = PrimitiveManager(self.motors)
self._syncing = False
if sync:
self.start_sync()
def close(self):
""" Cleans the robot by stopping synchronization and all controllers."""
self.stop_sync()
[c.io.close() for c in self._controllers]
def __repr__(self):
return '<Robot motors={}>'.format(self.motors)
def start_sync(self):
""" Starts all the synchonization loop (sensor/effector controllers). """
if self._syncing:
return
[c.start() for c in self._controllers]
[c.wait_to_start() for c in self._controllers]
self._primitive_manager.start()
self._primitive_manager._running.wait()
self._syncing = True
logger.info('Starting robot synchronization.')
def stop_sync(self):
""" Stops all the synchonization loop (sensor/effector controllers). """
if not self._syncing:
return
if self._primitive_manager.running:
self._primitive_manager.stop()
[c.stop() for c in self._controllers]
self._syncing = False
logger.info('Stopping robot synchronization.')
def attach_primitive(self, primitive, name):
setattr(self, name, primitive)
self._attached_primitives[name] = primitive
primitive.name = name
logger.info("Attaching primitive '%s' to the robot.", name)
@property
def motors(self):
""" Returns all the motors attached to the robot. """
return self._motors
@property
def sensors(self):
""" Returns all the sensors attached to the robot. """
return self._sensors
@property
def active_primitives(self):
""" Returns all the primitives currently running on the robot. """
return self._primitive_manager._prim
@property
def primitives(self):
""" Returns all the primitives name attached to the robot. """
return self._attached_primitives.values()
@property
def compliant(self):
""" Returns a list of all the compliant motors. """
return [m for m in self.motors if m.compliant]
@compliant.setter
def compliant(self, is_compliant):
""" Switches all motors to compliant (resp. non compliant) mode. """
for m in self.motors:
m.compliant = is_compliant
def goto_position(self, position_for_motors, duration, control=None, wait=False):
""" Moves a subset of the motors to a position within a specific duration.
:param dict position_for_motors: which motors you want to move {motor_name: pos, motor_name: pos,...}
:param float duration: duration of the move
:param str control: control type ('dummy', 'minjerk')
:param bool wait: whether or not to wait for the end of the move
.. note::In case of dynamixel motors, the speed is automatically adjusted so the goal position is reached after the chosen duration.
"""
for i, (motor_name, position) in enumerate(position_for_motors.iteritems()):
w = False if i < len(position_for_motors) - 1 else wait
m = getattr(self, motor_name)
m.goto_position(position, duration, control, wait=w)
def power_up(self):
""" Changes all settings to guarantee the motors will be used at their maximum power. """
for m in self.motors:
m.compliant = False
m.moving_speed = 0
m.torque_limit = 100.0
def to_config(self):
""" Generates the config for the current robot.
.. note:: The generated config should be used as a basis and must probably be modified.
"""
from ..dynamixel.controller import DxlController
dxl_controllers = [c for c in self._controllers
if isinstance(c, DxlController)]
config = {}
config['controllers'] = {}
for i, c in enumerate(dxl_controllers):
name = 'dxl_controller_{}'.format(i)
config['controllers'][name] = {
'port': c.io.port,
'sync_read': c.io._sync_read,
'attached_motors': [m.name for m in c.motors],
}
config['motors'] = {}
for m in self.motors:
config['motors'][m.name] = {
'id': m.id,
'type': m.model,
'offset': m.offset,
'orientation': 'direct' if m.direct else 'indirect',
'angle_limit': m.angle_limit,
}
config['motorgroups'] = {}
return config
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
* 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 org.apache.kafka.clients.consumer.internals;
import org.apache.kafka.clients.consumer.Consumer;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.IsolationLevel;
import static org.apache.kafka.clients.consumer.internals.ConsumerUtils.configuredIsolationLevel;
/**
* {@link FetchConfig} represents the static configuration for fetching records from Kafka. It is simply a way
* to bundle the immutable settings that were presented at the time the {@link Consumer} was created for later use by
* classes like {@link Fetcher}, {@link CompletedFetch}, etc.
*/
public class FetchConfig {
public final int minBytes;
public final int maxBytes;
public final int maxWaitMs;
public final int fetchSize;
public final int maxPollRecords;
public final boolean checkCrcs;
public final String clientRackId;
public final IsolationLevel isolationLevel;
/**
* Constructs a new {@link FetchConfig} using explicitly provided values. This is provided here for tests that
* want to exercise different scenarios can construct specific configuration values rather than going through
* the hassle of constructing a {@link ConsumerConfig}.
*/
public FetchConfig(int minBytes,
int maxBytes,
int maxWaitMs,
int fetchSize,
int maxPollRecords,
boolean checkCrcs,
String clientRackId,
IsolationLevel isolationLevel) {
this.minBytes = minBytes;
this.maxBytes = maxBytes;
this.maxWaitMs = maxWaitMs;
this.fetchSize = fetchSize;
this.maxPollRecords = maxPollRecords;
this.checkCrcs = checkCrcs;
this.clientRackId = clientRackId;
this.isolationLevel = isolationLevel;
}
/**
* Constructs a new {@link FetchConfig} using values from the given {@link ConsumerConfig consumer configuration}
* settings:
*
* <ul>
* <li>{@link #minBytes}: {@link ConsumerConfig#FETCH_MIN_BYTES_CONFIG}</li>
* <li>{@link #maxBytes}: {@link ConsumerConfig#FETCH_MAX_BYTES_CONFIG}</li>
* <li>{@link #maxWaitMs}: {@link ConsumerConfig#FETCH_MAX_WAIT_MS_CONFIG}</li>
* <li>{@link #fetchSize}: {@link ConsumerConfig#MAX_PARTITION_FETCH_BYTES_CONFIG}</li>
* <li>{@link #maxPollRecords}: {@link ConsumerConfig#MAX_POLL_RECORDS_CONFIG}</li>
* <li>{@link #checkCrcs}: {@link ConsumerConfig#CHECK_CRCS_CONFIG}</li>
* <li>{@link #clientRackId}: {@link ConsumerConfig#CLIENT_RACK_CONFIG}</li>
* <li>{@link #isolationLevel}: {@link ConsumerConfig#ISOLATION_LEVEL_CONFIG}</li>
* </ul>
*
* @param config Consumer configuration
*/
public FetchConfig(ConsumerConfig config) {
this.minBytes = config.getInt(ConsumerConfig.FETCH_MIN_BYTES_CONFIG);
this.maxBytes = config.getInt(ConsumerConfig.FETCH_MAX_BYTES_CONFIG);
this.maxWaitMs = config.getInt(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG);
this.fetchSize = config.getInt(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG);
this.maxPollRecords = config.getInt(ConsumerConfig.MAX_POLL_RECORDS_CONFIG);
this.checkCrcs = config.getBoolean(ConsumerConfig.CHECK_CRCS_CONFIG);
this.clientRackId = config.getString(ConsumerConfig.CLIENT_RACK_CONFIG);
this.isolationLevel = configuredIsolationLevel(config);
}
@Override
public String toString() {
return "FetchConfig{" +
"minBytes=" + minBytes +
", maxBytes=" + maxBytes +
", maxWaitMs=" + maxWaitMs +
", fetchSize=" + fetchSize +
", maxPollRecords=" + maxPollRecords +
", checkCrcs=" + checkCrcs +
", clientRackId='" + clientRackId + '\'' +
", isolationLevel=" + isolationLevel +
'}';
}
}
|
java
|
github
|
https://github.com/apache/kafka
|
clients/src/main/java/org/apache/kafka/clients/consumer/internals/FetchConfig.java
|
from fractions import Fraction
if __name__ == "__main__":
n = input()
y = map(int, raw_input().split())
used = set()
for i in xrange(1, n):
if i in used:
continue
k = Fraction(y[i] - y[0], i)
in_line = set()
in_line.add(0)
in_line.add(i)
for j in xrange(i + 1, n):
k_j = Fraction(y[j] - y[0], j)
if k_j == k:
in_line.add(j)
used.add(j)
out_line = []
find = True
for j in xrange(1, n):
if j not in in_line:
if len(out_line) > 0:
k_j = Fraction(y[j] - out_line[-1][1], j - out_line[-1][0])
if k_j != k:
find = False
break
out_line.append((j, y[j]))
if len(out_line) == 0:
find = False
if find:
break
if not find:
if n == 2:
find = True
else:
k = y[2] - y[1]
if y[1] - y[0] != k:
find = True
for j in xrange(2, n):
if y[j] - y[j - 1] != k:
find = False
break
if find:
print 'Yes'
else:
print 'No'
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/env python
# Requirements
# - pyvmomi >= 6.0.0.2016.4
# TODO:
# * more jq examples
# * optional folder heriarchy
"""
$ jq '._meta.hostvars[].config' data.json | head
{
"alternateguestname": "",
"instanceuuid": "5035a5cd-b8e8-d717-e133-2d383eb0d675",
"memoryhotaddenabled": false,
"guestfullname": "Red Hat Enterprise Linux 7 (64-bit)",
"changeversion": "2016-05-16T18:43:14.977925Z",
"uuid": "4235fc97-5ddb-7a17-193b-9a3ac97dc7b4",
"cpuhotremoveenabled": false,
"vpmcenabled": false,
"firmware": "bios",
"""
from __future__ import print_function
import argparse
import atexit
import datetime
import getpass
import jinja2
import os
import six
import ssl
import sys
import uuid
from collections import defaultdict
from six.moves import configparser
from time import time
HAS_PYVMOMI = False
try:
from pyVmomi import vim
from pyVim.connect import SmartConnect, Disconnect
HAS_PYVMOMI = True
except ImportError:
pass
try:
import json
except ImportError:
import simplejson as json
hasvcr = False
try:
import vcr
hasvcr = True
except ImportError:
pass
class VMwareMissingHostException(Exception):
pass
class VMWareInventory(object):
__name__ = 'VMWareInventory'
guest_props = False
instances = []
debug = False
load_dumpfile = None
write_dumpfile = None
maxlevel = 1
lowerkeys = True
config = None
cache_max_age = None
cache_path_cache = None
cache_path_index = None
server = None
port = None
username = None
password = None
host_filters = []
groupby_patterns = []
if (sys.version_info > (3, 0)):
safe_types = [int, bool, str, float, None]
else:
safe_types = [int, long, bool, str, float, None]
iter_types = [dict, list]
bad_types = ['Array', 'disabledMethod', 'declaredAlarmState']
skip_keys = ['declaredalarmstate',
'disabledmethod',
'dynamicproperty',
'dynamictype',
'environmentbrowser',
'managedby',
'parent',
'childtype']
# translation table for attributes to fetch for known vim types
if not HAS_PYVMOMI:
vimTable = {}
else:
vimTable = {
vim.Datastore: ['_moId', 'name'],
vim.ResourcePool: ['_moId', 'name'],
}
def _empty_inventory(self):
return {"_meta" : {"hostvars" : {}}}
def __init__(self, load=True):
self.inventory = self._empty_inventory()
if load:
# Read settings and parse CLI arguments
self.parse_cli_args()
self.read_settings()
# Check the cache
cache_valid = self.is_cache_valid()
# Handle Cache
if self.args.refresh_cache or not cache_valid:
self.do_api_calls_update_cache()
else:
self.debugl('loading inventory from cache')
self.inventory = self.get_inventory_from_cache()
def debugl(self, text):
if self.args.debug:
try:
text = str(text)
except UnicodeEncodeError:
text = text.encode('ascii','ignore')
print('%s %s' % (datetime.datetime.now(), text))
def show(self):
# Data to print
self.debugl('dumping results')
data_to_print = None
if self.args.host:
data_to_print = self.get_host_info(self.args.host)
elif self.args.list:
# Display list of instances for inventory
data_to_print = self.inventory
return json.dumps(data_to_print, indent=2)
def is_cache_valid(self):
''' Determines if the cache files have expired, or if it is still valid '''
valid = False
if os.path.isfile(self.cache_path_cache):
mod_time = os.path.getmtime(self.cache_path_cache)
current_time = time()
if (mod_time + self.cache_max_age) > current_time:
valid = True
return valid
def do_api_calls_update_cache(self):
''' Get instances and cache the data '''
instances = self.get_instances()
self.instances = instances
self.inventory = self.instances_to_inventory(instances)
self.write_to_cache(self.inventory, self.cache_path_cache)
def write_to_cache(self, data, cache_path):
''' Dump inventory to json file '''
with open(self.cache_path_cache, 'wb') as f:
f.write(json.dumps(data))
def get_inventory_from_cache(self):
''' Read in jsonified inventory '''
jdata = None
with open(self.cache_path_cache, 'rb') as f:
jdata = f.read()
return json.loads(jdata)
def read_settings(self):
''' Reads the settings from the vmware_inventory.ini file '''
scriptbasename = __file__
scriptbasename = os.path.basename(scriptbasename)
scriptbasename = scriptbasename.replace('.py', '')
defaults = {'vmware': {
'server': '',
'port': 443,
'username': '',
'password': '',
'validate_certs': True,
'ini_path': os.path.join(os.path.dirname(__file__), '%s.ini' % scriptbasename),
'cache_name': 'ansible-vmware',
'cache_path': '~/.ansible/tmp',
'cache_max_age': 3600,
'max_object_level': 1,
'alias_pattern': '{{ config.name + "_" + config.uuid }}',
'host_pattern': '{{ guest.ipaddress }}',
'host_filters': '{{ guest.gueststate == "running" }}',
'groupby_patterns': '{{ guest.guestid }},{{ "templates" if config.template else "guests"}}',
'lower_var_keys': True }
}
if six.PY3:
config = configparser.ConfigParser()
else:
config = configparser.SafeConfigParser()
# where is the config?
vmware_ini_path = os.environ.get('VMWARE_INI_PATH', defaults['vmware']['ini_path'])
vmware_ini_path = os.path.expanduser(os.path.expandvars(vmware_ini_path))
config.read(vmware_ini_path)
# apply defaults
for k,v in defaults['vmware'].items():
if not config.has_option('vmware', k):
config.set('vmware', k, str(v))
# where is the cache?
self.cache_dir = os.path.expanduser(config.get('vmware', 'cache_path'))
if self.cache_dir and not os.path.exists(self.cache_dir):
os.makedirs(self.cache_dir)
# set the cache filename and max age
cache_name = config.get('vmware', 'cache_name')
self.cache_path_cache = self.cache_dir + "/%s.cache" % cache_name
self.debugl('cache path is %s' % self.cache_path_cache)
self.cache_max_age = int(config.getint('vmware', 'cache_max_age'))
# mark the connection info
self.server = os.environ.get('VMWARE_SERVER', config.get('vmware', 'server'))
self.debugl('server is %s' % self.server)
self.port = int(os.environ.get('VMWARE_PORT', config.get('vmware', 'port')))
self.username = os.environ.get('VMWARE_USERNAME', config.get('vmware', 'username'))
self.debugl('username is %s' % self.username)
self.password = os.environ.get('VMWARE_PASSWORD', config.get('vmware', 'password'))
self.validate_certs = os.environ.get('VMWARE_VALIDATE_CERTS', config.get('vmware', 'validate_certs'))
if self.validate_certs in ['no', 'false', 'False', False]:
self.validate_certs = False
else:
self.validate_certs = True
self.debugl('cert validation is %s' % self.validate_certs)
# behavior control
self.maxlevel = int(config.get('vmware', 'max_object_level'))
self.debugl('max object level is %s' % self.maxlevel)
self.lowerkeys = config.get('vmware', 'lower_var_keys')
if type(self.lowerkeys) != bool:
if str(self.lowerkeys).lower() in ['yes', 'true', '1']:
self.lowerkeys = True
else:
self.lowerkeys = False
self.debugl('lower keys is %s' % self.lowerkeys)
self.host_filters = list(config.get('vmware', 'host_filters').split(','))
self.debugl('host filters are %s' % self.host_filters)
self.groupby_patterns = list(config.get('vmware', 'groupby_patterns').split(','))
self.debugl('groupby patterns are %s' % self.groupby_patterns)
# Special feature to disable the brute force serialization of the
# virtulmachine objects. The key name for these properties does not
# matter because the values are just items for a larger list.
if config.has_section('properties'):
self.guest_props = []
for prop in config.items('properties'):
self.guest_props.append(prop[1])
# save the config
self.config = config
def parse_cli_args(self):
''' Command line argument processing '''
parser = argparse.ArgumentParser(description='Produce an Ansible Inventory file based on PyVmomi')
parser.add_argument('--debug', action='store_true', default=False,
help='show debug info')
parser.add_argument('--list', action='store_true', default=True,
help='List instances (default: True)')
parser.add_argument('--host', action='store',
help='Get all the variables about a specific instance')
parser.add_argument('--refresh-cache', action='store_true', default=False,
help='Force refresh of cache by making API requests to VSphere (default: False - use cache files)')
parser.add_argument('--max-instances', default=None, type=int,
help='maximum number of instances to retrieve')
self.args = parser.parse_args()
def get_instances(self):
''' Get a list of vm instances with pyvmomi '''
instances = []
kwargs = {'host': self.server,
'user': self.username,
'pwd': self.password,
'port': int(self.port) }
if hasattr(ssl, 'SSLContext') and not self.validate_certs:
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.verify_mode = ssl.CERT_NONE
kwargs['sslContext'] = context
instances = self._get_instances(kwargs)
return instances
def _get_instances(self, inkwargs):
''' Make API calls '''
instances = []
si = SmartConnect(**inkwargs)
self.debugl('retrieving all instances')
if not si:
print("Could not connect to the specified host using specified "
"username and password")
return -1
atexit.register(Disconnect, si)
content = si.RetrieveContent()
# Create a search container for virtualmachines
self.debugl('creating containerview for virtualmachines')
container = content.rootFolder
viewType = [vim.VirtualMachine]
recursive = True
containerView = content.viewManager.CreateContainerView(container, viewType, recursive)
children = containerView.view
for child in children:
# If requested, limit the total number of instances
if self.args.max_instances:
if len(instances) >= (self.args.max_instances):
break
instances.append(child)
self.debugl("%s total instances in container view" % len(instances))
if self.args.host:
instances = [x for x in instances if x.name == self.args.host]
instance_tuples = []
for instance in sorted(instances):
if self.guest_props != False:
ifacts = self.facts_from_proplist(instance)
else:
ifacts = self.facts_from_vobj(instance)
instance_tuples.append((instance, ifacts))
self.debugl('facts collected for all instances')
return instance_tuples
def instances_to_inventory(self, instances):
''' Convert a list of vm objects into a json compliant inventory '''
self.debugl('re-indexing instances based on ini settings')
inventory = self._empty_inventory()
inventory['all'] = {}
inventory['all']['hosts'] = []
last_idata = None
total = len(instances)
for idx,instance in enumerate(instances):
# make a unique id for this object to avoid vmware's
# numerous uuid's which aren't all unique.
thisid = str(uuid.uuid4())
idata = instance[1]
# Put it in the inventory
inventory['all']['hosts'].append(thisid)
inventory['_meta']['hostvars'][thisid] = idata.copy()
inventory['_meta']['hostvars'][thisid]['ansible_uuid'] = thisid
# Make a map of the uuid to the alias the user wants
name_mapping = self.create_template_mapping(inventory,
self.config.get('vmware', 'alias_pattern'))
# Make a map of the uuid to the ssh hostname the user wants
host_mapping = self.create_template_mapping(inventory,
self.config.get('vmware', 'host_pattern'))
# Reset the inventory keys
for k,v in name_mapping.items():
if not host_mapping or not k in host_mapping:
continue
# set ansible_host (2.x)
try:
inventory['_meta']['hostvars'][k]['ansible_host'] = host_mapping[k]
# 1.9.x backwards compliance
inventory['_meta']['hostvars'][k]['ansible_ssh_host'] = host_mapping[k]
except Exception as e:
continue
if k == v:
continue
# add new key
inventory['all']['hosts'].append(v)
inventory['_meta']['hostvars'][v] = inventory['_meta']['hostvars'][k]
# cleanup old key
inventory['all']['hosts'].remove(k)
inventory['_meta']['hostvars'].pop(k, None)
self.debugl('pre-filtered hosts:')
for i in inventory['all']['hosts']:
self.debugl(' * %s' % i)
# Apply host filters
for hf in self.host_filters:
if not hf:
continue
self.debugl('filter: %s' % hf)
filter_map = self.create_template_mapping(inventory, hf, dtype='boolean')
for k,v in filter_map.items():
if not v:
# delete this host
inventory['all']['hosts'].remove(k)
inventory['_meta']['hostvars'].pop(k, None)
self.debugl('post-filter hosts:')
for i in inventory['all']['hosts']:
self.debugl(' * %s' % i)
# Create groups
for gbp in self.groupby_patterns:
groupby_map = self.create_template_mapping(inventory, gbp)
for k,v in groupby_map.items():
if v not in inventory:
inventory[v] = {}
inventory[v]['hosts'] = []
if k not in inventory[v]['hosts']:
inventory[v]['hosts'].append(k)
return inventory
def create_template_mapping(self, inventory, pattern, dtype='string'):
''' Return a hash of uuid to templated string from pattern '''
mapping = {}
for k,v in inventory['_meta']['hostvars'].items():
t = jinja2.Template(pattern)
newkey = None
try:
newkey = t.render(v)
newkey = newkey.strip()
except Exception as e:
self.debugl(e)
if not newkey:
continue
elif dtype == 'integer':
newkey = int(newkey)
elif dtype == 'boolean':
if newkey.lower() == 'false':
newkey = False
elif newkey.lower() == 'true':
newkey = True
elif dtype == 'string':
pass
mapping[k] = newkey
return mapping
def facts_from_proplist(self, vm):
'''Get specific properties instead of serializing everything'''
rdata = {}
for prop in self.guest_props:
self.debugl('getting %s property for %s' % (prop, vm.name))
key = prop
if self.lowerkeys:
key = key.lower()
if not '.' in prop:
# props without periods are direct attributes of the parent
rdata[key] = getattr(vm, prop)
else:
# props with periods are subkeys of parent attributes
parts = prop.split('.')
total = len(parts) - 1
# pointer to the current object
val = None
# pointer to the current result key
lastref = rdata
for idx,x in enumerate(parts):
# if the val wasn't set yet, get it from the parent
if not val:
val = getattr(vm, x)
else:
# in a subkey, get the subprop from the previous attrib
try:
val = getattr(val, x)
except AttributeError as e:
self.debugl(e)
# lowercase keys if requested
if self.lowerkeys:
x = x.lower()
# change the pointer or set the final value
if idx != total:
if x not in lastref:
lastref[x] = {}
lastref = lastref[x]
else:
lastref[x] = val
return rdata
def facts_from_vobj(self, vobj, level=0):
''' Traverse a VM object and return a json compliant data structure '''
# pyvmomi objects are not yet serializable, but may be one day ...
# https://github.com/vmware/pyvmomi/issues/21
# WARNING:
# Accessing an object attribute will trigger a SOAP call to the remote.
# Increasing the attributes collected or the depth of recursion greatly
# increases runtime duration and potentially memory+network utilization.
if level == 0:
try:
self.debugl("get facts for %s" % vobj.name)
except Exception as e:
self.debugl(e)
rdata = {}
methods = dir(vobj)
methods = [str(x) for x in methods if not x.startswith('_')]
methods = [x for x in methods if not x in self.bad_types]
methods = [x for x in methods if not x.lower() in self.skip_keys]
methods = sorted(methods)
for method in methods:
# Attempt to get the method, skip on fail
try:
methodToCall = getattr(vobj, method)
except Exception as e:
continue
# Skip callable methods
if callable(methodToCall):
continue
if self.lowerkeys:
method = method.lower()
rdata[method] = self._process_object_types(
methodToCall,
thisvm=vobj,
inkey=method
)
return rdata
def _process_object_types(self, vobj, thisvm=None, inkey=None, level=0):
''' Serialize an object '''
rdata = {}
if vobj is None:
rdata = None
elif type(vobj) in self.vimTable:
rdata = {}
for key in self.vimTable[type(vobj)]:
rdata[key] = getattr(vobj, key)
elif issubclass(type(vobj), str) or isinstance(vobj, str):
if vobj.isalnum():
rdata = vobj
else:
rdata = vobj.decode('ascii', 'ignore')
elif issubclass(type(vobj), bool) or isinstance(vobj, bool):
rdata = vobj
elif issubclass(type(vobj), int) or isinstance(vobj, int):
rdata = vobj
elif issubclass(type(vobj), float) or isinstance(vobj, float):
rdata = vobj
elif issubclass(type(vobj), long) or isinstance(vobj, long):
rdata = vobj
elif issubclass(type(vobj), list) or issubclass(type(vobj), tuple):
rdata = []
try:
vobj = sorted(vobj)
except Exception as e:
pass
for idv, vii in enumerate(vobj):
if (level+1 <= self.maxlevel):
vid = self._process_object_types(
vii,
thisvm=thisvm,
inkey=inkey+'['+str(idv)+']',
level=(level+1)
)
if vid:
rdata.append(vid)
elif issubclass(type(vobj), dict):
pass
elif issubclass(type(vobj), object):
methods = dir(vobj)
methods = [str(x) for x in methods if not x.startswith('_')]
methods = [x for x in methods if not x in self.bad_types]
methods = [x for x in methods if not x.lower() in self.skip_keys]
methods = sorted(methods)
for method in methods:
# Attempt to get the method, skip on fail
try:
methodToCall = getattr(vobj, method)
except Exception as e:
continue
if callable(methodToCall):
continue
if self.lowerkeys:
method = method.lower()
if (level+1 <= self.maxlevel):
rdata[method] = self._process_object_types(
methodToCall,
thisvm=thisvm,
inkey=inkey+'.'+method,
level=(level+1)
)
else:
pass
return rdata
def get_host_info(self, host):
''' Return hostvars for a single host '''
if host in self.inventory['_meta']['hostvars']:
return self.inventory['_meta']['hostvars'][host]
elif self.args.host and self.inventory['_meta']['hostvars']:
# check if the machine has the name requested
keys = self.inventory['_meta']['hostvars'].keys()
match = None
for k,v in self.inventory['_meta']['hostvars'].items():
if self.inventory['_meta']['hostvars'][k]['name'] == self.args.host:
match = k
break
if match:
return self.inventory['_meta']['hostvars'][match]
else:
raise VMwareMissingHostException('%s not found' % host)
else:
raise VMwareMissingHostException('%s not found' % host)
if __name__ == "__main__":
# Run the script
print(VMWareInventory().show())
|
unknown
|
codeparrot/codeparrot-clean
| ||
import re
from livestreamer.plugin import Plugin
from livestreamer.plugin.api import http, validate
from livestreamer.stream import RTMPStream
INFO_URL = "http://mvn.vaughnsoft.net/video/edge/{domain}_{channel}"
DOMAIN_MAP = {
"breakers": "btv",
"vapers": "vtv",
"vaughnlive": "live",
}
_url_re = re.compile("""
http(s)?://(\w+\.)?
(?P<domain>vaughnlive|breakers|instagib|vapers).tv
/(?P<channel>[^/&?]+)
""", re.VERBOSE)
_channel_not_found_re = re.compile("<title>Channel Not Found")
def decode_token(token):
return token.replace("0m0", "")
_schema = validate.Schema(
validate.transform(lambda s: s.split(";:mvnkey%")),
validate.length(2),
validate.union({
"server": validate.all(
validate.get(0),
validate.text
),
"token": validate.all(
validate.get(1),
validate.text,
validate.transform(decode_token)
)
})
)
class VaughnLive(Plugin):
@classmethod
def can_handle_url(cls, url):
return _url_re.match(url)
def _get_streams(self):
res = http.get(self.url)
if _channel_not_found_re.search(res.text):
return
match = _url_re.match(self.url)
params = match.groupdict()
params["domain"] = DOMAIN_MAP.get(params["domain"], params["domain"])
info = http.get(INFO_URL.format(**params), schema=_schema)
swfUrl = "http://vaughnlive.tv" + re.compile('swfobject.embedSWF\("(/\d+/swf/[0-9A-Za-z]+\.swf)"').findall(res.text)[0]
stream = RTMPStream(self.session, {
"rtmp": "rtmp://{0}/live".format(info["server"]),
"app": "live?{0}".format(info["token"]),
"swfVfy": swfUrl,
"pageUrl": self.url,
"live": True,
"playpath": "{domain}_{channel}".format(**params),
})
return dict(live=stream)
__plugin__ = VaughnLive
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
* Copyright (c) 2017 Mockito contributors
* This program is made available under the terms of the MIT License.
*/
package org.mockito.internal.configuration.plugins;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import java.io.File;
import java.net.URL;
import java.util.Collections;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.internal.util.io.IOUtil;
import org.mockito.plugins.PluginSwitch;
import org.mockitoutil.TestBase;
public class PluginFinderTest extends TestBase {
@Mock PluginSwitch switcher;
@InjectMocks PluginFinder finder;
public @Rule TemporaryFolder tmp = new TemporaryFolder();
@Test
public void empty_resources() {
assertNull(finder.findPluginClass(Collections.<URL>emptyList()));
}
@Test
public void no_valid_impl() throws Exception {
File f = tmp.newFile();
// when
IOUtil.writeText(" \n ", f);
// then
assertNull(finder.findPluginClass(asList(f.toURI().toURL())));
}
@Test
public void single_implementation() throws Exception {
File f = tmp.newFile();
when(switcher.isEnabled("foo.Foo")).thenReturn(true);
// when
IOUtil.writeText(" foo.Foo ", f);
// then
assertEquals("foo.Foo", finder.findPluginClass(asList(f.toURI().toURL())));
}
@Test
public void single_implementation_disabled() throws Exception {
File f = tmp.newFile();
when(switcher.isEnabled("foo.Foo")).thenReturn(false);
// when
IOUtil.writeText(" foo.Foo ", f);
// then
assertEquals(null, finder.findPluginClass(asList(f.toURI().toURL())));
}
@Test
public void multiple_implementations_only_one_enabled() throws Exception {
File f1 = tmp.newFile();
File f2 = tmp.newFile();
when(switcher.isEnabled("Bar")).thenReturn(true);
// when
IOUtil.writeText("Foo", f1);
IOUtil.writeText("Bar", f2);
// then
assertEquals("Bar", finder.findPluginClass(asList(f1.toURI().toURL(), f2.toURI().toURL())));
}
@Test
public void multiple_implementations_only_one_useful() throws Exception {
File f1 = tmp.newFile();
File f2 = tmp.newFile();
when(switcher.isEnabled(anyString())).thenReturn(true);
// when
IOUtil.writeText(" ", f1);
IOUtil.writeText("X", f2);
// then
assertEquals("X", finder.findPluginClass(asList(f1.toURI().toURL(), f2.toURI().toURL())));
}
@Test
public void multiple_empty_implementations() throws Exception {
File f1 = tmp.newFile();
File f2 = tmp.newFile();
when(switcher.isEnabled(anyString())).thenReturn(true);
// when
IOUtil.writeText(" ", f1);
IOUtil.writeText("\n", f2);
// then
assertEquals(null, finder.findPluginClass(asList(f1.toURI().toURL(), f2.toURI().toURL())));
}
@Test
public void problems_loading_impl() throws Exception {
String fileName = "xxx";
File f = tmp.newFile(fileName);
// when
IOUtil.writeText("Bar", f);
when(switcher.isEnabled(anyString())).thenThrow(new RuntimeException("Boo!"));
try {
// when
finder.findPluginClass(asList(f.toURI().toURL()));
// then
fail();
} catch (Exception e) {
assertThat(e).hasMessageContaining(fileName);
assertThat(e.getCause()).hasMessage("Boo!");
}
}
}
|
java
|
github
|
https://github.com/mockito/mockito
|
mockito-core/src/test/java/org/mockito/internal/configuration/plugins/PluginFinderTest.java
|
test_kind: js_test
selector:
roots:
- jstests/core/**/*.js
- jstests/fle2/**/*.js
- src/mongo/db/modules/*/jstests/fle2/**/*.js
exclude_files:
# These tests are run in sharded_jscore_txns.
- jstests/core/txns/**/*.js
# The following tests fail because a certain command or functionality is not supported by
# mongos. This command or functionality is placed in a comment next to the failing test.
- jstests/core/**/apitest_db.js # serverStatus output doesn't have storageEngine.
- jstests/core/**/awaitdata_getmore_cmd.js # capped collections.
- jstests/core/**/bypass_doc_validation.js # sharded $out output not permitted
- jstests/core/**/check_shard_index.js # checkShardingIndex.
- jstests/core/**/compact_keeps_indexes.js # compact.
- jstests/core/**/currentop.js # uses fsync.
- jstests/core/**/dbhash.js # dbhash.
- jstests/core/**/fsync.js # uses fsync.
- jstests/core/**/geo_s2cursorlimitskip.js # profiling.
- jstests/core/**/geo_update_btree2.js # notablescan.
- jstests/core/**/queryoptimizera.js # "local" database.
- jstests/core/**/startup_log.js # "local" database.
- jstests/core/**/tailable_cursor_invalidation.js # capped collections.
- jstests/core/**/tailable_getmore_batch_size.js # capped collections.
- jstests/core/**/tailable_skip_limit.js # capped collections.
- jstests/core/**/query/top/top.js # top.
# The following tests fail because mongos behaves differently from mongod when testing certain
# functionality. The differences are in a comment next to the failing test.
- jstests/core/**/explain_missing_database.js # Behavior with no db different on mongos.
- jstests/core/**/geo_2d_explain.js # executionSuccess in different spot in explain().
- jstests/core/**/geo_s2explain.js # inputStage in different spot in explain().
- jstests/core/**/geo_s2sparse.js # keysPerIndex in different spot in validate().
- jstests/core/**/operation_latency_histogram.js # Stats are counted differently on mongos, SERVER-24880.
# The following tests fail because explain expect a different plan query when collections live on separate shards
# This test expects sharded collections to be sharded across multiple shards.
- jstests/core/administrative/current_op/currentop_shell.js
# TODO: Remove after fixing SERVER-103278. executionStats.nReturned is incorrect for sharded distinct commands.
- jstests/core/**/distinct_index1.js
# TODO SERVER-32311: These tests use plan stage helpers which can't handle sharded explain output.
- jstests/core/**/expr_index_use.js
- jstests/core/**/index_multikey.js
- jstests/core/**/query/explain/optimized_match_explain.js
- jstests/core/**/sort_array.js
# These tests drop and create indexes throughout their execution. Index creation might fail when
# movePrimary is in progress.
- jstests/core/query/agg_hint.js
- jstests/core/index/express_write.js
# The following tests are excluded specifically for this passthrough suite.
# TransitionTo/FromDedicated runs remove/addShard which implicitly will set a cluster parameter, which
# will conflict with tests that explicitly set cluster parameters.
- jstests/core/query/query_settings/**/*.js
- jstests/core/query/queryable_encryption/query_settings_fle.js
# These tests expect index creation to fail on a shard that contains an initial document with
# parallel arrays. The index creation will succeed on the shard without a document and
# as we transition to dedicated, the balancer will try an insert the document with a parallel
# array on the shard with the index created.
- jstests/core/index/geo/geo_multikey1.js
# These tests expect index creation to fail, which can block the config shard from transitioning
# to the dedicated state. Index creation failure will also block subsequent config transition attempts.
- jstests/core/index/geo/geo_invalid_polygon.js
# These timeseries tests use a helper that runs and expects a chunk migration to succeed, which can
# conflict with a config transition.
- jstests/core/timeseries/ddl/bucket_granularity.js
- jstests/core/timeseries/ddl/bucket_span_and_rounding_seconds.js
- jstests/core/timeseries/ddl/bucket_timestamp_rounding.js
- jstests/core/timeseries/ddl/timeseries_bucket_index.js
- jstests/core/timeseries/ddl/timeseries_clustered_index_options.js
- jstests/core/timeseries/ddl/timeseries_collation.js
- jstests/core/timeseries/ddl/timeseries_create.js
- jstests/core/timeseries/ddl/timeseries_create_collection.js
- jstests/core/timeseries/ddl/timeseries_index.js
- jstests/core/timeseries/ddl/timeseries_index_collation.js
- jstests/core/timeseries/ddl/timeseries_index_partial.js
- jstests/core/timeseries/ddl/timeseries_index_stats.js
- jstests/core/timeseries/ddl/timeseries_index_ttl_partial.js
- jstests/core/timeseries/ddl/timeseries_index_use.js
- jstests/core/timeseries/ddl/timeseries_metric_index_2dsphere.js
- jstests/core/timeseries/ddl/timeseries_nondefault_collation.js
- jstests/core/timeseries/ddl/timeseries_special_indexes_metadata.js
- jstests/core/timeseries/ddl/timeseries_sparse_index.js
- jstests/core/timeseries/ddl/timeseries_user_system_buckets.js
- jstests/core/timeseries/geo/partialFilterExpression_with_internalBucketGeoWithin.js
- jstests/core/timeseries/geo/timeseries_geonear_measurements.js
- jstests/core/timeseries/geo/timeseries_internal_bucket_geo_within.js
- jstests/core/timeseries/query/timeseries_explain_update.js
- jstests/core/timeseries/query/timeseries_block_explain.js
- jstests/core/timeseries/query/bucket_unpacking_group_reorder_fixed_buckets.js
- jstests/core/timeseries/query/bucket_unpacking_with_compound_sort_on_point_queries.js
- jstests/core/timeseries/query/bucket_unpacking_with_limit.js
- jstests/core/timeseries/query/bucket_unpacking_with_match_fixed_buckets.js
- jstests/core/timeseries/query/bucket_unpacking_with_sort.js
- jstests/core/timeseries/query/bucket_unpacking_with_sort_extended_range.js
- jstests/core/timeseries/query/bucket_unpacking_with_sort_negative.js
- jstests/core/timeseries/query/bucket_unpacking_with_sort_on_multiple_fields_point_queries.js
- jstests/core/timeseries/query/bucket_unpacking_with_sort_on_single_field_point_queries.js
- jstests/core/timeseries/query/bucket_unpacking_with_sort_plan_cache.js
- jstests/core/timeseries/query/bucket_unpacking_with_sort_with_collation.js
- jstests/core/timeseries/query/bucket_unpacking_with_sort_with_geo.js
- jstests/core/timeseries/query/timeseries_bucket_level_filter.js
- jstests/core/timeseries/query/timeseries_computed_field.js
- jstests/core/timeseries/query/timeseries_filter_extended_range.js
- jstests/core/timeseries/query/timeseries_find.js
- jstests/core/timeseries/query/timeseries_group.js
- jstests/core/timeseries/query/timeseries_groupby_reorder.js
- jstests/core/timeseries/query/timeseries_groupby_reorder_expr.js
- jstests/core/timeseries/query/timeseries_hint.js
- jstests/core/timeseries/query/timeseries_id_range.js
- jstests/core/timeseries/query/timeseries_internal_bounded_sort.js
- jstests/core/timeseries/query/timeseries_internal_bounded_sort_compound.js
- jstests/core/timeseries/query/timeseries_internal_bounded_sort_compound_mixed_types.js
- jstests/core/timeseries/query/timeseries_internal_bounded_sort_overflow.js
- jstests/core/timeseries/query/timeseries_lastpoint.js
- jstests/core/timeseries/query/timeseries_lastpoint_common_sort_key.js
- jstests/core/timeseries/query/timeseries_lookup.js
- jstests/core/timeseries/query/timeseries_match.js
- jstests/core/timeseries/query/timeseries_match_pushdown.js
- jstests/core/timeseries/query/timeseries_match_pushdown_with_project.js
- jstests/core/timeseries/query/timeseries_merge.js
- jstests/core/timeseries/query/timeseries_out_non_sharded.js
- jstests/core/timeseries/query/timeseries_partial_index_opt.js
- jstests/core/timeseries/query/timeseries_predicates.js
- jstests/core/timeseries/query/timeseries_project.js
- jstests/core/timeseries/query/timeseries_resume_after.js
- jstests/core/timeseries/query/timeseries_sbe.js
- jstests/core/timeseries/query/timeseries_streaming_group.js
- jstests/core/timeseries/query/timeseries_top_k_sort_optimization.js
- jstests/core/timeseries/query/timeseries_union_with.js
- jstests/core/timeseries/write/timeseries_bucket_limit_count.js
- jstests/core/timeseries/write/timeseries_bucket_limit_time_range.js
- jstests/core/timeseries/write/timeseries_bucket_manual_removal.js
- jstests/core/timeseries/write/timeseries_delete_compressed_buckets.js
- jstests/core/timeseries/write/timeseries_delete_hint.js
- jstests/core/timeseries/write/timeseries_delete_with_meta.js
- jstests/core/timeseries/write/timeseries_delete_with_meta_concurrent.js
- jstests/core/timeseries/write/timeseries_findAndModify_deletes_hints.js
- jstests/core/timeseries/write/timeseries_findAndModify_updates_hints.js
- jstests/core/timeseries/write/timeseries_insert_after_delete.js
- jstests/core/timeseries/write/timeseries_insert_after_update.js
- jstests/core/timeseries/write/timeseries_insert_compresses_bucket.js
- jstests/core/timeseries/write/timeseries_metadata.js
- jstests/core/timeseries/write/timeseries_min_max.js
- jstests/core/timeseries/write/timeseries_out_of_order.js
- jstests/core/timeseries/write/timeseries_reopened_bucket_insert.js
- jstests/core/timeseries/write/timeseries_schema_validation.js
- jstests/core/timeseries/write/timeseries_simple.js
- jstests/core/timeseries/write/timeseries_sparse.js
- jstests/core/timeseries/write/timeseries_update.js
- jstests/core/timeseries/write/timeseries_update_compressed_buckets.js
- jstests/core/timeseries/write/timeseries_update_concurrent.js
- jstests/core/timeseries/write/timeseries_update_hint.js
- jstests/core/timeseries/write/timeseries_update_one.js
# moveChunk can be blocked by multi updates causing these tests to not be able to transition to dedicated.
- jstests/core/index/geo/geo_update_btree.js
- jstests/core/query/delete/remove_adjacent_index_keys.js
# Exclude tests that run cleanupOrphaned, which can fail running on a config shard if a
# concurrent migration fails due to the config shard transitioning to dedicated.
- jstests/core/administrative/cleanup_orphaned.js
- jstests/core/catalog/views/views_all_commands.js
- jstests/core/repro/commands_namespace_parsing.js
# Runs commands using legacy queries, which are not supported on sessions.
- jstests/core/**/query/exhaust.js
# TODO SERVER-96199 Re-enable this test once FLE updates to a document's shard key work
- src/mongo/db/modules/enterprise/jstests/fle2/find_and_modify_replace.js
# TODO SERVER-114065 isIxscanMultikey checks the first shard only, which may not be accurate in a sharded with migrations.
- jstests/core/query/array/array_index_and_nonIndex_consistent.js
# TODO SERVER-114826 Investigate the possibility to re-enable excluded tests with random_migrations
- jstests/core/query/run_all_plans_pbt.js
- jstests/core/index/index_partial_create_drop.js
- jstests/core/query/json_schema/items.js
- jstests/core/query/exists/existsb.js
- jstests/core/timeseries/query/agg_stage_coverage.js
- jstests/core/index/geo/geo_near_random1.js
- jstests/core/index/geo/geo_exactfetch.js
exclude_with_any_tags:
- assumes_standalone_mongod
- assumes_against_mongod_not_mongos
# This passthrough implicitly shards the accessed collections. Do not run tests where collections
# can't be created on `getCollection` call.
- assumes_no_implicit_collection_creation_on_get_collection
# Tests tagged with the following will fail because they assume collections are not sharded.
- assumes_no_implicit_collection_creation_after_drop
- assumes_no_implicit_index_creation
- assumes_unsharded_collection
- cannot_create_unique_index_when_using_hashed_shard_key
# system.profile collection doesn't exist on mongos.
- requires_profiling
# Capped collections cannot be sharded
- requires_capped
# The following tags are excluded specifically for this suite.
- config_shard_incompatible
- assumes_stable_shard_list
# Currently this passthrough enables the balancer to allow the config transition to successfully complete.
- assumes_balancer_off
# Fast count doesn't filter orphan documents
- requires_fastcount
# This suite performs balancing of unsharded collection in background using moveCollection that
# changes collections UUID
- assumes_stable_collection_uuid
- does_not_support_retryable_writes
- requires_non_retryable_writes
# implicitly_retry_on_migration_in_progress.js alters find/aggregate commands
# so that the whole result set is returned through a single batch
- assumes_no_implicit_cursor_exhaustion
executor:
archive:
hooks:
- CheckReplDBHash
- CheckMetadataConsistencyInBackground
- ValidateCollections
config:
shell_options:
eval: >-
await import("jstests/libs/override_methods/enable_sessions.js");
await import("jstests/libs/override_methods/implicitly_shard_accessed_collections.js");
await import("jstests/libs/override_methods/implicitly_retry_on_shard_transition_errors.js");
global_vars:
TestData:
alwaysInjectTransactionNumber: true
shardsAddedRemoved: true
hasRandomShardsAddedRemoved: true
runningWithBalancer: true
sessionOptions:
retryWrites: true
hooks:
- class: ContinuousAddRemoveShard
transition_configsvr: true
add_remove_random_shards: true
- class: CheckReplDBHash
- class: CheckMetadataConsistencyInBackground
shell_options:
global_vars:
TestData:
shardsAddedRemoved: true
hasRandomShardsAddedRemoved: true
pauseMigrationsDuringMultiUpdates: true
- class: ValidateCollections
- class: CheckShardFilteringMetadata
- class: CheckOrphansDeleted
- class: CleanEveryN
n: 20
fixture:
class: ShardedClusterFixture
config_shard: "any"
num_shards: 3
num_mongos: 3
mongos_options:
set_parameters:
enableTestCommands: 1
mongod_options:
set_parameters:
enableTestCommands: 1
skipDroppingHashedShardKeyIndex: true
featureFlagReshardingForTimeseries: true
reshardingMinimumOperationDurationMillis: 0
set_cluster_parameter:
parameter: pauseMigrationsDuringMultiUpdates
value:
enabled: True
enable_balancer: true
random_migrations: true
|
unknown
|
github
|
https://github.com/mongodb/mongo
|
buildscripts/resmokeconfig/suites/sharded_collections_jscore_passthrough_with_config_transitions_and_add_remove_shard.yml
|
from django.test import TestCase
class AdminBasicTest(TestCase):
def index_page(self, username='staff', password='123'):
self.assertTrue(self.client.login(username=username, password=password))
return self.client.get('/admin/')
def test_admin_loads(self):
self.assertEqual(self.index_page().status_code, 200)
def test_permissions(self):
index = self.index_page()
self.assertContains(index, 'Foos')
self.assertNotContains(index, 'Bars')
self.assertNotContains(index, 'Users')
self.assertNotContains(index, 'Test app menu')
super_index = self.index_page('superuser', '123')
self.assertContains(super_index, 'Users', 3) # menu and dashboard items
self.assertContains(super_index, 'Test app menu')
def test_app_index(self):
self.client.login(username='staff', password='123')
res = self.client.get('/admin/test_app/')
self.assertEqual(res.status_code, 200)
self.assertContains(res, 'Foos')
self.assertNotContains(res, 'Bars')
self.client.login(username='superuser', password='123')
res = self.client.get('/admin/test_app/')
self.assertContains(res, 'Foos')
self.assertContains(res, 'Bars')
self.assertContains(res, 'Users', 2) # only items from menu
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/bin/sh
test_description='test untracked cache'
GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME=main
export GIT_TEST_DEFAULT_INITIAL_BRANCH_NAME
. ./test-lib.sh
# On some filesystems (e.g. FreeBSD's ext2 and ufs) directory mtime
# is updated lazily after contents in the directory changes, which
# forces the untracked cache code to take the slow path. A test
# that wants to make sure that the fast path works correctly should
# call this helper to make mtime of the containing directory in sync
# with the reality before checking the fast path behaviour.
#
# See <20160803174522.5571-1-pclouds@gmail.com> if you want to know
# more.
GIT_FORCE_UNTRACKED_CACHE=true
export GIT_FORCE_UNTRACKED_CACHE
sync_mtime () {
find . -type d -exec ls -ld {} + >/dev/null
}
avoid_racy() {
sleep 1
}
status_is_clean() {
git status --porcelain >../status.actual &&
test_must_be_empty ../status.actual
}
# Ignore_Untracked_Cache, abbreviated to 3 letters because then people can
# compare commands side-by-side, e.g.
# iuc status --porcelain >expect &&
# git status --porcelain >actual &&
# test_cmp expect actual
iuc () {
git ls-files -s >../current-index-entries
git ls-files -t | sed -ne s/^S.//p >../current-sparse-entries
GIT_INDEX_FILE=.git/tmp_index
export GIT_INDEX_FILE
git update-index --index-info <../current-index-entries
git update-index --skip-worktree $(cat ../current-sparse-entries)
git -c core.untrackedCache=false "$@"
ret=$?
rm ../current-index-entries
rm $GIT_INDEX_FILE
unset GIT_INDEX_FILE
return $ret
}
get_relevant_traces () {
# From the GIT_TRACE2_PERF data of the form
# $TIME $FILE:$LINE | d0 | main | data | r1 | ? | ? | read_directo | $RELEVANT_STAT
# extract the $RELEVANT_STAT fields. We don't care about region_enter
# or region_leave, or stats for things outside read_directory.
INPUT_FILE=$1
OUTPUT_FILE=$2
grep data.*read_directo $INPUT_FILE |
cut -d "|" -f 9 |
grep -v visited \
>"$OUTPUT_FILE"
}
test_lazy_prereq UNTRACKED_CACHE '
{ git update-index --test-untracked-cache; ret=$?; } &&
test $ret -ne 1
'
if ! test_have_prereq UNTRACKED_CACHE; then
skip_all='This system does not support untracked cache'
test_done
fi
test_expect_success 'core.untrackedCache is unset' '
test_must_fail git config --get core.untrackedCache
'
test_expect_success 'setup' '
git init --template= worktree &&
cd worktree &&
mkdir done dtwo dthree &&
touch one two three done/one dtwo/two dthree/three &&
test-tool chmtime =-300 one two three done/one dtwo/two dthree/three &&
test-tool chmtime =-300 done dtwo dthree &&
test-tool chmtime =-300 . &&
git add one two done/one &&
mkdir .git/info &&
: >.git/info/exclude &&
git update-index --untracked-cache &&
test_oid_cache <<-EOF
root sha1:e6fcc8f2ee31bae321d66afd183fcb7237afae6e
root sha256:b90c672088c015b9c83876e919da311bad4cd39639fb139f988af6a11493b974
exclude sha1:13263c0978fb9fad16b2d580fb800b6d811c3ff0
exclude sha256:fe4aaa1bbbbce4cb8f73426748a14c5ad6026b26f90505a0bf2494b165a5b76c
done sha1:1946f0437f90c5005533cbe1736a6451ca301714
done sha256:7f079501d79f665b3acc50f5e0e9e94509084d5032ac20113a37dd5029b757cc
EOF
'
test_expect_success 'untracked cache is empty' '
test-tool dump-untracked-cache >../actual &&
cat >../expect-empty <<EOF &&
info/exclude $ZERO_OID
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
EOF
test_cmp ../expect-empty ../actual
'
cat >../status.expect <<EOF &&
A done/one
A one
A two
?? dthree/
?? dtwo/
?? three
EOF
cat >../dump.expect <<EOF &&
info/exclude $EMPTY_BLOB
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $ZERO_OID recurse valid
dthree/
dtwo/
three
/done/ $ZERO_OID recurse valid
/dthree/ $ZERO_OID recurse check_only valid
three
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_expect_success 'status first time (empty cache)' '
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../actual &&
iuc status --porcelain >../status.iuc &&
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:3
....gitignore-invalidation:1
....directory-invalidation:0
....opendir:4
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'untracked cache after first status' '
test-tool dump-untracked-cache >../actual &&
test_cmp ../dump.expect ../actual
'
test_expect_success 'status second time (fully populated cache)' '
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../actual &&
iuc status --porcelain >../status.iuc &&
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:0
....directory-invalidation:0
....opendir:0
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'untracked cache after second status' '
test-tool dump-untracked-cache >../actual &&
test_cmp ../dump.expect ../actual
'
cat >../status_uall.expect <<EOF &&
A done/one
A one
A two
?? dthree/three
?? dtwo/two
?? three
EOF
# Bypassing the untracked cache here is not desirable from an
# end-user perspective, but is expected in the current design.
# The untracked cache data stored for a -unormal run cannot be
# correctly used in a -uall run - it would yield incorrect output.
test_expect_success 'untracked cache is bypassed with -uall' '
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status -uall --porcelain >../actual &&
iuc status -uall --porcelain >../status.iuc &&
test_cmp ../status_uall.expect ../status.iuc &&
test_cmp ../status_uall.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'untracked cache remains after bypass' '
test-tool dump-untracked-cache >../actual &&
test_cmp ../dump.expect ../actual
'
test_expect_success 'if -uall is configured, untracked cache gets populated by default' '
test_config status.showuntrackedfiles all &&
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../actual &&
iuc status --porcelain >../status.iuc &&
test_cmp ../status_uall.expect ../status.iuc &&
test_cmp ../status_uall.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:3
....gitignore-invalidation:1
....directory-invalidation:0
....opendir:4
EOF
test_cmp ../trace.expect ../trace.relevant
'
cat >../dump_uall.expect <<EOF &&
info/exclude $EMPTY_BLOB
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000000
/ $ZERO_OID recurse valid
three
/done/ $ZERO_OID recurse valid
/dthree/ $ZERO_OID recurse valid
three
/dtwo/ $ZERO_OID recurse valid
two
EOF
test_expect_success 'if -uall was configured, untracked cache is populated' '
test-tool dump-untracked-cache >../actual &&
test_cmp ../dump_uall.expect ../actual
'
test_expect_success 'if -uall is configured, untracked cache is used by default' '
test_config status.showuntrackedfiles all &&
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../actual &&
iuc status --porcelain >../status.iuc &&
test_cmp ../status_uall.expect ../status.iuc &&
test_cmp ../status_uall.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:0
....directory-invalidation:0
....opendir:0
EOF
test_cmp ../trace.expect ../trace.relevant
'
# Bypassing the untracked cache here is not desirable from an
# end-user perspective, but is expected in the current design.
# The untracked cache data stored for a -all run cannot be
# correctly used in a -unormal run - it would yield incorrect
# output.
test_expect_success 'if -uall is configured, untracked cache is bypassed with -unormal' '
test_config status.showuntrackedfiles all &&
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status -unormal --porcelain >../actual &&
iuc status -unormal --porcelain >../status.iuc &&
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'repopulate untracked cache for -unormal' '
git status --porcelain
'
test_expect_success 'modify in root directory, one dir invalidation' '
: >four &&
test-tool chmtime =-240 four &&
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
A done/one
A one
A two
?? dthree/
?? dtwo/
?? four
?? three
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:0
....directory-invalidation:1
....opendir:1
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'verify untracked cache dump' '
test-tool dump-untracked-cache >../actual &&
cat >../expect <<EOF &&
info/exclude $EMPTY_BLOB
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $ZERO_OID recurse valid
dthree/
dtwo/
four
three
/done/ $ZERO_OID recurse valid
/dthree/ $ZERO_OID recurse check_only valid
three
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_cmp ../expect ../actual
'
test_expect_success 'new .gitignore invalidates recursively' '
echo four >.gitignore &&
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
A done/one
A one
A two
?? .gitignore
?? dthree/
?? dtwo/
?? three
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:1
....directory-invalidation:1
....opendir:4
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'verify untracked cache dump' '
test-tool dump-untracked-cache >../actual &&
cat >../expect <<EOF &&
info/exclude $EMPTY_BLOB
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $(test_oid root) recurse valid
.gitignore
dthree/
dtwo/
three
/done/ $ZERO_OID recurse valid
/dthree/ $ZERO_OID recurse check_only valid
three
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_cmp ../expect ../actual
'
test_expect_success 'new info/exclude invalidates everything' '
echo three >>.git/info/exclude &&
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
A done/one
A one
A two
?? .gitignore
?? dtwo/
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:1
....directory-invalidation:0
....opendir:4
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'verify untracked cache dump' '
test-tool dump-untracked-cache >../actual &&
cat >../expect <<EOF &&
info/exclude $(test_oid exclude)
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $(test_oid root) recurse valid
.gitignore
dtwo/
/done/ $ZERO_OID recurse valid
/dthree/ $ZERO_OID recurse check_only valid
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_cmp ../expect ../actual
'
test_expect_success 'move two from tracked to untracked' '
git rm --cached two &&
test-tool dump-untracked-cache >../actual &&
cat >../expect <<EOF &&
info/exclude $(test_oid exclude)
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $(test_oid root) recurse
/done/ $ZERO_OID recurse valid
/dthree/ $ZERO_OID recurse check_only valid
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_cmp ../expect ../actual
'
test_expect_success 'status after the move' '
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
A done/one
A one
?? .gitignore
?? dtwo/
?? two
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:0
....directory-invalidation:0
....opendir:1
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'verify untracked cache dump' '
test-tool dump-untracked-cache >../actual &&
cat >../expect <<EOF &&
info/exclude $(test_oid exclude)
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $(test_oid root) recurse valid
.gitignore
dtwo/
two
/done/ $ZERO_OID recurse valid
/dthree/ $ZERO_OID recurse check_only valid
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_cmp ../expect ../actual
'
test_expect_success 'move two from untracked to tracked' '
git add two &&
test-tool dump-untracked-cache >../actual &&
cat >../expect <<EOF &&
info/exclude $(test_oid exclude)
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $(test_oid root) recurse
/done/ $ZERO_OID recurse valid
/dthree/ $ZERO_OID recurse check_only valid
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_cmp ../expect ../actual
'
test_expect_success 'status after the move' '
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
A done/one
A one
A two
?? .gitignore
?? dtwo/
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:0
....directory-invalidation:0
....opendir:1
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'verify untracked cache dump' '
test-tool dump-untracked-cache >../actual &&
cat >../expect <<EOF &&
info/exclude $(test_oid exclude)
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $(test_oid root) recurse valid
.gitignore
dtwo/
/done/ $ZERO_OID recurse valid
/dthree/ $ZERO_OID recurse check_only valid
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_cmp ../expect ../actual
'
test_expect_success 'set up for sparse checkout testing' '
echo two >done/.gitignore &&
echo three >>done/.gitignore &&
echo two >done/two &&
git add -f done/two done/.gitignore &&
git commit -m "first commit"
'
test_expect_success 'status after commit' '
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
?? .gitignore
?? dtwo/
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:0
....directory-invalidation:0
....opendir:2
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'untracked cache correct after commit' '
test-tool dump-untracked-cache >../actual &&
cat >../expect <<EOF &&
info/exclude $(test_oid exclude)
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $(test_oid root) recurse valid
.gitignore
dtwo/
/done/ $ZERO_OID recurse valid
/dthree/ $ZERO_OID recurse check_only valid
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_cmp ../expect ../actual
'
test_expect_success 'set up sparse checkout' '
echo "done/[a-z]*" >.git/info/sparse-checkout &&
test_config core.sparsecheckout true &&
git checkout main &&
git update-index --force-untracked-cache &&
git status --porcelain >/dev/null && # prime the cache
test_path_is_missing done/.gitignore &&
test_path_is_file done/one
'
test_expect_success 'create/modify files, some of which are gitignored' '
echo two bis >done/two &&
echo three >done/three && # three is gitignored
echo four >done/four && # four is gitignored at a higher level
echo five >done/five && # five is not gitignored
test-tool chmtime =-180 done/two done/three done/four done/five done &&
# we need to ensure that the root dir is touched (in the past);
test-tool chmtime =-180 . &&
sync_mtime
'
test_expect_success 'test sparse status with untracked cache' '
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../status.actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
M done/two
?? .gitignore
?? done/five
?? dtwo/
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../status.actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:1
....directory-invalidation:2
....opendir:2
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'untracked cache correct after status' '
test-tool dump-untracked-cache >../actual &&
cat >../expect <<EOF &&
info/exclude $(test_oid exclude)
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $(test_oid root) recurse valid
.gitignore
dtwo/
/done/ $(test_oid done) recurse valid
five
/dthree/ $ZERO_OID recurse check_only valid
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_cmp ../expect ../actual
'
test_expect_success 'test sparse status again with untracked cache' '
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../status.actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
M done/two
?? .gitignore
?? done/five
?? dtwo/
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../status.actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:0
....directory-invalidation:0
....opendir:0
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'set up for test of subdir and sparse checkouts' '
mkdir done/sub &&
mkdir done/sub/sub &&
echo "sub" > done/sub/sub/file &&
test-tool chmtime =-120 done/sub/sub/file done/sub/sub done/sub done
'
test_expect_success 'test sparse status with untracked cache and subdir' '
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../status.actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
M done/two
?? .gitignore
?? done/five
?? done/sub/
?? dtwo/
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../status.actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:2
....gitignore-invalidation:0
....directory-invalidation:1
....opendir:3
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'verify untracked cache dump (sparse/subdirs)' '
test-tool dump-untracked-cache >../actual &&
cat >../expect-from-test-dump <<EOF &&
info/exclude $(test_oid exclude)
core.excludesfile $ZERO_OID
exclude_per_dir .gitignore
flags 00000006
/ $(test_oid root) recurse valid
.gitignore
dtwo/
/done/ $(test_oid done) recurse valid
five
sub/
/done/sub/ $ZERO_OID recurse check_only valid
sub/
/done/sub/sub/ $ZERO_OID recurse check_only valid
file
/dthree/ $ZERO_OID recurse check_only valid
/dtwo/ $ZERO_OID recurse check_only valid
two
EOF
test_cmp ../expect-from-test-dump ../actual
'
test_expect_success 'test sparse status again with untracked cache and subdir' '
: >../trace.output &&
GIT_TRACE2_PERF="$TRASH_DIRECTORY/trace.output" \
git status --porcelain >../status.actual &&
iuc status --porcelain >../status.iuc &&
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../status.actual &&
get_relevant_traces ../trace.output ../trace.relevant &&
cat >../trace.expect <<EOF &&
....path:
....node-creation:0
....gitignore-invalidation:0
....directory-invalidation:0
....opendir:0
EOF
test_cmp ../trace.expect ../trace.relevant
'
test_expect_success 'move entry in subdir from untracked to cached' '
git add dtwo/two &&
git status --porcelain >../status.actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
M done/two
A dtwo/two
?? .gitignore
?? done/five
?? done/sub/
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../status.actual
'
test_expect_success 'move entry in subdir from cached to untracked' '
git rm --cached dtwo/two &&
git status --porcelain >../status.actual &&
iuc status --porcelain >../status.iuc &&
cat >../status.expect <<EOF &&
M done/two
?? .gitignore
?? done/five
?? done/sub/
?? dtwo/
EOF
test_cmp ../status.expect ../status.iuc &&
test_cmp ../status.expect ../status.actual
'
test_expect_success '--no-untracked-cache removes the cache' '
git update-index --no-untracked-cache &&
test-tool dump-untracked-cache >../actual &&
echo "no untracked cache" >../expect-no-uc &&
test_cmp ../expect-no-uc ../actual
'
test_expect_success 'git status does not change anything' '
git status &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-no-uc ../actual
'
test_expect_success 'setting core.untrackedCache to true and using git status creates the cache' '
git config core.untrackedCache true &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-no-uc ../actual &&
git status &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-from-test-dump ../actual
'
test_expect_success 'using --no-untracked-cache does not fail when core.untrackedCache is true' '
git update-index --no-untracked-cache &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-no-uc ../actual &&
git update-index --untracked-cache &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-empty ../actual
'
test_expect_success 'setting core.untrackedCache to false and using git status removes the cache' '
git config core.untrackedCache false &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-empty ../actual &&
git status &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-no-uc ../actual
'
test_expect_success 'using --untracked-cache does not fail when core.untrackedCache is false' '
git update-index --untracked-cache &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-empty ../actual
'
test_expect_success 'setting core.untrackedCache to keep' '
git config core.untrackedCache keep &&
git update-index --untracked-cache &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-empty ../actual &&
git status &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-from-test-dump ../actual &&
git update-index --no-untracked-cache &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-no-uc ../actual &&
git update-index --force-untracked-cache &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-empty ../actual &&
git status &&
test-tool dump-untracked-cache >../actual &&
test_cmp ../expect-from-test-dump ../actual
'
test_expect_success 'test ident field is working' '
mkdir ../other_worktree &&
cp -R done dthree dtwo four three ../other_worktree &&
GIT_WORK_TREE=../other_worktree git status 2>../err &&
echo "warning: untracked cache is disabled on this system or location" >../expect &&
test_cmp ../expect ../err
'
test_expect_success 'untracked cache survives a checkout' '
git commit --allow-empty -m empty &&
test-tool dump-untracked-cache >../before &&
test_when_finished "git checkout main" &&
git checkout -b other_branch &&
test-tool dump-untracked-cache >../after &&
test_cmp ../before ../after &&
test_commit test &&
test-tool dump-untracked-cache >../before &&
git checkout main &&
test-tool dump-untracked-cache >../after &&
test_cmp ../before ../after
'
test_expect_success 'untracked cache survives a commit' '
test-tool dump-untracked-cache >../before &&
git add done/two &&
git commit -m commit &&
test-tool dump-untracked-cache >../after &&
test_cmp ../before ../after
'
test_expect_success 'teardown worktree' '
cd ..
'
test_expect_success SYMLINKS 'setup worktree for symlink test' '
git init worktree-symlink &&
cd worktree-symlink &&
git config core.untrackedCache true &&
mkdir one two &&
touch one/file two/file &&
git add one/file two/file &&
git commit -m"first commit" &&
git rm -rf one &&
ln -s two one &&
git add one &&
git commit -m"second commit"
'
test_expect_success SYMLINKS '"status" after symlink replacement should be clean with UC=true' '
git checkout HEAD~ &&
status_is_clean &&
status_is_clean &&
git checkout main &&
avoid_racy &&
status_is_clean &&
status_is_clean
'
test_expect_success SYMLINKS '"status" after symlink replacement should be clean with UC=false' '
git config core.untrackedCache false &&
git checkout HEAD~ &&
status_is_clean &&
status_is_clean &&
git checkout main &&
avoid_racy &&
status_is_clean &&
status_is_clean
'
test_expect_success 'setup worktree for non-symlink test' '
git init worktree-non-symlink &&
cd worktree-non-symlink &&
git config core.untrackedCache true &&
mkdir one two &&
touch one/file two/file &&
git add one/file two/file &&
git commit -m"first commit" &&
git rm -rf one &&
cp two/file one &&
git add one &&
git commit -m"second commit"
'
test_expect_success '"status" after file replacement should be clean with UC=true' '
git checkout HEAD~ &&
status_is_clean &&
status_is_clean &&
git checkout main &&
avoid_racy &&
status_is_clean &&
test-tool dump-untracked-cache >../actual &&
grep -F "recurse valid" ../actual >../actual.grep &&
cat >../expect.grep <<EOF &&
/ $ZERO_OID recurse valid
/two/ $ZERO_OID recurse valid
EOF
status_is_clean &&
test_cmp ../expect.grep ../actual.grep
'
test_expect_success '"status" after file replacement should be clean with UC=false' '
git config core.untrackedCache false &&
git checkout HEAD~ &&
status_is_clean &&
status_is_clean &&
git checkout main &&
avoid_racy &&
status_is_clean &&
status_is_clean
'
test_expect_success 'empty repo (no index) and core.untrackedCache' '
git init emptyrepo &&
git -C emptyrepo -c core.untrackedCache=true write-tree
'
test_done
|
unknown
|
github
|
https://github.com/git/git
|
t/t7063-status-untracked-cache.sh
|
# -*- coding: utf-8 -*-
__license__ = 'GPL v3'
__copyright__ = '2009, John Schember <john at nachtimwald.com>'
__docformat__ = 'restructuredtext en'
'''
Device driver for Bookeen's Cybook Gen 3
'''
from calibre.devices.usbms.driver import USBMS
class README(USBMS):
name = 'Binatone Readme Device Interface'
gui_name = 'Binatone Readme'
description = _('Communicate with the Binatone Readme eBook reader.')
author = 'John Schember'
supported_platforms = ['windows', 'osx', 'linux']
# Ordered list of supported formats
# Be sure these have an entry in calibre.devices.mime
FORMATS = ['txt']
VENDOR_ID = [0x04fc]
PRODUCT_ID = [0x5563]
BCD = [0x0100]
VENDOR_NAME = ''
WINDOWS_MAIN_MEM = 'MASS_STORAGE'
WINDOWS_CARD_A_MEM = 'MASS_STORAGE'
MAIN_MEMORY_VOLUME_LABEL = 'Readme Main Memory'
STORAGE_CARD_VOLUME_LABEL = 'Readme Storage Card'
SUPPORTS_SUB_DIRS = True
def linux_swap_drives(self, drives):
if len(drives) < 2: return drives
drives = list(drives)
t = drives[0]
drives[0] = drives[1]
drives[1] = t
return tuple(drives)
def windows_sort_drives(self, drives):
if len(drives) < 2: return drives
main = drives.get('main', None)
carda = drives.get('carda', None)
if main and carda:
drives['main'] = carda
drives['carda'] = main
return drives
|
unknown
|
codeparrot/codeparrot-clean
| ||
# Copyright 2014 PressLabs SRL
#
# 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 getpass
import os
import socket
import tempfile
import grp
import sys
from logging import Formatter
from logging.handlers import TimedRotatingFileHandler, SysLogHandler
from collections import OrderedDict
from urlparse import urlparse
from gitfs.log import log
from gitfs.cache import lru_cache
class Args(object):
def __init__(self, parser):
self.DEFAULTS = OrderedDict([
("repo_path", (self.get_repo_path, "string")),
("user", (self.get_current_user, "string")),
("group", (self.get_current_group, "string")),
("username", ("", "string")),
("password", ("", "string")),
("ssh_key", (self.get_ssh_key, "string")),
("ssh_user", (self.get_ssh_user, "string")),
("foreground", (False, "bool")),
("branch", ("master", "string")),
("allow_other", (False, "bool")),
("allow_root", (True, "bool")),
("commiter_name", (self.get_commiter_user, "string")),
("commiter_email", (self.get_commiter_email, "string")),
("max_size", (10, "float")),
("fetch_timeout", (30, "float")),
("idle_fetch_timeout", (30 * 60, "float")), # 30 min
("merge_timeout", (5, "float")),
("debug", (False, "bool")),
("log", ("syslog", "string")),
("log_level", ("warning", "string")),
("cache_size", (800, "int")),
("sentry_dsn", (self.get_sentry_dsn, "string")),
("ignore_file", ("", "string")),
("hard_ignore", ("", "string")),
("min_idle_times", (10, "float")),
])
self.config = self.build_config(parser.parse_args())
def build_config(self, args):
if args.o:
for arg in args.o.split(","):
if "=" in arg:
item, value = arg.split("=")
setattr(args, item, value)
return self.check_args(self.set_defaults(args))
def check_args(self, args):
# check allow_other and allow_root
if args.allow_other:
args.allow_root = False
else:
args.allow_root = True
# check log_level
if args.debug:
args.log_level = 'debug'
# setup logging
if args.log != "syslog":
handler = TimedRotatingFileHandler(args.log, when="midnight")
handler.setFormatter(Formatter(fmt='%(asctime)s %(threadName)s: '
'%(message)s',
datefmt='%B-%d-%Y %H:%M:%S'))
else:
if sys.platform == 'darwin':
handler = SysLogHandler(address="/var/run/syslog")
else:
handler = SysLogHandler(address="/dev/log")
logger_fmt = 'GitFS on {mount_point} [%(process)d]: %(threadName)s: '\
'%(message)s'.format(mount_point=args.mount_point)
handler.setFormatter(Formatter(fmt=logger_fmt))
if args.sentry_dsn != '':
from raven.conf import setup_logging
from raven.handlers.logging import SentryHandler
sentry_handler = SentryHandler(args.sentry_dsn)
sentry_handler.setLevel("ERROR")
setup_logging(sentry_handler)
log.addHandler(sentry_handler)
handler.setLevel(args.log_level.upper())
log.setLevel(args.log_level.upper())
log.addHandler(handler)
# set cache size
lru_cache.maxsize = args.cache_size
# return absolute repository's path
args.repo_path = os.path.abspath(args.repo_path)
return args
def __getattr__(self, attr):
if attr in self.__dict__:
return self.__dict__[attr]
else:
return getattr(self.__dict__['config'], attr)
def set_defaults(self, args):
for option, value in self.DEFAULTS.iteritems():
new_value = getattr(args, option, None)
if not new_value:
value = value[0]
if callable(value):
value = value(args)
else:
if value[1] == "string":
value = new_value
elif value[1] == "bool":
if new_value.lower() == "true":
value = True
if new_value.lower() == "false":
value = False
elif value[1] == "float":
value = float(new_value)
elif value[1] == "int":
value = int(new_value)
setattr(args, option, value)
return args
def get_current_group(self, args):
gid = os.getegid()
return grp.getgrgid(gid).gr_name
def get_current_user(self, args):
return getpass.getuser()
def get_commiter_user(self, args):
return args.user
def get_commiter_email(self, args):
return "%s@%s" % (args.user, socket.gethostname())
def get_repo_path(self, args):
return tempfile.mkdtemp(dir="/var/lib/gitfs")
def get_ssh_key(self, args):
return os.environ["HOME"] + "/.ssh/id_rsa"
def get_sentry_dsn(self, args):
return os.environ["SENTRY_DSN"] if "SENTRY_DSN" in os.environ else ""
def get_ssh_user(self, args):
url = args.remote_url
parse_result = urlparse(url)
if not parse_result.scheme:
url = 'ssh://' + url
parse_result = urlparse(url)
return parse_result.username if parse_result.username else ""
|
unknown
|
codeparrot/codeparrot-clean
| ||
#
# 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.
"""
Example Airflow DAG for Google Cloud Storage to Google Cloud Storage transfer operators.
"""
import os
from airflow import models
from airflow.providers.google.cloud.operators.gcs import GCSSynchronizeBucketsOperator
from airflow.providers.google.cloud.transfers.gcs_to_gcs import GCSToGCSOperator
from airflow.utils.dates import days_ago
BUCKET_1_SRC = os.environ.get("GCP_GCS_BUCKET_1_SRC", "test-gcs-sync-1-src")
BUCKET_1_DST = os.environ.get("GCP_GCS_BUCKET_1_DST", "test-gcs-sync-1-dst")
BUCKET_2_SRC = os.environ.get("GCP_GCS_BUCKET_2_SRC", "test-gcs-sync-2-src")
BUCKET_2_DST = os.environ.get("GCP_GCS_BUCKET_2_DST", "test-gcs-sync-2-dst")
BUCKET_3_SRC = os.environ.get("GCP_GCS_BUCKET_3_SRC", "test-gcs-sync-3-src")
BUCKET_3_DST = os.environ.get("GCP_GCS_BUCKET_3_DST", "test-gcs-sync-3-dst")
OBJECT_1 = os.environ.get("GCP_GCS_OBJECT_1", "test-gcs-to-gcs-1")
OBJECT_2 = os.environ.get("GCP_GCS_OBJECT_2", "test-gcs-to-gcs-2")
with models.DAG(
"example_gcs_to_gcs", start_date=days_ago(1), schedule_interval=None, tags=['example']
) as dag:
# [START howto_synch_bucket]
sync_bucket = GCSSynchronizeBucketsOperator(
task_id="sync_bucket", source_bucket=BUCKET_1_SRC, destination_bucket=BUCKET_1_DST
)
# [END howto_synch_bucket]
# [START howto_synch_full_bucket]
sync_full_bucket = GCSSynchronizeBucketsOperator(
task_id="sync_full_bucket",
source_bucket=BUCKET_1_SRC,
destination_bucket=BUCKET_1_DST,
delete_extra_files=True,
allow_overwrite=True,
)
# [END howto_synch_full_bucket]
# [START howto_synch_to_subdir]
sync_to_subdirectory = GCSSynchronizeBucketsOperator(
task_id="sync_to_subdirectory",
source_bucket=BUCKET_1_SRC,
destination_bucket=BUCKET_1_DST,
destination_object="subdir/",
)
# [END howto_synch_to_subdir]
# [START howto_sync_from_subdir]
sync_from_subdirectory = GCSSynchronizeBucketsOperator(
task_id="sync_from_subdirectory",
source_bucket=BUCKET_1_SRC,
source_object="subdir/",
destination_bucket=BUCKET_1_DST,
)
# [END howto_sync_from_subdir]
# [START howto_operator_gcs_to_gcs_single_file]
copy_single_file = GCSToGCSOperator(
task_id="copy_single_gcs_file",
source_bucket=BUCKET_1_SRC,
source_object=OBJECT_1,
destination_bucket=BUCKET_1_DST, # If not supplied the source_bucket value will be used
destination_object="backup_" + OBJECT_1, # If not supplied the source_object value will be used
)
# [END howto_operator_gcs_to_gcs_single_file]
# [START howto_operator_gcs_to_gcs_wildcard]
copy_files_with_wildcard = GCSToGCSOperator(
task_id="copy_files_with_wildcard",
source_bucket=BUCKET_1_SRC,
source_object="data/*.txt",
destination_bucket=BUCKET_1_DST,
destination_object="backup/",
)
# [END howto_operator_gcs_to_gcs_wildcard]
# [START howto_operator_gcs_to_gcs_without_wildcard]
copy_files_without_wildcard = GCSToGCSOperator(
task_id="copy_files_without_wildcard",
source_bucket=BUCKET_1_SRC,
source_object="subdir/",
destination_bucket=BUCKET_1_DST,
destination_object="backup/",
)
# [END howto_operator_gcs_to_gcs_without_wildcard]
# [START howto_operator_gcs_to_gcs_delimiter]
copy_files_with_delimiter = GCSToGCSOperator(
task_id="copy_files_with_delimiter",
source_bucket=BUCKET_1_SRC,
source_object="data/",
destination_bucket=BUCKET_1_DST,
destination_object="backup/",
delimiter='.txt',
)
# [END howto_operator_gcs_to_gcs_delimiter]
# [START howto_operator_gcs_to_gcs_list]
copy_files_with_list = GCSToGCSOperator(
task_id="copy_files_with_list",
source_bucket=BUCKET_1_SRC,
source_objects=[OBJECT_1, OBJECT_2], # Instead of files each element could be a wildcard expression
destination_bucket=BUCKET_1_DST,
destination_object="backup/",
)
# [END howto_operator_gcs_to_gcs_list]
# [START howto_operator_gcs_to_gcs_single_file_move]
move_single_file = GCSToGCSOperator(
task_id="move_single_file",
source_bucket=BUCKET_1_SRC,
source_object=OBJECT_1,
destination_bucket=BUCKET_1_DST,
destination_object="backup_" + OBJECT_1,
move_object=True,
)
# [END howto_operator_gcs_to_gcs_single_file_move]
# [START howto_operator_gcs_to_gcs_list_move]
move_files_with_list = GCSToGCSOperator(
task_id="move_files_with_list",
source_bucket=BUCKET_1_SRC,
source_objects=[OBJECT_1, OBJECT_2],
destination_bucket=BUCKET_1_DST,
destination_object="backup/",
)
# [END howto_operator_gcs_to_gcs_list_move]
|
unknown
|
codeparrot/codeparrot-clean
| ||
// Copyright IBM Corp. 2016, 2025
// SPDX-License-Identifier: BUSL-1.1
package pki
import (
"strings"
"github.com/hashicorp/vault/builtin/logical/pki/issuing"
)
func (sc *storageContext) isDefaultKeySet() (bool, error) {
config, err := sc.getKeysConfig()
if err != nil {
return false, err
}
return strings.TrimSpace(config.DefaultKeyId.String()) != "", nil
}
func (sc *storageContext) isDefaultIssuerSet() (bool, error) {
config, err := sc.getIssuersConfig()
if err != nil {
return false, err
}
return strings.TrimSpace(config.DefaultIssuerId.String()) != "", nil
}
func (sc *storageContext) updateDefaultKeyId(id issuing.KeyID) error {
config, err := sc.getKeysConfig()
if err != nil {
return err
}
if config.DefaultKeyId != id {
return sc.setKeysConfig(&issuing.KeyConfigEntry{
DefaultKeyId: id,
})
}
return nil
}
func (sc *storageContext) updateDefaultIssuerId(id issuing.IssuerID) error {
config, err := sc.getIssuersConfig()
if err != nil {
return err
}
if config.DefaultIssuerId != id {
config.DefaultIssuerId = id
return sc.setIssuersConfig(config)
}
return nil
}
|
go
|
github
|
https://github.com/hashicorp/vault
|
builtin/logical/pki/config_util.go
|
[
{
"pk": 1,
"model": "auth.group",
"fields": {
"name": "my_group",
"permissions": []
}
},
{
"pk": 1,
"model": "auth.user",
"fields": {
"username": "my_username",
"first_name": "",
"last_name": "",
"is_active": true,
"is_superuser": true,
"is_staff": true,
"last_login": "2012-01-13 00:14:00",
"groups": [
[
"my_group"
]
],
"user_permissions": [],
"password": "pbkdf2_sha256$10000$LUyhxJjuLwXF$f6Zbpnx1L5dPze8m0itBaHMDyZ/n6JyhuavQy2RrBIM=",
"email": "email@example.com",
"date_joined": "2012-01-13 00:14:00"
}
}
]
|
json
|
github
|
https://github.com/django/django
|
tests/auth_tests/fixtures/natural.json
|
# 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.
# ==============================================================================
"""Tests for binary transforms."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.dataframe import tensorflow_dataframe as df
from tensorflow.contrib.learn.python.learn.dataframe.transforms.binary_transforms import BINARY_TRANSFORMS
NUMPY_ARRAY_SIZE = 100
SCALAR = 50.0
TEST_NAME_PREFIX = "testBinaryOp_"
class BinaryTransformTestCase(tf.test.TestCase):
"""Test class for binary transforms."""
@classmethod
def add_test_case(cls, fn_name, op):
def _test(self):
rng = np.arange(-NUMPY_ARRAY_SIZE // 2,
NUMPY_ARRAY_SIZE // 2,
dtype="float32")
frame = df.TensorFlowDataFrame.from_numpy(rng,
batch_size=len(rng),
shuffle=False)
frame["sqr"] = frame["value"].square()
self.assertTrue(hasattr(frame["value"], fn_name))
frame["series_result"] = getattr(frame["value"],
fn_name)(frame["sqr"])
frame["scalar_result"] = getattr(frame["value"], fn_name)(SCALAR)
frame_built = frame.build()
expected_series_tensor = op(frame_built["value"], frame_built["sqr"])
actual_series_tensor = frame_built["series_result"]
expected_scalar_tensor = op(frame_built["value"], SCALAR)
actual_scalar_tensor = frame_built["scalar_result"]
session = tf.Session()
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=session, coord=coord)
actual_series, expected_series, actual_scalar, expected_scalar = (
session.run([actual_series_tensor, expected_series_tensor,
actual_scalar_tensor, expected_scalar_tensor]))
coord.request_stop()
coord.join(threads)
np.testing.assert_almost_equal(expected_series, actual_series)
np.testing.assert_almost_equal(expected_scalar, actual_scalar)
setattr(cls, "{}{}".format(TEST_NAME_PREFIX, op.__name__), _test)
for bt in BINARY_TRANSFORMS:
BinaryTransformTestCase.add_test_case(*bt)
# Check that the number of test methods matches the number of binary transforms.
test_methods = [test for test in dir(BinaryTransformTestCase)
if test.startswith(TEST_NAME_PREFIX)]
assert len(test_methods) == len(BINARY_TRANSFORMS)
if __name__ == "__main__":
tf.test.main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vi:ts=4:et
#
# Usage: python retriever-multi.py <file with URLs to fetch> [<# of
# concurrent connections>]
#
import sys
import pycurl
# We should ignore SIGPIPE when using pycurl.NOSIGNAL - see
# the libcurl tutorial for more info.
try:
import signal
signal.signal(signal.SIGPIPE, signal.SIG_IGN)
except ImportError:
pass
# Get args
num_conn = 10
try:
if sys.argv[1] == "-":
urls = sys.stdin.readlines()
else:
urls = open(sys.argv[1]).readlines()
if len(sys.argv) >= 3:
num_conn = int(sys.argv[2])
except:
print("Usage: %s <file with URLs to fetch> [<# of concurrent connections>]" % sys.argv[0])
raise SystemExit
# Make a queue with (url, filename) tuples
queue = []
for url in urls:
url = url.strip()
if not url or url[0] == "#":
continue
filename = "doc_%03d.dat" % (len(queue) + 1)
queue.append((url, filename))
# Check args
assert queue, "no URLs given"
num_urls = len(queue)
num_conn = min(num_conn, num_urls)
assert 1 <= num_conn <= 10000, "invalid number of concurrent connections"
print("PycURL %s (compiled against 0x%x)" % (pycurl.version, pycurl.COMPILE_LIBCURL_VERSION_NUM))
print("----- Getting", num_urls, "URLs using", num_conn, "connections -----")
# Pre-allocate a list of curl objects
m = pycurl.CurlMulti()
m.handles = []
for i in range(num_conn):
c = pycurl.Curl()
c.fp = None
c.setopt(pycurl.FOLLOWLOCATION, 1)
c.setopt(pycurl.MAXREDIRS, 5)
c.setopt(pycurl.CONNECTTIMEOUT, 30)
c.setopt(pycurl.TIMEOUT, 300)
c.setopt(pycurl.NOSIGNAL, 1)
m.handles.append(c)
# Main loop
freelist = m.handles[:]
num_processed = 0
while num_processed < num_urls:
# If there is an url to process and a free curl object, add to multi stack
while queue and freelist:
url, filename = queue.pop(0)
c = freelist.pop()
c.fp = open(filename, "wb")
c.setopt(pycurl.URL, url)
c.setopt(pycurl.WRITEDATA, c.fp)
m.add_handle(c)
# store some info
c.filename = filename
c.url = url
# Run the internal curl state machine for the multi stack
while 1:
ret, num_handles = m.perform()
if ret != pycurl.E_CALL_MULTI_PERFORM:
break
# Check for curl objects which have terminated, and add them to the freelist
while 1:
num_q, ok_list, err_list = m.info_read()
for c in ok_list:
c.fp.close()
c.fp = None
m.remove_handle(c)
print("Success:", c.filename, c.url, c.getinfo(pycurl.EFFECTIVE_URL))
freelist.append(c)
for c, errno, errmsg in err_list:
c.fp.close()
c.fp = None
m.remove_handle(c)
print("Failed: ", c.filename, c.url, errno, errmsg)
freelist.append(c)
num_processed = num_processed + len(ok_list) + len(err_list)
if num_q == 0:
break
# Currently no more I/O is pending, could do something in the meantime
# (display a progress bar, etc.).
# We just call select() to sleep until some more data is available.
m.select(1.0)
# Cleanup
for c in m.handles:
if c.fp is not None:
c.fp.close()
c.fp = None
c.close()
m.close()
|
unknown
|
codeparrot/codeparrot-clean
| ||
/* Copyright 2019 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.
==============================================================================*/
#ifndef TENSORFLOW_CORE_UTIL_DEBUG_EVENTS_WRITER_H_
#define TENSORFLOW_CORE_UTIL_DEBUG_EVENTS_WRITER_H_
#include <atomic>
#include <deque>
#include <memory>
#include <unordered_map>
#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/record_writer.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/macros.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/debug_event.pb.h"
namespace tensorflow {
namespace tfdbg {
// The set of files generated by a debugged TensorFlow program.
enum DebugEventFileType {
METADATA,
SOURCE_FILES,
STACK_FRAMES,
GRAPHS,
EXECUTION,
GRAPH_EXECUTION_TRACES,
};
// Helper class for DebugEventsWriter.
// This class manages the writing of data to a single TFRecord file.
// Each object of the DebugEventsWriter class below involves multiple
// TFRecord files, and hence utilizes multiple objects of this helper class.
class SingleDebugEventFileWriter {
public:
explicit SingleDebugEventFileWriter(const std::string& file_path);
absl::Status Init();
void WriteSerializedDebugEvent(absl::string_view debug_event_str);
absl::Status Flush();
absl::Status Close();
const std::string FileName();
private:
Env* env_;
const std::string file_path_;
std::atomic_int_fast32_t num_outstanding_events_;
std::unique_ptr<WritableFile> writable_file_;
std::unique_ptr<io::RecordWriter> record_writer_ TF_PT_GUARDED_BY(writer_mu_);
mutex writer_mu_;
};
// The DebugEvents writer class.
class DebugEventsWriter {
public:
#ifndef SWIG
// Prefix of version string present in the first entry of every event file.
// Default size of each circular buffer (unit: number of DebugEvent protos).
static constexpr const int64_t kDefaultCyclicBufferSize = 1000;
static constexpr const char* kFileNamePrefix = "tfdbg_events";
static constexpr const char* kMetadataSuffix = "metadata";
static constexpr const char* kSourceFilesSuffix = "source_files";
static constexpr const char* kStackFramesSuffix = "stack_frames";
static constexpr const char* kGraphsSuffix = "graphs";
static constexpr const char* kExecutionSuffix = "execution";
static constexpr const char* kGraphExecutionTracesSuffix =
"graph_execution_traces";
static constexpr const char* kVersionPrefix = "debug.Event:";
static constexpr const int kCurrentFormatVersion = 1;
#endif
// Get the DebugEventsWriter for the given dump_root.
// For a given dump_root value, it is a singleton. tfdbg event files come in
// sets of six. The singleton pattern avoids storing multiple sets in a single
// folder, which might cause confusion.
//
// If an instance of DebugEventsWriter has already been created at a
// `dump_root`, calling this method with the same `dump_root` will return
// the existing instance.
//
// Args:
// dump_root: Dump root directory. If it doesn't exist, will be created.
// tfdbg_run_id: Debugging run ID of the writer.
// circular_buffer_size: Circular buffer size (in number of DebugEvent
// protos). If set to a value <=0, will abolish the circular-buffer
// behavior.
// Returns:
// A pointer to a DebugEventsWriter object: a per-dump_root singleton.
static DebugEventsWriter* GetDebugEventsWriter(
const std::string& dump_root, const std::string& tfdbg_run_id,
int64_t circular_buffer_size);
// Look up existing events writer by dump_root.
// If no DebugEventsWriter has been created at the dump_root, a non-OK
// Status will be returned. Else an OK status will be returned, with
// the pointer to the existing instance provided by reference.
static absl::Status LookUpDebugEventsWriter(
const std::string& dump_root, DebugEventsWriter** debug_events_writer);
~DebugEventsWriter();
// Sets the debug event filenames and opens file for writing.
// All files (see the DebugEventFileType enum) share the same prefix and
// differ only in their suffixes. If not called by user, will be invoked
// automatically by a call to FileName() or any of the Write*() methods().
// Idempotent: if the metadata file exists and is open, this is a no-op.
// If on the other hand the file was opened, but has since disappeared (e.g.
// deleted by another process), this will open a new file.
absl::Status Init();
// The four DebugEvent fields below are written _without_ the circular
// buffer. Source file contents are written to the *.source_files file.
// Takes ownership of source_file.
absl::Status WriteSourceFile(SourceFile* source_file);
// Stack frames are written to the *.code_locations file.
// Takes ownership of stack_frame_with_id.
absl::Status WriteStackFrameWithId(StackFrameWithId* stack_frame_with_id);
// Graph op creation events are written to the *.graphs file.
// Takes ownership of graph_op_creation.
absl::Status WriteGraphOpCreation(GraphOpCreation* graph_op_creation);
// Debugged graphs are written to the *.graphs file.
// Takes ownership of debugged_graph.
absl::Status WriteDebuggedGraph(DebuggedGraph* debugged_graph);
// The two DebugEvent fields below are written to the circular buffer
// and saved to disk only at the FlushExecutionFiles() call.
// Execution events (eager execution of an op or a tf.function) are written
// to the *.execution file. Takes ownership of execution.
absl::Status WriteExecution(Execution* execution);
// Graph execution traces (graph-internal tensor values or their summaries)
// are written to the *.graph_execution_traces file.
// Takes ownership of graph_execution_trace.
absl::Status WriteGraphExecutionTrace(
GraphExecutionTrace* graph_execution_trace);
// Write a graph execution trace without using a protocol buffer.
// Instead, pass the raw values related to the graph execution trace.
// Args:
// tfdbg_context_id: A unique ID for the context of interest, e.g., a
// concreted compiled tf.function that the op of interest belongs to.
// op_name: Name of the op that this graph execution trace is concerned
// with. Applicable only to the single-tensor trace case. For cases in
// which the trace concerns multiple tensors, this is an empty string.
// output_slot: Output slot index of the op that this trace is concerned
// with.
// tensor_debug_mode: An integer that represents the tensor-debug mode
// enum. tensor_value: The value of the tensor that describes the
// tensor(s)
// that this trace is concerned with. The semantics of this tensor value
// depends on the value of `tensor_debug_mode`.
absl::Status WriteGraphExecutionTrace(const std::string& tfdbg_context_id,
const std::string& device_name,
const std::string& op_name,
int32_t output_slot,
int32_t tensor_debug_mode,
const Tensor& tensor_value);
// Writes a serialized DebugEvent to one of the debug-events files
// concerned with the non-execution events: the SOURCE_FILES, STACK_FRAMES
// and GRAPHS files.
// NOTE: Actually used in the Python binding, to avoid overhead of
// serializing and parsing protos at the language interface.
void WriteSerializedNonExecutionDebugEvent(const std::string& debug_event_str,
DebugEventFileType type);
// Writes a serialized DebugEvent to one of the debug-events files
// concerned with the execution-related events: the EXECUTION and
// GRAPH_EXECUTION_TRACES files. This involves the cyclic-buffer behavior if
// circular_buffer_size is configured to be >0.
// NOTE: Actually used in the Python binding, to avoid overhead of
// serializing and parsing protos at the language interface.
void WriteSerializedExecutionDebugEvent(const std::string& debug_event_str,
DebugEventFileType type);
// Given name of the device, retrieve a unique integer ID. As a side effect,
// if this is the first time this object encounters the device name,
// writes a DebuggedDevice proto to the .graphs file in the file set.
int RegisterDeviceAndGetId(const std::string& device_name);
// EventWriter automatically flushes and closes on destruction, but
// this method is provided for users who want to write to disk sooner
// and/or check for success.
// FlushNonExecutionFiles() pushes outstanding DebugEvents not written
// events to the circular buffer to their respective files.
absl::Status FlushNonExecutionFiles();
// Writes current contents of the circular buffers to their respective
// debug event files and clears the circular buffers.
absl::Status FlushExecutionFiles();
// Close() calls FlushNonExecutionFiles() and FlushExecutionFiles()
// and then closes the current debug events files.
absl::Status Close();
private:
static std::unordered_map<std::string, std::unique_ptr<DebugEventsWriter>>*
// Get a static map from dump-root path to DebugEventsWriter objects.
// This helps the per-dump-root singletone pattern.
GetDebugEventsWriterMap();
// Guards calls to the GetDebugEventsWriter() method.
static mutex factory_mu_;
DebugEventsWriter(const std::string& dump_root,
const std::string& tfdbg_run_id,
int64_t circular_buffer_size);
// Get the path prefix. The same for all files, which differ only in the
// suffix.
std::string FileName(DebugEventFileType type);
// Initialize the TFRecord writer for non-metadata file type.
absl::Status InitNonMetadataFile(DebugEventFileType type);
absl::Status SerializeAndWriteDebugEvent(DebugEvent* debug_event,
DebugEventFileType type);
void SelectWriter(DebugEventFileType type,
std::unique_ptr<SingleDebugEventFileWriter>** writer);
const std::string GetSuffix(DebugEventFileType type);
std::string GetFileNameInternal(DebugEventFileType type);
Env* env_;
const std::string dump_root_;
const std::string tfdbg_run_id_;
std::string file_prefix_;
bool is_initialized_ TF_GUARDED_BY(initialization_mu_);
mutex initialization_mu_;
const int64_t circular_buffer_size_;
std::deque<std::string> execution_buffer_ TF_GUARDED_BY(execution_buffer_mu_);
mutex execution_buffer_mu_;
std::deque<std::string> graph_execution_trace_buffer_
TF_GUARDED_BY(graph_execution_trace_buffer_mu_);
mutex graph_execution_trace_buffer_mu_;
absl::flat_hash_map<std::string, int> device_name_to_id_
TF_GUARDED_BY(device_mu_);
mutex device_mu_;
std::unique_ptr<SingleDebugEventFileWriter> metadata_writer_;
std::unique_ptr<SingleDebugEventFileWriter> source_files_writer_;
std::unique_ptr<SingleDebugEventFileWriter> stack_frames_writer_;
std::unique_ptr<SingleDebugEventFileWriter> graphs_writer_;
std::unique_ptr<SingleDebugEventFileWriter> execution_writer_;
std::unique_ptr<SingleDebugEventFileWriter> graph_execution_traces_writer_;
DebugEventsWriter(const DebugEventsWriter&) = delete;
void operator=(const DebugEventsWriter&) = delete;
friend class DebugEventsWriterTest;
};
} // namespace tfdbg
} // namespace tensorflow
#endif // TENSORFLOW_CORE_UTIL_DEBUG_EVENTS_WRITER_H_
|
c
|
github
|
https://github.com/tensorflow/tensorflow
|
tensorflow/core/util/debug_events_writer.h
|
import os, sys, re
SourceFilePath = sys.argv[1]
TargetFilePath = sys.argv[2]
print "source = " + SourceFilePath
print "target = " + TargetFilePath
# open the source file
SourceLines = open(SourceFilePath, 'rU').readlines()
# new content
ComponentTitle = []
AsciidocLines = []
IndexLines = []
#if the first character is a point, then check further, else get the next line
#.TH Header
re_TH = re.compile(r'^\.TH')
#.TP Paragraph
re_TP = re.compile(r'^\.TP')
#.HP ?
re_HP = re.compile(r'^\.HP')
#.TQ Paragraph
re_TQ = re.compile(r'^\.TQ')
#.SH NAME
#.SH SYNOPSYS
re_SH = re.compile(r'^\.SH\s+(.+)\n')
#.B
re_B = re.compile(r'^\.B')
#.de TQ
re_de_TQ = re.compile(r'^\.de TQ')
#.br
re_br = re.compile(r'^\.br')
#.ns
re_ns = re.compile(r'^\.ns')
#..
re_pointpoint = re.compile(r'^\.\.')
#markup
re_fI = re.compile(r'\\fI')
re_fB = re.compile(r'\\fB')
re_fR = re.compile(r'\\fR')
re_longdash = re.compile(r'\\-')
re_erroneous_markup = re.compile( ('\*\*\*\*|\_\_\_\_') )
#.\" Comments
re_comment = re.compile(r'^\.\\"')
i = 0
while (i < len(SourceLines)):
#/fI until the next /fB or /fR means that until the next markup marker
#
result_re_fI = re_fI.search(SourceLines[i])
result_re_fB = re_fB.search(SourceLines[i])
result_re_fR = re_fR.search(SourceLines[i])
result_re_longdash = re_longdash.search(SourceLines[i])
#first time for gettin into while loop
CurrLine = SourceLines[i]
str_asciiline = ""
int_Character = 0
last_formatting_char = ''
#
while ((result_re_fI != None) \
or (result_re_fB != None) \
or (result_re_fR != None)):
#parse CurrLine
#search for the first delimiter \f with next character 'I', 'B' or 'R'
#when the first characters are found. The part of the string before will
#go to the str_asciiline, the last_formatting_char will be remembered
#because in asciidoc italic needs to be closed like this _italic_
int_Character = CurrLine.find("\\f")
#tempchar1 = CurrLine[int_Character+1]
#tempchar2 = CurrLine[int_Character+2]
if (int_Character != -1) :
if (CurrLine[int_Character+2]=='I'):
str_asciiline = str_asciiline + \
CurrLine[0:int_Character] + \
last_formatting_char + \
"__"
last_formatting_char = "__"
if (CurrLine[int_Character+2]=='B'):
str_asciiline = str_asciiline + \
CurrLine[0:int_Character] + \
last_formatting_char + \
"**"
last_formatting_char = "**"
if (CurrLine[int_Character+2]=='R'):
str_asciiline = str_asciiline + \
CurrLine[0:int_Character] + \
last_formatting_char + \
""
last_formatting_char = ""
#
CurrLine = CurrLine[int_Character+3:len(CurrLine)]
#check for more
result_re_fI = re_fI.search(CurrLine)
result_re_fB = re_fB.search(CurrLine)
result_re_fR = re_fR.search(CurrLine)
#
if ((result_re_fI == None) \
and (result_re_fB == None) \
and (result_re_fR == None)):
#exiting the while loop, the SourceLines[1] now must contain the
#cleaned version of the sentence for further processing
str_asciiline += CurrLine + last_formatting_char
#str_asciiline.append(last_formatting_char)
SourceLines[i] = str_asciiline
#
#check for **** or ____ in str_asciiline and remove these
#this happens for example when the sourcefile has \\fB\\fB in the
#line. This will result in **** and renders faulty in asciidoc
result_re_erroneous_markup = re_erroneous_markup.search(SourceLines[i])
if (result_re_erroneous_markup != None):
SourceLines[i] = re_erroneous_markup.sub('',SourceLines[i])
if (result_re_longdash != None):
#SourceLines[i].replace("\\-","--")
CurrLine = re_longdash.sub("--",SourceLines[i])
SourceLines[i] = CurrLine
#done markup
#
result_re_TH = re_TH.search(SourceLines[i])
if (result_re_TH != None):
# the title must be split from the line, added, and underlined with the
# same amount of '=' signs underneath
CompTitle=SourceLines[i].split(' ')[1]
ComponentTitle.append(CompTitle+'\n')
ComponentTitle.append("="*len(CompTitle)+'\n\n')
#ComponentTitle.append('\n')
#
result_re_SH = re_SH.search(SourceLines[i])
if (result_re_SH != None):
#.SH has been found, get the name, put it in the index and add the line
CompHeader=result_re_SH.groups()[0]
#if the header is between quotes, like: "see also" then strip the
#quotes and change the space to a dash. in the indexlines array
CompHeader = CompHeader.strip('\"')
CompHeaderDashed = CompHeader.replace(" ", "-")
#result_re_between_quotes = re_between_quotes.search(CompHeader)
AsciidocLines.append("\n\n" + "===== " + \
"[[" + CompHeaderDashed.lower() + "]]" \
+ CompHeader + "\n")
IndexLines.append(". <<" + CompHeaderDashed.lower() + "," + \
CompHeader + ">>" + "\n")
#
result_re_B = re_B.search(SourceLines[i])
if (result_re_B != None):
#read the line, remove the ".B " and add to the Asciidoclines
CurrLine=SourceLines[i][3:len(SourceLines[i])]
AsciidocLines.append(CurrLine)
#
#if we are in a paragraph, continue with filling and parsing lines until
#the next paragraph is encountered
#
result_re_TP = re_TP.search(SourceLines[i])
if (result_re_TP != None):
#add empty line
AsciidocLines.append('\n')
#
#these lines should not do anything and are to be ignored
result_re_comment = re_comment.search(SourceLines[i])
result_re_de_TQ = re_de_TQ.search(SourceLines[i])
result_br = re_br.search(SourceLines[i])
result_HP = re_HP.search(SourceLines[i])
result_TQ = re_TQ.search(SourceLines[i])
result_ns = re_ns.search(SourceLines[i])
result_pointpoint = re_pointpoint.search(SourceLines[i])
if not ((result_re_comment != None) \
or (result_re_de_TQ != None) \
or (result_br != None) \
or (result_HP != None) \
or (result_TQ != None) \
or (result_ns != None) \
or (result_pointpoint != None)):
#nothing to be done unless all other results are none
#in that situation just copy the lines
if (result_re_B == None) \
and (result_re_SH == None) \
and (result_re_TP == None) \
and (result_re_TH == None):
AsciidocLines.append(SourceLines[i])
i += 1
#return to while loop
#now write all info into the target file
AsciidocFile = open(TargetFilePath, 'w+')
AsciidocFile.writelines(ComponentTitle)
AsciidocFile.writelines(IndexLines)
AsciidocFile.writelines(AsciidocLines)
AsciidocFile.close()
|
unknown
|
codeparrot/codeparrot-clean
| ||
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form;
class CallbackTransformer implements DataTransformerInterface
{
private \Closure $transform;
private \Closure $reverseTransform;
public function __construct(callable $transform, callable $reverseTransform)
{
$this->transform = $transform(...);
$this->reverseTransform = $reverseTransform(...);
}
public function transform(mixed $data): mixed
{
return ($this->transform)($data);
}
public function reverseTransform(mixed $data): mixed
{
return ($this->reverseTransform)($data);
}
}
|
php
|
github
|
https://github.com/symfony/symfony
|
src/Symfony/Component/Form/CallbackTransformer.php
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_DATA_SERVICE_DATASET_STORE_H_
#define TENSORFLOW_CORE_DATA_SERVICE_DATASET_STORE_H_
#include <memory>
#include <string>
#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/data/service/dispatcher_state.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/io/record_reader.h"
#include "tensorflow/core/lib/io/record_writer.h"
#include "tensorflow/core/platform/env.h"
namespace tensorflow {
namespace data {
// An interface for storing and getting dataset definitions.
class DatasetStore {
public:
virtual ~DatasetStore() = default;
// Stores the given dataset under the given key. Overwrites a dataset if it
// already exists.
virtual absl::Status Put(const std::string& key,
const DatasetDef& dataset) = 0;
// Gets the dataset for the given key, storing the dataset in `dataset_def`.
virtual absl::Status Get(const std::string& key,
std::shared_ptr<const DatasetDef>& dataset_def) = 0;
};
// Dataset store which reads and writes datasets within a directory.
// The dataset with key `key` is stored at the path "datasets_dir/key".
class FileSystemDatasetStore : public DatasetStore {
public:
explicit FileSystemDatasetStore(const std::string& datasets_dir);
FileSystemDatasetStore(const FileSystemDatasetStore&) = delete;
FileSystemDatasetStore& operator=(const FileSystemDatasetStore&) = delete;
absl::Status Put(const std::string& key, const DatasetDef& dataset) override;
absl::Status Get(const std::string& key,
std::shared_ptr<const DatasetDef>& dataset_def) override;
private:
const std::string datasets_dir_;
};
// DatasetStore which stores all datasets in memory. This is useful when the
// dispatcher doesn't have a work directory configured.
class MemoryDatasetStore : public DatasetStore {
public:
MemoryDatasetStore() = default;
MemoryDatasetStore(const MemoryDatasetStore&) = delete;
MemoryDatasetStore& operator=(const MemoryDatasetStore&) = delete;
absl::Status Put(const std::string& key, const DatasetDef& dataset) override;
absl::Status Get(const std::string& key,
std::shared_ptr<const DatasetDef>& dataset_def) override;
private:
// Mapping from key to dataset definition.
absl::flat_hash_map<std::string, std::shared_ptr<const DatasetDef>> datasets_;
};
} // namespace data
} // namespace tensorflow
#endif // TENSORFLOW_CORE_DATA_SERVICE_DATASET_STORE_H_
|
c
|
github
|
https://github.com/tensorflow/tensorflow
|
tensorflow/core/data/service/dataset_store.h
|
#!/usr/bin/env python3
#
# This file is part of sarracenia.
# The sarracenia suite is Free and is proudly provided by the Government of Canada
# Copyright (C) Her Majesty The Queen in Right of Canada, Environment Canada, 2008-2015
#
# Questions or bugs report: dps-client@ec.gc.ca
# sarracenia repository: git://git.code.sf.net/p/metpx/git
# Documentation: http://metpx.sourceforge.net/#SarraDocumentation
#
# sr_credentials.py : python3 utility tool to configure all protocol credentials
#
#
# Code contributed by:
# Michel Grenier - Shared Services Canada
# Last Changed : Dec 29 11:42:11 EST 2015
#
########################################################################
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
#
# in the credential file, one description per line
# url option1=value1, option2=value2
#
# ex:
#
# sftp://alice@herhost/ ssh_keyfile=/home/myself/mykeys/.ssh.id_dsa
# ftp://georges:Gpass@hishost/ passive = True, binary = True
#
# (passive true and binary true are credentials default and may be omitted)
#
import os,urllib,urllib.parse,sys,re
# a class for credential details/options
# add any other options here... and process in parse
class credential_details:
def __init__(self):
self.url = None
self.ssh_keyfile = None
self.passive = True
self.binary = True
self.tls = False
self.prot_p = False
def __str__(self):
s = ''
s += self.url.geturl()
s += " %s" % self.ssh_keyfile
s += " %s" % self.passive
s += " %s" % self.binary
s += " %s" % self.tls
s += " %s" % self.prot_p
return s
# class credentials
class sr_credentials:
def __init__(self, logger):
self.logger = logger
self.credentials = {}
self.pwre=re.compile(':[^/:]*@')
self.logger.debug("sr_credentials __init__")
def add(self,urlstr,details=None):
# need to create url object
if details == None :
details = credential_details()
details.url = urllib.parse.urlparse(urlstr)
self.credentials[urlstr] = details
def get(self, urlstr ):
self.logger.debug("sr_credentials get %s" % urlstr)
# already cached
if self.has(urlstr) :
#self.logger.debug("sr_credentials get in cache %s %s" % (urlstr,self.credentials[urlstr]))
return True, self.credentials[urlstr]
# create url object if needed
url = urllib.parse.urlparse(urlstr)
# resolved from defined credentials
ok, details = self.resolve(urlstr, url)
if ok : return True, details
# not found... is it valid ?
if not self.isValid(url) :
return False,None
# cache it as is... we dont want to validate every time
self.add(urlstr)
self.logger.debug("sr_credentials get add %s %s" % (urlstr,self.credentials[urlstr]))
return False,self.credentials[urlstr]
def has(self, urlstr ):
self.logger.debug("sr_credentials has %s" % urlstr)
return urlstr in self.credentials
def isTrue(self,S):
s = S.lower()
if s == 'true' or s == 'yes' or s == 'on' or s == '1': return True
return False
def isValid(self,url,details=None):
# network location
if url.netloc == '' :
# file (why here? anyway)
if url.scheme == 'file' : return True
return False
# amqp... vhost not check: default /
# user and password provided we are ok
user = url.username != None and url.username != ''
pasw = url.password != None and url.password != ''
both = user and pasw
# we have everything
if both : return True
# we have no user and no pasw (http normal, https... no cert, sftp hope for .ssh/config)
if not user and not pasw :
if url.scheme in ['http','https','sftp'] : return True
return False
# we have a pasw no user
if pasw :
# not sure... sftp hope to get user from .ssh/config
if url.scheme == 'sftp' : return True
return False
# we only have a user ... permitted only for sftp
if url.scheme != 'sftp' : return False
# sftp and an ssh_keyfile was provided... check that it exists
if details and details.ssh_keyfile :
if not os.path.exists(details.ssh_keyfile): return False
# sftp with a user (and perhaps a valid ssh_keyfile)
return True
def parse(self,line):
self.logger.debug("sr_credentials parse %s" % self.pwre.sub(':<secret!>@', line, count=1) )
try:
sline = line.strip()
if len(sline) == 0 or sline[0] == '#' : return
# first field url string = protocol://user:password@host:port[/vost]
parts = sline.split()
urlstr = parts[0]
url = urllib.parse.urlparse(urlstr)
# credential details
details = credential_details()
details.url = url
# no option
if len(parts) == 1 :
if not self.isValid(url,details) :
self.logger.error("bad credential 1 (%s)" % line)
return
self.add(urlstr,details)
return
# parsing options : comma separated option names
# some option has name = value : like ssh_keyfile
optline = sline.replace(urlstr,'')
optline = optline.strip()
optlist = optline.split(',')
for optval in optlist:
parts = optval.split('=')
keyword = parts[0].strip()
if keyword == 'ssh_keyfile' : details.ssh_keyfile = parts[1].strip()
elif keyword == 'passive' : details.passive = True
elif keyword == 'active' : details.passive = False
elif keyword == 'binary' : details.binary = True
elif keyword == 'ascii' : details.binary = False
elif keyword == 'ssl' : details.tls = False
elif keyword == 'tls' : details.tls = True
elif keyword == 'prot_p' : details.prot_p = True
else: self.logger.warning("bad credential option (%s)" % keyword)
# need to check validity
if not self.isValid(url,details) :
self.logger.error("bad credential 2 (%s)" % line)
return
# seting options to protocol
self.add(urlstr,details)
except:
(stype, svalue, tb) = sys.exc_info()
self.logger.error("sr_credentials/parse Type: %s, Value: %s" % (stype, svalue))
self.logger.error("sr_credentials parse %s" % line)
def read(self,path):
self.logger.debug("sr_credentials read")
# read in provided credentials (not mandatory)
try :
if os.path.exists(path):
f = open(path,'r')
lines = f.readlines()
f.close
for line in lines :
self.parse(line)
except :
(stype, svalue, tb) = sys.exc_info()
self.logger.error("sr_credentials/read Type: %s, Value: %s" % (stype, svalue))
self.logger.error("sr_credentials read path = %s" % path)
#self.logger.debug("credentials = %s\n" % self.credentials)
def resolve(self,urlstr, url = None):
# create url object if needed
if not url :
url = urllib.parse.urlparse(urlstr)
# resolving credentials
for s in self.credentials :
details = self.credentials[s]
u = details.url
if url.scheme != u.scheme : continue
if url.hostname != u.hostname : continue
if url.port != u.port : continue
if url.username != u.username :
if url.username != None : continue
if url.password != u.password :
if url.password != None : continue
# for AMQP... vhost checking
# amqp users have same credentials for any vhost
# default / may not be set...
if 'amqp' in url.scheme :
url_vhost = url.path
u_vhost = u.path
if url_vhost == '' : url_vhost = '/'
if u_vhost == '' : u_vhost = '/'
if url_vhost != u_vhost : continue
# resolved : cache it and return
self.credentials[urlstr] = details
#self.logger.debug("sr_credentials get resolved %s %s" % (urlstr,details))
return True, details
return False, None
|
unknown
|
codeparrot/codeparrot-clean
| ||
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-04-06 17:38
from __future__ import unicode_literals
import cmput404_project.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
('img', models.ImageField(default=b'images/defaultUserImage.png', upload_to=b'images/')),
('github', models.CharField(blank=True, default=b'', max_length=200)),
('bio', models.CharField(blank=True, default=b'', max_length=200)),
('is_active', models.BooleanField(default=False)),
('host', models.URLField(default=b'http://127.0.0.1:8000')),
('displayName', models.CharField(max_length=200)),
('id', models.CharField(max_length=100, primary_key=True, serialize=False)),
('url', models.URLField()),
('temp', models.BooleanField(default=False)),
('user', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='author', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Comment',
fields=[
('id', models.CharField(default=uuid.uuid4, max_length=100, primary_key=True, serialize=False)),
('comment', models.TextField()),
('contentType', models.CharField(choices=[(b'text/plain', b'Plain'), (b'text/markdown', b'Markdown'), (b'application/base64', b'Github'), (b'image/png;base64', b'PNG'), (b'image/jpeg;base64', b'JPEG')], default=b'PUBLIC', max_length=20)),
('published', models.DateTimeField(default=django.utils.timezone.now)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cmput404_project.Author')),
],
),
migrations.CreateModel(
name='Friend',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('requestee', models.URLField()),
('requestee_id', models.CharField(max_length=200)),
('requestee_host', models.CharField(default=b'Host', max_length=100)),
('requestee_displayName', models.CharField(default=b'AuthorName', max_length=30)),
('requester', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='follow', to='cmput404_project.Author')),
],
),
migrations.CreateModel(
name='friend_request',
fields=[
('request_id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('request_date', models.DateTimeField(verbose_name=b'date published')),
('status', models.BooleanField(default=False)),
('request_receiver', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='receiver', to=settings.AUTH_USER_MODEL)),
('request_sender', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sender', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Node',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('host', models.URLField(unique=True)),
('auth_username', models.CharField(max_length=50)),
('auth_password', models.CharField(max_length=50)),
('api_prefix', models.CharField(blank=True, default=b'/service', max_length=50)),
('shareImage', models.BooleanField(default=True)),
('auth_post_url', models.CharField(default=b'author/posts/?format=json', max_length=50)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Notify',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('requester', models.URLField()),
('requester_displayName', models.CharField(default=b'AuthorName', max_length=30)),
('requester_host', models.CharField(default=b'Host', max_length=100)),
('requester_id', models.CharField(default=b'id', max_length=200)),
('requestee', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notify', to='cmput404_project.Author')),
],
),
migrations.CreateModel(
name='Post',
fields=[
('id', models.CharField(default=uuid.uuid4, max_length=100, primary_key=True, serialize=False)),
('visibility', models.CharField(choices=[(b'PUBLIC', b'Public'), (b'FOAF', b'Friend of friend'), (b'FRIENDS', b'Friends'), (b'PRIVATE', b'Private'), (b'SERVERONLY', b'Server Only')], default=b'PUBLIC', max_length=20)),
('contentType', models.CharField(choices=[(b'text/plain', b'Plain'), (b'text/markdown', b'Markdown'), (b'application/base64', b'Github'), (b'image/png;base64', b'PNG'), (b'image/jpeg;base64', b'JPEG')], default=b'text/plain', max_length=20)),
('description', models.CharField(blank=True, max_length=100)),
('title', models.CharField(blank=True, max_length=50)),
('source', models.URLField()),
('origin', models.URLField()),
('content', models.TextField()),
('published', models.DateTimeField(default=django.utils.timezone.now)),
('unlisted', models.BooleanField(default=False)),
('temp', models.BooleanField(default=False)),
('visibleTo', models.CharField(blank=True, max_length=100)),
('categories', models.CharField(blank=True, max_length=100)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cmput404_project.Author')),
],
),
migrations.CreateModel(
name='PostImages',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('post_image', models.ImageField(upload_to=cmput404_project.models.content_file_name)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='images', to='cmput404_project.Post')),
],
),
migrations.AddField(
model_name='comment',
name='post',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='cmput404_project.Post'),
),
]
|
unknown
|
codeparrot/codeparrot-clean
| ||
// Copyright IBM Corp. 2016, 2025
// SPDX-License-Identifier: BUSL-1.1
package http
import (
"encoding/json"
"net/http"
"reflect"
"testing"
"time"
"github.com/hashicorp/vault/vault"
)
func TestSysLeader_get(t *testing.T) {
core, _, _ := vault.TestCoreUnsealed(t)
ln, addr := TestServer(t, core)
defer ln.Close()
resp, err := http.Get(addr + "/v1/sys/leader")
if err != nil {
t.Fatalf("err: %s", err)
}
var actual map[string]interface{}
expected := map[string]interface{}{
"ha_enabled": false,
"is_self": false,
"leader_address": "",
"leader_cluster_address": "",
"performance_standby": false,
"performance_standby_last_remote_wal": json.Number("0"),
"active_time": time.Time{}.UTC().Format(time.RFC3339),
}
testResponseStatus(t, resp, 200)
testResponseBody(t, resp, &actual)
if !reflect.DeepEqual(actual, expected) {
t.Fatalf("bad: %#v \n%#v", actual, expected)
}
}
|
go
|
github
|
https://github.com/hashicorp/vault
|
http/sys_leader_test.go
|
import operator
from django.template import Engine, Library
from django.utils import six
engine = Engine(app_dirs=True)
register = Library()
@register.inclusion_tag('inclusion.html')
def inclusion_no_params():
"""Expected inclusion_no_params __doc__"""
return {"result": "inclusion_no_params - Expected result"}
inclusion_no_params.anything = "Expected inclusion_no_params __dict__"
@register.inclusion_tag(engine.get_template('inclusion.html'))
def inclusion_no_params_from_template():
"""Expected inclusion_no_params_from_template __doc__"""
return {"result": "inclusion_no_params_from_template - Expected result"}
inclusion_no_params_from_template.anything = "Expected inclusion_no_params_from_template __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_one_param(arg):
"""Expected inclusion_one_param __doc__"""
return {"result": "inclusion_one_param - Expected result: %s" % arg}
inclusion_one_param.anything = "Expected inclusion_one_param __dict__"
@register.inclusion_tag(engine.get_template('inclusion.html'))
def inclusion_one_param_from_template(arg):
"""Expected inclusion_one_param_from_template __doc__"""
return {"result": "inclusion_one_param_from_template - Expected result: %s" % arg}
inclusion_one_param_from_template.anything = "Expected inclusion_one_param_from_template __dict__"
@register.inclusion_tag('inclusion.html', takes_context=False)
def inclusion_explicit_no_context(arg):
"""Expected inclusion_explicit_no_context __doc__"""
return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg}
inclusion_explicit_no_context.anything = "Expected inclusion_explicit_no_context __dict__"
@register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=False)
def inclusion_explicit_no_context_from_template(arg):
"""Expected inclusion_explicit_no_context_from_template __doc__"""
return {"result": "inclusion_explicit_no_context_from_template - Expected result: %s" % arg}
inclusion_explicit_no_context_from_template.anything = "Expected inclusion_explicit_no_context_from_template __dict__"
@register.inclusion_tag('inclusion.html', takes_context=True)
def inclusion_no_params_with_context(context):
"""Expected inclusion_no_params_with_context __doc__"""
return {"result": "inclusion_no_params_with_context - Expected result (context value: %s)" % context['value']}
inclusion_no_params_with_context.anything = "Expected inclusion_no_params_with_context __dict__"
@register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=True)
def inclusion_no_params_with_context_from_template(context):
"""Expected inclusion_no_params_with_context_from_template __doc__"""
return {"result": "inclusion_no_params_with_context_from_template - Expected result (context value: %s)" % context['value']}
inclusion_no_params_with_context_from_template.anything = "Expected inclusion_no_params_with_context_from_template __dict__"
@register.inclusion_tag('inclusion.html', takes_context=True)
def inclusion_params_and_context(context, arg):
"""Expected inclusion_params_and_context __doc__"""
return {"result": "inclusion_params_and_context - Expected result (context value: %s): %s" % (context['value'], arg)}
inclusion_params_and_context.anything = "Expected inclusion_params_and_context __dict__"
@register.inclusion_tag(engine.get_template('inclusion.html'), takes_context=True)
def inclusion_params_and_context_from_template(context, arg):
"""Expected inclusion_params_and_context_from_template __doc__"""
return {"result": "inclusion_params_and_context_from_template - Expected result (context value: %s): %s" % (context['value'], arg)}
inclusion_params_and_context_from_template.anything = "Expected inclusion_params_and_context_from_template __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_two_params(one, two):
"""Expected inclusion_two_params __doc__"""
return {"result": "inclusion_two_params - Expected result: %s, %s" % (one, two)}
inclusion_two_params.anything = "Expected inclusion_two_params __dict__"
@register.inclusion_tag(engine.get_template('inclusion.html'))
def inclusion_two_params_from_template(one, two):
"""Expected inclusion_two_params_from_template __doc__"""
return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)}
inclusion_two_params_from_template.anything = "Expected inclusion_two_params_from_template __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_one_default(one, two='hi'):
"""Expected inclusion_one_default __doc__"""
return {"result": "inclusion_one_default - Expected result: %s, %s" % (one, two)}
inclusion_one_default.anything = "Expected inclusion_one_default __dict__"
@register.inclusion_tag(engine.get_template('inclusion.html'))
def inclusion_one_default_from_template(one, two='hi'):
"""Expected inclusion_one_default_from_template __doc__"""
return {"result": "inclusion_one_default_from_template - Expected result: %s, %s" % (one, two)}
inclusion_one_default_from_template.anything = "Expected inclusion_one_default_from_template __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_unlimited_args(one, two='hi', *args):
"""Expected inclusion_unlimited_args __doc__"""
return {"result": "inclusion_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))}
inclusion_unlimited_args.anything = "Expected inclusion_unlimited_args __dict__"
@register.inclusion_tag(engine.get_template('inclusion.html'))
def inclusion_unlimited_args_from_template(one, two='hi', *args):
"""Expected inclusion_unlimited_args_from_template __doc__"""
return {"result": "inclusion_unlimited_args_from_template - Expected result: %s" % (', '.join(six.text_type(arg) for arg in [one, two] + list(args)))}
inclusion_unlimited_args_from_template.anything = "Expected inclusion_unlimited_args_from_template __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_only_unlimited_args(*args):
"""Expected inclusion_only_unlimited_args __doc__"""
return {"result": "inclusion_only_unlimited_args - Expected result: %s" % (', '.join(six.text_type(arg) for arg in args))}
inclusion_only_unlimited_args.anything = "Expected inclusion_only_unlimited_args __dict__"
@register.inclusion_tag(engine.get_template('inclusion.html'))
def inclusion_only_unlimited_args_from_template(*args):
"""Expected inclusion_only_unlimited_args_from_template __doc__"""
return {"result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % (', '.join(six.text_type(arg) for arg in args))}
inclusion_only_unlimited_args_from_template.anything = "Expected inclusion_only_unlimited_args_from_template __dict__"
@register.inclusion_tag('test_incl_tag_current_app.html', takes_context=True)
def inclusion_tag_current_app(context):
"""Expected inclusion_tag_current_app __doc__"""
return {}
inclusion_tag_current_app.anything = "Expected inclusion_tag_current_app __dict__"
@register.inclusion_tag('test_incl_tag_use_l10n.html', takes_context=True)
def inclusion_tag_use_l10n(context):
"""Expected inclusion_tag_use_l10n __doc__"""
return {}
inclusion_tag_use_l10n.anything = "Expected inclusion_tag_use_l10n __dict__"
@register.inclusion_tag('inclusion.html')
def inclusion_unlimited_args_kwargs(one, two='hi', *args, **kwargs):
"""Expected inclusion_unlimited_args_kwargs __doc__"""
# Sort the dictionary by key to guarantee the order for testing.
sorted_kwarg = sorted(six.iteritems(kwargs), key=operator.itemgetter(0))
return {"result": "inclusion_unlimited_args_kwargs - Expected result: %s / %s" % (
', '.join(six.text_type(arg) for arg in [one, two] + list(args)),
', '.join('%s=%s' % (k, v) for (k, v) in sorted_kwarg)
)}
inclusion_unlimited_args_kwargs.anything = "Expected inclusion_unlimited_args_kwargs __dict__"
@register.inclusion_tag('inclusion.html', takes_context=True)
def inclusion_tag_without_context_parameter(arg):
"""Expected inclusion_tag_without_context_parameter __doc__"""
return {}
inclusion_tag_without_context_parameter.anything = "Expected inclusion_tag_without_context_parameter __dict__"
@register.inclusion_tag('inclusion_extends1.html')
def inclusion_extends1():
return {}
@register.inclusion_tag('inclusion_extends2.html')
def inclusion_extends2():
return {}
|
unknown
|
codeparrot/codeparrot-clean
| ||
#!/usr/bin/python
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: rds_param_group
version_added: "1.5"
short_description: manage RDS parameter groups
description:
- Creates, modifies, and deletes RDS parameter groups. This module has a dependency on python-boto >= 2.5.
options:
state:
description:
- Specifies whether the group should be present or absent.
required: true
default: present
aliases: []
choices: [ 'present' , 'absent' ]
name:
description:
- Database parameter group identifier.
required: true
default: null
aliases: []
description:
description:
- Database parameter group description. Only set when a new group is added.
required: false
default: null
aliases: []
engine:
description:
- The type of database for this group. Required for state=present.
required: false
default: null
aliases: []
choices: [ 'mysql5.1', 'mysql5.5', 'mysql5.6', 'oracle-ee-11.2', 'oracle-se-11.2', 'oracle-se1-11.2', 'postgres9.3', 'sqlserver-ee-10.5', 'sqlserver-ee-11.0', 'sqlserver-ex-10.5', 'sqlserver-ex-11.0', 'sqlserver-se-10.5', 'sqlserver-se-11.0', 'sqlserver-web-10.5', 'sqlserver-web-11.0']
immediate:
description:
- Whether to apply the changes immediately, or after the next reboot of any associated instances.
required: false
default: null
aliases: []
params:
description:
- Map of parameter names and values. Numeric values may be represented as K for kilo (1024), M for mega (1024^2), G for giga (1024^3), or T for tera (1024^4), and these values will be expanded into the appropriate number before being set in the parameter group.
required: false
default: null
aliases: []
choices: [ 'mysql5.1', 'mysql5.5', 'mysql5.6', 'oracle-ee-11.2', 'oracle-se-11.2', 'oracle-se1-11.2', 'postgres9.3', 'sqlserver-ee-10.5', 'sqlserver-ee-11.0', 'sqlserver-ex-10.5', 'sqlserver-ex-11.0', 'sqlserver-se-10.5', 'sqlserver-se-11.0', 'sqlserver-web-10.5', 'sqlserver-web-11.0']
region:
description:
- The AWS region to use. If not specified then the value of the EC2_REGION environment variable, if any, is used.
required: true
default: null
aliases: [ 'aws_region', 'ec2_region' ]
aws_access_key:
description:
- AWS access key. If not set then the value of the AWS_ACCESS_KEY environment variable is used.
required: false
default: null
aliases: [ 'ec2_access_key', 'access_key' ]
aws_secret_key:
description:
- AWS secret key. If not set then the value of the AWS_SECRET_KEY environment variable is used.
required: false
default: null
aliases: [ 'ec2_secret_key', 'secret_key' ]
requirements: [ "boto" ]
author: Scott Anderson
'''
EXAMPLES = '''
# Add or change a parameter group, in this case setting auto_increment_increment to 42 * 1024
- rds_param_group:
state: present
name: norwegian_blue
description: 'My Fancy Ex Parrot Group'
engine: 'mysql5.6'
params:
auto_increment_increment: "42K"
# Remove a parameter group
- rds_param_group:
state: absent
name: norwegian_blue
'''
import sys
import time
VALID_ENGINES = [
'mysql5.1',
'mysql5.5',
'mysql5.6',
'oracle-ee-11.2',
'oracle-se-11.2',
'oracle-se1-11.2',
'postgres9.3',
'sqlserver-ee-10.5',
'sqlserver-ee-11.0',
'sqlserver-ex-10.5',
'sqlserver-ex-11.0',
'sqlserver-se-10.5',
'sqlserver-se-11.0',
'sqlserver-web-10.5',
'sqlserver-web-11.0',
]
try:
import boto.rds
from boto.exception import BotoServerError
except ImportError:
print "failed=True msg='boto required for this module'"
sys.exit(1)
# returns a tuple: (whether or not a parameter was changed, the remaining parameters that weren't found in this parameter group)
class NotModifiableError(StandardError):
def __init__(self, error_message, *args):
super(NotModifiableError, self).__init__(error_message, *args)
self.error_message = error_message
def __repr__(self):
return 'NotModifiableError: %s' % self.error_message
def __str__(self):
return 'NotModifiableError: %s' % self.error_message
INT_MODIFIERS = {
'K': 1024,
'M': pow(1024, 2),
'G': pow(1024, 3),
'T': pow(1024, 4),
}
TRUE_VALUES = ('on', 'true', 'yes', '1',)
def set_parameter(param, value, immediate):
"""
Allows setting parameters with 10M = 10* 1024 * 1024 and so on.
"""
converted_value = value
if param.type == 'string':
converted_value = str(value)
elif param.type == 'integer':
if isinstance(value, basestring):
try:
for modifier in INT_MODIFIERS.keys():
if value.endswith(modifier):
converted_value = int(value[:-1]) * INT_MODIFIERS[modifier]
converted_value = int(converted_value)
except ValueError:
# may be based on a variable (ie. {foo*3/4}) so
# just pass it on through to boto
converted_value = str(value)
elif type(value) == bool:
converted_value = 1 if value else 0
else:
converted_value = int(value)
elif param.type == 'boolean':
if isinstance(value, basestring):
converted_value = value in TRUE_VALUES
else:
converted_value = bool(value)
param.value = converted_value
param.apply(immediate)
def modify_group(group, params, immediate=False):
""" Set all of the params in a group to the provided new params. Raises NotModifiableError if any of the
params to be changed are read only.
"""
changed = {}
new_params = dict(params)
for key in new_params.keys():
if group.has_key(key):
param = group[key]
new_value = new_params[key]
try:
old_value = param.value
except ValueError:
# some versions of boto have problems with retrieving
# integer values from params that may have their value
# based on a variable (ie. {foo*3/4}), so grab it in a
# way that bypasses the property functions
old_value = param._value
if old_value != new_value:
if not param.is_modifiable:
raise NotModifiableError('Parameter %s is not modifiable.' % key)
changed[key] = {'old': param.value, 'new': new_value}
set_parameter(param, new_value, immediate)
del new_params[key]
return changed, new_params
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
state = dict(required=True, choices=['present', 'absent']),
name = dict(required=True),
engine = dict(required=False, choices=VALID_ENGINES),
description = dict(required=False),
params = dict(required=False, aliases=['parameters'], type='dict'),
immediate = dict(required=False, type='bool'),
)
)
module = AnsibleModule(argument_spec=argument_spec)
state = module.params.get('state')
group_name = module.params.get('name').lower()
group_engine = module.params.get('engine')
group_description = module.params.get('description')
group_params = module.params.get('params') or {}
immediate = module.params.get('immediate') or False
if state == 'present':
for required in ['name', 'description', 'engine', 'params']:
if not module.params.get(required):
module.fail_json(msg = str("Parameter %s required for state='present'" % required))
else:
for not_allowed in ['description', 'engine', 'params']:
if module.params.get(not_allowed):
module.fail_json(msg = str("Parameter %s not allowed for state='absent'" % not_allowed))
# Retrieve any AWS settings from the environment.
ec2_url, aws_access_key, aws_secret_key, region = get_ec2_creds(module)
if not region:
module.fail_json(msg = str("region not specified and unable to determine region from EC2_REGION."))
try:
conn = boto.rds.connect_to_region(region, aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key)
except boto.exception.BotoServerError, e:
module.fail_json(msg = e.error_message)
group_was_added = False
try:
changed = False
try:
all_groups = conn.get_all_dbparameter_groups(group_name, max_records=100)
exists = len(all_groups) > 0
except BotoServerError, e:
if e.error_code != 'DBParameterGroupNotFound':
module.fail_json(msg = e.error_message)
exists = False
if state == 'absent':
if exists:
conn.delete_parameter_group(group_name)
changed = True
else:
changed = {}
if not exists:
new_group = conn.create_parameter_group(group_name, engine=group_engine, description=group_description)
group_was_added = True
# If a "Marker" is present, this group has more attributes remaining to check. Get the next batch, but only
# if there are parameters left to set.
marker = None
while len(group_params):
next_group = conn.get_all_dbparameters(group_name, marker=marker)
changed_params, group_params = modify_group(next_group, group_params, immediate)
changed.update(changed_params)
if hasattr(next_group, 'Marker'):
marker = next_group.Marker
else:
break
except BotoServerError, e:
module.fail_json(msg = e.error_message)
except NotModifiableError, e:
msg = e.error_message
if group_was_added:
msg = '%s The group "%s" was added first.' % (msg, group_name)
module.fail_json(msg=msg)
module.exit_json(changed=changed)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
main()
|
unknown
|
codeparrot/codeparrot-clean
| ||
/*
An implementation of the I/O abstract base classes hierarchy
as defined by PEP 3116 - "New I/O"
Classes defined here: IOBase, RawIOBase.
Written by Amaury Forgeot d'Arc and Antoine Pitrou
*/
#include "Python.h"
#include "pycore_call.h" // _PyObject_CallMethod()
#include "pycore_fileutils.h" // _PyFile_Flush
#include "pycore_long.h" // _PyLong_GetOne()
#include "pycore_object.h" // _PyType_HasFeature()
#include "pycore_pyerrors.h" // _PyErr_ChainExceptions1()
#include "pycore_weakref.h" // FT_CLEAR_WEAKREFS()
#include <stddef.h> // offsetof()
#include "_iomodule.h"
/*[clinic input]
module _io
class _io._IOBase "PyObject *" "clinic_state()->PyIOBase_Type"
class _io._RawIOBase "PyObject *" "clinic_state()->PyRawIOBase_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=9006b7802ab8ea85]*/
/*
* IOBase class, an abstract class
*/
typedef struct {
PyObject_HEAD
PyObject *dict;
PyObject *weakreflist;
} iobase;
#define iobase_CAST(op) ((iobase *)(op))
PyDoc_STRVAR(iobase_doc,
"The abstract base class for all I/O classes.\n"
"\n"
"This class provides dummy implementations for many methods that\n"
"derived classes can override selectively; the default implementations\n"
"represent a file that cannot be read, written or seeked.\n"
"\n"
"Even though IOBase does not declare read, readinto, or write because\n"
"their signatures will vary, implementations and clients should\n"
"consider those methods part of the interface. Also, implementations\n"
"may raise UnsupportedOperation when operations they do not support are\n"
"called.\n"
"\n"
"The basic type used for binary data read from or written to a file is\n"
"bytes. Other bytes-like objects are accepted as method arguments too.\n"
"In some cases (such as readinto), a writable object is required. Text\n"
"I/O classes work with str data.\n"
"\n"
"Note that calling any method (except additional calls to close(),\n"
"which are ignored) on a closed stream should raise a ValueError.\n"
"\n"
"IOBase (and its subclasses) support the iterator protocol, meaning\n"
"that an IOBase object can be iterated over yielding the lines in a\n"
"stream.\n"
"\n"
"IOBase also supports the :keyword:`with` statement. In this example,\n"
"fp is closed after the suite of the with statement is complete:\n"
"\n"
"with open('spam.txt', 'r') as fp:\n"
" fp.write('Spam and eggs!')\n");
/* Internal methods */
/* Use this function whenever you want to check the internal `closed` status
of the IOBase object rather than the virtual `closed` attribute as returned
by whatever subclass. */
static int
iobase_is_closed(PyObject *self)
{
return PyObject_HasAttrWithError(self, &_Py_ID(__IOBase_closed));
}
static PyObject *
iobase_unsupported(_PyIO_State *state, const char *message)
{
PyErr_SetString(state->unsupported_operation, message);
return NULL;
}
/* Positioning */
/*[clinic input]
@permit_long_docstring_body
_io._IOBase.seek
cls: defining_class
offset: int(unused=True)
The stream position, relative to 'whence'.
whence: int(unused=True, c_default='0') = os.SEEK_SET
The relative position to seek from.
/
Change the stream position to the given byte offset.
The offset is interpreted relative to the position indicated by whence.
Values for whence are:
* os.SEEK_SET or 0 -- start of stream (the default); offset should be zero or positive
* os.SEEK_CUR or 1 -- current stream position; offset may be negative
* os.SEEK_END or 2 -- end of stream; offset is usually negative
Return the new absolute position.
[clinic start generated code]*/
static PyObject *
_io__IOBase_seek_impl(PyObject *self, PyTypeObject *cls,
int Py_UNUSED(offset), int Py_UNUSED(whence))
/*[clinic end generated code: output=8bd74ea6538ded53 input=a21b5aad416ff6a9]*/
{
_PyIO_State *state = get_io_state_by_cls(cls);
return iobase_unsupported(state, "seek");
}
/*[clinic input]
_io._IOBase.tell
Return current stream position.
[clinic start generated code]*/
static PyObject *
_io__IOBase_tell_impl(PyObject *self)
/*[clinic end generated code: output=89a1c0807935abe2 input=04e615fec128801f]*/
{
return _PyObject_CallMethod(self, &_Py_ID(seek), "ii", 0, 1);
}
/*[clinic input]
_io._IOBase.truncate
cls: defining_class
size: object(unused=True) = None
/
Truncate file to size bytes.
File pointer is left unchanged. Size defaults to the current IO position
as reported by tell(). Return the new size.
[clinic start generated code]*/
static PyObject *
_io__IOBase_truncate_impl(PyObject *self, PyTypeObject *cls,
PyObject *Py_UNUSED(size))
/*[clinic end generated code: output=2013179bff1fe8ef input=660ac20936612c27]*/
{
_PyIO_State *state = get_io_state_by_cls(cls);
return iobase_unsupported(state, "truncate");
}
/* Flush and close methods */
/*[clinic input]
_io._IOBase.flush
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
[clinic start generated code]*/
static PyObject *
_io__IOBase_flush_impl(PyObject *self)
/*[clinic end generated code: output=7cef4b4d54656a3b input=773be121abe270aa]*/
{
/* XXX Should this return the number of bytes written??? */
int closed = iobase_is_closed(self);
if (!closed) {
Py_RETURN_NONE;
}
if (closed > 0) {
PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
}
return NULL;
}
static PyObject *
iobase_closed_get(PyObject *self, void *context)
{
int closed = iobase_is_closed(self);
if (closed < 0) {
return NULL;
}
return PyBool_FromLong(closed);
}
static int
iobase_check_closed(PyObject *self)
{
PyObject *res;
int closed;
/* This gets the derived attribute, which is *not* __IOBase_closed
in most cases! */
closed = PyObject_GetOptionalAttr(self, &_Py_ID(closed), &res);
if (closed > 0) {
closed = PyObject_IsTrue(res);
Py_DECREF(res);
if (closed > 0) {
PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
return -1;
}
}
return closed;
}
PyObject *
_PyIOBase_check_closed(PyObject *self, PyObject *args)
{
if (iobase_check_closed(self)) {
return NULL;
}
if (args == Py_True) {
return Py_None;
}
Py_RETURN_NONE;
}
static PyObject *
iobase_check_seekable(PyObject *self, PyObject *args)
{
_PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
return _PyIOBase_check_seekable(state, self, args);
}
static PyObject *
iobase_check_readable(PyObject *self, PyObject *args)
{
_PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
return _PyIOBase_check_readable(state, self, args);
}
static PyObject *
iobase_check_writable(PyObject *self, PyObject *args)
{
_PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
return _PyIOBase_check_writable(state, self, args);
}
PyObject *
_PyIOBase_cannot_pickle(PyObject *self, PyObject *args)
{
PyErr_Format(PyExc_TypeError,
"cannot pickle '%.100s' instances", _PyType_Name(Py_TYPE(self)));
return NULL;
}
/* XXX: IOBase thinks it has to maintain its own internal state in
`__IOBase_closed` and call flush() by itself, but it is redundant with
whatever behaviour a non-trivial derived class will implement. */
/*[clinic input]
_io._IOBase.close
Flush and close the IO object.
This method has no effect if the file is already closed.
[clinic start generated code]*/
static PyObject *
_io__IOBase_close_impl(PyObject *self)
/*[clinic end generated code: output=63c6a6f57d783d6d input=f4494d5c31dbc6b7]*/
{
int rc1, rc2, closed = iobase_is_closed(self);
if (closed < 0) {
return NULL;
}
if (closed) {
Py_RETURN_NONE;
}
rc1 = _PyFile_Flush(self);
PyObject *exc = PyErr_GetRaisedException();
rc2 = PyObject_SetAttr(self, &_Py_ID(__IOBase_closed), Py_True);
_PyErr_ChainExceptions1(exc);
if (rc1 < 0 || rc2 < 0) {
return NULL;
}
Py_RETURN_NONE;
}
/* Finalization and garbage collection support */
static void
iobase_finalize(PyObject *self)
{
PyObject *res;
int closed;
/* Save the current exception, if any. */
PyObject *exc = PyErr_GetRaisedException();
/* If `closed` doesn't exist or can't be evaluated as bool, then the
object is probably in an unusable state, so ignore. */
if (PyObject_GetOptionalAttr(self, &_Py_ID(closed), &res) <= 0) {
PyErr_Clear();
closed = -1;
}
else {
closed = PyObject_IsTrue(res);
Py_DECREF(res);
if (closed == -1)
PyErr_Clear();
}
if (closed == 0) {
/* Signal close() that it was called as part of the object
finalization process. */
if (PyObject_SetAttr(self, &_Py_ID(_finalizing), Py_True))
PyErr_Clear();
res = PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(close));
if (res == NULL) {
PyErr_FormatUnraisable("Exception ignored "
"while finalizing file %R", self);
}
else {
Py_DECREF(res);
}
}
/* Restore the saved exception. */
PyErr_SetRaisedException(exc);
}
int
_PyIOBase_finalize(PyObject *self)
{
int is_zombie;
/* If _PyIOBase_finalize() is called from a destructor, we need to
resurrect the object as calling close() can invoke arbitrary code. */
is_zombie = (Py_REFCNT(self) == 0);
if (is_zombie)
return PyObject_CallFinalizerFromDealloc(self);
else {
PyObject_CallFinalizer(self);
return 0;
}
}
static int
iobase_traverse(PyObject *op, visitproc visit, void *arg)
{
iobase *self = iobase_CAST(op);
Py_VISIT(Py_TYPE(self));
Py_VISIT(self->dict);
return 0;
}
static int
iobase_clear(PyObject *op)
{
iobase *self = iobase_CAST(op);
Py_CLEAR(self->dict);
return 0;
}
/* Destructor */
static void
iobase_dealloc(PyObject *op)
{
/* NOTE: since IOBaseObject has its own dict, Python-defined attributes
are still available here for close() to use.
However, if the derived class declares a __slots__, those slots are
already gone.
*/
iobase *self = iobase_CAST(op);
if (_PyIOBase_finalize(op) < 0) {
/* When called from a heap type's dealloc, the type will be
decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
if (_PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE)) {
Py_INCREF(Py_TYPE(self));
}
return;
}
PyTypeObject *tp = Py_TYPE(self);
_PyObject_GC_UNTRACK(self);
FT_CLEAR_WEAKREFS(op, self->weakreflist);
Py_CLEAR(self->dict);
tp->tp_free(self);
Py_DECREF(tp);
}
/* Inquiry methods */
/*[clinic input]
_io._IOBase.seekable
Return whether object supports random access.
If False, seek(), tell() and truncate() will raise OSError.
This method may need to do a test seek().
[clinic start generated code]*/
static PyObject *
_io__IOBase_seekable_impl(PyObject *self)
/*[clinic end generated code: output=4c24c67f5f32a43d input=b976622f7fdf3063]*/
{
Py_RETURN_FALSE;
}
PyObject *
_PyIOBase_check_seekable(_PyIO_State *state, PyObject *self, PyObject *args)
{
PyObject *res = PyObject_CallMethodNoArgs(self, &_Py_ID(seekable));
if (res == NULL)
return NULL;
if (res != Py_True) {
Py_CLEAR(res);
iobase_unsupported(state, "File or stream is not seekable.");
return NULL;
}
if (args == Py_True) {
Py_DECREF(res);
}
return res;
}
/*[clinic input]
_io._IOBase.readable
Return whether object was opened for reading.
If False, read() will raise OSError.
[clinic start generated code]*/
static PyObject *
_io__IOBase_readable_impl(PyObject *self)
/*[clinic end generated code: output=e48089250686388b input=285b3b866a0ec35f]*/
{
Py_RETURN_FALSE;
}
/* May be called with any object */
PyObject *
_PyIOBase_check_readable(_PyIO_State *state, PyObject *self, PyObject *args)
{
PyObject *res = PyObject_CallMethodNoArgs(self, &_Py_ID(readable));
if (res == NULL)
return NULL;
if (res != Py_True) {
Py_CLEAR(res);
iobase_unsupported(state, "File or stream is not readable.");
return NULL;
}
if (args == Py_True) {
Py_DECREF(res);
}
return res;
}
/*[clinic input]
_io._IOBase.writable
Return whether object was opened for writing.
If False, write() will raise OSError.
[clinic start generated code]*/
static PyObject *
_io__IOBase_writable_impl(PyObject *self)
/*[clinic end generated code: output=406001d0985be14f input=9dcac18a013a05b5]*/
{
Py_RETURN_FALSE;
}
/* May be called with any object */
PyObject *
_PyIOBase_check_writable(_PyIO_State *state, PyObject *self, PyObject *args)
{
PyObject *res = PyObject_CallMethodNoArgs(self, &_Py_ID(writable));
if (res == NULL)
return NULL;
if (res != Py_True) {
Py_CLEAR(res);
iobase_unsupported(state, "File or stream is not writable.");
return NULL;
}
if (args == Py_True) {
Py_DECREF(res);
}
return res;
}
/* Context manager */
static PyObject *
iobase_enter(PyObject *self, PyObject *args)
{
if (iobase_check_closed(self))
return NULL;
return Py_NewRef(self);
}
static PyObject *
iobase_exit(PyObject *self, PyObject *args)
{
return PyObject_CallMethodNoArgs(self, &_Py_ID(close));
}
/* Lower-level APIs */
/* XXX Should these be present even if unimplemented? */
/*[clinic input]
_io._IOBase.fileno
cls: defining_class
/
Return underlying file descriptor if one exists.
Raise OSError if the IO object does not use a file descriptor.
[clinic start generated code]*/
static PyObject *
_io__IOBase_fileno_impl(PyObject *self, PyTypeObject *cls)
/*[clinic end generated code: output=7caaa32a6f4ada3d input=1927c8bea5c85099]*/
{
_PyIO_State *state = get_io_state_by_cls(cls);
return iobase_unsupported(state, "fileno");
}
/*[clinic input]
_io._IOBase.isatty
Return whether this is an 'interactive' stream.
Return False if it can't be determined.
[clinic start generated code]*/
static PyObject *
_io__IOBase_isatty_impl(PyObject *self)
/*[clinic end generated code: output=60cab77cede41cdd input=9ef76530d368458b]*/
{
if (iobase_check_closed(self))
return NULL;
Py_RETURN_FALSE;
}
/* Readline(s) and writelines */
/*[clinic input]
_io._IOBase.readline
size as limit: Py_ssize_t(accept={int, NoneType}) = -1
/
Read and return a line from the stream.
If size is specified, at most size bytes will be read.
The line terminator is always b'\n' for binary files; for text
files, the newlines argument to open can be used to select the line
terminator(s) recognized.
[clinic start generated code]*/
static PyObject *
_io__IOBase_readline_impl(PyObject *self, Py_ssize_t limit)
/*[clinic end generated code: output=4479f79b58187840 input=d0c596794e877bff]*/
{
/* For backwards compatibility, a (slowish) readline(). */
PyObject *peek, *buffer, *result;
Py_ssize_t old_size = -1;
if (PyObject_GetOptionalAttr(self, &_Py_ID(peek), &peek) < 0) {
return NULL;
}
buffer = PyByteArray_FromStringAndSize(NULL, 0);
if (buffer == NULL) {
Py_XDECREF(peek);
return NULL;
}
while (limit < 0 || PyByteArray_GET_SIZE(buffer) < limit) {
Py_ssize_t nreadahead = 1;
PyObject *b;
if (peek != NULL) {
PyObject *readahead = PyObject_CallOneArg(peek, _PyLong_GetOne());
if (readahead == NULL) {
/* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
when EINTR occurs so we needn't do it ourselves. */
if (_PyIO_trap_eintr()) {
continue;
}
goto fail;
}
if (!PyBytes_Check(readahead)) {
PyErr_Format(PyExc_OSError,
"peek() should have returned a bytes object, "
"not '%.200s'", Py_TYPE(readahead)->tp_name);
Py_DECREF(readahead);
goto fail;
}
if (PyBytes_GET_SIZE(readahead) > 0) {
Py_ssize_t n = 0;
const char *buf = PyBytes_AS_STRING(readahead);
if (limit >= 0) {
do {
if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
break;
if (buf[n++] == '\n')
break;
} while (1);
}
else {
do {
if (n >= PyBytes_GET_SIZE(readahead))
break;
if (buf[n++] == '\n')
break;
} while (1);
}
nreadahead = n;
}
Py_DECREF(readahead);
}
b = _PyObject_CallMethod(self, &_Py_ID(read), "n", nreadahead);
if (b == NULL) {
/* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
when EINTR occurs so we needn't do it ourselves. */
if (_PyIO_trap_eintr()) {
continue;
}
goto fail;
}
if (!PyBytes_Check(b)) {
PyErr_Format(PyExc_OSError,
"read() should have returned a bytes object, "
"not '%.200s'", Py_TYPE(b)->tp_name);
Py_DECREF(b);
goto fail;
}
if (PyBytes_GET_SIZE(b) == 0) {
Py_DECREF(b);
break;
}
old_size = PyByteArray_GET_SIZE(buffer);
if (PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b)) < 0) {
Py_DECREF(b);
goto fail;
}
memcpy(PyByteArray_AS_STRING(buffer) + old_size,
PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));
Py_DECREF(b);
if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
break;
}
result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
PyByteArray_GET_SIZE(buffer));
Py_XDECREF(peek);
Py_DECREF(buffer);
return result;
fail:
Py_XDECREF(peek);
Py_DECREF(buffer);
return NULL;
}
static PyObject *
iobase_iter(PyObject *self)
{
if (iobase_check_closed(self))
return NULL;
return Py_NewRef(self);
}
static PyObject *
iobase_iternext(PyObject *self)
{
PyObject *line = PyObject_CallMethodNoArgs(self, &_Py_ID(readline));
if (line == NULL)
return NULL;
if (PyObject_Size(line) <= 0) {
/* Error or empty */
Py_DECREF(line);
return NULL;
}
return line;
}
/*[clinic input]
_io._IOBase.readlines
hint: Py_ssize_t(accept={int, NoneType}) = -1
/
Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.
[clinic start generated code]*/
static PyObject *
_io__IOBase_readlines_impl(PyObject *self, Py_ssize_t hint)
/*[clinic end generated code: output=2f50421677fa3dea input=9400c786ea9dc416]*/
{
Py_ssize_t length = 0;
PyObject *result, *it = NULL;
result = PyList_New(0);
if (result == NULL)
return NULL;
if (hint <= 0) {
/* XXX special-casing this made sense in the Python version in order
to remove the bytecode interpretation overhead, but it could
probably be removed here. */
PyObject *ret = PyObject_CallMethodObjArgs(result, &_Py_ID(extend),
self, NULL);
if (ret == NULL) {
goto error;
}
Py_DECREF(ret);
return result;
}
it = PyObject_GetIter(self);
if (it == NULL) {
goto error;
}
while (1) {
Py_ssize_t line_length;
PyObject *line = PyIter_Next(it);
if (line == NULL) {
if (PyErr_Occurred()) {
goto error;
}
else
break; /* StopIteration raised */
}
if (PyList_Append(result, line) < 0) {
Py_DECREF(line);
goto error;
}
line_length = PyObject_Size(line);
Py_DECREF(line);
if (line_length < 0) {
goto error;
}
if (line_length > hint - length)
break;
length += line_length;
}
Py_DECREF(it);
return result;
error:
Py_XDECREF(it);
Py_DECREF(result);
return NULL;
}
/*[clinic input]
_io._IOBase.writelines
lines: object
/
Write a list of lines to stream.
Line separators are not added, so it is usual for each of the
lines provided to have a line separator at the end.
[clinic start generated code]*/
static PyObject *
_io__IOBase_writelines(PyObject *self, PyObject *lines)
/*[clinic end generated code: output=976eb0a9b60a6628 input=cac3fc8864183359]*/
{
PyObject *iter, *res;
if (iobase_check_closed(self))
return NULL;
iter = PyObject_GetIter(lines);
if (iter == NULL)
return NULL;
while (1) {
PyObject *line = PyIter_Next(iter);
if (line == NULL) {
if (PyErr_Occurred()) {
Py_DECREF(iter);
return NULL;
}
else
break; /* Stop Iteration */
}
res = NULL;
do {
res = PyObject_CallMethodObjArgs(self, &_Py_ID(write), line, NULL);
} while (res == NULL && _PyIO_trap_eintr());
Py_DECREF(line);
if (res == NULL) {
Py_DECREF(iter);
return NULL;
}
Py_DECREF(res);
}
Py_DECREF(iter);
Py_RETURN_NONE;
}
#define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
#include "clinic/iobase.c.h"
#undef clinic_state
static PyMethodDef iobase_methods[] = {
_IO__IOBASE_SEEK_METHODDEF
_IO__IOBASE_TELL_METHODDEF
_IO__IOBASE_TRUNCATE_METHODDEF
_IO__IOBASE_FLUSH_METHODDEF
_IO__IOBASE_CLOSE_METHODDEF
_IO__IOBASE_SEEKABLE_METHODDEF
_IO__IOBASE_READABLE_METHODDEF
_IO__IOBASE_WRITABLE_METHODDEF
{"_checkClosed", _PyIOBase_check_closed, METH_NOARGS},
{"_checkSeekable", iobase_check_seekable, METH_NOARGS},
{"_checkReadable", iobase_check_readable, METH_NOARGS},
{"_checkWritable", iobase_check_writable, METH_NOARGS},
_IO__IOBASE_FILENO_METHODDEF
_IO__IOBASE_ISATTY_METHODDEF
{"__enter__", iobase_enter, METH_NOARGS},
{"__exit__", iobase_exit, METH_VARARGS},
_IO__IOBASE_READLINE_METHODDEF
_IO__IOBASE_READLINES_METHODDEF
_IO__IOBASE_WRITELINES_METHODDEF
{NULL, NULL}
};
static PyGetSetDef iobase_getset[] = {
{"__dict__", PyObject_GenericGetDict, NULL, NULL},
{"closed", iobase_closed_get, NULL, NULL},
{NULL}
};
static struct PyMemberDef iobase_members[] = {
{"__weaklistoffset__", Py_T_PYSSIZET, offsetof(iobase, weakreflist), Py_READONLY},
{"__dictoffset__", Py_T_PYSSIZET, offsetof(iobase, dict), Py_READONLY},
{NULL},
};
static PyType_Slot iobase_slots[] = {
{Py_tp_dealloc, iobase_dealloc},
{Py_tp_doc, (void *)iobase_doc},
{Py_tp_traverse, iobase_traverse},
{Py_tp_clear, iobase_clear},
{Py_tp_iter, iobase_iter},
{Py_tp_iternext, iobase_iternext},
{Py_tp_methods, iobase_methods},
{Py_tp_members, iobase_members},
{Py_tp_getset, iobase_getset},
{Py_tp_finalize, iobase_finalize},
{0, NULL},
};
PyType_Spec _Py_iobase_spec = {
.name = "_io._IOBase",
.basicsize = sizeof(iobase),
.flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
Py_TPFLAGS_IMMUTABLETYPE),
.slots = iobase_slots,
};
/*
* RawIOBase class, Inherits from IOBase.
*/
PyDoc_STRVAR(rawiobase_doc,
"Base class for raw binary I/O.");
/*
* The read() method is implemented by calling readinto(); derived classes
* that want to support read() only need to implement readinto() as a
* primitive operation. In general, readinto() can be more efficient than
* read().
*
* (It would be tempting to also provide an implementation of readinto() in
* terms of read(), in case the latter is a more suitable primitive operation,
* but that would lead to nasty recursion in case a subclass doesn't implement
* either.)
*/
/*[clinic input]
_io._RawIOBase.read
size as n: Py_ssize_t = -1
/
[clinic start generated code]*/
static PyObject *
_io__RawIOBase_read_impl(PyObject *self, Py_ssize_t n)
/*[clinic end generated code: output=6cdeb731e3c9f13c input=b6d0dcf6417d1374]*/
{
PyObject *b, *res;
if (n < 0) {
return PyObject_CallMethodNoArgs(self, &_Py_ID(readall));
}
b = PyByteArray_FromStringAndSize(NULL, n);
if (b == NULL) {
return NULL;
}
res = PyObject_CallMethodObjArgs(self, &_Py_ID(readinto), b, NULL);
if (res == NULL || res == Py_None) {
goto cleanup;
}
Py_ssize_t bytes_filled = PyNumber_AsSsize_t(res, PyExc_ValueError);
Py_CLEAR(res);
if (bytes_filled == -1 && PyErr_Occurred()) {
goto cleanup;
}
if (bytes_filled < 0 || bytes_filled > n) {
PyErr_Format(PyExc_ValueError,
"readinto returned %zd outside buffer size %zd",
bytes_filled, n);
goto cleanup;
}
if (PyByteArray_Resize(b, bytes_filled) < 0) {
goto cleanup;
}
res = PyObject_CallMethodNoArgs(b, &_Py_ID(take_bytes));
cleanup:
Py_DECREF(b);
return res;
}
/*[clinic input]
_io._RawIOBase.readall
Read until EOF, using multiple read() call.
[clinic start generated code]*/
static PyObject *
_io__RawIOBase_readall_impl(PyObject *self)
/*[clinic end generated code: output=1987b9ce929425a0 input=688874141213622a]*/
{
PyBytesWriter *writer = PyBytesWriter_Create(0);
if (writer == NULL) {
return NULL;
}
while (1) {
PyObject *data = _PyObject_CallMethod(self, &_Py_ID(read),
"i", DEFAULT_BUFFER_SIZE);
if (!data) {
/* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
when EINTR occurs so we needn't do it ourselves. */
if (_PyIO_trap_eintr()) {
continue;
}
PyBytesWriter_Discard(writer);
return NULL;
}
if (data == Py_None) {
if (PyBytesWriter_GetSize(writer) == 0) {
PyBytesWriter_Discard(writer);
return data;
}
Py_DECREF(data);
break;
}
if (!PyBytes_Check(data)) {
Py_DECREF(data);
PyErr_SetString(PyExc_TypeError, "read() should return bytes");
PyBytesWriter_Discard(writer);
return NULL;
}
if (PyBytes_GET_SIZE(data) == 0) {
/* EOF */
Py_DECREF(data);
break;
}
if (PyBytesWriter_WriteBytes(writer,
PyBytes_AS_STRING(data),
PyBytes_GET_SIZE(data)) < 0) {
Py_DECREF(data);
PyBytesWriter_Discard(writer);
return NULL;
}
Py_DECREF(data);
}
return PyBytesWriter_Finish(writer);
}
static PyObject *
rawiobase_readinto(PyObject *self, PyObject *args)
{
PyErr_SetNone(PyExc_NotImplementedError);
return NULL;
}
static PyObject *
rawiobase_write(PyObject *self, PyObject *args)
{
PyErr_SetNone(PyExc_NotImplementedError);
return NULL;
}
static PyMethodDef rawiobase_methods[] = {
_IO__RAWIOBASE_READ_METHODDEF
_IO__RAWIOBASE_READALL_METHODDEF
{"readinto", rawiobase_readinto, METH_VARARGS},
{"write", rawiobase_write, METH_VARARGS},
{NULL, NULL}
};
static PyType_Slot rawiobase_slots[] = {
{Py_tp_doc, (void *)rawiobase_doc},
{Py_tp_methods, rawiobase_methods},
{0, NULL},
};
/* Do not set Py_TPFLAGS_HAVE_GC so that tp_traverse and tp_clear are inherited */
PyType_Spec _Py_rawiobase_spec = {
.name = "_io._RawIOBase",
.flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
Py_TPFLAGS_IMMUTABLETYPE),
.slots = rawiobase_slots,
};
|
c
|
github
|
https://github.com/python/cpython
|
Modules/_io/iobase.c
|
from __future__ import unicode_literals
import six
from . import strings
# from jaraco.util.dictlib
class KeyTransformingDict(dict):
"""
A dict subclass that transforms the keys before they're used.
Subclasses may override the default key_transform to customize behavior.
"""
@staticmethod
def key_transform(key):
return key
def __init__(self, *args, **kargs):
super(KeyTransformingDict, self).__init__()
# build a dictionary using the default constructs
d = dict(*args, **kargs)
# build this dictionary using transformed keys.
for item in d.items():
self.__setitem__(*item)
def __setitem__(self, key, val):
key = self.key_transform(key)
super(KeyTransformingDict, self).__setitem__(key, val)
def __getitem__(self, key):
key = self.key_transform(key)
return super(KeyTransformingDict, self).__getitem__(key)
def __contains__(self, key):
key = self.key_transform(key)
return super(KeyTransformingDict, self).__contains__(key)
def __delitem__(self, key):
key = self.key_transform(key)
return super(KeyTransformingDict, self).__delitem__(key)
def setdefault(self, key, *args, **kwargs):
key = self.key_transform(key)
return super(KeyTransformingDict, self).setdefault(key, *args, **kwargs)
def pop(self, key, *args, **kwargs):
key = self.key_transform(key)
return super(KeyTransformingDict, self).pop(key, *args, **kwargs)
class IRCDict(KeyTransformingDict):
"""
A dictionary of names whose keys are case-insensitive according to the
IRC RFC rules.
>>> d = IRCDict({'[This]': 'that'}, A='foo')
The dict maintains the original case:
>>> '[This]' in ''.join(d.keys())
True
But the keys can be referenced with a different case
>>> d['a'] == 'foo'
True
>>> d['{this}'] == 'that'
True
>>> d['{THIS}'] == 'that'
True
>>> '{thiS]' in d
True
This should work for operations like delete and pop as well.
>>> d.pop('A') == 'foo'
True
>>> del d['{This}']
>>> len(d)
0
"""
@staticmethod
def key_transform(key):
if isinstance(key, six.string_types):
key = strings.IRCFoldedCase(key)
return key
|
unknown
|
codeparrot/codeparrot-clean
| ||
"use strict";
const identifierUtil = require("../lib/util/identifier");
describe("util/identifier", () => {
describe("makePathsRelative", () => {
describe("given a context and a pathConstruct", () => {
it("computes the correct relative results for the path construct", () => {
for (const [context, pathConstruct, expected] of [
[
"/some/dir/",
"/some/dir/to/somewhere|some/other/dir!../more/dir",
"./to/somewhere|some/other/dir!../more/dir"
],
[
"/dir/",
"/dir/to/somewhere|some/other/dir!../more/dir",
"./to/somewhere|some/other/dir!../more/dir"
],
[
"/",
"/dir/to/somewhere|some/other/dir!../more/dir",
"./dir/to/somewhere|some/other/dir!../more/dir"
],
[
"c:\\some\\dir\\",
"c:\\some\\dir\\to\\somewhere|some/other/dir!../more/dir",
"./to/somewhere|some/other/dir!../more/dir"
],
[
"c:\\some\\dir\\",
"C:\\some\\dir\\to\\somewhere|some/other/dir!../more/dir",
"./to/somewhere|some/other/dir!../more/dir"
],
[
"C:\\some\\dir",
"C:\\some\\dir\\to\\somewhere|some/other/dir!../more/dir",
"./to/somewhere|some/other/dir!../more/dir"
],
[
"C:\\\\some\\dir",
"c:\\some\\\\dir\\to\\\\somewhere|some/other/dir!../more/dir",
"./to/somewhere|some/other/dir!../more/dir"
],
["/dir", "/dir/to/somewhere??ref-123", "./to/somewhere??ref-123"]
]) {
expect(identifierUtil.makePathsRelative(context, pathConstruct)).toBe(
expected
);
}
});
});
});
describe("getUndoPath", () => {
const cases = [
["file.js", ""],
["file.js", "./", true],
["dir/file.js", "../"],
["dir/file.js", "../", true],
["./file.js", ""],
[".dir/file.js", "../"],
["./dir/file.js", "../"],
["./dir/././file.js", "../"],
["./dir/../file.js", ""],
["./dir/../file.js", "./", true],
["../file.js", "d/"],
["../file.js", "./d/", true],
["../dir/file.js", "../d/"],
[".././../dir/file.js", "../c/d/"],
["./.././../dir/file.js", "../c/d/"],
["../dir/../file.js", "d/"],
["../dir/../file.js", "./d/", true]
];
for (const [filename, expected, enforceRelative] of cases) {
it(`should handle ${filename} correctly${
enforceRelative ? " (enforced relative path)" : ""
}`, () => {
for (const outputPath of [
"/a/b/c/d",
"C:\\a\\b\\c\\d",
"/a/b/c/d/",
"C:\\a\\b\\c\\d\\"
]) {
expect(
identifierUtil.getUndoPath(filename, outputPath, enforceRelative)
).toBe(expected);
}
});
}
});
describe("parseResourceWithoutFragment", () => {
// [input, expectedPath, expectedQuery]
/** @type {[string, string, string][]} */
const cases = [
["path#hash?query", "path#hash", "?query"],
["path?query#hash", "path", "?query#hash"],
["\0#path\0??\0#query#hash", "#path?", "?#query#hash"],
[
'./loader.js?{"items":["a\0^","b\0!","c#","d"]}',
"./loader.js",
'?{"items":["a^","b!","c#","d"]}'
],
[
"C:\\Users\\\0#\\repo\\loader.js?",
"C:\\Users\\#\\repo\\loader.js",
"?"
],
["/Users/\0#/repo/loader-\0#.js", "/Users/#/repo/loader-#.js", ""]
];
for (const case_ of cases) {
it(case_[0], () => {
const { resource, path, query } =
identifierUtil.parseResourceWithoutFragment(case_[0]);
expect(case_[0]).toBe(resource);
expect(case_[1]).toBe(path);
expect(case_[2]).toBe(query);
});
}
});
});
|
javascript
|
github
|
https://github.com/webpack/webpack
|
test/identifier.unittest.js
|
#
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
# License: http://pyasn1.sf.net/license.html
#
import logging
from pyasn1.compat.octets import octs2ints
from pyasn1 import error
from pyasn1 import __version__
__all__ = ['Debug', 'setLogger', 'hexdump']
flagNone = 0x0000
flagEncoder = 0x0001
flagDecoder = 0x0002
flagAll = 0xffff
flagMap = {
'encoder': flagEncoder,
'decoder': flagDecoder,
'all': flagAll
}
class Printer(object):
# noinspection PyShadowingNames
def __init__(self, logger=None, handler=None, formatter=None):
if logger is None:
logger = logging.getLogger('pyasn1')
logger.setLevel(logging.DEBUG)
if handler is None:
handler = logging.StreamHandler()
if formatter is None:
formatter = logging.Formatter('%(asctime)s %(name)s: %(message)s')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)
self.__logger = logger
def __call__(self, msg):
self.__logger.debug(msg)
def __str__(self):
return '<python built-in logging>'
if hasattr(logging, 'NullHandler'):
NullHandler = logging.NullHandler
else:
# Python 2.6 and older
class NullHandler(logging.Handler):
def emit(self, record):
pass
class Debug(object):
defaultPrinter = None
def __init__(self, *flags, **options):
self._flags = flagNone
if options.get('printer') is not None:
self._printer = options.get('printer')
elif self.defaultPrinter is not None:
self._printer = self.defaultPrinter
if 'loggerName' in options:
# route our logs to parent logger
self._printer = Printer(
logger=logging.getLogger(options['loggerName']),
handler=NullHandler()
)
else:
self._printer = Printer()
self('running pyasn1 version %s' % __version__)
for f in flags:
inverse = f and f[0] in ('!', '~')
if inverse:
f = f[1:]
try:
if inverse:
self._flags &= ~flagMap[f]
else:
self._flags |= flagMap[f]
except KeyError:
raise error.PyAsn1Error('bad debug flag %s' % f)
self('debug category \'%s\' %s' % (f, inverse and 'disabled' or 'enabled'))
def __str__(self):
return 'logger %s, flags %x' % (self._printer, self._flags)
def __call__(self, msg):
self._printer(msg)
def __and__(self, flag):
return self._flags & flag
def __rand__(self, flag):
return flag & self._flags
logger = 0
def setLogger(l):
global logger
logger = l
def hexdump(octets):
return ' '.join(
['%s%.2X' % (n % 16 == 0 and ('\n%.5d: ' % n) or '', x)
for n, x in zip(range(len(octets)), octs2ints(octets))]
)
class Scope(object):
def __init__(self):
self._list = []
def __str__(self): return '.'.join(self._list)
def push(self, token):
self._list.append(token)
def pop(self):
return self._list.pop()
scope = Scope()
|
unknown
|
codeparrot/codeparrot-clean
| ||
import numpy as nm
from sfepy.linalg import dot_sequences
from sfepy.terms.terms import Term, terms
class PiezoCouplingTerm(Term):
r"""
Piezoelectric coupling term. Can be evaluated.
:Definition:
.. math::
\int_{\Omega} g_{kij}\ e_{ij}(\ul{v}) \nabla_k p \mbox{ , }
\int_{\Omega} g_{kij}\ e_{ij}(\ul{u}) \nabla_k q
:Arguments 1:
- material : :math:`g_{kij}`
- virtual : :math:`\ul{v}`
- state : :math:`p`
:Arguments 2:
- material : :math:`g_{kij}`
- state : :math:`\ul{u}`
- virtual : :math:`q`
:Arguments 3:
- material : :math:`g_{kij}`
- parameter_v : :math:`\ul{u}`
- parameter_s : :math:`p`
"""
name = 'dw_piezo_coupling'
arg_types = (('material', 'virtual', 'state'),
('material', 'state', 'virtual'),
('material', 'parameter_v', 'parameter_s'))
arg_shapes = {'material' : 'D, S',
'virtual/grad' : ('D', None), 'state/grad' : 1,
'virtual/div' : (1, None), 'state/div' : 'D',
'parameter_v' : 'D', 'parameter_s' : 1}
modes = ('grad', 'div', 'eval')
def get_fargs(self, mat, vvar, svar,
mode=None, term_mode=None, diff_var=None, **kwargs):
if self.mode == 'grad':
qp_var, qp_name = svar, 'grad'
else:
qp_var, qp_name = vvar, 'cauchy_strain'
vvg, _ = self.get_mapping(vvar)
if mode == 'weak':
aux = nm.array([0], ndmin=4, dtype=nm.float64)
if diff_var is None:
# grad or strain according to mode.
val_qp = self.get(qp_var, qp_name)
fmode = 0
else:
val_qp = aux
fmode = 1
if self.mode == 'grad':
strain, grad = aux, val_qp
else:
strain, grad = val_qp, aux
fmode += 2
return strain, grad, mat, vvg, fmode
elif mode == 'eval':
strain = self.get(vvar, 'cauchy_strain')
grad = self.get(svar, 'grad')
return strain, grad, mat, vvg
else:
raise ValueError('unsupported evaluation mode in %s! (%s)'
% (self.name, mode))
def get_eval_shape(self, mat, vvar, svar,
mode=None, term_mode=None, diff_var=None, **kwargs):
n_el, n_qp, dim, n_en, n_c = self.get_data_shape(vvar)
return (n_el, 1, 1, 1), vvar.dtype
def set_arg_types( self ):
self.function = {
'grad' : terms.dw_piezo_coupling,
'div' : terms.dw_piezo_coupling,
'eval' : terms.d_piezo_coupling,
}[self.mode]
class PiezoStressTerm(Term):
r"""
Evaluate piezoelectric stress tensor.
It is given in the usual vector form exploiting symmetry: in 3D it has 6
components with the indices ordered as :math:`[11, 22, 33, 12, 13, 23]`, in
2D it has 3 components with the indices ordered as :math:`[11, 22, 12]`.
Supports 'eval', 'el_avg' and 'qp' evaluation modes.
:Definition:
.. math::
\int_{\Omega} g_{kij} \nabla_k p
:Arguments:
- material : :math:`g_{kij}`
- parameter : :math:`p`
"""
name = 'ev_piezo_stress'
arg_types = ('material', 'parameter')
arg_shapes = {'material' : 'D, S', 'parameter' : '1'}
@staticmethod
def function(out, val_qp, vg, fmode):
if fmode == 2:
out[:] = val_qp
status = 0
else:
status = vg.integrate(out, val_qp, fmode)
return status
def get_fargs(self, mat, parameter,
mode=None, term_mode=None, diff_var=None, **kwargs):
vg, _ = self.get_mapping(parameter)
grad = self.get(parameter, 'grad')
val_qp = dot_sequences(mat, grad, mode='ATB')
fmode = {'eval' : 0, 'el_avg' : 1, 'qp' : 2}.get(mode, 1)
return val_qp, vg, fmode
def get_eval_shape(self, mat, parameter,
mode=None, term_mode=None, diff_var=None, **kwargs):
n_el, n_qp, dim, n_en, n_c = self.get_data_shape(parameter)
if mode != 'qp':
n_qp = 1
return (n_el, n_qp, dim * (dim + 1) // 2, 1), parameter.dtype
class PiezoStrainTerm(PiezoStressTerm):
r"""
Evaluate piezoelectric strain tensor.
It is given in the usual vector form exploiting symmetry: in 3D it has 6
components with the indices ordered as :math:`[11, 22, 33, 12, 13, 23]`, in
2D it has 3 components with the indices ordered as :math:`[11, 22, 12]`.
Supports 'eval', 'el_avg' and 'qp' evaluation modes.
:Definition:
.. math::
\int_{\Omega} g_{kij} e_{ij}(\ul{u})
:Arguments:
- material : :math:`g_{kij}`
- parameter : :math:`\ul{u}`
"""
name = 'ev_piezo_strain'
arg_shapes = {'material' : 'D, S', 'parameter' : 'D'}
def get_fargs(self, mat, parameter,
mode=None, term_mode=None, diff_var=None, **kwargs):
vg, _ = self.get_mapping(parameter)
strain = self.get(parameter, 'cauchy_strain')
val_qp = dot_sequences(mat, strain, mode='AB')
fmode = {'eval': 0, 'el_avg': 1, 'qp': 2}.get(mode, 1)
return val_qp, vg, fmode
def get_eval_shape(self, mat, parameter,
mode=None, term_mode=None, diff_var=None, **kwargs):
n_el, n_qp, dim, n_en, n_c = self.get_data_shape(parameter)
if mode != 'qp':
n_qp = 1
return (n_el, n_qp, dim, 1), parameter.dtype
|
unknown
|
codeparrot/codeparrot-clean
| ||
from __future__ import unicode_literals
from collections import OrderedDict
import keyword
import re
from optparse import make_option
from django.core.management.base import NoArgsCommand, CommandError
from django.db import connections, DEFAULT_DB_ALIAS
class Command(NoArgsCommand):
help = "Introspects the database tables in the given database and outputs a Django model module."
option_list = NoArgsCommand.option_list + (
make_option('--database', action='store', dest='database',
default=DEFAULT_DB_ALIAS, help='Nominates a database to '
'introspect. Defaults to using the "default" database.'),
)
requires_system_checks = False
db_module = 'django.db'
def handle_noargs(self, **options):
try:
for line in self.handle_inspection(options):
self.stdout.write("%s\n" % line)
except NotImplementedError:
raise CommandError("Database inspection isn't supported for the currently selected database backend.")
def handle_inspection(self, options):
connection = connections[options.get('database')]
# 'table_name_filter' is a stealth option
table_name_filter = options.get('table_name_filter')
table2model = lambda table_name: table_name.title().replace('_', '').replace(' ', '').replace('-', '')
strip_prefix = lambda s: s[1:] if s.startswith("u'") else s
with connection.cursor() as cursor:
yield "# This is an auto-generated Django model module."
yield "# You'll have to do the following manually to clean this up:"
yield "# * Rearrange models' order"
yield "# * Make sure each model has one field with primary_key=True"
yield "# * Remove `managed = False` lines for those models you wish to give write DB access"
yield "# Feel free to rename the models, but don't rename db_table values or field names."
yield "#"
yield "# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [app_label]'"
yield "# into your database."
yield "from __future__ import unicode_literals"
yield ''
yield 'from %s import models' % self.db_module
known_models = []
for table_name in connection.introspection.table_names(cursor):
if table_name_filter is not None and callable(table_name_filter):
if not table_name_filter(table_name):
continue
yield ''
yield ''
yield 'class %s(models.Model):' % table2model(table_name)
known_models.append(table2model(table_name))
try:
relations = connection.introspection.get_relations(cursor, table_name)
except NotImplementedError:
relations = {}
try:
indexes = connection.introspection.get_indexes(cursor, table_name)
except NotImplementedError:
indexes = {}
used_column_names = [] # Holds column names used in the table so far
for i, row in enumerate(connection.introspection.get_table_description(cursor, table_name)):
comment_notes = [] # Holds Field notes, to be displayed in a Python comment.
extra_params = OrderedDict() # Holds Field parameters such as 'db_column'.
column_name = row[0]
is_relation = i in relations
att_name, params, notes = self.normalize_col_name(
column_name, used_column_names, is_relation)
extra_params.update(params)
comment_notes.extend(notes)
used_column_names.append(att_name)
# Add primary_key and unique, if necessary.
if column_name in indexes:
if indexes[column_name]['primary_key']:
extra_params['primary_key'] = True
elif indexes[column_name]['unique']:
extra_params['unique'] = True
if is_relation:
rel_to = "self" if relations[i][1] == table_name else table2model(relations[i][1])
if rel_to in known_models:
field_type = 'ForeignKey(%s' % rel_to
else:
field_type = "ForeignKey('%s'" % rel_to
else:
# Calling `get_field_type` to get the field type string and any
# additional paramters and notes.
field_type, field_params, field_notes = self.get_field_type(connection, table_name, row)
extra_params.update(field_params)
comment_notes.extend(field_notes)
field_type += '('
# Don't output 'id = meta.AutoField(primary_key=True)', because
# that's assumed if it doesn't exist.
if att_name == 'id' and extra_params == {'primary_key': True}:
if field_type == 'AutoField(':
continue
elif field_type == 'IntegerField(' and not connection.features.can_introspect_autofield:
comment_notes.append('AutoField?')
# Add 'null' and 'blank', if the 'null_ok' flag was present in the
# table description.
if row[6]: # If it's NULL...
if field_type == 'BooleanField(':
field_type = 'NullBooleanField('
else:
extra_params['blank'] = True
if not field_type in ('TextField(', 'CharField('):
extra_params['null'] = True
field_desc = '%s = %s%s' % (
att_name,
# Custom fields will have a dotted path
'' if '.' in field_type else 'models.',
field_type,
)
if extra_params:
if not field_desc.endswith('('):
field_desc += ', '
field_desc += ', '.join([
'%s=%s' % (k, strip_prefix(repr(v)))
for k, v in extra_params.items()])
field_desc += ')'
if comment_notes:
field_desc += ' # ' + ' '.join(comment_notes)
yield ' %s' % field_desc
for meta_line in self.get_meta(table_name):
yield meta_line
def normalize_col_name(self, col_name, used_column_names, is_relation):
"""
Modify the column name to make it Python-compatible as a field name
"""
field_params = {}
field_notes = []
new_name = col_name.lower()
if new_name != col_name:
field_notes.append('Field name made lowercase.')
if is_relation:
if new_name.endswith('_id'):
new_name = new_name[:-3]
else:
field_params['db_column'] = col_name
new_name, num_repl = re.subn(r'\W', '_', new_name)
if num_repl > 0:
field_notes.append('Field renamed to remove unsuitable characters.')
if new_name.find('__') >= 0:
while new_name.find('__') >= 0:
new_name = new_name.replace('__', '_')
if col_name.lower().find('__') >= 0:
# Only add the comment if the double underscore was in the original name
field_notes.append("Field renamed because it contained more than one '_' in a row.")
if new_name.startswith('_'):
new_name = 'field%s' % new_name
field_notes.append("Field renamed because it started with '_'.")
if new_name.endswith('_'):
new_name = '%sfield' % new_name
field_notes.append("Field renamed because it ended with '_'.")
if keyword.iskeyword(new_name):
new_name += '_field'
field_notes.append('Field renamed because it was a Python reserved word.')
if new_name[0].isdigit():
new_name = 'number_%s' % new_name
field_notes.append("Field renamed because it wasn't a valid Python identifier.")
if new_name in used_column_names:
num = 0
while '%s_%d' % (new_name, num) in used_column_names:
num += 1
new_name = '%s_%d' % (new_name, num)
field_notes.append('Field renamed because of name conflict.')
if col_name != new_name and field_notes:
field_params['db_column'] = col_name
return new_name, field_params, field_notes
def get_field_type(self, connection, table_name, row):
"""
Given the database connection, the table name, and the cursor row
description, this routine will return the given field type name, as
well as any additional keyword parameters and notes for the field.
"""
field_params = OrderedDict()
field_notes = []
try:
field_type = connection.introspection.get_field_type(row[1], row)
except KeyError:
field_type = 'TextField'
field_notes.append('This field type is a guess.')
# This is a hook for DATA_TYPES_REVERSE to return a tuple of
# (field_type, field_params_dict).
if type(field_type) is tuple:
field_type, new_params = field_type
field_params.update(new_params)
# Add max_length for all CharFields.
if field_type == 'CharField' and row[3]:
field_params['max_length'] = int(row[3])
if field_type == 'DecimalField':
if row[4] is None or row[5] is None:
field_notes.append(
'max_digits and decimal_places have been guessed, as this '
'database handles decimal fields as float')
field_params['max_digits'] = row[4] if row[4] is not None else 10
field_params['decimal_places'] = row[5] if row[5] is not None else 5
else:
field_params['max_digits'] = row[4]
field_params['decimal_places'] = row[5]
return field_type, field_params, field_notes
def get_meta(self, table_name):
"""
Return a sequence comprising the lines of code necessary
to construct the inner Meta class for the model corresponding
to the given database table name.
"""
return ["",
" class Meta:",
" managed = False",
" db_table = '%s'" % table_name]
|
unknown
|
codeparrot/codeparrot-clean
| ||
import locale
def fmt(value: int | float, decimals: int = 1) -> str:
return locale.format_string(f'%.{decimals}f', value, grouping=True)
|
python
|
github
|
https://github.com/python/cpython
|
Lib/profiling/sampling/_format_utils.py
|
import sys, argparse, os
sys.path.append('../')
import settings
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--T', action='store',
default=1000,
help='number of rounds')
parser.add_argument('--dataset', action='store', choices=['synth','mq2007','mq2008', 'yahoo'])
## parser.add_argument('--policies', action='store', choices=['finite', 'tree', 'linear'], default='linear')
parser.add_argument('--L', action='store', default=3)
parser.add_argument('--I', action='store', default=5)
parser.add_argument('--start', action='store', default=0)
parser.add_argument('--server', action='store')
parser.add_argument('--user', action='store')
Args = parser.parse_args(sys.argv[1:])
print(Args)
string = "ssh %s@%s 'cd ~/projects/oracle_cb/code/; %s Experiments.py --dataset %s --T %s --I %s --L %s --noise 0.1 --grid True --start %s > logs/%s_T=%s_L=%s_S=%s.log 2>&1 &'" % (Args.user, Args.server, settings.REMOTE_PATH_TO_PYTHON, Args.dataset, Args.T, Args.I, Args.L, Args.start, Args.dataset, Args.T, Args.L, Args.start)
print(string)
os.system(string)
|
unknown
|
codeparrot/codeparrot-clean
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.