repo_name
stringlengths 6
61
| path
stringlengths 4
230
| copies
stringlengths 1
3
| size
stringlengths 4
6
| text
stringlengths 1.01k
850k
| license
stringclasses 15
values | hash
int64 -9,220,477,234,079,998,000
9,219,060,020B
| line_mean
float64 11.6
96.6
| line_max
int64 32
939
| alpha_frac
float64 0.26
0.9
| autogenerated
bool 1
class | ratio
float64 1.62
6.1
| config_test
bool 2
classes | has_no_keywords
bool 2
classes | few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
caiogit/bird-a | backend/birda/bModel/widget_catalog/form.py | 1 | 3389 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# -------------------------------------- #
# Enables python3-like strings handling
from __future__ import unicode_literals
str = unicode
# -------------------------------------- #
import collections
from birda.bModel.widget import Widget
from birda.bModel import BIRDA
from birda.storage.utils import (
get_types,
get_property,
prettify,
get_co_list,
get_by_lang
)
# Consts ...
# ============================================================================ #
class FormWidget(Widget):
def __init__(self, conn, rdfw=None, uri=''):
super(FormWidget, self).__init__(
conn, rdfw=rdfw, uri=uri,
actionable=True, hierarchical=True)
self.attributes.update( self._get_specific_attributes() )
# --------------------------------- #
def _get_specific_attributes(self):
"""
Get the attributes specific for this type of widget
:return: Dictionary containing widget properties
"""
a = collections.OrderedDict()
a['maps_type'] = get_property(self.conn, self.uri, BIRDA.mapsType, rdfw=self.rdfw, lexical=True, single=True)
a['base_uri'] = get_property(self.conn, self.uri, BIRDA.hasBaseIRI, rdfw=self.rdfw, lexical=True, single=True)
a['label_property'] = get_property(self.conn, self.uri, BIRDA.usesPropertyForLabel, rdfw=self.rdfw, lexical=True, single=True)
a['descr_property'] = get_property(self.conn, self.uri, BIRDA.usesPropertyForDescription, rdfw=self.rdfw, lexical=True, single=True)
def fields2list(fields):
if fields:
return [ str(f).strip() for f in str(fields).split(',') ]
else:
return []
a['local_name'] = {}
a['local_name']['fields'] = fields2list( get_property(self.conn, self.uri, BIRDA.hasLocalNameFields, rdfw=self.rdfw, lexical=True, single=True) )
a['local_name']['separator'] = get_property(self.conn, self.uri, BIRDA.hasLocalNameSeparator, rdfw=self.rdfw, lexical=True, single=True)
a['local_name']['tokenSeparator'] = get_property(self.conn, self.uri, BIRDA.hasLocalNameTokenSeparator, rdfw=self.rdfw, lexical=True, single=True)
a['local_name']['renderer'] = get_property(self.conn, self.uri, BIRDA.hasLocalNameRenderer, rdfw=self.rdfw, lexical=True, single=True)
return a
# --------------------------------- #
def to_rdf(self, value, lang=None):
"""
See Widget.to_rdf declaration
"""
raise NotImplementedError('This method should not be invoked on a Form widget')
# --------------------------------- #
def getJSON(self, lang):
"""
Inherited from Widget
(pop and re-add fields for a better readability of output json)
"""
j = super(FormWidget, self).getJSON(lang)
fields = j.pop('fields')
j.pop('w_type')
uri = j.pop('widget_uri')
j['form_uri'] = uri
j['maps_type'] = self.attributes['maps_type']
j['base_uri'] = self.attributes['base_uri']
j['label_property'] = self.attributes['label_property']
j['descr_property'] = self.attributes['descr_property']
if self.attributes['local_name']['fields']:
j['local_name'] = self.attributes['local_name']
else:
# Will be created by the schema
#j['local_name'] = {}
pass
j['fields'] = fields
return j
# ---------------------------------------------------------------------------- #
# ============================================================================ #
if __name__ == '__main__':
pass | gpl-3.0 | -8,831,213,653,689,240,000 | 28.736842 | 148 | 0.59103 | false | 3.2871 | false | false | false |
PennyDreadfulMTG/Penny-Dreadful-Tools | discordbot/command.py | 1 | 11736 | import collections
import datetime
import re
from copy import copy
from typing import Callable, Dict, List, Optional, Sequence, Set, Tuple, Union
from discord import ChannelType, Client, DMChannel, File, GroupChannel, TextChannel
from discord.abc import Messageable
from discord.ext import commands
from discord.member import Member
from discord.message import Message
from discordbot import emoji
from magic import card, card_price, fetcher, image_fetcher, oracle
from magic.models import Card
from magic.whoosh_search import SearchResult, WhooshSearcher
from shared import configuration, dtutil
from shared.lazy import lazy_property
DEFAULT_CARDS_SHOWN = 4
MAX_CARDS_SHOWN = 10
DISAMBIGUATION_EMOJIS = [':one:', ':two:', ':three:', ':four:', ':five:']
DISAMBIGUATION_EMOJIS_BY_NUMBER = {1: '1⃣', 2: '2⃣', 3: '3⃣', 4: '4⃣', 5: '5⃣'}
DISAMBIGUATION_NUMBERS_BY_EMOJI = {'1⃣': 1, '2⃣': 2, '3⃣': 3, '4⃣': 4, '5⃣': 5}
HELP_GROUPS: Set[str] = set()
@lazy_property
def searcher() -> WhooshSearcher:
return WhooshSearcher()
async def respond_to_card_names(message: Message, client: Client) -> None:
# Don't parse messages with Gatherer URLs because they use square brackets in the querystring.
if 'gatherer.wizards.com' in message.content.lower():
return
compat = message.channel.type == ChannelType.text and client.get_user(268547439714238465) in message.channel.members
queries = parse_queries(message.content, compat)
if len(queries) > 0:
await message.channel.trigger_typing()
results = results_from_queries(queries)
cards = []
for i in results:
(r, mode, preferred_printing) = i
if r.has_match() and not r.is_ambiguous():
cards.extend(cards_from_names_with_mode([r.get_best_match()], mode, preferred_printing))
elif r.is_ambiguous():
cards.extend(cards_from_names_with_mode(r.get_ambiguous_matches(), mode, preferred_printing))
await post_cards(client, cards, message.channel, message.author)
def parse_queries(content: str, scryfall_compatability_mode: bool) -> List[str]:
to_scan = re.sub('`{1,3}[^`]*?`{1,3}', '', content, re.DOTALL) # Ignore angle brackets inside backticks. It's annoying in #code.
if scryfall_compatability_mode:
queries = re.findall(r'(?<!\[)\[([^\]]*)\](?!\])', to_scan) # match [card] but not [[card]]
else:
queries = re.findall(r'\[?\[([^\]]*)\]\]?', to_scan)
return [card.canonicalize(query) for query in queries if len(query) > 2]
def cards_from_names_with_mode(cards: Sequence[Optional[str]], mode: str, preferred_printing: Optional[str] = None) -> List[Card]:
return [copy_with_mode(oracle.load_card(c), mode, preferred_printing) for c in cards if c is not None]
def copy_with_mode(oracle_card: Card, mode: str, preferred_printing: str = None) -> Card:
c = copy(oracle_card)
c['mode'] = mode
c['preferred_printing'] = preferred_printing
return c
def parse_mode(query: str) -> Tuple[str, str, Optional[str]]:
mode = ''
preferred_printing = None
if query.startswith('$'):
mode = '$'
query = query[1:]
if '|' in query:
query, preferred_printing = query.split('|')
preferred_printing = preferred_printing.lower().strip()
return (mode, query, preferred_printing)
def results_from_queries(queries: List[str]) -> List[Tuple[SearchResult, str, Optional[str]]]:
all_results = []
for query in queries:
mode, query, preferred_printing = parse_mode(query)
result = searcher().search(query)
all_results.append((result, mode, preferred_printing))
return all_results
def complex_search(query: str) -> List[Card]:
if query == '':
return []
_, cardnames = fetcher.search_scryfall(query)
cbn = oracle.cards_by_name()
return [cbn[name] for name in cardnames if cbn.get(name) is not None]
def roughly_matches(s1: str, s2: str) -> bool:
return simplify_string(s1).find(simplify_string(s2)) >= 0
def simplify_string(s: str) -> str:
s = ''.join(s.split())
return re.sub(r'[\W_]+', '', s).lower()
def disambiguation(cards: List[str]) -> str:
if len(cards) > 5:
return ','.join(cards)
return ' '.join([' '.join(x) for x in zip(DISAMBIGUATION_EMOJIS, cards)])
async def disambiguation_reactions(message: Message, cards: List[str]) -> None:
for i in range(1, len(cards) + 1):
await message.add_reaction(DISAMBIGUATION_EMOJIS_BY_NUMBER[i])
async def single_card_or_send_error(channel: TextChannel, args: str, author: Member, command: str) -> Optional[Card]:
if not args:
await send(channel, '{author}: Please specify a card name.'.format(author=author.mention))
return None
result, mode, preferred_printing = results_from_queries([args])[0]
if result.has_match() and not result.is_ambiguous():
return cards_from_names_with_mode([result.get_best_match()], mode, preferred_printing)[0]
if result.is_ambiguous():
message = await send(channel, '{author}: Ambiguous name for {c}. Suggestions: {s} (click number below)'.format(author=author.mention, c=command, s=disambiguation(result.get_ambiguous_matches()[0:5])))
await disambiguation_reactions(message, result.get_ambiguous_matches()[0:5])
else:
await send(channel, '{author}: No matches.'.format(author=author.mention))
return None
# pylint: disable=too-many-arguments
async def single_card_text(client: Client, channel: TextChannel, args: str, author: Member, f: Callable[[Card], str], command: str, show_legality: bool = True) -> None:
c = await single_card_or_send_error(channel, args, author, command)
if c is not None:
name = c.name
info_emoji = emoji.info_emoji(c, show_legality=show_legality)
text = emoji.replace_emoji(f(c), client)
message = f'**{name}** {info_emoji} {text}'
await send(channel, message)
async def post_cards(
client: Client,
cards: List[Card],
channel: Messageable,
replying_to: Optional[Member] = None,
additional_text: str = '',
) -> None:
if len(cards) == 0:
await post_no_cards(channel, replying_to)
return
not_pd = configuration.get_list('not_pd')
disable_emoji = str(channel.id) in not_pd or (getattr(channel, 'guild', None) is not None and str(channel.guild.id) in not_pd)
cards = uniqify_cards(cards)
if len(cards) > MAX_CARDS_SHOWN:
cards = cards[:DEFAULT_CARDS_SHOWN]
if len(cards) == 1:
text = single_card_text_internal(client, cards[0], disable_emoji)
else:
text = ', '.join('{name} {legal} {price}'.format(name=card.name, legal=((emoji.info_emoji(card)) if not disable_emoji else ''), price=((card_price.card_price_string(card, True)) if card.get('mode', None) == '$' else '')) for card in cards)
if len(cards) > MAX_CARDS_SHOWN:
image_file = None
else:
with channel.typing():
image_file = await image_fetcher.download_image_async(cards)
if image_file is None:
text += '\n\n'
if len(cards) == 1:
text += emoji.replace_emoji(cards[0].oracle_text, client)
else:
text += 'No image available.'
text += additional_text
if image_file is None:
await send(channel, text)
else:
await send_image_with_retry(channel, image_file, text)
async def post_no_cards(channel: Messageable, replying_to: Optional[Member] = None) -> None:
if replying_to is not None:
text = '{author}: No matches.'.format(author=replying_to.mention)
else:
text = 'No matches.'
message = await send(channel, text)
await message.add_reaction('❎')
async def send(channel: Messageable, content: str, file: Optional[File] = None) -> Message:
new_s = escape_underscores(content)
return await channel.send(file=file, content=new_s)
async def send_image_with_retry(channel: Messageable, image_file: str, text: str = '') -> None:
message = await send(channel, file=File(image_file), content=text)
if message and message.attachments and message.attachments[0].size == 0:
print('Message size is zero so resending')
await message.delete()
await send(channel, file=File(image_file), content=text)
def single_card_text_internal(client: Client, requested_card: Card, disable_emoji: bool) -> str:
mana = emoji.replace_emoji('|'.join(requested_card.mana_cost or []), client)
mana = mana.replace('|', ' // ')
legal = ' — ' + emoji.info_emoji(requested_card, verbose=True)
if disable_emoji:
legal = ''
if requested_card.get('mode', None) == '$':
text = '{name} {legal} — {price}'.format(name=requested_card.name, price=card_price.card_price_string(requested_card), legal=legal)
else:
text = '{name} {mana} — {type}{legal}'.format(name=requested_card.name, mana=mana, type=requested_card.type_line, legal=legal)
if requested_card.bugs:
for bug in requested_card.bugs:
text += '\n:lady_beetle:{rank} bug: {bug}'.format(bug=bug['description'], rank=bug['classification'])
if bug['last_confirmed'] < (dtutil.now() - datetime.timedelta(days=60)):
time_since_confirmed = (dtutil.now() - bug['last_confirmed']).total_seconds()
text += ' (Last confirmed {time} ago.)'.format(time=dtutil.display_time(time_since_confirmed, 1))
return text
# See #5532 and #5566.
def escape_underscores(s: str) -> str:
new_s = ''
in_url, in_emoji = False, False
for char in s:
if char == ':':
in_emoji = True
elif char not in 'abcdefghijklmnopqrstuvwxyz_':
in_emoji = False
if char == '<':
in_url = True
elif char == '>':
in_url = False
if char == '_' and not in_url and not in_emoji:
new_s += '\\_'
else:
new_s += char
return new_s
# Given a list of cards return one (aribtrarily) for each unique name in the list.
def uniqify_cards(cards: List[Card]) -> List[Card]:
# Remove multiple printings of the same card from the result set.
results: Dict[str, Card] = collections.OrderedDict()
for c in cards:
results[card.canonicalize(c.name)] = c
return list(results.values())
def guild_or_channel_id(channel: Union[TextChannel, DMChannel, GroupChannel]) -> int:
return getattr(channel, 'guild', channel).id
class MtgContext(commands.Context):
async def send_image_with_retry(self, image_file: str, text: str = '') -> None:
message = await self.send(file=File(image_file), content=text)
if message and message.attachments and message.attachments[0].size == 0:
print('Message size is zero so resending')
await message.delete()
await self.send(file=File(image_file), content=text)
async def single_card_text(self, c: Card, f: Callable, show_legality: bool = True) -> None:
not_pd = configuration.get_list('not_pd')
if str(self.channel.id) in not_pd or (getattr(self.channel, 'guild', None) is not None and str(self.channel.guild.id) in not_pd):
show_legality = False
name = c.name
info_emoji = emoji.info_emoji(c, show_legality=show_legality)
text = emoji.replace_emoji(f(c), self.bot)
message = f'**{name}** {info_emoji} {text}'
await self.send(message)
async def post_cards(self, cards: List[Card], replying_to: Optional[Member] = None, additional_text: str = '') -> None:
# this feels awkward, but shrug
await post_cards(self.bot, cards, self.channel, replying_to, additional_text)
| gpl-3.0 | 8,189,535,629,934,954,000 | 44.204633 | 247 | 0.644517 | false | 3.363401 | false | false | false |
StellarCN/py-stellar-base | stellar_sdk/client/response.py | 1 | 1266 | import json
__all__ = ["Response"]
class Response:
"""The :class:`Response <Response>` object, which contains a
server's response to an HTTP request.
:param status_code: response status code
:param text: response content
:param headers: response headers
:param url: request url
"""
def __init__(self, status_code: int, text: str, headers: dict, url: str) -> None:
self.status_code: int = status_code
self.text: str = text
self.headers: dict = headers
self.url: str = url
def json(self) -> dict:
"""convert the content to dict
:return: the content from server
"""
return json.loads(self.text)
def __eq__(self, other: object) -> bool:
if not isinstance(other, self.__class__):
return NotImplemented # pragma: no cover
return (
self.status_code == other.status_code
and self.text == other.text
and self.headers == other.headers
and self.url == other.url
)
def __str__(self):
return (
f"<Response [status_code={self.status_code}, "
f"text={self.text}, "
f"headers={self.headers}, "
f"url={self.url}]>"
)
| apache-2.0 | -5,366,735,543,725,622,000 | 27.133333 | 85 | 0.555292 | false | 4.083871 | false | false | false |
Nexenta/JujuCharm | nexentaedge/steps/nedeployPrecheck.py | 1 | 3257 | import re
import subprocess
from nexentaedge.settings import Settings
from nexentaedge.nedgeBlockerException import NedgeBlockerException
from baseConfigurationStep import BaseConfigurationStep
blocker_patterns = ['^.*(Less\s+then\s+\d+.*disks)$',
'^.*(Interface.*missing).*$',
'^.*(Network interface too slow)$',
'^.*(Not enough RAM memory.*GB).*$'
]
class NedeployPrecheck(BaseConfigurationStep):
def __init__(self):
pass
def process(self, environment):
neadmCmd = self.create_precheck_cmd(environment)
print("NEDEPLOY cmd is: {0}".format(' '.join(neadmCmd)))
try:
subprocess.check_output(neadmCmd,
stderr=subprocess.STDOUT,
universal_newlines=True)
except subprocess.CalledProcessError as ex:
print(" OUTPUT:\n{}".format(ex.output))
blockers = self.get_blockers(ex.output)
raise NedgeBlockerException(blockers)
def get_blockers(self, error_output):
results = []
for pattern in blocker_patterns:
m = re.search(pattern, error_output, re.MULTILINE)
if m:
results.append(m.group(1))
print('MATCHED {}'.format(m.group(1)))
return results
def create_precheck_cmd(self, environment):
node_private_ip = environment['node_private_ip']
node_type = environment['node_type']
replicast_eth = environment['replicast_eth']
nodocker = environment['nodocker']
profile = environment['profile']
exclude = environment['exclude']
reserved = environment['reserved']
print("\tnode_private_ip : {}".format(node_private_ip))
print("\tnode_type : {}".format(node_type))
print("\treplicast_eth : {}".format(replicast_eth))
print("\tnodocker : {}".format(nodocker))
print("\tprofile : {}".format(profile))
print("\texclude : {}".format(exclude))
print("\treserved : {}".format(reserved))
neadmCmd = [Settings.NEDEPLOY_CMD, 'precheck',
node_private_ip, 'root:nexenta', '-i',
replicast_eth]
if node_type == 'mgmt':
neadmCmd.append('-m')
activation_key = environment['nedge_activation_key']
if not activation_key:
raise NedgeBlockerException(['No activation key is provided'])
elif node_type == 'gateway':
# ADD GATEWAY parameter to deploy solo cmd
print("Gateway type selected!! ")
# profile section
neadmCmd.append('-t')
if profile.lower() == 'balanced':
neadmCmd.append('balanced')
elif profile.lower() == 'performance':
neadmCmd.append('performance')
else:
neadmCmd.append('capacity')
if nodocker is True:
neadmCmd.append('--nodocker')
if exclude:
neadmCmd.append('-x')
neadmCmd.append(exclude)
if reserved:
neadmCmd.append('-X')
neadmCmd.append(reserved)
return neadmCmd
| apache-2.0 | -7,315,549,671,154,198,000 | 32.927083 | 78 | 0.559718 | false | 4.308201 | false | false | false |
shaochangbin/crosswalk | app/tools/android/compress_js_and_css.py | 1 | 1535 | #!/usr/bin/env python
# Copyright (c) 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import fnmatch
import os
import stat
import subprocess
def GetJARFilename():
# Version of YUI Compressor.
version = "2.4.8"
# yuicompressor-*.jar was gotten from http://yui.github.io/yuicompressor/.
file_name = "yuicompressor-%s.jar" % version
cur_dir = os.path.realpath(os.path.dirname(__file__))
return os.path.join(cur_dir, "libs", file_name)
def GetFileList(path, ext, sub_dir = True):
if os.path.exists(path):
file_list = []
for name in os.listdir(path):
full_name = os.path.join(path, name)
st = os.lstat(full_name)
if stat.S_ISDIR(st.st_mode) and sub_dir:
file_list += GetFileList(full_name, ext)
elif os.path.isfile(full_name):
if fnmatch.fnmatch(full_name, ext):
file_list.append(full_name)
return file_list
else:
return []
def ExecuteCmd(path, ext):
file_list = GetFileList(path, "*." + ext)
for file_full_path in file_list:
if os.path.exists(file_full_path):
cmd_args = ["java", "-jar", GetJARFilename(), "--type=" + ext,
file_full_path, "-o", file_full_path]
subprocess.call(cmd_args)
class CompressJsAndCss(object):
def __init__(self, input_path):
self.input_path = input_path
def CompressJavaScript(self):
ExecuteCmd(self.input_path, "js")
def CompressCss(self):
ExecuteCmd(self.input_path, "css")
| bsd-3-clause | 4,080,109,300,917,108,000 | 29.098039 | 76 | 0.660586 | false | 3.11359 | false | false | false |
mitschabaude/nanopores | scripts/numerics/diffusion_with_force_profile.py | 1 | 4313 | """
TODO:
-) understand no boundary condition
-) validate understanding with analytical solution
"""
import nanopores, dolfin, os
from nanopores.physics.simplepnps import SimpleNernstPlanckProblem
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import force_profiles
from collections import defaultdict
nanopores.add_params(
savefig = False
)
class DiffusionProblem1D(SimpleNernstPlanckProblem):
method = SimpleNernstPlanckProblem.method
method["iterative"] = False
@staticmethod
def initial_u(V, c0):
u = dolfin.Function(V)
u.interpolate(dolfin.Constant(c0))
return u
@staticmethod
def forms(V, geo, phys, F):
dx = geo.dx()
grad = phys.grad
kT = dolfin.Constant(phys.kT)
D = dolfin.Constant(Dtarget(phys.rTarget))
lscale = dolfin.Constant(phys.lscale)
n = dolfin.FacetNormal(geo.mesh)
c = dolfin.TrialFunction(V)
d = dolfin.TestFunction(V)
FF = dolfin.as_vector([F])
J = -D*grad(c) + D/kT*FF*c
a = dolfin.inner(J, grad(d))*dx
L = dolfin.Constant(0.)*d*dx
aNoBC = -lscale*dolfin.inner(J, n*d)*geo.ds("bottom")
a += aNoBC
return a, L
@staticmethod
def bcs(V, geo, c0):
bc = dict(
top = c0,
#bottom = c0,
)
return geo.pwBC(V, "c0", value=bc)
def current(geo, phys, c, F):
dx = geo.dx()
grad = phys.grad
lscale = phys.lscale
mol = phys.mol
kT = dolfin.Constant(phys.kT)
D = dolfin.Constant(Dtarget(phys.rTarget))
FF = dolfin.as_vector([F])
print "v = %s" % (Dtarget(phys.rTarget)*F(0.)/phys.kT,)
j = -D*grad(c) + D/kT*FF*c
#dolfin.plot(j)
#dolfin.interactive()
L = 20.
r0 = 1./lscale
Across = r0**2 * dolfin.pi
# current in N/s
J = mol * Across * dolfin.assemble(j[0]/dolfin.Constant(L) * dx)
# current in N/ms
J = J * 1e-3
return J
def Dtarget(r):
return nanopores.kT/(6*dolfin.pi*nanopores.eta*r)
def J_FEM(F, c0):
geo = force_profiles.geo
phys = nanopores.Physics(geo=geo, rTarget=rMol*1e-9, lscale=1e9)
pde = nanopores.solve_pde(DiffusionProblem1D, geo=geo, phys=phys,
F=F, c0=c0, verbose=False)
c = pde.solution
return c, current(geo, phys, c, F)
def gather_currents(name, c0):
currents = defaultdict(list)
qmols = []
for results in force_profiles.Forces(name):
qmols.append(results["Q"])
for key in "F", "Fi", "Fi2":
f = results[key]
f = force_profiles.function_from_lambda(lambda z: 1e-12*f(z))
u, J = J_FEM(f, c0)
currents[key].append(J)
#force_profiles.plot_function(f, label="Q="+str(Q))
#if key=="F":
# force_profiles.plot_function(u, label="Q="+str(results["Q"]))
print "Q %s, J %s, Ji %s, Jib %s" % (
qmols[-1], currents["F"][-1], currents["Fi"][-1], currents["Fi2"][-1])
return qmols, currents
c0 = 1.6605 # [mol/m**3] = 1 molecule per (10nm)**3
#names = {0.25: "r025", 0.5: "r05", 0.2: "r02", 0.4: "r04", 0.75: "r075"}
items = (0.25, "r025"), (0.5, "r05"), (0.75, "r075")
figures = os.path.expanduser("~") + "/papers/pnps-numerics/figures/"
for rMol, name in items:
#plt.figure()
qmols, currents = gather_currents(name, c0)
#plt.legend()
fig, ax = plt.subplots()
ax.plot(qmols, currents["F"], "s-g", label="finite")
ax.plot(qmols, currents["Fi"], "s-b", label="point")
ax.plot(qmols, currents["Fi2"], "s-r", label="point, corrected")
#ax.set_aspect('equal')
tick_spacing = 1.
ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
#ax.set_ylim([-0.4, 0.]) #xaxis.set_ticks(np.arange(start, end, 0.712123))
#ax.grid(True, which='both')
#ax.axhline(y=0, color='#cccccc')
plt.title("r = %s" %rMol)
plt.xlabel("Molecule charge [q]")
plt.ylabel("Molecule current [1/ms]")
plt.legend()
if savefig:
fig = plt.gcf()
fig.set_size_inches(5, 4)
plt.savefig(figures + "molcurrent_r%.2f.eps" % rMol, bbox_inches='tight')
#plt.show()
| mit | -9,171,758,129,615,507,000 | 28.340136 | 81 | 0.566659 | false | 2.830052 | false | false | false |
dpazel/music_rep | structure/beam.py | 1 | 4540 | """
File: beam.py
Purpose: Defines the Beam note construct.
"""
from structure.abstract_note_collective import AbstractNoteCollective
from structure.note import Note
from structure.tuplet import Tuplet
from fractions import Fraction
from timemodel.duration import Duration
class Beam(AbstractNoteCollective):
"""
Beam is a grouping operation, having a set scaling ratio of 1/2, but unbounded aggregate duration.
The basic idea of a beam is that for a stand alone beam, you can only add Note's of duration 1/4 or less.
That duration is retained under the beam.
However when a beam is added to a beam, it takes an additional reduction factor of 1/2.
Note that these factors aggregate multiplicatively through self.contextual_reduction_factor
"""
FACTOR = Fraction(1, 2)
NOTE_QUALIFIER_DURATION = Duration(1, 4)
def __init__(self, abstract_note_list=list()):
"""
Constructor
Args:
abstract_note_list: list of notes, beams, and tuplets to add consecutively under the beam.
"""
AbstractNoteCollective.__init__(self)
self.append(abstract_note_list)
@property
def duration(self):
"""
This is an override of AbstractNoteCollective.duration.
Tuplet and Beam override this to do a simple summation of linearly laid out notes and sub-notes.
The reason is that the layout algorithm of these subclasses cannot use the relative_position
attribute as the algorithm determines that.
"""
d = Duration(0)
for note in self.sub_notes:
d += note.duration
return d
def append(self, notes):
"""
Append a set of abstract notes to the beam
Args:
notes: either a list of notes or a single note to add to the beam.
"""
if isinstance(notes, list):
for n in notes:
self.append(n)
return
elif isinstance(notes, Note) or isinstance(notes, AbstractNoteCollective):
self.add(notes, len(self.sub_notes))
def add(self, note, index):
"""
Beams can only add less than 1/4 notes, and arbitrary beams and tuplets.
Only added beams incur a reduction factor of 1/2
For collective notes, always apply the factor.
"""
if note.parent is not None:
raise Exception('Cannot add note already assigned a parent')
if index < 0 or index > len(self.sub_notes):
raise Exception('add note, index {0} not in range[0, {1}]'.format(index, len(self.sub_notes)))
if isinstance(note, Note):
if note.base_duration >= Duration(1, 4):
raise Exception(
"Attempt to add note with duration {0} greater than or equal to {1}".
format(note.duration, Beam.NOTE_QUALIFIER_DURATION))
new_factor = self.contextual_reduction_factor
elif isinstance(note, Beam):
new_factor = self.contextual_reduction_factor * Beam.FACTOR
elif isinstance(note, Tuplet):
new_factor = self.contextual_reduction_factor
else:
raise Exception('illegal type {0}'.format(type(note)))
self.sub_notes.insert(index, note)
note.parent = self
note.apply_factor(new_factor)
# The following call will adjust layout from this point right upward
self.upward_forward_reloc_layout(note)
# see if prior note is tied, and if so, break the tie.
first_note = note
if not isinstance(note, Note):
first_note = note.get_first_note()
# If empty beam or tuplet is added, there is nothing to look for in terms of ties.
if first_note is None:
return
prior = first_note.prior_note()
if prior is not None and prior.is_tied_to:
prior.untie()
# notify up the tree of what has changed
self.notes_added([note])
def __str__(self):
base = 'Beam(Dur({0})Off({1})f={2})'.format(self.duration, self.relative_position,
self.contextual_reduction_factor)
s = base + '[' + (']' if len(self.sub_notes) == 0 else '\n')
for n in self.sub_notes:
s += ' ' + str(n) + '\n'
s += ']' if len(self.sub_notes) != 0 else ''
return s
| mit | -7,834,370,034,548,237,000 | 37.151261 | 111 | 0.593392 | false | 4.223256 | false | false | false |
jolicode/slack-secret-santa | tasks.py | 1 | 8811 | from invoke import task
from shlex import quote
from colorama import Fore
import json
import os
import re
import requests
import subprocess
@task
def build(c):
"""
Build the infrastructure
"""
command = 'build'
command += ' --build-arg PROJECT_NAME=%s' % c.project_name
command += ' --build-arg USER_ID=%s' % c.user_id
with Builder(c):
for service in c.services_to_build_first:
docker_compose(c, '%s %s' % (command, service))
docker_compose(c, command)
@task
def up(c):
"""
Build and start the infrastructure
"""
build(c)
docker_compose(c, 'up --remove-orphans --detach')
@task
def start(c):
"""
Build and start the infrastructure, then install the application (composer, yarn, ...)
"""
if c.dinghy:
machine_running = c.run('dinghy status', hide=True).stdout
if machine_running.splitlines()[0].strip() != 'VM: running':
c.run('dinghy up --no-proxy')
c.run('docker-machine ssh dinghy "echo \'nameserver 8.8.8.8\' | sudo tee -a /etc/resolv.conf && sudo /etc/init.d/docker restart"')
stop_workers(c)
up(c)
cache_clear(c)
install(c)
migrate(c)
start_workers(c)
print(Fore.GREEN + 'The stack is now up and running.')
help(c)
@task
def install(c):
"""
Install the application (composer, yarn, ...)
"""
with Builder(c):
if os.path.isfile(c.root_dir + '/' + c.project_directory + '/composer.json'):
docker_compose_run(c, 'composer install -n --prefer-dist --optimize-autoloader', no_deps=True)
if os.path.isfile(c.root_dir + '/' + c.project_directory + '/yarn.lock'):
run_in_docker_or_locally_for_dinghy(c, 'yarn', no_deps=True)
elif os.path.isfile(c.root_dir + '/' + c.project_directory + '/package.json'):
run_in_docker_or_locally_for_dinghy(c, 'npm install', no_deps=True)
@task
def cache_clear(c):
"""
Clear the application cache
"""
# with Builder(c):
# docker_compose_run(c, 'rm -rf var/cache/ && php bin/console cache:warmup', no_deps=True)
@task
def migrate(c):
"""
Migrate database schema
"""
# with Builder(c):
# docker_compose_run(c, 'php bin/console doctrine:database:create --if-not-exists')
# docker_compose_run(c, 'php bin/console doctrine:migration:migrate -n --allow-no-migration')
@task
def builder(c, user="app"):
"""
Open a shell (bash) into a builder container
"""
with Builder(c):
docker_compose_run(c, 'bash', user=user, bare_run=True)
@task
def logs(c):
"""
Display infrastructure logs
"""
docker_compose(c, 'logs -f --tail=150')
@task
def ps(c):
"""
List containers status
"""
docker_compose(c, 'ps --all')
@task
def stop(c):
"""
Stop the infrastructure
"""
docker_compose(c, 'stop')
@task
def tests(c):
"""
Launch tests
"""
with Builder(c):
docker_compose_run(c, 'bin/phpunit')
@task
def qa(c):
"""
Run static analysis tools
"""
with Builder(c):
# Make tests analyses working with Symfony's PHPUnit bridge
docker_compose_run(c, 'vendor/bin/simple-phpunit install', no_deps=True)
docker_compose_run(c, 'vendor/bin/phpstan analyse', no_deps=True)
@task
def cs(c, dry_run=False):
"""
Fix coding standards in code
"""
with Builder(c):
if dry_run:
docker_compose_run(c, 'vendor/bin/php-cs-fixer fix --config=.php_cs --dry-run --diff', no_deps=True)
else:
docker_compose_run(c, 'vendor/bin/php-cs-fixer fix --config=.php_cs', no_deps=True)
docker_compose_run(c, 'pycodestyle --ignore=E501,W605,E722 invoke.py tasks.py', no_deps=True)
@task
def start_workers(c):
"""
Start the workers
"""
workers = get_workers(c)
if (len(workers) == 0):
return
c.start_workers = True
c.run('docker update --restart=unless-stopped %s' % (' '.join(workers)), hide='both')
docker_compose(c, 'up --remove-orphans --detach')
@task
def stop_workers(c):
"""
Stop the workers
"""
workers = get_workers(c)
if (len(workers) == 0):
return
c.start_workers = False
c.run('docker update --restart=no %s' % (' '.join(workers)), hide='both')
c.run('docker stop %s' % (' '.join(workers)), hide='both')
@task
def destroy(c, force=False):
"""
Clean the infrastructure (remove container, volume, networks)
"""
if not force:
ok = confirm_choice('Are you sure? This will permanently remove all containers, volumes, networks... created for this project.')
if not ok:
return
with Builder(c):
docker_compose(c, 'down --remove-orphans --volumes --rmi=local')
@task(default=True)
def help(c):
"""
Display some help and available urls for the current project
"""
print('Run ' + Fore.GREEN + 'inv help' + Fore.RESET + ' to display this help.')
print('')
print('Run ' + Fore.GREEN + 'inv --help' + Fore.RESET + ' to display invoke help.')
print('')
print('Run ' + Fore.GREEN + 'inv -l' + Fore.RESET + ' to list all the available tasks.')
c.run('inv --list')
print(Fore.GREEN + 'Available URLs for this project:' + Fore.RESET)
for domain in [c.root_domain] + c.extra_domains:
print("* " + Fore.YELLOW + "https://" + domain + Fore.RESET)
try:
response = json.loads(requests.get('http://%s:8080/api/http/routers' % (c.root_domain)).text)
gen = (router for router in response if re.match("^%s-(.*)@docker$" % (c.project_name), router['name']))
for router in gen:
if router['service'] != 'frontend-%s' % (c.project_name):
host = re.search('Host\(\`(?P<host>.*)\`\)', router['rule']).group('host')
if host:
scheme = 'https' if 'https' in router['using'] else router['using'][0]
print("* " + Fore.YELLOW + scheme + "://" + host + Fore.RESET)
print('')
except:
pass
def run_in_docker_or_locally_for_dinghy(c, command, no_deps=False):
"""
Mac users have a lot of problems running Yarn / Webpack on the Docker stack so this func allow them to run these tools on their host
"""
if c.dinghy:
with c.cd(c.project_directory):
c.run(command)
else:
docker_compose_run(c, command, no_deps=no_deps)
def docker_compose_run(c, command_name, service="builder", user="app", no_deps=False, workdir=None, port_mapping=False, bare_run=False):
args = [
'run',
'--rm',
'-u %s' % quote(user),
]
if no_deps:
args.append('--no-deps')
if port_mapping:
args.append('--service-ports')
if workdir is not None:
args.append('-w %s' % quote(workdir))
docker_compose(c, '%s %s /bin/sh -c "exec %s"' % (
' '.join(args),
quote(service),
command_name
), bare_run=bare_run)
def docker_compose(c, command_name, bare_run=False):
domains = '`' + '`, `'.join([c.root_domain] + c.extra_domains) + '`'
# This list should be in sync with the one in invoke.py
env = {
'PROJECT_NAME': c.project_name,
'PROJECT_DIRECTORY': c.project_directory,
'PROJECT_ROOT_DOMAIN': c.root_domain,
'PROJECT_DOMAINS': domains,
'PROJECT_START_WORKERS': str(c.start_workers),
'COMPOSER_CACHE_DIR': c.composer_cache_dir,
}
cmd = 'docker-compose -p %s %s %s' % (
c.project_name,
' '.join('-f "' + c.root_dir + '/infrastructure/docker/' + file + '"' for file in c.docker_compose_files),
command_name
)
# bare_run bypass invoke run() function
# see https://github.com/pyinvoke/invoke/issues/744
# Use it ONLY for task where you need to interact with the container like builder
if (bare_run):
env.update(os.environ)
subprocess.run(cmd, shell=True, env=env)
else:
c.run(cmd, pty=not c.power_shell, env=env)
def get_workers(c):
"""
Find worker containers for the current project
"""
cmd = c.run('docker ps -a --filter "label=docker-starter.worker.%s" --quiet' % c.project_name, hide='both')
return list(filter(None, cmd.stdout.rsplit("\n")))
def confirm_choice(message):
confirm = input('%s [y]es or [N]o: ' % message)
return re.compile('^y').search(confirm)
class Builder:
def __init__(self, c):
self.c = c
def __enter__(self):
self.docker_compose_files = self.c.docker_compose_files
self.c.docker_compose_files = ['docker-compose.builder.yml'] + self.docker_compose_files
def __exit__(self, type, value, traceback):
self.c.docker_compose_files = self.docker_compose_files
| mit | 2,870,649,700,403,755,000 | 26.194444 | 142 | 0.590852 | false | 3.346373 | false | false | false |
PrincessTeruko/TsunArt | posts/views.py | 1 | 1114 | from django.conf import settings
from django.contrib.auth.forms import AuthenticationForm
from django.core.urlresolvers import reverse
from django.db.models import Count
from django.http import Http404, HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.csrf import ensure_csrf_cookie
from core.common import *
from posts.forms import PostForm
from posts.models import Post
from users.models import User
@ensure_csrf_cookie
def post_form(request, post_id=None):
user = User.objects.get(user=request.user)
post = Post.objects.get(pk=post_id)
if user == post.author:
form = PostForm(instance=post, request=request)
else:
return reject_user()
return render(request, 'posts/edit.html', {
'settings': settings,
'user': user,
'title': 'Edit ' + post.title,
'post': post,
'form': form,
})
@ensure_csrf_cookie
def gallery(request, query=None):
return render(request, 'posts/booru.html', {
'settings': settings,
'user': get_user(request.user),
'posts': Post.objects.exclude(media=False, hidden=False),
})
| mit | 6,976,874,274,254,265,000 | 28.315789 | 67 | 0.745961 | false | 3.266862 | false | false | false |
GDGLima/contentbox | third_party/search/views.py | 13 | 2007 | from django.conf import settings
from djangotoolbox.http import JSONResponse
def live_search_results(request, model, search_index='search_index', limit=30,
result_item_formatting=None, query_converter=None,
converter=None, redirect=False):
"""
Performs a search in searched_model and prints the results as
text, so it can be used by auto-complete scripts.
limit indicates the number of results to be returned.
A JSON file is sent to the browser. It contains a list of
objects that are created by the function indicated by
the parameter result_item_formatting. It is executed for every result
item.
Example:
result_item_formatting=lambda course: {
'value': course.name + '<br />Prof: ' + course.prof.name,
'result': course.name + ' ' + course.prof.name,
'data': redirect=='redirect' and
{'link': course.get_absolute_url()} or {},
}
"""
query = request.GET.get('query', '')
try:
limit_override = int(request.GET.get('limit', limit))
if limit_override < limit:
limit = limit_override
except:
pass
search_index = getattr(model, search_index)
language = getattr(request, 'LANGUAGE_CODE', settings.LANGUAGE_CODE)
results = search_index.search(query, language=language)
if query_converter:
results = query_converter(request, results)
results = results[:limit]
if converter:
results = converter(results)
data = []
for item in results:
if result_item_formatting:
entry = result_item_formatting(item)
else:
value = getattr(item, search_index.fields_to_index[0])
entry = {'value': force_escape(value), 'result': value}
if 'data' not in entry:
entry['data'] = {}
if redirect:
if 'link' not in entry['data']:
entry['data']['link'] = item.get_absolute_url()
data.append(entry)
return JSONResponse(data) | apache-2.0 | -635,962,334,027,517,400 | 36.886792 | 78 | 0.627304 | false | 4.087576 | false | false | false |
ctrlrsf/cloudflare2loggly | sftplib.py | 1 | 2067 | """
Simple SFTP client using Paramiko
"""
from __future__ import print_function
import logging
import paramiko
LOG = logging.getLogger('sftplib')
class SFTPClient(object):
"""
Simple SFTP client using Paramiko
"""
def __init__(self, hostname, port, username, key_file):
"""
Create the SFTPLib object for connection
"""
self.sftp = None
self.transport = None
self.hostname = hostname
self.port = port
self.username = username
self.key_file = key_file
def login(self):
"""
Log into SFTP server and establish the connection
"""
try:
rsa_key = paramiko.RSAKey.from_private_key_file(self.key_file)
self.transport = paramiko.Transport((self.hostname, self.port))
self.transport.connect(username=self.username, pkey=rsa_key)
self.sftp = paramiko.SFTPClient.from_transport(self.transport)
except Exception as exception:
print('Caught exception: {}'.format(exception))
LOG.error('Caught exception: %s', exception)
self.transport.close()
def list_files(self):
"""
Get list of files on SFTP server
"""
file_list = self.sftp.listdir('.')
return file_list
def get_file(self, remotename, dst_dir):
"""
Download file from SFTP server
"""
try:
self.sftp.get(remotename, dst_dir)
return True
except Exception as exception:
LOG.error("Exception raised: %s", exception)
return False
def remove_file(self, remotename):
"""
Delete a file on the remote server
"""
try:
self.sftp.remove(remotename)
return True
except Exception as exception:
LOG.error("Exception raised: %s", exception)
return False
def close(self):
"""
Close the SFTP connection
"""
self.sftp.close()
self.transport.close()
| mit | 3,358,563,962,904,878,000 | 26.197368 | 75 | 0.568457 | false | 4.416667 | false | false | false |
dhp-denero/LibrERP | l10n_sale_report/ddt.py | 2 | 6515 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2011 Associazione OpenERP Italia
# (<http://www.openerp-italia.org>).
# Copyright (C) 2014 Didotech SRL
# All Rights Reserved
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from openerp.report import report_sxw
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT
from datetime import datetime
class Parser(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(Parser, self).__init__(cr, uid, name, context)
self.localcontext.update({
'time': time,
'raggruppa': self._raggruppa,
'raggruppaddt': self._raggruppaddt,
'righe': self._righe,
'righeddt': self._righeddt,
'indirizzo': self._indirizzo,
'div': self._div,
'italian_number': self._get_italian_number,
'pallet_sum': self._get_pallet_sum,
'get_description': self._get_description,
})
def _get_description(self, order_name):
order_obj = self.pool['sale.order']
description = []
if order_name and not self.pool['res.users'].browse(
self.cr, self.uid, self.uid).company_id.disable_sale_ref_invoice_report:
order_ids = order_obj.search(self.cr, self.uid, [('name', '=', order_name)])
if len(order_ids) == 1:
order = order_obj.browse(self.cr, self.uid, order_ids[0])
order_date = datetime.strptime(order.date_order, DEFAULT_SERVER_DATE_FORMAT)
if order.client_order_ref:
description.append(u'Rif. Ns. Ordine {order} del {order_date}, Vs. Ordine {client_order}'.format(order=order.name, order_date=order_date.strftime("%d/%m/%Y"), client_order=order.client_order_ref))
else:
description.append(u'Rif. Ns. Ordine {order} del {order_date}'.format(order=order.name, order_date=order_date.strftime("%d/%m/%Y")))
return ' / '.join(description)
def _div(self, up, down):
res = 0
if down:
res = up / down
return res
def _get_italian_number(self, number, precision=2, no_zero=False):
if not number and no_zero:
return ''
elif not number:
return '0,00'
if number < 0:
sign = '-'
else:
sign = ''
## Requires Python >= 2.7:
#before, after = "{:.{digits}f}".format(number, digits=precision).split('.')
## Works with Python 2.6:
if precision:
before, after = "{0:10.{digits}f}".format(number, digits=precision).strip('- ').split('.')
else:
before = "{0:10.{digits}f}".format(number, digits=precision).strip('- ').split('.')[0]
after = ''
belist = []
end = len(before)
for i in range(3, len(before) + 3, 3):
start = len(before) - i
if start < 0:
start = 0
belist.append(before[start: end])
end = len(before) - i
before = '.'.join(reversed(belist))
if no_zero and int(number) == float(number) or precision == 0:
return sign + before
else:
return sign + before + ',' + after
def _raggruppa(self, righe_fattura):
indice_movimenti = {}
movimenti_filtrati = []
for riga in righe_fattura:
if riga.origin in indice_movimenti and riga.origin in indice_movimenti[riga.origin]:
print riga
print riga.origin
else:
if riga.origin:
print 'Riga Buona'
if riga.ddt_origin in indice_movimenti:
indice_movimenti[riga.ddt_origin][riga.sale_origin] = riga.sale_origin
else:
indice_movimenti[riga.ddt_origin] = {riga.sale_origin: riga.sale_origin}
movimenti_filtrati.append(riga)
else:
continue
print indice_movimenti
print movimenti_filtrati
return movimenti_filtrati
def _righe(self, righe_fattura, filtro):
righe_filtrate = []
print filtro
print righe_fattura
for riga in righe_fattura:
if ((riga.origin == filtro.origin)):
righe_filtrate.append(riga)
return righe_filtrate
def _raggruppaddt(self, righe_ddt):
indice_movimenti = {}
movimenti_filtrati = []
print righe_ddt
for riga in righe_ddt:
if riga.origin in indice_movimenti:
print riga.origin
else:
indice_movimenti[riga.origin] = riga.origin
movimenti_filtrati.append(riga)
print indice_movimenti
return movimenti_filtrati
def _righeddt(self, righe_ddt, filtro):
righe_filtrate = []
print filtro
print righe_ddt
for riga in righe_ddt:
if riga.origin == filtro.origin:
righe_filtrate.append(riga)
return righe_filtrate
def _indirizzo(self, partner):
address = self.pool['res.partner'].address_get(self.cr, self.uid, [partner.id], ['default', 'invoice'])
return self.pool['res.partner.address'].browse(self.cr, self.uid, address['invoice'] or address['default'])
def _get_pallet_sum(self, product_ul_id, partner_id):
pallet_sum = self.pool['product.ul'].get_pallet_sum(
self.cr, self.uid, [product_ul_id], 'pallet_sum', None, context={'partner_id': partner_id}
)
return pallet_sum[product_ul_id]
| agpl-3.0 | -3,769,366,328,522,302,500 | 39.216049 | 216 | 0.560246 | false | 3.629526 | false | false | false |
ptisserand/ansible | lib/ansible/modules/windows/win_chocolatey.py | 7 | 7785 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2014, Trond Hindenes <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_chocolatey
version_added: "1.9"
short_description: Manage packages using chocolatey
description:
- Manage packages using Chocolatey (U(http://chocolatey.org/)).
- If Chocolatey is missing from the system, the module will install it.
- List of packages can be found at U(http://chocolatey.org/packages).
requirements:
- chocolatey >= 0.10.5 (will be upgraded if older)
options:
name:
description:
- Name of the package to be installed.
- This must be a single package name.
required: yes
state:
description:
- State of the package on the system.
choices:
- absent
- downgrade
- latest
- present
- reinstalled
default: present
force:
description:
- Forces install of the package (even if it already exists).
- Using C(force) will cause ansible to always report that a change was made.
type: bool
default: 'no'
upgrade:
description:
- If package is already installed it, try to upgrade to the latest version or to the specified version.
- As of Ansible v2.3 this is deprecated, set parameter C(state) to C(latest) for the same result.
type: bool
default: 'no'
version:
description:
- Specific version of the package to be installed.
- Ignored when C(state) is set to C(absent).
source:
description:
- Specify source rather than using default chocolatey repository.
install_args:
description:
- Arguments to pass to the native installer.
version_added: '2.1'
params:
description:
- Parameters to pass to the package
version_added: '2.1'
allow_empty_checksums:
description:
- Allow empty checksums to be used.
type: bool
default: 'no'
version_added: '2.2'
ignore_checksums:
description:
- Ignore checksums altogether.
type: bool
default: 'no'
version_added: '2.2'
ignore_dependencies:
description:
- Ignore dependencies, only install/upgrade the package itself.
type: bool
default: 'no'
version_added: '2.1'
timeout:
description:
- The time to allow chocolatey to finish before timing out.
default: 2700
version_added: '2.3'
aliases: [ execution_timeout ]
skip_scripts:
description:
- Do not run I(chocolateyInstall.ps1) or I(chocolateyUninstall.ps1) scripts.
type: bool
default: 'no'
version_added: '2.4'
proxy_url:
description:
- Proxy url used to install chocolatey and the package.
version_added: '2.4'
proxy_username:
description:
- Proxy username used to install chocolatey and the package.
- When dealing with a username with double quote characters C("), they
need to be escaped with C(\) beforehand. See examples for more details.
version_added: '2.4'
proxy_password:
description:
- Proxy password used to install chocolatey and the package.
- See notes in C(proxy_username) when dealing with double quotes in a
password.
version_added: '2.4'
allow_prerelease:
description:
- Allow install of prerelease packages.
- If state C(state) is C(latest) the highest prerelease package will be installed.
type: bool
default: 'no'
version_added: '2.6'
notes:
- Provide the C(version) parameter value as a string (e.g. C('6.1')), otherwise it
is considered to be a floating-point number and depending on the locale could
become C(6,1), which will cause a failure.
- When using verbosity 2 or less (C(-vv)) the C(stdout) output will be restricted.
- When using verbosity 4 (C(-vvvv)) the C(stdout) output will be more verbose.
- When using verbosity 5 (C(-vvvvv)) the C(stdout) output will include debug output.
- This module will install or upgrade Chocolatey when needed.
- Some packages need an interactive user logon in order to install. You can use (C(become)) to achieve this.
- Even if you are connecting as local Administrator, using (C(become)) to become Administrator will give you an interactive user logon, see examples below.
- Use (M(win_hotfix) to install hotfixes instead of (M(win_chocolatey)) as (M(win_hotfix)) avoids using wusa.exe which cannot be run remotely.
author:
- Trond Hindenes (@trondhindenes)
- Peter Mounce (@petemounce)
- Pepe Barbe (@elventear)
- Adam Keech (@smadam813)
- Pierre Templier (@ptemplier)
'''
# TODO:
# * Better parsing when a package has dependencies - currently fails
# * Time each item that is run
# * Support 'changed' with gems - would require shelling out to `gem list` first and parsing, kinda defeating the point of using chocolatey.
# * Version provided not as string might be translated to 6,6 depending on Locale (results in errors)
EXAMPLES = r'''
- name: Install git
win_chocolatey:
name: git
state: present
- name: Upgrade installed packages
win_chocolatey:
name: all
state: latest
- name: Install notepadplusplus version 6.6
win_chocolatey:
name: notepadplusplus.install
version: '6.6'
- name: Install git from specified repository
win_chocolatey:
name: git
source: https://someserver/api/v2/
- name: Uninstall git
win_chocolatey:
name: git
state: absent
- name: Install multiple packages
win_chocolatey:
name: '{{ item }}'
state: present
with_items:
- procexp
- putty
- windirstat
- name: uninstall multiple packages
win_chocolatey:
name: '{{ item }}'
state: absent
with_items:
- procexp
- putty
- windirstat
- name: Install curl using proxy
win_chocolatey:
name: curl
proxy_url: http://proxy-server:8080/
proxy_username: joe
proxy_password: p@ssw0rd
- name: Install curl with proxy credentials that contain quotes
win_chocolatey:
name: curl
proxy_url: http://proxy-server:8080/
proxy_username: user with \"escaped\" double quotes
proxy_password: pass with \"escaped\" double quotes
- name: Install a package that requires 'become'
win_chocolatey:
name: officepro2013
become: yes
become_user: Administrator
become_method: runas
'''
RETURN = r'''
choco_bootstrap_output:
description: DEPRECATED, will be removed in 2.6, use stdout instead.
returned: changed, choco task returned a failure
type: str
sample: Chocolatey upgraded 1/1 packages.
choco_error_cmd:
description: DEPRECATED, will be removed in 2.6, use command instead.
returned: changed, choco task returned a failure
type: str
sample: choco.exe install -r --no-progress -y sysinternals --timeout 2700 --failonunfound
choco_error_log:
description: DEPRECATED, will be removed in 2.6, use stdout instead.
returned: changed, choco task returned a failure
type: str
sample: sysinternals not installed. The package was not found with the source(s) listed
command:
description: The full command used in the chocolatey task.
returned: changed
type: str
sample: choco.exe install -r --no-progress -y sysinternals --timeout 2700 --failonunfound
rc:
description: The return code from the chocolatey task.
returned: changed
type: int
sample: 0
stdout:
description: The stdout from the chocolatey task. The verbosity level of the
messages are affected by Ansible verbosity setting, see notes for more
details.
returned: changed
type: str
sample: Chocolatey upgraded 1/1 packages.
'''
| gpl-3.0 | 2,074,543,620,453,216,000 | 30.77551 | 155 | 0.694798 | false | 3.632758 | false | false | false |
alice1017/gitTools | git-ref.py | 1 | 5307 | #!/usr/bin/env python
#coding: utf-8
import sys
from util import core
from util import adjust
from util.git import *
from argparse import ArgumentParser, SUPPRESS
# usage
# git ref b81fe395c0bf28c4be8 -> ハッシュ[b81fe395c0bf28c4be8]の[hash値]を出力
# git ref tag -> タグ[tag]の[hash値]を出力
# git ref -t b81fe395c0bf28c4be8 -> ハッシュ[b81fe395c0bf28c4be8]の[type値]を出力
# git ref b81fe395c0bf28c4be8 --file git-todo.py -> ハッシュ[b81fe395c0bf28c4be8]の[git-todo.py]の[hash値]を出力
# git ref b81fe395c0bf28c4be8 --cat-file git-todo.py -> ハッシュ[b81fe395c0bf28c4be8]の[git-todo.py]の[中身]を出力
# git ref --ls HEAD -> コミット[HEAD]の[ls-tree -r]を表示
# git ref --detail HEAD -> コミット[HEAD]の[git show]を表示
parser = ArgumentParser(prog="git ref",
description="This script can show reference hash or files easyly.")
parser.add_argument("reference", action="store",
help="Please set hash of reference.\
If you not set other options, \
script show full hash value.")
parser.add_argument("-l", "--ls", action="store_true",
help="Show all files with hash in commit.")
parser.add_argument("-t", "--type", action="store_true",
help="Show type of hash.")
parser.add_argument("-f", "--file", action="store",
help="Show file object hash in commit.")
parser.add_argument("-p", "--pretty-print", action="store", dest="pretty_print",
metavar="FILE", help="Show file contents.")
class ArgumentNamespace:
def __setattr__(self, key, value):
self.__dict__[key] = value
def __repr__(self):
return "ArgumentNamespace(%s)" % ", ".join(
[k+"='%s'"%v for k,v in vars(self).iteritems()])
def is_only_ref(self):
"""Return True if there is only reference argument"""
if args.file == None and args.type == False and args.ls == False and args.pretty_print == None:
return True
def is_only_ls(self):
"""Return True if there is only --ls option"""
if args.ls == False:
return False
if args.ls == True:
if args.file == None and args.type == False and args.pretty_print == None:
return True
else:
parser.error("this option can't use concomitantly.")
def is_only_type(self):
"""Return True if there is only --type option"""
if args.type == False:
return False
if args.type == True:
if args.file == None and args.ls == False and args.pretty_print == None:
return True
else:
parser.error("this option can't use concomitantly.")
def is_only_file(self):
"""Return True is there is only --file option"""
if args.file == None:
return False
if args.file:
if args.type == False and args.ls == False and args.pretty_print == None:
return True
else:
parser.error("this option can't use concomitantly.")
def is_only_pretty_print(self):
"""Return True is there is only --pretty-print option"""
if args.pretty_print == None:
return False
if args.pretty_print:
if args.type == False and args.ls == False and args.file == None:
return True
else:
parser.error("this option can't use concomitantly.")
def check_ref(reference):
"""This function check reference whether it's valid ref, Return True"""
try:
# Run git rev-parse --verify [ref]
verified = git("rev-parse", "--verify", reference)
except:
# If it is invalid, Call error
parser.error("invalid reference.")
sys.exit(1)
return True
def main(args):
ref = args.reference
check_ref(ref)
# User set reference only
if args.is_only_ref():
print git("rev-parse", ref)
return 0
# User set --ls
elif args.is_only_ls():
print git("ls-tree", "-r", ref)
return 0
# User set --type
elif args.is_only_type():
print git("cat-file", "-t", ref)
return 0
# User set --file
elif args.is_only_file():
body = git("ls-tree", ref, args.file)
if len(body) == 0:
parser.error("%s file does not found." % args.file)
print body.split(" ")[-1].split("\t")[0]
return 0
# User set --pretty-print
elif args.is_only_pretty_print():
body = git("ls-tree", ref, args.pretty_print)
if len(body) == 0:
parser.error("%s file does not found." % args.file)
hash_var = body.split(" ")[-1].split("\t")[0]
print git("cat-file", "-p", hash_var)
return 0
if __name__ == "__main__":
if len(sys.argv) == 1:
parser.parse_args(["-h"])
#args = parser.parse_args()
args = parser.parse_args(namespace=ArgumentNamespace())
#print args
sys.exit(main(args))
| mit | 2,252,298,493,873,955,000 | 27.478022 | 108 | 0.549682 | false | 3.533061 | false | false | false |
Rekoc/EmmaWebSite | WebSite/models.py | 1 | 1364 | from django.db import models
# Create your models here.
class Article(models.Model):
titre = models.CharField(max_length=100)
auteur = models.CharField(max_length=42)
contenu = models.TextField(null=True)
date = models.DateTimeField(auto_now_add=True, auto_now=False,
verbose_name="Date de parution")
image_couverture = models.ImageField(upload_to="images_articles/")
image1 = models.ImageField(upload_to="images_articles/", blank=True)
image2 = models.ImageField(upload_to="images_articles/", blank=True)
image3 = models.ImageField(upload_to="images_articles/", blank=True)
image4 = models.ImageField(upload_to="images_articles/", blank=True)
image5 = models.ImageField(upload_to="images_articles/", blank=True)
image6 = models.ImageField(upload_to="images_articles/", blank=True)
categorie = models.ForeignKey('Categorie')
def __str__(self):
return self.titre
class Categorie(models.Model):
nom = models.CharField(max_length=30)
def __str__(self):
return self.nom
class Prices(models.Model):
titre = models.CharField(max_length=50)
english_title = models.CharField(max_length=50, default="NULL")
price = models.IntegerField(default=0)
category = models.BooleanField(default=False)
def __str__(self):
return self.titre
| gpl-3.0 | -6,574,491,940,388,614,000 | 35.864865 | 72 | 0.687683 | false | 3.618037 | false | false | false |
neil-davis/penfold | src/features/steps/plugin_steps.py | 1 | 1960 | import logging
from behave import given, when, then
from penfold import PenfoldPluginManager
from penfold import InputOutputFactory
log = logging.getLogger(__name__)
@then(u'execute the plugin')
def execute_the_plugin(context):
input_name1, input_value1 = context._first_input
context._plugin.set_input_value(input_name1, input_value1)
if context._second_input is not None:
input_name2, input_value2 = context._second_input
context._plugin.set_input_value(input_name2, input_value2)
context._plugin.execute()
context._output_values = context._plugin.output_values
@given(u'the name "{name}" of a valid plugin')
def the_name_name__of_a_valid_plugin(context, name):
context._first_input = None
context._second_input = None
context._plugin_name = name
app = PenfoldPluginManager()
plugin = app.get_plugin_by_name(context._plugin_name)
context._plugin = plugin
@then(u'test that the output named "{output_name}" has the value "{output_value}"')
def test_that_the_output_named_outputname_has_the_value_outputvalue(context, output_name, output_value):
log.debug("output={}".format(context._output_values[output_name]))
assert str(context._output_values[output_name]) == output_value
@given(u'the value "{value}" of the first input "{name}"')
def the_value_value_of_the_first_input_input(context, name, value):
context._first_input = (name, value)
@given(u'the value "{value}" of the second input "{name}"')
def the_value_of_the_second_input(context, value, name):
context._second_input = (name, value)
@when(u'a set if input values is set')
def a_set_if_input_values_is_set(context):
iof = InputOutputFactory()
all_input_rows = []
for row in context.table:
input_set = []
for i in range(len(row)):
input_set.append(iof.create(row.headings[i], row[i]))
all_input_rows.append(input_set)
context._input_rows = all_input_rows
| gpl-3.0 | -5,694,026,608,792,462,000 | 33.385965 | 104 | 0.694898 | false | 3.316413 | false | false | false |
staticsan/light-layers | lightlayers.py | 1 | 8961 | #!/usr/bin/python
#
"""
LightLayers module for Holiday by Moorescloud
Copyright (c) 2013, Wade Bowmer
License: ..
"""
__author__ = 'Wade Bowmer'
__version__ = '0.01-dev'
__license__ = 'MIT'
import time
import colours
class LightLayer:
remote = False
addr = ''
NUM_GLOBES = 50
stream = { }
current_time = 0
furthest_edge = 0
time_step = 50 # milli-seconds
stream = { }
def __init__(self, remote=False, addr=''):
"""Remote mode only, at the moment."""
if remote:
self.remote = True
self.addr = addr
self.stream[self.current_time] = [ [0, 0, 0, 0] for g in range(self.NUM_GLOBES) ] # red green blue transparency
def setcolour(self, col):
"""Generic colour checks. Also does a lookup if you've provided a name."""
if type(col) is list and len(col) == 3:
return [ self.limit(col[i], 0, 0xff) for i in [0, 1, 2] ]
if type(col) is str:
col = col.lower().replace(' ','')
if col in colours.colourMap:
return list(colours.colourMap[col])
return False
def limit(self, value, bottom, top):
"""Helper function to range limit values."""
return max(bottom, min(value, top))
def setglobe(self, globe, col, trans=100):
"""Set a single globe"""
self.setblock(globe, globe, col, trans)
def setblock(self, globe_start, globe_end, col, trans=100):
"""Set a range of lights to the same colour. If you want to _not_ set the transparancy, use gradient()."""
col = self.setcolour(col)
if col:
col.append(self.limit(trans, 0, 100))
globe_start = self.limit(globe_start, 0, self.NUM_GLOBES-1)
globe_end = self.limit(globe_end, 0, self.NUM_GLOBES-1)
for g in range(globe_start, globe_end+1):
self.stream[self.current_time][g] = list(col)
def ramp(self, globe_start, globe_end, first_time, overlap=100, mode="up"): # aka raise
"""Set an increasing brightness/transparency ramp
This call does NOT set colour.
first_time is how long the first light will take in milliseconds
overlap is the percentage overlap subsequent lights will take. Overlap of 100 will bring them all up at once.
"""
globe_start = self.limit(globe_start, 0, self.NUM_GLOBES-1)
globe_end = self.limit(globe_end, 0, self.NUM_GLOBES-1)
overlap = self.limit(overlap, 0, 100)
if first_time == 0:
for g in range(globe_start, globe_end+1):
self.stream[current_time][g][3] = 0xff
else:
time_advance = first_time
time_overlap = int(time_advance * (100 - overlap)/100 / self.time_step) * self.time_step
gtime = self.current_time
first_time = float(first_time)
for g in range(globe_start, globe_end+1):
# print "Setting %d from %d" % (g, gtime)
self.fill_to(gtime + time_advance)
t = gtime
while t <= gtime + time_advance:
# print "Setting %f:%d to %f" % (t, g, (t - gtime) / first_time)
if mode == "down":
self.stream[t][g][3] = int(0xff - (t - gtime) / first_time * 0xff)
else:
self.stream[t][g][3] = int((t - gtime) / first_time * 0xff)
t += self.time_step
gtime = gtime + time_overlap
return
def gradient(self, globe_start, globe_end, colour_from, colour_to):
"""Set a gradient across a section of lights.
"""
globe_start = self.limit(globe_start, 0, self.NUM_GLOBES-1)
globe_end = self.limit(globe_end, 0, self.NUM_GLOBES-1)
span = globe_end - globe_start
colour_from = self.setcolour(colour_from)
colour_to = self.setcolour(colour_to)
here = self.current_time + 0
g = globe_start
while g <= globe_end:
factor = (g - globe_start)*100 / span
unfactor = float(100 - factor) / 100
factor = float(factor) / 100
# print "Wash of %f:%f" % (factor, unfactor)
self.stream[here][g] = [
int(colour_from[0] * unfactor + colour_to[0] * factor),
int(colour_from[1] * unfactor + colour_to[1] * factor),
int(colour_from[2] * unfactor + colour_to[2] * factor),
self.stream[self.current_time][g][3] ]
t = here
while t <= self.furthest_edge:
self.stream[t][g] = [ self.stream[here][g][0], self.stream[here][g][1], self.stream[here][g][2], self.stream[t][g][3] ]
t += self.time_step
g += 1
def wash(self, globe_start, globe_end, steps, delay, start_from, colour_list):
"""Set a moving gradient."""
globe_start = self.limit(globe_start, 0, self.NUM_GLOBES-1)
globe_end = self.limit(globe_end, 0, self.NUM_GLOBES-1)
if delay < 0:
delay = 0
# Setup the raw colours
colours = [ ]
c = self.setcolour(colour_list.pop())
while c and len(colour_list) > 1:
d = max(0, colour_list.pop())
from_c = c
c = self.setcolour(colour_list)
if c:
x = 0
while x < d:
factor = (x - d)*100 / d
unfactor = float(100 - factor)/100
factor = float(factor)/100
colours.append( [
int(from_c[0] * unfactor + c[0] * factor),
int(from_c[1] * unfactor + c[1] * factor),
int(from_c[2] * unfactor + c[2] * factor) ])
x += 1
if c:
colours.append(c)
# Now paint them
span = globe_end - globe_start
here = self.current_time + 0
self.fill_to(here + steps * delay)
inner_step = delay
while steps > 0:
c = start_from
for g in range(globe_start, globe_end+1):
self.stream[here][g] = [ colours[c][0], colours[c][1], colours[c][2], self.stream[here][g][3] ]
c += 1
inner_step -= self.time_step
if inner_step <= 0:
inner_step = delay
steps -= 1
start_from += 1
here += self.time_step
def rotate(self, globe_start, globe_end, steps, distance, delay):
"""Rotate the colours of a subset of globes."""
globe_start = self.limit(globe_start, 0, self.NUM_GLOBES-1)
globe_end = self.limit(globe_end, 0, self.NUM_GLOBES-1)
span = globe_end - globe_start
if delay < 0:
delay = 0
if distance == 0:
return # whoops nothing to do!
colours = []
for g in range(globe_start, globe_end+1):
colours.append([ self.stream[self.current_time][g][0], self.stream[self.current_time][g][1], self.stream[self.current_time][g][2] ])
self.fill_to(self.current_time + steps * delay)
# while steps > 0:
# def shift(self,
def wait(self, delay=False):
"""Move the "current" time forward by this amount in milliseconds.
Called without an argument will move 'now' to the latest that's been recorded.
"""
if delay == False:
self.current_time = self.furthest_edge
else:
distance = self.current_time + delay
self.fill_to(distance)
self.current_time = distance
def fill_to(self, target):
"""Extends the light storage forward in time, copying the most-recent values.
Calling with a target before the furthest extent will do nothing.
"""
here = self.furthest_edge
# print "Filling %d to %d" % (here, target)
current_globes = self.stream[here]
self.furthest_edge += self.time_step
while self.furthest_edge <= target:
self.stream[self.furthest_edge] = [ current_globes[g][:] for g in range(self.NUM_GLOBES) ]
self.furthest_edge += self.time_step
self.furthest_edge -= self.time_step
return
def go(self):
"""This is intended for debugging."""
t = 0
times = self.stream.keys()
times.sort()
for t in times:
print "%d: " % t,
for g in self.stream[t]:
if g[3] > 0:
print '%02x%02x%02x_%d' % (g[0], g[1], g[2], g[3]),
else:
print '-',
print
def render(self):
self.render_rest()
def render_udp(self):
"""Renders the output to a Holiday device using UDP
Local rendering is currently not supported.
"""
t = 0
delay = float(self.time_step) / 1000 / 2
"""The render routine sends out a UDP packet using the SecretAPI"""
if (self.remote == True):
import socket, array
port = 9988
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
while t < self.current_time:
packet = array.array('B', [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # initialize basic packet, ignore first 10 bytes
for c in self.stream[t]:
if c[3] == 0xff:
packet.append(c[0])
packet.append(c[1])
packet.append(c[2])
else:
packet.append((c[0] * c[3])>> 8)
packet.append((c[1] * c[3])>> 8)
packet.append((c[2] * c[3])>> 8)
sock.sendto(packet, (self.addr, port))
time.sleep(delay)
t += self.time_step
else:
self.go()
def render_rest(self):
"""Renders the output to a Holiday device using HTTP/REST
Local rendering is currently not supported.
"""
t = 0
delay = float(self.time_step) / 1000 / 2
if (self.remote == True):
import requests, json
while t < self.current_time:
globes = []
for c in self.stream[t]:
if c[3] == 100:
globes.append("#%02x%02x%02x" % (c[0], c[1], c[2]))
else:
globes.append("#%02x%02x%02x" % ((c[0] * c[3])>> 8, (c[1] * c[3])>> 8, (c[2] * c[3])>> 8))
message = json.dumps({ "lights": globes })
r = requests.put('http://%s/iotas/0.1/device/moorescloud.holiday/localhost/setlights' % self.addr, data=message)
time.sleep(delay)
t += self.time_step
else:
self.go()
if __name__ == '__main__':
layer = LightLayer(remote=False)
print layer
| mit | -1,845,444,021,206,732,800 | 30.222997 | 135 | 0.626827 | false | 2.690183 | false | false | false |
dmccloskey/SBaaS_quantification | SBaaS_quantification/stage01_quantification_peakInformation_io.py | 1 | 36429 | # System
import json,re
# SBaaS
from .stage01_quantification_peakInformation_query import stage01_quantification_peakInformation_query
from .stage01_quantification_MQResultsTable_query import stage01_quantification_MQResultsTable_query
# Resources
from io_utilities.base_importData import base_importData
from io_utilities.base_exportData import base_exportData
from matplotlib_utilities.matplot import matplot
from SBaaS_base.sbaas_template_io import sbaas_template_io
from ddt_python.ddt_container import ddt_container
class stage01_quantification_peakInformation_io(stage01_quantification_peakInformation_query,
stage01_quantification_MQResultsTable_query,
sbaas_template_io):
def export_scatterLinePlot_peakInformation_matplot(self,experiment_id_I,sample_names_I=[],
sample_types_I=['Standard'],
component_names_I=[],
peakInfo_I = ['retention_time'],
acquisition_date_and_time_I=[None,None],
x_title_I='Time [hrs]',y_title_I='Retention Time [min]',y_data_type_I='acquisition_date_and_time',
plot_type_I='single',
filename_O = 'tmp',
figure_format_O = 'png'):
'''Analyze retention-time, height, s/n, and assymetry'''
#INPUT:
# experiment_id_I
# sample_names_I
# sample_types_I
# component_names_I
# peakInfo_I
# acquisition_date_and_time_I = ['%m/%d/%Y %H:%M','%m/%d/%Y %H:%M']
# y_data_type_I = 'acquisition_date_and_time' or 'count'
# plot_type_I = 'single', 'multiple', or 'sub'
print('export_peakInformation...')
#TODO: remove after refactor
mplot = matplot();
#convert string date time to datetime
# e.g. time.strptime('4/15/2014 15:51','%m/%d/%Y %H:%M')
acquisition_date_and_time = [];
if acquisition_date_and_time_I and acquisition_date_and_time_I[0] and acquisition_date_and_time_I[1]:
for dateandtime in acquisition_date_and_time_I:
time_struct = strptime(dateandtime,'%m/%d/%Y %H:%M')
dt = datetime.fromtimestamp(mktime(time_struct))
acquisition_date_and_time.append(dt);
else: acquisition_date_and_time=[None,None]
data_O = [];
component_names_all = [];
# get sample names
if sample_names_I and sample_types_I and len(sample_types_I)==1:
sample_names = sample_names_I;
sample_types = [sample_types_I[0] for sn in sample_names];
else:
sample_names = [];
sample_types = [];
for st in sample_types_I:
sample_names_tmp = [];
sample_names_tmp = self.get_sampleNames_experimentIDAndSampleType(experiment_id_I,st);
sample_names.extend(sample_names_tmp);
sample_types_tmp = [];
sample_types_tmp = [st for sn in sample_names_tmp];
sample_types.extend(sample_types_tmp);
for sn in sample_names:
print('analyzing peakInformation for sample_name ' + sn);
# get sample description
desc = {};
desc = self.get_description_experimentIDAndSampleID_sampleDescription(experiment_id_I,sn);
# get component names
if component_names_I:
component_names = component_names_I;
else:
component_names = [];
component_names = self.get_componentsNames_experimentIDAndSampleName(experiment_id_I,sn);
component_names_all.extend(component_names);
for cn in component_names:
# get rt, height, s/n
sst_data = {};
sst_data = self.get_peakInfo_sampleNameAndComponentName(sn,cn,acquisition_date_and_time);
if sst_data:
tmp = {};
tmp.update(sst_data);
tmp.update(desc);
tmp.update({'sample_name':sn});
data_O.append(tmp);
# Plot data over time
if component_names_I:
# use input order
component_names_unique = component_names_I;
else:
# use alphabetical order
component_names_unique = list(set(component_names_all));
component_names_unique.sort();
if plot_type_I == 'single':
for cn in component_names_unique:
data_parameters = {};
data_parameters_stats = {};
for parameter in peakInfo_I:
data_parameters[parameter] = [];
acquisition_date_and_times = [];
acquisition_date_and_times_hrs = [];
sample_names_parameter = [];
sample_types_parameter = [];
component_group_name = None;
for sn_cnt,sn in enumerate(sample_names):
for d in data_O:
if d['sample_name'] == sn and d['component_name'] == cn and d[parameter]:
data_parameters[parameter].append(d[parameter]);
acquisition_date_and_times.append(d['acquisition_date_and_time'])
acquisition_date_and_times_hrs.append(d['acquisition_date_and_time'].year*8765.81277 + d['acquisition_date_and_time'].month*730.484 + d['acquisition_date_and_time'].day*365.242 + d['acquisition_date_and_time'].hour + d['acquisition_date_and_time'].minute / 60. + d['acquisition_date_and_time'].second / 3600.); #convert using datetime object
sample_names_parameter.append(sn);
sample_types_parameter.append(sample_types[sn_cnt])
component_group_name = d['component_group_name'];
# normalize time
acquisition_date_and_times_hrs.sort();
t_start = min(acquisition_date_and_times_hrs);
for t_cnt,t in enumerate(acquisition_date_and_times_hrs):
if y_data_type_I == 'acquisition_date_and_time':acquisition_date_and_times_hrs[t_cnt] = t - t_start;
elif y_data_type_I == 'count':acquisition_date_and_times_hrs[t_cnt] = t_cnt;
title = cn + '\n' + parameter;
filename = filename_O + '_' + experiment_id_I + '_' + cn + '_' + parameter + figure_format_O;
mplot.scatterLinePlot(title,x_title_I,y_title_I,acquisition_date_and_times_hrs,data_parameters[parameter],fit_func_I='lowess',show_eqn_I=False,show_r2_I=False,filename_I=filename,show_plot_I=False);
if plot_type_I == 'multiple':
for parameter in peakInfo_I:
data_parameters = [];
acquisition_date_and_times = [];
acquisition_date_and_times_hrs = [];
sample_names_parameter = [];
sample_types_parameter = [];
component_group_names = [];
component_names = [];
for cn_cnt,cn in enumerate(component_names_unique):
data = [];
acquisition_date_and_time = [];
acquisition_date_and_time_hrs = [];
sample_name_parameter = [];
sample_type_parameter = [];
for sn_cnt,sn in enumerate(sample_names):
for d in data_O:
if d['sample_name'] == sn and d['component_name'] == cn and d[parameter]:
data.append(d[parameter])
acquisition_date_and_time.append(d['acquisition_date_and_time'])
acquisition_date_and_time_hrs.append(d['acquisition_date_and_time'].year*8765.81277 + d['acquisition_date_and_time'].month*730.484 + d['acquisition_date_and_time'].day*365.242 + d['acquisition_date_and_time'].hour + d['acquisition_date_and_time'].minute / 60. + d['acquisition_date_and_time'].second / 3600.); #convert using datetime object
sample_name_parameter.append(sn);
sample_type_parameter.append(sample_types[sn_cnt])
if sn_cnt == 0:
component_group_names.append(d['component_group_name']);
component_names.append(d['component_name']);
# normalize time
acquisition_date_and_time_hrs.sort();
t_start = min(acquisition_date_and_time_hrs);
for t_cnt,t in enumerate(acquisition_date_and_time_hrs):
if y_data_type_I == 'acquisition_date_and_time':acquisition_date_and_time_hrs[t_cnt] = t - t_start;
elif y_data_type_I == 'count':acquisition_date_and_time_hrs[t_cnt] = t_cnt;
data_parameters.append(data);
acquisition_date_and_times.append(acquisition_date_and_time)
acquisition_date_and_times_hrs.append(acquisition_date_and_time_hrs);
sample_names_parameter.append(sample_name_parameter);
sample_types_parameter.append(sample_type_parameter)
title = parameter;
filename = filename_O + '_' + experiment_id_I + '_' + parameter + figure_format_O;
mplot.multiScatterLinePlot(title,x_title_I,y_title_I,acquisition_date_and_times_hrs,data_parameters,data_labels_I=component_group_names,fit_func_I=None,show_eqn_I=False,show_r2_I=False,filename_I=filename,show_plot_I=False);
def export_scatterLinePlot_peakResolution_matplot(self,experiment_id_I,sample_names_I=[],sample_types_I=['Standard'],component_name_pairs_I=[],
peakInfo_I = ['rt_dif','resolution'],
acquisition_date_and_time_I=[None,None],
x_title_I='Time [hrs]',y_title_I='Retention Time [min]',y_data_type_I='acquisition_date_and_time',
plot_type_I='single'):
'''Analyze resolution for critical pairs'''
#Input:
# experiment_id_I
# sample_names_I
# sample_types_I
# component_name_pairs_I = [[component_name_1,component_name_2],...]
# acquisition_date_and_time_I = ['%m/%d/%Y %H:%M','%m/%d/%Y %H:%M']
#TODO: remove after refactor
mplot = matplot();
print('export_peakInformation_resolution...')
#convert string date time to datetime
# e.g. time.strptime('4/15/2014 15:51','%m/%d/%Y %H:%M')
acquisition_date_and_time = [];
if acquisition_date_and_time_I and acquisition_date_and_time_I[0] and acquisition_date_and_time_I[1]:
for dateandtime in acquisition_date_and_time_I:
time_struct = strptime(dateandtime,'%m/%d/%Y %H:%M')
dt = datetime.fromtimestamp(mktime(time_struct))
acquisition_date_and_time.append(dt);
else: acquisition_date_and_time=[None,None]
data_O = [];
component_names_pairs_all = [];
# get sample names
if sample_names_I and sample_types_I and len(sample_types_I)==1:
sample_names = sample_names_I;
sample_types = [sample_types_I[0] for sn in sample_names];
else:
sample_names = [];
sample_types = [];
for st in sample_types_I:
sample_names_tmp = [];
sample_names_tmp = self.get_sampleNames_experimentIDAndSampleType(experiment_id_I,st);
sample_names.extend(sample_names_tmp);
sample_types_tmp = [];
sample_types_tmp = [st for sn in sample_names_tmp];
sample_types.extend(sample_types_tmp);
for sn in sample_names:
print('analyzing peakInformation for sample_name ' + sn);
for component_name_pair in component_name_pairs_I:
# get critical pair data
cpd1 = {};
cpd2 = {};
cpd1 = self.get_peakInfo_sampleNameAndComponentName(sn,component_name_pair[0],acquisition_date_and_time);
cpd2 = self.get_peakInfo_sampleNameAndComponentName(sn,component_name_pair[1],acquisition_date_and_time);
# calculate the RT difference and resolution
rt_dif = 0.0;
rt_dif = abs(cpd1['retention_time']-cpd2['retention_time'])
resolution = 0.0;
resolution = rt_dif/(0.5*(cpd1['width_at_50']+cpd2['width_at_50']));
# record data
data_O.append({'component_name_pair':component_name_pair,
'rt_dif':rt_dif,
'resolution':resolution,
'component_group_name_pair':[cpd1['component_group_name'],cpd2['component_group_name']],
'sample_name':sn,
'acquisition_date_and_time':cpd1['acquisition_date_and_time']});
if plot_type_I == 'single':
for cnp in component_name_pairs_I:
data_parameters = {};
data_parameters_stats = {};
for parameter in peakInfo_I:
data_parameters[parameter] = [];
acquisition_date_and_times = [];
acquisition_date_and_times_hrs = [];
sample_names_parameter = [];
sample_types_parameter = [];
component_group_name_pair = None;
for sn_cnt,sn in enumerate(sample_names):
for d in data_O:
if d['sample_name'] == sn and d['component_name_pair'] == cnp and d[parameter]:
data_parameters[parameter].append(d[parameter]);
acquisition_date_and_times.append(d['acquisition_date_and_time'])
acquisition_date_and_times_hrs.append(d['acquisition_date_and_time'].year*8765.81277 + d['acquisition_date_and_time'].month*730.484 + d['acquisition_date_and_time'].day*365.242 + d['acquisition_date_and_time'].hour + d['acquisition_date_and_time'].minute / 60. + d['acquisition_date_and_time'].second / 3600.); #convert using datetime object
sample_names_parameter.append(sn);
sample_types_parameter.append(sample_types[sn_cnt])
component_group_name_pair = d['component_group_name_pair'];
# normalize time
acquisition_date_and_times_hrs.sort();
t_start = min(acquisition_date_and_times_hrs);
for t_cnt,t in enumerate(acquisition_date_and_times_hrs):
if y_data_type_I == 'acquisition_date_and_time':acquisition_date_and_times_hrs[t_cnt] = t - t_start;
elif y_data_type_I == 'count':acquisition_date_and_times_hrs[t_cnt] = t_cnt;
title = cn + '\n' + parameter;
filename = 'data/_output/' + experiment_id_I + '_' + cn + '_' + parameter + '.png'
mplot.scatterLinePlot(title,x_title_I,y_title_I,acquisition_date_and_times_hrs,data_parameters[parameter],fit_func_I='lowess',show_eqn_I=False,show_r2_I=False,filename_I=filename,show_plot_I=False);
if plot_type_I == 'multiple':
for parameter in peakInfo_I:
data_parameters = [];
acquisition_date_and_times = [];
acquisition_date_and_times_hrs = [];
sample_names_parameter = [];
sample_types_parameter = [];
component_group_names_pair = [];
component_names_pair = [];
for cnp_cnt,cnp in enumerate(component_name_pairs_I):
data = [];
acquisition_date_and_time = [];
acquisition_date_and_time_hrs = [];
sample_name_parameter = [];
sample_type_parameter = [];
for sn_cnt,sn in enumerate(sample_names):
for d in data_O:
if d['sample_name'] == sn and d['component_name_pair'] == cnp and d[parameter]:
data.append(d[parameter])
acquisition_date_and_time.append(d['acquisition_date_and_time'])
acquisition_date_and_time_hrs.append(d['acquisition_date_and_time'].year*8765.81277 + d['acquisition_date_and_time'].month*730.484 + d['acquisition_date_and_time'].day*365.242 + d['acquisition_date_and_time'].hour + d['acquisition_date_and_time'].minute / 60. + d['acquisition_date_and_time'].second / 3600.); #convert using datetime object
sample_name_parameter.append(sn);
sample_type_parameter.append(sample_types[sn_cnt])
if sn_cnt == 0:
component_group_names_pair.append(d['component_group_name_pair']);
component_names_pair.append(d['component_name_pair']);
# normalize time
acquisition_date_and_time_hrs.sort();
t_start = min(acquisition_date_and_time_hrs);
for t_cnt,t in enumerate(acquisition_date_and_time_hrs):
if y_data_type_I == 'acquisition_date_and_time':acquisition_date_and_time_hrs[t_cnt] = t - t_start;
elif y_data_type_I == 'count':acquisition_date_and_time_hrs[t_cnt] = t_cnt;
data_parameters.append(data);
acquisition_date_and_times.append(acquisition_date_and_time)
acquisition_date_and_times_hrs.append(acquisition_date_and_time_hrs);
sample_names_parameter.append(sample_name_parameter);
sample_types_parameter.append(sample_type_parameter)
# create data labels
data_labels = [];
for component_group_names in component_group_names_pair:
data_labels.append(component_group_names[0] + '/' + component_group_names[1]);
title = parameter;
filename = 'data/_output/' + experiment_id_I + '_' + parameter + '.eps'
mplot.multiScatterLinePlot(title,x_title_I,y_title_I,acquisition_date_and_times_hrs,data_parameters,data_labels_I=data_labels,fit_func_I=None,show_eqn_I=False,show_r2_I=False,filename_I=filename,show_plot_I=False);
def export_boxAndWhiskersPlot_peakInformation_matplot(self,experiment_id_I,
peakInfo_parameter_I = ['height','retention_time','width_at_50','signal_2_noise'],
component_names_I=[],
filename_O = 'tmp',
figure_format_O = '.png'):
'''generate a boxAndWhiskers plot from peakInformation table'''
#TODO: remove after refactor
mplot = matplot();
print('export_boxAndWhiskersPlot...')
if peakInfo_parameter_I:
peakInfo_parameter = peakInfo_parameter_I;
else:
peakInfo_parameter = [];
peakInfo_parameter = self.get_peakInfoParameter_experimentID_dataStage01PeakInformation(experiment_id_I);
for parameter in peakInfo_parameter:
data_plot_mean = [];
data_plot_cv = [];
data_plot_ci = [];
data_plot_parameters = [];
data_plot_component_names = [];
data_plot_data = [];
data_plot_units = [];
if component_names_I:
component_names = component_names_I;
else:
component_names = [];
component_names = self.get_componentNames_experimentIDAndPeakInfoParameter_dataStage01PeakInformation(experiment_id_I,parameter);
for cn in component_names:
print('generating boxAndWhiskersPlot for component_name ' + cn);
# get the data
data = {};
data = self.get_row_experimentIDAndPeakInfoParameterComponentName_dataStage01PeakInformation(experiment_id_I,parameter,cn)
if data and data['peakInfo_ave']:
# record data for plotting
data_plot_mean.append(data['peakInfo_ave']);
data_plot_cv.append(data['peakInfo_cv']);
data_plot_ci.append([data['peakInfo_lb'],data['peakInfo_ub']]);
data_plot_data.append(data['peakInfo_data']);
data_plot_parameters.append(parameter);
data_plot_component_names.append(data['component_group_name']);
data_plot_units.append('Retention_time [min]');
# visualize the stats:
data_plot_se = [(x[1]-x[0])/2 for x in data_plot_ci]
filename = filename_O + '_' + experiment_id_I + '_' + parameter + figure_format_O;
mplot.boxAndWhiskersPlot(data_plot_parameters[0],data_plot_component_names,data_plot_units[0],'samples',data_plot_data,data_plot_mean,data_plot_ci,filename_I=filename,show_plot_I=False);
def export_boxAndWhiskersPlot_peakResolution_matplot(self,experiment_id_I,component_name_pairs_I=[],
peakInfo_parameter_I = ['rt_dif','resolution'],
filename_O = 'tmp',
figure_format_O = '.png'):
'''generate a boxAndWhiskers plot from peakResolution table'''
#TODO: remove after refactor
mplot = matplot();
print('export_boxAndWhiskersPlot...')
if peakInfo_parameter_I:
peakInfo_parameter = peakInfo_parameter_I;
else:
peakInfo_parameter = [];
peakInfo_parameter = self.get_peakInfoParameter_experimentID_dataStage01PeakResolution(experiment_id_I);
for parameter in peakInfo_parameter:
data_plot_mean = [];
data_plot_cv = [];
data_plot_ci = [];
data_plot_parameters = [];
data_plot_component_names = [];
data_plot_data = [];
data_plot_units = [];
if component_name_pairs_I:
component_name_pairs = component_name_pairs_I;
else:
component_name_pairs = [];
component_name_pairs = self.get_componentNamePairs_experimentIDAndPeakInfoParameter_dataStage01PeakResolution(experiment_id_I,parameter);
for cn in component_name_pairs:
# get the data
data = {};
data = self.get_row_experimentIDAndPeakInfoParameterComponentName_dataStage01PeakResolution(experiment_id_I,parameter,cn)
if data and data['peakInfo_ave']:
# record data for plotting
data_plot_mean.append(data['peakInfo_ave']);
data_plot_cv.append(data['peakInfo_cv']);
data_plot_ci.append([data['peakInfo_lb'],data['peakInfo_ub']]);
data_plot_data.append(data['peakInfo_data']);
data_plot_parameters.append(parameter);
data_plot_component_names.append(data['component_group_name_pair'][0]+'/'+data['component_group_name_pair'][0]);
data_plot_units.append('Retention_time [min]');
# visualize the stats:
data_plot_se = [(x[1]-x[0])/2 for x in data_plot_ci]
filename = filename_O + '_' + experiment_id_I + '_' + parameter + figure_format_O;
mplot.boxAndWhiskersPlot(data_plot_parameters[0],data_plot_component_names,data_plot_units[0],'samples',data_plot_data,data_plot_mean,data_plot_ci,filename_I=filename,show_plot_I=False);
def export_boxAndWhiskersPlot_peakInformation_js(
self,
experiment_id_I=[],
analysis_id_I=[],
sample_name_abbreviations_I=[],
component_names_I=[],
component_group_names_I=[],
peakInfo_I = ['height','retention_time','width_at_50','signal_2_noise'],
data_dir_I='tmp'):
'''Export data for a box and whiskers plot from peakInformation
INPUT:
#TODO add in template for box and whiskers plot from stats
'''
print('export_boxAndWhiskersPlot...')
data_O = [];
#if peakInfo_parameter_I:
# peakInfo_parameter = peakInfo_parameter_I;
#else:
# peakInfo_parameter = [];
# peakInfo_parameter = self.get_peakInfoParameter_experimentID_dataStage01PeakInformation(experiment_id_I);
#for parameter in peakInfo_parameter:
# if component_names_I:
# component_names = component_names_I;
# else:
# component_names = [];
# component_names = self.get_componentNames_experimentIDAndPeakInfoParameter_dataStage01PeakInformation(experiment_id_I,parameter);
# for cn in component_names:
# print('generating boxAndWhiskersPlot for component_name ' + cn);
# # get the data
# row = [];
# row = self.get_row_experimentIDAndPeakInfoParameterComponentName_dataStage01PeakInformation(experiment_id_I,parameter,cn);
# if row:
# #TODO: fix type in database 'acqusition_date_and_times'
# tmp_list = [];
# for d in row['acqusition_date_and_times']:
# tmp = None;
# tmp = self.convert_datetime2string(d);
# tmp_list.append(tmp);
# row['acqusition_date_and_times'] = tmp_list;
# row['component_name'] = re.escape(row['component_name']);
# data_O.append(row);
data_O = self.get_row_analysisID_dataStage01PeakInformation(
analysis_id_I=analysis_id_I,
experiment_id_I=experiment_id_I,
peakInfo_parameter_I=peakInfo_I,
component_name_I=component_names_I,
component_group_name_I=component_group_names_I,
sample_name_abbreviation_I=sample_name_abbreviations_I
)
# dump chart parameters to a js files
data1_keys = ['experiment_id',
'component_group_name',
'component_name',
'peakInfo_parameter',
#'peakInfo_ave',
#'peakInfo_cv',
#'peakInfo_lb',
#'peakInfo_ub',
#'peakInfo_units',
'sample_name_abbreviation',
#'sample_names',
#'sample_types',
#'acqusition_date_and_times'
];
data1_nestkeys = ['component_name'];
data1_keymap = {'xdata':'component_name',
'ydatamean':'peakInfo_ave',
'ydatalb':'peakInfo_lb',
'ydataub':'peakInfo_ub',
#'ydatamin':None,
#'ydatamax':None,
#'ydataiq1':None,
#'ydataiq3':None,
#'ydatamedian':None,
'serieslabel':'peakInfo_parameter',
'featureslabel':'component_name'};
# make the data object
dataobject_O = [{"data":data_O,"datakeys":data1_keys,"datanestkeys":data1_nestkeys}];
# make the tile parameter objects
formtileparameters_O = {'tileheader':'Filter menu','tiletype':'html','tileid':"filtermenu1",'rowid':"row1",'colid':"col1",
'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-4"};
formparameters_O = {'htmlid':'filtermenuform1',"htmltype":'form_01',"formsubmitbuttonidtext":{'id':'submit1','text':'submit'},"formresetbuttonidtext":{'id':'reset1','text':'reset'},"formupdatebuttonidtext":{'id':'update1','text':'update'}};
formtileparameters_O.update(formparameters_O);
svgparameters_O = {"svgtype":'boxandwhiskersplot2d_02',"svgkeymap":[data1_keymap],
'svgid':'svg1',
"svgmargin":{ 'top': 50, 'right': 150, 'bottom': 50, 'left': 50 },
"svgwidth":500,"svgheight":350,
"svgx1axislabel":"component_name",
"svgy1axislabel":"parameter_value",
'svgformtileid':'filtermenu1','svgresetbuttonid':'reset1','svgsubmitbuttonid':'submit1'};
svgtileparameters_O = {'tileheader':'Custom box and whiskers plot',
'tiletype':'svg',
'tileid':"tile2",
'rowid':"row1",
'colid':"col2",
'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-8"};
svgtileparameters_O.update(svgparameters_O);
tableparameters_O = {"tabletype":'responsivetable_01',
'tableid':'table1',
"tablefilters":None,
"tableclass":"table table-condensed table-hover",
'tableformtileid':'filtermenu1','tableresetbuttonid':'reset1','tablesubmitbuttonid':'submit1'};
tabletileparameters_O = {'tileheader':'peakInformation','tiletype':'table','tileid':"tile3",'rowid':"row2",'colid':"col1",
'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-12"};
tabletileparameters_O.update(tableparameters_O);
parametersobject_O = [formtileparameters_O,svgtileparameters_O,tabletileparameters_O];
tile2datamap_O = {"filtermenu1":[0],"tile2":[0],"tile3":[0]};
# dump the data to a json file
ddtutilities = ddt_container(parameters_I = parametersobject_O,data_I = dataobject_O,tile2datamap_I = tile2datamap_O,filtermenu_I = None);
if data_dir_I=='tmp':
filename_str = self.settings['visualization_data'] + '/tmp/ddt_data.js'
elif data_dir_I=='data_json':
data_json_O = ddtutilities.get_allObjects_js();
return data_json_O;
with open(filename_str,'w') as file:
file.write(ddtutilities.get_allObjects());
def export_boxAndWhiskersPlot_peakResolution_js(self,experiment_id_I,
component_name_pairs_I=[],
peakInfo_parameter_I = ['rt_dif','resolution'],
data_dir_I='tmp'):
'''Export data for a box and whiskers plot'''
print('export_boxAndWhiskersPlot...')
data_O=[];
if peakInfo_parameter_I:
peakInfo_parameter = peakInfo_parameter_I;
else:
peakInfo_parameter = [];
peakInfo_parameter = self.get_peakInfoParameter_experimentID_dataStage01PeakResolution(experiment_id_I);
for parameter in peakInfo_parameter:
if component_name_pairs_I:
component_name_pairs = component_name_pairs_I;
else:
component_name_pairs = [];
component_name_pairs = self.get_componentNamePairs_experimentIDAndPeakInfoParameter_dataStage01PeakResolution(experiment_id_I,parameter);
for cn in component_name_pairs:
# get the data
row = {};
row = self.get_row_experimentIDAndPeakInfoParameterComponentName_dataStage01PeakResolution(experiment_id_I,parameter,cn)
if row and row['peakInfo_ave']:
#TODO: fix type in database 'acqusition_date_and_times'
tmp_list = [];
for d in row['acqusition_date_and_times']:
tmp = None;
tmp = self.convert_datetime2string(d);
tmp_list.append(tmp);
row['acqusition_date_and_times'] = tmp_list;
data_O.append(row);
# dump chart parameters to a js files
data1_keys = ['experiment_id',
'component_group_name_pair',
'component_name_pair',
'peakInfo_parameter',
#'peakInfo_ave',
#'peakInfo_cv',
#'peakInfo_lb',
#'peakInfo_ub',
#'peakInfo_units',
'sample_names',
'sample_types',
#'acqusition_date_and_times'
];
data1_nestkeys = ['component_name_pair'];
data1_keymap = {'xdata':'component_name_pair',
'ydatamean':'peakInfo_ave',
'ydatalb':'peakInfo_lb',
'ydataub':'peakInfo_ub',
#'ydatamin':None,
#'ydatamax':None,
#'ydataiq1':None,
#'ydataiq3':None,
#'ydatamedian':None,
'serieslabel':'peakInfo_parameter',
'featureslabel':'component_name_pair'};
# make the data object
dataobject_O = [{"data":data_O,"datakeys":data1_keys,"datanestkeys":data1_nestkeys}];
# make the tile parameter objects
formtileparameters_O = {'tileheader':'Filter menu','tiletype':'html','tileid':"filtermenu1",'rowid':"row1",'colid':"col1",
'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-4"};
formparameters_O = {'htmlid':'filtermenuform1',"htmltype":'form_01',"formsubmitbuttonidtext":{'id':'submit1','text':'submit'},"formresetbuttonidtext":{'id':'reset1','text':'reset'},"formupdatebuttonidtext":{'id':'update1','text':'update'}};
formtileparameters_O.update(formparameters_O);
svgparameters_O = {"svgtype":'boxandwhiskersplot2d_01',"svgkeymap":[data1_keymap],
'svgid':'svg1',
"svgmargin":{ 'top': 50, 'right': 150, 'bottom': 50, 'left': 50 },
"svgwidth":500,"svgheight":350,
"svgx1axislabel":"component_name_pair","svgy1axislabel":"parameter_value",
'svgformtileid':'filtermenu1','svgresetbuttonid':'reset1','svgsubmitbuttonid':'submit1'};
svgtileparameters_O = {'tileheader':'Custom box and whiskers plot','tiletype':'svg','tileid':"tile2",'rowid':"row1",'colid':"col2",
'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-8"};
svgtileparameters_O.update(svgparameters_O);
tableparameters_O = {"tabletype":'responsivetable_01',
'tableid':'table1',
"tablefilters":None,
"tableclass":"table table-condensed table-hover",
'tableformtileid':'filtermenu1','tableresetbuttonid':'reset1','tablesubmitbuttonid':'submit1'};
tabletileparameters_O = {'tileheader':'peakResolution','tiletype':'table','tileid':"tile3",'rowid':"row2",'colid':"col1",
'tileclass':"panel panel-default",'rowclass':"row",'colclass':"col-sm-12"};
tabletileparameters_O.update(tableparameters_O);
parametersobject_O = [formtileparameters_O,svgtileparameters_O,tabletileparameters_O];
tile2datamap_O = {"filtermenu1":[0],"tile2":[0],"tile3":[0]};
# dump the data to a json file
ddtutilities = ddt_container(parameters_I = parametersobject_O,data_I = dataobject_O,tile2datamap_I = tile2datamap_O,filtermenu_I = None);
if data_dir_I=='tmp':
filename_str = self.settings['visualization_data'] + '/tmp/ddt_data.js'
elif data_dir_I=='data_json':
data_json_O = ddtutilities.get_allObjects_js();
return data_json_O;
with open(filename_str,'w') as file:
file.write(ddtutilities.get_allObjects());
| mit | 7,779,765,412,555,950,000 | 58.718033 | 374 | 0.544706 | false | 3.943596 | false | false | false |
dhondta/tinyscript | tinyscript/preimports/ncodecs/morse.py | 1 | 2619 | # -*- coding: UTF-8 -*-
"""Morse Codec - morse content encoding.
This codec:
- en/decodes strings from str to str
- en/decodes strings from bytes to bytes
- decodes file content to str (read)
- encodes file content from str to bytes (write)
"""
from ._utils import *
ENCMAP = {
# letters
'a': ".-", 'b': "-...", 'c': "-.-.", 'd': "-..", 'e': ".", 'f': "..-.",
'g': "--.", 'h': "....", 'i': "..", 'j': ".---", 'k': "-.-", 'l': ".-..",
'm': "--", 'n': "-.", 'o': "---", 'p': ".--.", 'q': "--.-", 'r': ".-.",
's': "...", 't': "-", 'u': "..-", 'v': "...-", 'w': ".--", 'x': "-..-",
'y': "-.--", 'z': "--..",
# digits
'1': ".----", '2': "..---", '3': "...--", '4': "....-", '5': ".....",
'6': "-....", '7': "--...", '8': "---..", '9': "----.", '0': "-----",
# punctuation
',': "--..--", '.': ".-.-.-", ':' : "---...", '?': "..--..", '/': "-..-.",
'-': "-....-", '=' : "-...-", '(': "-.--.", ')': "-.--.-", '@' : ".--.-.",
'\'': ".----.", '_': "..--.-", '!': "-.-.--", '&': ".-...", '"': ".-..-.",
';': "-.-.-.", '$': "...-..-",
# word separator
' ' : "/",
}
DECMAP = {v: k for k, v in ENCMAP.items()}
REPLACE_CHAR = "#"
class MorseError(ValueError):
pass
class MorseDecodeError(MorseError):
pass
class MorseEncodeError(MorseError):
pass
def morse_encode(text, errors="strict"):
r = ""
for i, c in enumerate(ensure_str(text)):
try:
r += ENCMAP[c] + " "
except KeyError:
if errors == "strict":
raise MorseEncodeError("'morse' codec can't encode character "
"'{}' in position {}".format(c, i))
elif errors == "replace":
r += REPLACE_CHAR + " "
elif errors == "ignore":
continue
else:
raise ValueError("Unsupported error handling {}".format(errors))
return r[:-1], len(text)
def morse_decode(text, errors="strict"):
r = ""
for i, c in enumerate(ensure_str(text).split()):
try:
r += DECMAP[c]
except KeyError:
if errors == "strict":
raise MorseDecodeError("'morse' codec can't decode character "
"'{}' in position {}".format(c, i))
elif errors == "replace":
r += REPLACE_CHAR
elif errors == "ignore":
continue
else:
raise ValueError("Unsupported error handling {}".format(errors))
return r, len(text)
codecs.add_codec("morse", morse_encode, morse_decode)
| agpl-3.0 | -4,708,215,410,679,469,000 | 30.554217 | 80 | 0.392516 | false | 3.344828 | false | false | false |
costadorione/purestream | servers/gamovideo.py | 1 | 2912 | # -*- coding: utf-8 -*-
#------------------------------------------------------------
# streamondemand - XBMC Plugin
# Conector para gamovideo
# http://www.mimediacenter.info/foro/viewforum.php?f=36
#------------------------------------------------------------
import re
from core import jsunpack
from core import logger
from core import scrapertools
headers = [["User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0"]]
def test_video_exists( page_url ):
logger.info("streamondemand.servers.gamovideo test_video_exists(page_url='%s')" % page_url)
data = scrapertools.cache_page(page_url, headers=headers)
if ("File was deleted" or "Not Found") in data:
return False, "[Gamovideo] El archivo no existe o ha sido borrado"
return True, ""
def get_video_url( page_url , premium = False , user="" , password="", video_password="" ):
logger.info("streamondemand.servers.gamovideo get_video_url(page_url='%s')" % page_url)
data = scrapertools.cache_page(page_url,headers=headers)
packer = scrapertools.find_single_match(data,"<script type='text/javascript'>(eval.function.p,a,c,k,e,d..*?)</script>")
unpacker = jsunpack.unpack(data) if packer != "" else ""
if unpacker != "": data = unpacker
data = re.sub(r'\n|\t|\s+', '', data)
host = scrapertools.get_match(data, '\[\{image:"(http://[^/]+/)')
mediaurl = host+scrapertools.get_match(data, ',\{file:"([^"]+)"').split("=")[1]+"/v.flv"
rtmp_url = scrapertools.get_match(data, 'file:"(rtmp[^"]+)"')
playpath = scrapertools.get_match(rtmp_url, 'vod\?h=[\w]+/(.*$)')
rtmp_url = rtmp_url.split(playpath)[0]+" playpath="+playpath+" swfUrl=http://gamovideo.com/player61/jwplayer.flash.swf"
video_urls = []
video_urls.append([scrapertools.get_filename_from_url(mediaurl)[-4:]+" [gamovideo]",mediaurl])
video_urls.append(["RTMP [gamovideo]",rtmp_url])
for video_url in video_urls:
logger.info("streamondemand.servers.gamovideo %s - %s" % (video_url[0],video_url[1]))
return video_urls
# Encuentra vídeos del servidor en el texto pasado
def find_videos(data):
encontrados = set()
devuelve = []
# http://gamovideo.com/auoxxtvyoy
# http://gamovideo.com/h1gvpjarjv88
# http://gamovideo.com/embed-sbb9ptsfqca2-588x360.html
patronvideos = 'gamovideo.com/(?:embed-|)([a-z0-9]+)'
logger.info("streamondemand.servers.gamovideo find_videos #"+patronvideos+"#")
matches = re.compile(patronvideos,re.DOTALL).findall(data)
for match in matches:
titulo = "[gamovideo]"
url = "http://gamovideo.com//embed-%s.html" % match
if url not in encontrados:
logger.info(" url="+url)
devuelve.append( [ titulo , url , 'gamovideo' ] )
encontrados.add(url)
else:
logger.info(" url duplicada="+url)
return devuelve
| gpl-3.0 | -6,720,686,270,816,700,000 | 38.876712 | 123 | 0.61594 | false | 3.143629 | false | false | false |
openstack/zaqar | zaqar/transport/wsgi/utils.py | 1 | 8333 | # Copyright (c) 2013 Rackspace, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy
# of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
import falcon
import jsonschema
from oslo_log import log as logging
import six
from zaqar.i18n import _
from zaqar.transport import utils
from zaqar.transport.wsgi import errors
JSONObject = dict
"""Represents a JSON object in Python."""
JSONArray = list
"""Represents a JSON array in Python."""
LOG = logging.getLogger(__name__)
#
# TODO(kgriffs): Create Falcon "before" hooks adapters for these functions
#
def deserialize(stream, len):
"""Deserializes JSON from a file-like stream.
This function deserializes JSON from a stream, including
translating read and parsing errors to HTTP error types.
:param stream: file-like object from which to read an object or
array of objects.
:param len: number of bytes to read from stream
:raises HTTPBadRequest: if the request is invalid
:raises HTTPServiceUnavailable: if the http service is unavailable
"""
if len is None:
description = _(u'Request body can not be empty')
raise errors.HTTPBadRequestBody(description)
try:
# TODO(kgriffs): read_json should stream the resulting list
# of messages, returning a generator rather than buffering
# everything in memory (bp/streaming-serialization).
return utils.read_json(stream, len)
except utils.MalformedJSON as ex:
LOG.debug(ex)
description = _(u'Request body could not be parsed.')
raise errors.HTTPBadRequestBody(description)
except utils.OverflowedJSONInteger as ex:
LOG.debug(ex)
description = _(u'JSON contains integer that is too large.')
raise errors.HTTPBadRequestBody(description)
except Exception:
# Error while reading from the network/server
description = _(u'Request body could not be read.')
LOG.exception(description)
raise errors.HTTPServiceUnavailable(description)
def sanitize(document, spec=None, doctype=JSONObject):
"""Validates a document and drops undesired fields.
:param document: A dict to verify according to `spec`.
:param spec: (Default None) Iterable describing expected fields,
yielding tuples with the form of:
(field_name, value_type, default_value)
Note that value_type may either be a Python type, or the
special string '*' to accept any type. default_value is the
default to give the field if it is missing, or None to require
that the field be present.
If spec is None, the incoming documents will not be validated.
:param doctype: type of document to expect; must be either
JSONObject or JSONArray.
:raises HTTPBadRequestBody: if the request is invalid
:returns: A sanitized, filtered version of the document. If the
document is a list of objects, each object will be filtered
and returned in a new list. If, on the other hand, the document
is expected to contain a single object, that object's fields will
be filtered and the resulting object will be returned.
"""
if doctype is JSONObject:
if not isinstance(document, JSONObject):
raise errors.HTTPDocumentTypeNotSupported()
return document if spec is None else filter(document, spec)
if doctype is JSONArray:
if not isinstance(document, JSONArray):
raise errors.HTTPDocumentTypeNotSupported()
if spec is None:
return document
return [filter(obj, spec) for obj in document]
raise TypeError('doctype must be either a JSONObject or JSONArray')
def filter(document, spec):
"""Validates and retrieves typed fields from a single document.
Sanitizes a dict-like document by checking it against a
list of field spec, and returning only those fields
specified.
:param document: dict-like object
:param spec: iterable describing expected fields, yielding
tuples with the form of: (field_name, value_type). Note that
value_type may either be a Python type, or the special
string '*' to accept any type.
:raises HTTPBadRequest: if any field is missing or not an
instance of the specified type
:returns: A filtered dict containing only the fields
listed in the spec
"""
filtered = {}
for name, value_type, default_value in spec:
filtered[name] = get_checked_field(document, name,
value_type, default_value)
return filtered
def get_checked_field(document, name, value_type, default_value):
"""Validates and retrieves a typed field from a document.
This function attempts to look up doc[name], and raises
appropriate HTTP errors if the field is missing or not an
instance of the given type.
:param document: dict-like object
:param name: field name
:param value_type: expected value type, or '*' to accept any type
:param default_value: Default value to use if the value is missing,
or None to make the value required.
:raises HTTPBadRequest: if the field is missing or not an
instance of value_type
:returns: value obtained from doc[name]
"""
try:
value = document[name]
except KeyError:
if default_value is not None:
value = default_value
else:
description = _(u'Missing "{name}" field.').format(name=name)
raise errors.HTTPBadRequestBody(description)
# PERF(kgriffs): We do our own little spec thing because it is way
# faster than jsonschema.
if value_type == '*' or isinstance(value, value_type):
return value
description = _(u'The value of the "{name}" field must be a {vtype}.')
description = description.format(name=name, vtype=value_type.__name__)
raise errors.HTTPBadRequestBody(description)
def load(req):
"""Reads request body, raising an exception if it is not JSON.
:param req: The request object to read from
:type req: falcon.Request
:return: a dictionary decoded from the JSON stream
:rtype: dict
:raises HTTPBadRequestBody: if JSON could not be parsed
"""
try:
return utils.read_json(req.stream, req.content_length)
except (utils.MalformedJSON, utils.OverflowedJSONInteger):
message = 'JSON could not be parsed.'
LOG.exception(message)
raise errors.HTTPBadRequestBody(message)
# TODO(cpp-cabrera): generalize this
def validate(validator, document):
"""Verifies a document against a schema.
:param validator: a validator to use to check validity
:type validator: jsonschema.Draft4Validator
:param document: document to check
:type document: dict
:raises HTTPBadRequestBody: if the request is invalid
"""
try:
validator.validate(document)
except jsonschema.ValidationError as ex:
raise errors.HTTPBadRequestBody(
'{0}: {1}'.format(ex.args, six.text_type(ex))
)
def message_url(message, base_path, claim_id=None):
path = "/".join([base_path, 'messages', message['id']])
if claim_id:
path += falcon.to_query_str({'claim_id': claim_id})
return path
def format_message_v1(message, base_path, claim_id=None):
return {
'href': message_url(message, base_path, claim_id),
'ttl': message['ttl'],
'age': message['age'],
'body': message['body'],
}
def format_message_v1_1(message, base_path, claim_id=None):
url = message_url(message, base_path, claim_id)
res = {
'id': message['id'],
'href': url,
'ttl': message['ttl'],
'age': message['age'],
'body': message['body']
}
if message.get('checksum'):
res['checksum'] = message.get('checksum')
return res
| apache-2.0 | 4,532,507,697,386,719,000 | 32.873984 | 79 | 0.675267 | false | 4.264585 | false | false | false |
mikehulluk/morphforge | src/morphforgecontrib/simulation/populations/group_analysis.py | 1 | 3491 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# 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.
#
# 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
# HOLDER 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 morphforgecontrib.traces.tracetools import SpikeFinder
from morphforge.traces.eventset import EventSet
import itertools
class PopAnalSpiking(object):
@classmethod
def evset_nth_spike(cls, res, tag_selector, n, comment=None, comment_incl_nspikes=False, evset_tags=None, evset_name=None):
comment = comment or ''
if evset_tags is None:
evset_tags = []
evset_tags.extend( ['Spike', 'Event'] )
traces = [trace for trace in res.get_traces()
if tag_selector(trace)]
spike_list = [SpikeFinder.find_spikes(tr, crossingthresh=0,
firingthres=None) for tr in traces]
spike_list = [spl[n] for spl in spike_list if len(spl) > n]
comment = '%s (%dth Spike)' % (comment, n)
if comment_incl_nspikes:
comment += ' (NSpikes: %d'%len(spike_list)
spikes = EventSet(spike_list, tags=evset_tags, name=evset_name, comment=comment)
return spikes
@classmethod
def evset_first_spike(cls, **kwargs):
return cls.evset_nth_spike(n=0, **kwargs)
@classmethod
def evset_all_spikes(cls, res, tag_selector, comment=None, comment_incl_nspikes=False, evset_tags=None, evset_name=None):
if evset_tags is None:
evset_tags = []
evset_tags.extend( ['Spike', 'Event'] )
comment = comment or ''
traces = [trace for trace in res.get_traces()
if tag_selector(trace)]
spike_list = [SpikeFinder.find_spikes(tr, crossingthresh=0, firingthres=None) for tr in traces]
spike_list = list(itertools.chain(*spike_list) )
#print ' -- SL', spike_list
comment='%s (All Spike)' if not comment else comment
if comment_incl_nspikes:
comment += ' (NSpikes: %d'%len(list(spike_list) )
spikes = EventSet(spike_list, tags=evset_tags, comment=comment, name=evset_name)
return spikes
| bsd-2-clause | -3,049,875,634,603,801,600 | 37.362637 | 127 | 0.651962 | false | 3.870288 | false | false | false |
mshameers/theory_website | app/utils.py | 1 | 1618 | import re
import unidecode
from functools import wraps
from flask import session, redirect, url_for
from datetime import datetime
from werkzeug.contrib.cache import SimpleCache
from wtforms.validators import regexp
from pytz import UTC
is_name = regexp(
# not using \w since it allows for unlimited underscores
r'^[a-zA-Z0-9]+([ \-\_][a-zA-Z0-9]+)*$',
message='Field characters can only be letters and digits with one space, \
underscore or hyphen as separator.'
)
def slugify(timenow, str):
"""Return slug genereated from date and specified unicoded string."""
date = datetime.date(timenow)
unistr = unidecode.unidecode(str).lower()
title = re.sub(r'\W+', '-', unistr).strip('-')
return '%i/%i/%i/%s' % (date.year, date.month, date.day, title)
def utcnow():
return datetime.utcnow().replace(tzinfo=UTC)
cache = SimpleCache()
def cached(timeout=5 * 60, key='cached/%s'):
# ~200 req/s => ~600-800 req/s
def decorator(f):
@wraps(f)
def decorated_function(*args, **kwargs):
cache_key = key % request.path
rv = cache.get(cache_key)
if rv is not None:
return rv
rv = f(*args, **kwargs)
cache.set(cache_key, rv, timeout=timeout)
return rv
return decorated_function
return decorator
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
logged = session.get('logged_in', None)
if not logged:
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function | gpl-2.0 | -4,017,023,542,743,401,000 | 29.54717 | 78 | 0.6267 | false | 3.728111 | false | false | false |
dreams6/pyerpcn | pyerp/fnd/gbl.py | 1 | 6577 | # -*- coding: utf-8 -*-
"""
maybe a better solution
http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser
"""
try:
import thread
except ImportError:
import dummy_thread as thread
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
from django.conf import settings
from pyerp.fnd.utils.version import get_svn_revision, get_version
__svnid__ = '$Id$'
__svn__ = get_svn_revision(__name__)
class GlobalManagementError(Exception):
"""
This exception is thrown when something bad happens with global
management.
"""
pass
class ThreadFndGlobal(object):
def __init__(self):
self.thread_context = {}
def get_user_id(self):
"""
取得当前线程用户ID.
"""
return self.get_attr('user_id', -1)
user_id = property(get_user_id)
def get_user(self):
"""
取得当前线程用户.
"""
usr = self.get_attr('user', None)
if usr is None:
from pyerp.fnd.models import AnonymousUser, User
if self.user_id==-1:
usr = AnonymousUser()
else:
try:
usr = User.objects.get(pk=self.user_id)
except User.DoesNotExist:
usr = AnonymousUser()
self.set_attr('user', usr)
return usr
user = property(get_user)
def get_session(self):
"""
取得当前线程Http回话.
"""
return self.get_attr('session', None)
session = property(get_session)
def get_resp_id(self):
return self.get_attr('resp_id', -1)
resp_id = property(get_resp_id)
def get_menu_id(self):
return self.get_attr('menu_id', -1)
menu_id = property(get_menu_id)
def get_function_id(self):
return self.get_attr('function_id', -1)
function_id = property(get_function_id)
def get_function(self):
"""
取得当前线程访问的function.
"""
return self.get_attr('function', None)
function = property(get_function)
def set_resp_id(self, value):
self.set_attr('resp_id', value)
def set_menu_id(self, value):
self.set_attr('menu_id', value)
def set_function(self, value):
self.set_attr('function_id', value and value.id or -1)
self.set_attr('function', value)
def get_org_id(self):
if 'org_id' in self.thread_context[thread_ident]:
return self.thread_context[thread_ident]['org_id']
# TODO 从profile中取得组织ID
orgid = 120
self.thread_context[thread_ident]['org_id'] = orgid
return orgid
org_id = property(get_org_id)
def get_language(self):
"""
返回用户使用的语言.
"""
return self.session['django_language']
language = property(get_language)
def get_appl_id(self):
return -1
appl_id = property(get_appl_id)
def get_site_id(self):
"""
这里的site指的是,使用多站点时,各个站点的ID.而非site控制器.
"""
return settings.SITE_ID
site_id = property(get_site_id)
def get_server_id(self):
return -1
server_id = property(get_server_id)
def get_context_prefix(self):
"""
取得当前context_prefix前缀, 使用mod_python时设定,context前缀
"""
return self.get_attr('context_prefix', '/')
context_prefix = property(get_context_prefix)
def get_site_prefix(self):
"""
取得当前site控制器前缀
"""
return self.get_attr('site_prefix', '')
site_prefix = property(get_site_prefix)
def get_thread_id(self):
"""
取得当前的线程ID
"""
return thread.get_ident()
thread_id = property(get_thread_id)
def get_attrs(self):
"""
取得当前线程级变量字典
"""
return self.thread_context[thread.get_ident()]
attrs = property(get_attrs)
def get_attr(self, key, default=None):
"""
根据指定key从当前线程变量中取得数据
"""
thread_ident = thread.get_ident()
if thread_ident in self.thread_context:
if key in self.thread_context[thread_ident]: # and self.thread_context[thread_ident][key]:
return self.thread_context[thread_ident][key]
else:
return default
else:
raise GlobalManagementError("This code isn't under global management. Please execute <gbl.enter_global_management> first.")
def set_attr(self, key, value):
"""
设定一个变量到线程级变量字典中
"""
thread_ident = thread.get_ident()
if thread_ident in self.thread_context:
self.thread_context[thread_ident][key] = value
else:
raise GlobalManagementError("This code isn't under global management")
def enter_global_management(self, user_id=-1, user=None, session=None):
"""
Enters global management for a running thread. It must be balanced with
the appropriate leave_global_management call, since the actual state is
managed as a stack.
The state and dirty flag are carried over from the surrounding block or
from the settings, if there is no surrounding block (dirty is always false
when no current block is running).
"""
thread_ident = thread.get_ident()
if thread_ident not in self.thread_context:
self.thread_context[thread_ident] = {}
if user is not None:
self.set_attr('user_id', user.id)
self.set_attr('user', user)
else:
# self.thread_context[thread_ident]["user_id"] = user_id
self.set_attr('user_id', user_id)
if session is not None:
self.set_attr('session', session)
def leave_global_management(self):
"""
Leaves transaction management for a running thread. A dirty flag is carried
over to the surrounding block, as a commit will commit all changes, even
those from outside. (Commits are on connection level.)
"""
thread_ident = thread.get_ident()
if thread_ident in self.thread_context:
del self.thread_context[thread_ident]
else:
raise GlobalManagementError("This code isn't under global management")
fnd_global = ThreadFndGlobal()
| gpl-3.0 | 9,184,875,610,303,837,000 | 27.744292 | 135 | 0.587609 | false | 3.510876 | false | false | false |
ryanjdillon/smartmove | smartmove/utils.py | 1 | 10244 | '''
This module contains utility functions using in Smartmove
'''
def mask_from_noncontiguous_indices(n, start_ind, stop_ind):
'''Create boolean mask from start stop indices of noncontiguous regions
Args
----
n: int
length of boolean array to fill
start_ind: numpy.ndarray
start index positions of non-contiguous regions
stop_ind: numpy.ndarray
stop index positions of non-contiguous regions
Returns
-------
mask: numpy.ndarray, shape (n,), dtype boolean
boolean mask array
'''
import numpy
mask = numpy.zeros(n, dtype=bool)
for i in range(len(start_ind)):
mask[start_ind[i]:stop_ind[i]] = True
return mask
def get_n_lines(file_path):
'''Get number of lines by calling bash command wc
Args
----
file_path: str
File whose lines to count
Returns
-------
n_lines: int
Number of lines in file
'''
import os
import subprocess
cmd = 'wc -l {0}'.format(file_path)
output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).stdout
n_lines = int((output).readlines()[0].split()[0])
return n_lines
def get_versions(module_name):
'''Return versions for repository and packages in requirements file
Args
----
module_name: str
Name of module calling this routine, stored with local git hash
Returns
-------
versions: OrderedDict
Dictionary of module name and dependencies with versions
'''
from collections import OrderedDict
import importlib
import os
versions = OrderedDict()
module = importlib.util.find_spec(module_name)
# Get path to pylleo requirements file
module_path = os.path.split(module.origin)[0]
requirements = os.path.join(module_path, 'requirements.txt')
# Add git hash for module to dict
cwd = os.getcwd()
os.chdir(module_path)
try:
versions[module_name] = get_githash('long')
except:
versions[module_name] = module.__version__
os.chdir(cwd)
return versions
def get_githash(hash_type):
'''Add git commit for reference to code that produced data
Args
----
hash_type: str
keyword determining length of has. 'long' gives full hash, 'short'
gives 6 character hash
Returns
-------
git_hash: str
Git hash as a 6 or 40 char string depending on keywork `hash_type`
'''
import subprocess
cmd = dict()
cmd['long'] = ['git', 'rev-parse', 'HEAD']
cmd['short'] = ['git', 'rev-parse', '--short', 'HEAD']
return subprocess.check_output(cmd[hash_type]).decode('ascii').strip()
def symlink(src, dest):
'''Failsafe creation of symlink if symlink already exists
Args
----
src: str
Path or file to create symlink to
dest: str
Path of new symlink
'''
import os
# Attempt to delete existing symlink
try:
os.remove(dest)
except:
pass
os.symlink(src, dest)
return None
def cat_path(d, ignore):
'''Concatenate dictionary key, value pairs to a single string
Args
----
d: dict
Dictionary for which key, value pairs should be concatenated to str
ignore: iterable
List of keys to exclude from concatenated string
Returns
-------
s: str
String with concatenated key, value pairs
'''
items = list(d.items())
s = ''
for i in range(len(items)):
key, value = items[i]
if key not in set(ignore):
s += '{}_{}__'.format(key, value)
return s[:-2]
def _parse_subdir(path):
'''Parse parameters in names of child directories to pandas dataframe
Child directories in `path` are parsed so that the parameter values in
their directory names can be easily searched using a pandas.DataFrame.
Parameters are separated by double `__` and values by single `_`. Names
that include an `_` are joined back together after they are split
Args
----
path: str
Parent path with directories names with parameters to parse
Returns
-------
paths_df: pandas.DataFrame
Dataframe with one row for each respective child directory and one
column for each parameter.
'''
import os
import numpy
import pandas
dir_list = numpy.asarray(os.listdir(path), dtype=object)
# Search root directory for directories to parse
for i in range(len(dir_list)):
if os.path.isdir(os.path.join(path,dir_list[i])):
name = dir_list[i]
# Split parameters in name
dir_list[i] = dir_list[i].split('__')
for j in range(len(dir_list[i])):
param = dir_list[i][j].split('_')
# Join names with `_` back together, make key/value tuple
key = '_'.join(param[:-1])
value = param[-1]
if value == 'None':
value = numpy.nan
param = (key, float(value))
dir_list[i][j] = param
# Convert list of tuples to dictionary
dir_list[i] = dict(dir_list[i])
# Add directory name to dict for later retrieval
dir_list[i]['name'] = name
else:
dir_list[i] = ''
# Remove entries that are files
dir_list = dir_list[~(dir_list == '')]
# Convert list of dictionaries to dictionary of lists
keys = dir_list[0].keys()
params = dict()
for i in range(len(dir_list)):
for key in dir_list[i]:
if key not in params:
params[key] = numpy.zeros(len(dir_list), object)
params[key][i] = dir_list[i][key]
return pandas.DataFrame(params)
def get_subdir(path, cfg):
'''Get path to glide output data for a given `cfg_glide`
Args
----
path: str
Tag data parent path
cfg: OrderedDict
Composite dictions of cfg dicts
Returns
-------
path_data: str
Absolute path to glide data output path
'''
import os
import pyotelem
def match_subdir(path, cfg):
import numpy
n_subdirs = 0
for d in os.listdir(path):
if os.path.isdir(os.path.join(path, d)):
n_subdirs += 1
if n_subdirs == 0:
raise SystemError('No data subdirectories in {}'.format(path))
params = _parse_subdir(path)
mask = numpy.zeros(n_subdirs, dtype=bool)
# Evalute directory params against configuration params
# Set directory mask to True where all parameters are matching
for i in range(len(params)):
match = list()
for key, val in cfg.items():
if params[key].iloc[i] == val:
match.append(True)
else:
match.append(False)
mask[i] = all(match)
idx = numpy.where(mask)[0]
if idx.size > 1:
raise SystemError('More than one matching directory found')
else:
idx = idx[0]
return params['name'].iloc[idx]
subdir_glide = match_subdir(path, cfg['glides'])
path = os.path.join(path, subdir_glide)
subdir_sgl = match_subdir(path, cfg['sgls'])
path = os.path.join(path, subdir_sgl)
subdir_filt = match_subdir(path, cfg['filter'])
return os.path.join(subdir_glide, subdir_sgl, subdir_filt)
def filter_sgls(n_samples, exp_ind, sgls, max_pitch, min_depth,
max_depth_delta, min_speed, max_speed, max_speed_delta):
'''Create mask filtering only glides matching criterea
Args
----
n_samples: int
Total number of samples in tag data
exp_ind: ndarray
Boolean array to slice tag data to only experimental period
sgls: pandas.DataFrame
A dataframe of subglide indices and summary information obtained
in `glideid`
max_pitch: float
Maximum allowable pitch during sub-glide
min_depth: float
Minimum allowable depth during sub-glide
max_depth_delta: float
Maximum allowable change in depth during sub-glide
min_speed: float
Minimum allowable speed during sub-glide
max_speed: float
Maximum allowable speed during sub-glide
max_speed_delta: float
Maximum allowable change in speed during sub-glide
Returns
-------
mask_data_sgl: ndarray
Boolean mask to slice tag dataframe to filtered sub-glides
mask_sgls: ndarray
Boolean mask to slice sgls dataframe to filtered sub-glides
'''
import numpy
import pyotelem
# Defined experiment indices
mask_exp = (sgls['start_idx'] >= exp_ind[0]) & \
(sgls['stop_idx'] <= exp_ind[-1])
# Found within a dive
mask_divid = ~numpy.isnan(sgls['dive_id'].astype(float))
# Uniformity in phase (dive direction)
mask_phase = (sgls['dive_phase'] == 'descent') | \
(sgls['dive_phase'] == 'ascent')
# Depth change and minimum depth constraints
mask_depth = (sgls['total_depth_change'] < max_depth_delta) & \
(sgls['total_depth_change'] > min_depth)
# Pitch angle constraint
mask_deg = (sgls['mean_pitch'] < max_pitch) & \
(sgls['mean_pitch'] > -max_pitch)
# Speed constraints
mask_speed = (sgls['mean_speed'] > min_speed) & \
(sgls['mean_speed'] < max_speed) & \
(sgls['total_speed_change'] < max_speed_delta)
# Concatenate masks
mask_sgls = mask_divid & mask_phase & mask_exp & \
mask_deg & mask_depth & mask_speed
# Extract glide start/stop indices within above constraints
start_ind = sgls[mask_sgls]['start_idx'].values
stop_ind = sgls[mask_sgls]['stop_idx'].values
# Create mask for all data from valid start/stop indices
mask_data_sgl = mask_from_noncontiguous_indices(n_samples, start_ind,
stop_ind)
# Catch error with no matching subglides
num_valid_sgls = len(numpy.where(mask_sgls)[0])
if num_valid_sgls == 0:
raise SystemError('No sublides found meeting filter criteria')
return mask_data_sgl, mask_sgls
| mit | 7,730,799,665,802,462,000 | 26.836957 | 77 | 0.596251 | false | 4.010963 | false | false | false |
GregDMeyer/dynamite | config_extensions.py | 1 | 5481 |
from os import environ
from os.path import join, dirname, realpath
from subprocess import check_output
from setuptools import Extension
from setuptools.command.build_ext import build_ext
import numpy
import petsc4py
import slepc4py
extension_names = [
'bsubspace',
'bbuild',
'bpetsc'
]
header_only = {
'bsubspace',
}
cython_only = {
'bbuild',
}
def extensions():
paths = configure_paths()
exts = []
for name in extension_names:
depends = []
object_files = []
extra_args = paths
if name not in cython_only:
depends += ['dynamite/_backend/{name}_impl.h'.format(name=name)]
if name not in header_only:
depends += ['dynamite/_backend/{name}_impl.c'.format(name=name)]
object_files = ['dynamite/_backend/{name}_impl.o'.format(name=name)]
if name == 'bpetsc':
depends += ['dynamite/_backend/bsubspace.pxd'
'dynamite/_backend/bcuda_impl.h',
'dynamite/_backend/bcuda_impl.cu',
'dynamite/_backend/shellcontext.h',
'dynamite/_backend/bsubspace_impl.h']
if check_cuda():
object_files += ['dynamite/_backend/bcuda_impl.o'.format(name=name)]
exts += [
Extension('dynamite._backend.{name}'.format(name=name),
sources = ['dynamite/_backend/{name}.pyx'.format(name=name)],
depends = depends,
extra_objects = object_files,
**extra_args)
]
return exts
USE_CUDA = None
def check_cuda():
'''
Whether PETSc was built with CUDA support
'''
global USE_CUDA
if USE_CUDA is not None:
return USE_CUDA
with open(join(environ['PETSC_DIR'],
environ['PETSC_ARCH'],
'include/petscconf.h')) as f:
for line in f:
if 'PETSC_HAVE_CUDA' in line:
USE_CUDA = True
break
else:
USE_CUDA = False
return USE_CUDA
def write_build_headers():
'''
Write a Cython include file with some constants that become
hardcoded into the backend build.
'''
print('Writing header files...')
with open(join(dirname(__file__), 'dynamite', '_backend', 'config.pxi'), 'w') as f:
f.write('DEF USE_CUDA = %d\n' % int(check_cuda()))
dnm_version = check_output(['git', 'describe', '--always'],
cwd = dirname(realpath(__file__)),
universal_newlines = True).strip()
f.write('DEF DNM_VERSION = "%s"\n' % dnm_version)
dnm_version = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
cwd = dirname(realpath(__file__)),
universal_newlines = True).strip()
f.write('DEF DNM_BRANCH = "%s"\n' % dnm_version)
def configure_paths():
if any(e not in environ for e in ['PETSC_DIR', 'PETSC_ARCH', 'SLEPC_DIR']):
raise ValueError('Must set environment variables PETSC_DIR, '
'PETSC_ARCH and SLEPC_DIR before installing! '
'If executing with sudo, you may want the -E '
'flag to pass environment variables through '
'sudo.')
PETSC_DIR = environ['PETSC_DIR']
PETSC_ARCH = environ['PETSC_ARCH']
SLEPC_DIR = environ['SLEPC_DIR']
includes = []
libs = []
includes += [join(PETSC_DIR, PETSC_ARCH, 'include'),
join(PETSC_DIR, 'include')]
libs += [join(PETSC_DIR, PETSC_ARCH, 'lib')]
includes += [join(SLEPC_DIR, PETSC_ARCH, 'include'),
join(SLEPC_DIR, 'include')]
libs += [join(SLEPC_DIR, PETSC_ARCH, 'lib')]
# python package includes
includes += [petsc4py.get_include(),
slepc4py.get_include(),
numpy.get_include()]
return dict(
include_dirs = includes,
library_dirs = libs,
runtime_library_dirs = libs,
libraries = ['petsc', 'slepc']
)
class MakeBuildExt(build_ext):
def run(self):
# build the object files
for name in extension_names:
if name in header_only | cython_only:
continue
make = check_output(['make', '{name}_impl.o'.format(name=name)],
cwd='dynamite/_backend')
print(make.decode())
if check_cuda():
make = check_output(['make', 'bcuda_impl.o'], cwd='dynamite/_backend')
print(make.decode())
# get the correct compiler from SLEPc
# there is probably a more elegant way to do this
makefile = 'include ${SLEPC_DIR}/lib/slepc/conf/slepc_common\n' + \
'print_compiler:\n\t$(CC)'
CC = check_output(['make', '-n', '-f', '-', 'print_compiler'],
input = makefile, encoding = 'utf-8')
# now set environment variables to that compiler
if 'CC' in environ:
_old_CC = environ['CC']
else:
_old_CC = None
environ['CC'] = CC
try:
build_ext.run(self)
finally:
# set CC back to its old value
if _old_CC is not None:
environ['CC'] = _old_CC
else:
environ.pop('CC')
| mit | 94,712,092,300,876,580 | 29.45 | 87 | 0.52089 | false | 3.881728 | false | false | false |
imatec/prueba_front | prueba_front.py | 1 | 6476 | # -*- coding: utf-8 -*-
import os
import logging
from flask import Flask, abort, request, jsonify, g, url_for, render_template
from flask.ext.script import Manager
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.httpauth import HTTPBasicAuth
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer
as Serializer, BadSignature, SignatureExpired)
from datetime import datetime
# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'supermegasecret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['EXPIRATION'] = 30
# extensions
manager = Manager(app)
db = SQLAlchemy(app)
http_auth = HTTPBasicAuth()
@manager.command
def db_reset():
'''Resetear BD'''
db.drop_all()
db.create_all()
@manager.command
def create_data():
'''Agregar datos a BD'''
db_reset()
create_users()
create_tickets()
def create_users():
# rut, rutdv, name, is_admin, password, is_enabled, username=None
User.create('6', 'K', 'Administrador', True, 'admin.passwd', True)
User.create('1', '9', 'Usuario 1', False, 'usuario1.passwd', True)
User.create('2', '7', 'Usuario 2', False, 'usuario2.passwd', True)
def create_tickets():
Ticket.create('ticket 01', 1, u'descripción ticket 01')
Ticket.create('ticket 02', 2, u'descripción ticket 02')
Ticket.create('ticket 03', 3, u'descripción ticket 03')
Ticket.create('ticket 04', 1, u'descripción ticket 04')
Ticket.create('ticket 05', 2, u'descripción ticket 05')
Ticket.create('ticket 06', 3, u'descripción ticket 06')
Ticket.create('ticket 07', 1, u'descripción ticket 07')
Ticket.create('ticket 08', 2, u'descripción ticket 08')
Ticket.create('ticket 09', 3, u'descripción ticket 09')
Ticket.create('ticket 10', 1, u'descripción ticket 10')
Ticket.create('ticket 11', 2, u'descripción ticket 11')
Ticket.create('ticket 12', 3, u'descripción ticket 12')
class Ticket(db.Model):
__tablename__ = 'tickets'
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime(), default=datetime.utcnow)
name = db.Column(db.String(64), nullable=False)
description = db.Column(db.String(255))
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
@classmethod
def create(cls, name, user_id, description=u""):
try:
ticket = Ticket(
name=name,
user_id=user_id,
description=description
)
db.session.add(ticket)
db.session.commit()
except Exception as e:
logging.exception(e)
def serialize(self):
return {
'id': self.id,
'timestamp': self.timestamp,
'name': self.name,
'description': self.description,
'user_id': self.user_id
}
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
rut = db.Column(db.String(64), nullable=False)
rutdv = db.Column(db.String(1), nullable=False)
username = db.Column(db.String(255), nullable=False, unique=True, index=True)
name = db.Column(db.String(255), nullable=False)
is_admin = db.Column(db.Boolean)
is_enabled = db.Column(db.Boolean)
member_since = db.Column(db.DateTime(), default=datetime.utcnow)
password_hash = db.Column(db.String(128))
def hash_password(self, password):
self.password_hash = pwd_context.encrypt(password)
def verify_password(self, password):
return pwd_context.verify(password, self.password_hash)
def generate_auth_token(self, expiration=app.config['EXPIRATION']):
s = Serializer(app.config['SECRET_KEY'], expires_in=expiration)
return s.dumps({'id': self.id})
@classmethod
def create(cls, rut, rutdv, name, is_admin, password, is_enabled, username=None):
try:
if not username:
username = "{0}-{1}".format(rut, rutdv).upper()
user = User(
username=username,
is_admin=is_admin,
name=name,
rut=rut,
rutdv=rutdv,
is_enabled=is_enabled
)
user.hash_password(password)
db.session.add(user)
db.session.commit()
except Exception as e:
logging.exception(e)
@staticmethod
def verify_auth_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
data = s.loads(token)
except SignatureExpired:
return None # valid token, but expired
except BadSignature:
return None # invalid token
user = User.query.get(data['id'])
return user
def serialize(self):
return {
'id': self.id,
'rut': self.rut,
'rutdv': self.rutdv,
'username': self.username,
'name': self.name,
'is_admin': self.is_admin,
'is_enabled': self.is_enabled,
'member_since': self.member_since,
}
@http_auth.verify_password
def verify_password(username_or_token, password):
# first try to authenticate by token
user = User.verify_auth_token(username_or_token)
if not user:
# try to authenticate with username/password
user = User.query.filter_by(username=username_or_token).first()
if not user or not user.verify_password(password):
return False
g.user = user
return True
@app.route('/')
def get_main():
return render_template('index.html')
@app.route('/api/users/<int:id>')
def get_user(id):
user = User.query.get(id)
if not user:
abort(400)
return jsonify({'username': user.username})
@app.route('/api/token')
@http_auth.login_required
def get_auth_token():
token = g.user.generate_auth_token(app.config['EXPIRATION'])
return jsonify({'token': token.decode('ascii'), 'duration': app.config['EXPIRATION']})
@app.route('/api/current')
@http_auth.login_required
def get_resource():
return jsonify({'data': g.user.serialize()})
@app.route('/api/tickets')
@http_auth.login_required
def get_tickets():
tickets = Ticket.query.all()
return jsonify({'data': [t.serialize() for t in tickets]})
if __name__ == '__main__':
manager.run()
| mit | 7,299,456,046,211,614,000 | 29.780952 | 90 | 0.619121 | false | 3.528384 | true | false | false |
jerrylei98/Dailydos | app.py | 1 | 3926 | from flask import Flask, render_template, request, redirect, session, url_for
import login_utils, tasks_utils
application = Flask(__name__)
@application.route("/", methods=['GET','POST'])
@application.route("/home", methods=['GET','POST'])
def home():
if 'logged_in' not in session:
session['logged_in'] = False
if 'user' not in session:
session['user'] = 'Guest'
# return render_template('home.html')
if request.method=="GET":
return render_template('home.html')
else:
button = request.form['button']
if button == "Create Account":
user = request.form['new_username']
password = request.form['new_password']
confirm = request.form['new_confirm_password']
#password match check
if (password == confirm):
#username and password lengths check
if "@" not in user:
return render_template('home.html',errorC="Username must be a valid email")
if len(password)<8:
return render_template('home.html',errorC="Password must be longer than 8 characters")
#account created successfully
if login_utils.create_user(user,password):
return render_template('home.html',successC="Account successfully created! Login to access DailyDos.")
#username taken error
else:
return render_template('home.html',errorC="Username already in use. Please chose a different username")
else:
return render_template('home.html',errorC="Passwords do not match")
#Login
#if credentials valid, log them in with session
if button == "Login":
user = request.form['login_username']
password = request.form['login_password']
if login_utils.authenticate(user,password):
session['user'] = user
session['logged_in'] = True
return redirect(url_for('tasks'))
#else renders login w/ error message
else:
return render_template("home.html",errorL="Invalid Username or Password")
@application.route("/tasks", methods=["GET","POST"])
def tasks():
tasks_list = tasks_utils.get_tasks(session['user'])
if session['logged_in'] == False:
return redirect('/home')
if request.method == "GET":
return render_template("tasks.html", tasks = tasks_list)
if request.method == "POST":
button = request.form['button']
if button == "Remove These":
#page_ids = request.form.get("do_delete")
checked = request.form.getlist("checks")
#checked = []
#for items in request.form.get("do_delete"):
# checked.append(items)
#selected = bool(checked)
#f = open('log_file', 'w')
#for keys in selected:
# f.write(selected)
#f.close()
tasks_utils.remove_tasks(checked)
tasks_list = tasks_utils.get_tasks(session['user'])
return render_template("tasks.html", tasks = tasks_list)
if button == "Clear All":
tasks_utils.clear_tasks(session['user'])
tasks_list = tasks_utils.get_tasks(session['user'])
return render_template("tasks.html", tasks = tasks_list)
else:
return render_template("tasks.html", tasks = tasks_list)
@application.route("/logout")
def logout():
session['user'] = "Guest"
session['logged_in'] = False
return redirect('/home')
application.secret_key = "pleasework"
if __name__=="__main__":
application.run(host='0.0.0.0')
"""
application.debug = True
application.secret_key = "onetwothreefour"
application.run(host='0.0.0.0', port = 5000)
"""
| mit | -311,086,397,280,734,200 | 39.895833 | 135 | 0.57081 | false | 4.295405 | false | false | false |
ucsb-cs/submit | submit/migrations/versions/32e8060589b8_add_missing_indexes.py | 1 | 1674 | """Add missing indexes.
Revision ID: 32e8060589b8
Revises: a3fe8c8a344
Create Date: 2014-02-11 17:21:00.718449
"""
# revision identifiers, used by Alembic.
revision = '32e8060589b8'
down_revision = 'a3fe8c8a344'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_index('ix_group_created_at', 'group', ['created_at'], unique=False)
op.create_index('ix_grouprequest_created_at', 'grouprequest', ['created_at'], unique=False)
op.create_index('ix_grouprequest_from_user_id', 'grouprequest', ['from_user_id'], unique=False)
op.create_index('ix_grouprequest_project_id', 'grouprequest', ['project_id'], unique=False)
op.create_index('ix_grouprequest_to_user_id', 'grouprequest', ['to_user_id'], unique=False)
op.create_index('ix_testableresult_created_at', 'testableresult', ['created_at'], unique=False)
op.create_index('ix_user_to_group_group_id', 'user_to_group', ['group_id'], unique=False)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_index('ix_user_to_group_group_id', table_name='user_to_group')
op.drop_index('ix_testableresult_created_at', table_name='testableresult')
op.drop_index('ix_grouprequest_to_user_id', table_name='grouprequest')
op.drop_index('ix_grouprequest_project_id', table_name='grouprequest')
op.drop_index('ix_grouprequest_from_user_id', table_name='grouprequest')
op.drop_index('ix_grouprequest_created_at', table_name='grouprequest')
op.drop_index('ix_group_created_at', table_name='group')
### end Alembic commands ###
| bsd-2-clause | 8,611,515,270,830,671,000 | 43.052632 | 99 | 0.701314 | false | 3.105751 | false | false | false |
ocadotechnology/wry | wry/AMTRedirection.py | 1 | 1893 | # 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 . import wsmanModule
AMT_REDIRECTION_STATE_MAP = {
0: 'Unknown',
1: 'Other',
2: 'Enabled',
3: 'Disabled',
4: 'Shutting Down',
5: 'Not Applicable',
6: 'Enabled but Offline',
7: 'In Test',
8: 'Deferred',
9: 'Quiesce',
10: 'Starting',
11: 'DMTF Reserved',
32768: (),
32769: ('IDER'),
32770: ('SoL'),
32771: ('IDER', 'SoL'),
}
class AMTRedirection(wsmanModule.wsmanModule):
'''Control over Serial-over-LAN and storage redirection.'''
_RESOURCES = {
'redirectionService': 'AMT_RedirectionService',
}
@property
def enabled_features(self):
state = self.RESOURCES['redirectionService'].get('EnabledState')
return AMT_REDIRECTION_STATE_MAP[state]
@enabled_features.setter
def enabled_features(self, features):
if not features:
value = 32768
elif 'SoL' in features and 'IDER' in features:
value = 32771
elif 'SoL' in features:
value = 32770
elif 'IDER' in features:
value = 32769
else:
raise ValueError('Invalid data provided. Please provide a list comprising only of the following elements: %s' % ', '.join([value.__repr__ for value in self.enabled.values]))
self.RESOURCES['redirectionService'].put(EnabledState = value)
| apache-2.0 | 1,549,599,297,185,251,800 | 31.637931 | 185 | 0.645536 | false | 3.741107 | false | false | false |
storborg/sidecar | sidecar/themes/light/__init__.py | 1 | 1199 | from pyramid_frontend.theme import Theme
from pyramid_frontend.images import FilterChain
from pyramid_frontend.assets.less import LessAsset
from pyramid_frontend.assets.requirejs import RequireJSAsset
class LightTheme(Theme):
key = 'light'
image_filters = (
FilterChain(
'thumb', width=330, height=220, extension='jpg',
crop=True, quality=80, sharpness=1.5),
FilterChain(
'square', width=300, height=300, extension='jpg',
crop=True, quality=80, sharpness=1.5),
FilterChain(
'about', width=400, height=300, extension='jpg',
quality=80, sharpness=1.5),
FilterChain(
'large', width=800, height=600, extension='jpg', resize=True,
quality=85, sharpness=1.5),
FilterChain(
'huge', width=2400, height=500, extension='jpg', quality=90,
sharpness=1.5),
)
assets = {
'main-less': LessAsset('/_light/css/main.less'),
'main-js': RequireJSAsset(
'/_light/js/main.js',
require_config_path='/_light/js/require_config.js',
require_base_url='/_light/js/vendor/',
),
}
| mit | 3,023,817,755,633,104,400 | 29.74359 | 73 | 0.58799 | false | 3.677914 | false | false | false |
shanzi/myicons | fontbuilder/ttf2eot/bytebuffer.py | 3 | 1339 | #!/usr/bin/env python
# encoding: utf-8
import io
import struct
class ByteBuffer(io.BytesIO):
def makefmt(self, width, littleEndian=False):
fmt = '<' if littleEndian else '>'
if width == 8: fmt += 'B'
elif width == 16: fmt += 'H'
elif width == 32: fmt += 'I'
else: fmt += 'L'
return fmt
def maskValue(self, width, value):
if width == 8: return value & 0xFF
elif width == 16: return value & 0xFFFF
elif width == 32: return value & 0xFFFFFFFF
return value
def getuint(self, width, pos):
oldpos = self.tell()
self.seek(pos)
fmt = self.makefmt(width, False)
value = struct.unpack(fmt, self.read(width / 8))
self.seek(oldpos)
return value[0]
def setuint(self, width, pos, value, littleEndian=False):
self.seek(pos)
fmt = self.makefmt(width, littleEndian)
maskedValue = self.maskValue(width, value)
self.write(struct.pack(fmt, maskedValue))
def writeuint(self, width, value, littleEndian=False):
fmt = self.makefmt(width, littleEndian)
self.write(struct.pack(fmt, value))
def readat(self, pos, length):
oldpos = self.tell()
self.seek(pos)
value = self.read(length)
self.seek(oldpos)
return value
| bsd-2-clause | -729,330,362,267,760,800 | 27.489362 | 61 | 0.584765 | false | 3.580214 | false | false | false |
xcxuanchen/eden_growth_model | BD5.py | 1 | 7485 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
class BallisticDeposition:
"""store all heights as a 1 dim array"""
def __init__(self, L_x, Periodic_BCs=None):
"""need to enter parameters as floats; actual system width is L_x-2 as edge columns are not used;
Insert True if you want to impose periodic boundary conditions"""
self.__xsize = L_x
self.__Periodic_BCs=Periodic_BCs
m = 0
n = 0
self.propagation_number=m #keeps track of how many times the instance has been propagated
self.total_particles=n
roughness_array=np.array([])
self.roughness_array=roughness_array #empty array used for roughness values
time_array=np.array([])
self.time_array=time_array #empty array used for corresponding time values
if isinstance(L_x, int) == True:
system_array = np.zeros((1, self.__xsize)) #indices go from 0 to self.__xsize-1
self.system_array = system_array
else:
raise Exception("need to insert an integer")
def __repr__(self):
return "%s(number of columns = %g)" % ("system size", self.__xsize)
def __str__(self):
return "[%s]" % (self.__xsize)
def size_of_system(self):
return self.__xsize
def current_array(self):
return self.system_array
def random_columns(self, n): #where n is the number of iterations; function generates random column numbers
#ONLY METHOD THAT CHANGES WHEN IMPOSING PERIODIC BOUNDARY CONDITIONS
if self.__Periodic_BCs == True:
self.chosen_columns=np.random.random_integers(0,self.__xsize-1, n) #inclusive of upper and lower bounds
else:
self.chosen_columns=np.random.random_integers(1,self.__xsize-2, n) #inclusive of upper and lower bounds
return self.chosen_columns
def array_search(self, j):
"""returns the height for a particular column"""
return self.system_array[0][j]
def update_array(self, h, j): #turns a site from 0 to 1 in a matrix
self.system_array.itemset((0,j),h)
return self.system_array
def deposit_particles(self, n):#here n is for the number of particles we are depositing on the lattice
self.random_columns(n) #every time is called get a DIFFERENT set of random numbers
for j in self.chosen_columns:#if statements applying boundary conditions
#also will work when BCs not imposed if edge columns are NEVER selected, i.e. system is effectively two columns smaller
if j==0:
p=self.array_search(0)+1
q=self.array_search(1)
r=self.array_search(self.__xsize-1)
if j==self.__xsize-1:
p=self.array_search(self.__xsize-1)+1
q=self.array_search(0)
r=self.array_search(self.__xsize-2)
else:
p=self.array_search(j)+1
q=self.array_search(j+1)
r=self.array_search(j-1)
x=[p,q,r]
h=max(x)
self.update_array(h, j)
#print j, self.system_array
return h
def roughness(self): #works out the roughness for a particular square matrix
"""returns the rougheness for the array"""
x=np.array([])
for j in np.arange(0, self.__xsize,1):
x=np.append(x, self.array_search(j))
y=np.average(x)
a=(x-y)**2
b=np.sum(a)
z=(1/(float(self.__xsize)))*b #remember edge columns are kept empty so column does not
w=z**0.5
return w
def roughness_dynamics(self, n, iterations):#generates a series of roughness values for a series of matrices
"""iterates the BD forward in time, depositing n particles for each of the iterations; takes instance of the BallisticDeposition class"""
self.n=n #property of the data analysis object
self.iterations=iterations #property of the dataanalysis object
self.propagation_number= self.propagation_number + self.iterations #property of the BallisticDeposition object; total no. of iterations ,i.e. data values
self.total_particles = self.total_particles + self.iterations*self.n #property of the BallisticDeposition object; total no. of particles deposited
x=np.array([])
m=1
while m<=iterations:
self.deposit_particles(n)
x=np.append(x, self.roughness())
m = m+1
print m-1
self.data=x
return self.data
def add_data(self):
"""filling data into separate roughness array and creating the matching time array; need to enter numpy array as the parameter"""
for i in np.arange(0, self.data.size):
self.roughness_array=np.append(self.roughness_array, self.data[i])
self.time_array=np.append(self.time_array, np.arange(self.total_particles-(self.iterations-1)*self.n, self.total_particles+self.n,self.n))
return self.roughness_array, self.time_array
def erase_data(self):
self.roughness_array=np.array([])
self.time_array=np.array([])
return self.roughness_array, self.time_array
def partial_erase_data(self, first_index, last_index):
"""erases all the elements in between and including those given by the indices"""
self.roughness_array=np.delete(self.roughness_array, np.arange(first_index, last_index+1))
self.time_array=np.delete(self.time_array, np.arange(first_index, last_index+1))
return self.roughness_array, self.time_array
def line_plot(self, line_of_best_fit=None):
log_t=np.log(self.time_array)
log_w=np.log(self.roughness_array)
m, b = np.polyfit(log_t, log_w, 1)
fig = plt.figure()
fig.suptitle('Log-log Plot of Roughness Against Time', fontsize=14, fontweight='bold')
ax = fig.add_subplot(111)
ax.set_title('axes title')
ax.set_xlabel('log(t)')
ax.set_ylabel('log(w)')
ax.plot(log_t, log_w, 'r+')
if line_of_best_fit == True:
ax.plot(log_t, m*log_t + b, '-')
ax.text(0.1,0.9, r'$\beta=$%g' % (m) , style='italic', horizontalalignment='left',verticalalignment='top', transform=ax.transAxes )
ax.text(0.1,0.8, 'Particles Deposited=%g' % (self.total_particles) , style='italic', horizontalalignment='left',verticalalignment='top', transform=ax.transAxes ) #position of test and the test itself
#plt.axis([40, 160, 0, 0.03])
plt.grid(True)
plt.show()
return None
def saturation_value(self):
w_sat = np.average(self.roughness_array)
| mit | -437,188,560,711,102,100 | 37.198953 | 209 | 0.562725 | false | 3.908616 | false | false | false |
zackw/active-geolocator | maps/make_geog_baseline.py | 1 | 10351 | #! /usr/bin/python3
"""Construct a geographic "baseline" matrix from a collection of
shapefiles (assumed to be maps of the Earth). Shapefiles can be
either "positive" or "negative". The baseline matrix represents a
grid laid over the Earth; points inside the union of positive geometry
and not inside the union of negative geometry will have value 1,
points well within the complementary space will have value 0, and
points right on the edge (as determined by the "fuzz" argument) will
have intermediate values. The grid will have points exactly on all
four edges, except when the westmost and eastmost meridians coincide,
in which case the eastmost meridian will not be included.
"""
import argparse
import functools
import math
import os
import sys
import fiona
import fiona.crs
import numpy as np
import pyproj
import shapely
import shapely.geometry
import shapely.ops
import shapely.prepared
import tables
from fiona.errors import FionaValueError
from argparse import ArgumentTypeError
class GeographicMatrix:
def __init__(self, args):
# WGS84 reference ellipsoid: see page 3-1 (physical page 34) of
# http://earth-info.nga.mil/GandG/publications/tr8350.2/wgs84fin.pdf
# A and F are exact, A is in meters.
A = 6378137 # equatorial semi-axis
F = 1/298.257223563 # flattening
B = A * (1-F) # polar semi-axis
lon_spacing = (args.resolution * 180) / (A * math.pi)
lat_spacing = (args.resolution * 180) / (B * math.pi)
fuzz_degrees = (args.fuzz * 180) / ((A+B) * math.pi / 2)
# To avoid rounding errors, precalculate the number of grid rows
# and columns so we can use linspace() rather than arange().
n_lon = int(math.floor((args.east - args.west) / lon_spacing))
n_lat = int(math.floor((args.north - args.south) / lat_spacing))
south = args.south
north = south + n_lat * lat_spacing
west = args.west
east = west + n_lon * lon_spacing
if (east - west) - 360.0 <= 1e-6:
sys.stderr.write("East-west wraparound, shrinking grid.\n")
n_lon -= 1
east -= lon_spacing
sys.stderr.write(
"Matrix dimensions {}x{}\n"
"Longitude spacing {:.9f}; eastmost grid error {:.9f}\n"
" Latitude spacing {:.9f}; northmost grid error {:.9f}\n"
.format(n_lon, n_lat,
lon_spacing, args.east - east,
lat_spacing, args.north - north))
lon = np.linspace(west, east, n_lon)
lat = np.linspace(south, north, n_lat)
mtx = np.zeros((n_lat, n_lon), dtype=np.float32)
# We save all the (adjusted) parameters from the command line
# so we can record them as metadata in the output file later.
self.resolution = args.resolution
self.fuzz = args.fuzz
self.north = north
self.south = south
self.west = west
self.east = east
self.lon_spacing = lon_spacing
self.lat_spacing = lat_spacing
# These are actually needed by process_geometry.
self.lon = lon
self.lat = lat
self.mtx = mtx
self.fuzz_deg = fuzz_degrees
self.geoms = []
def write_to(self, fname):
with tables.open_file(fname, 'w') as f:
M = f.create_carray(f.root, 'baseline',
tables.Atom.from_dtype(self.mtx.dtype),
self.mtx.shape,
filters=tables.Filters(complevel=6,
complib='zlib'))
M[:,:] = self.mtx[:,:]
M.attrs.resolution = self.resolution
M.attrs.fuzz = self.fuzz
M.attrs.north = self.north
M.attrs.south = self.south
M.attrs.east = self.east
M.attrs.west = self.west
M.attrs.lon_spacing = self.lon_spacing
M.attrs.lat_spacing = self.lat_spacing
M.attrs.longitudes = self.lon
M.attrs.latitudes = self.lat
# If you don't manually encode the strings, or if you use
# normal Python arrays, you get pickle barf in the file
# instead of a proper HDF vector-of-strings. I could
# combine these attributes into a record array, but this
# is simpler.
M.attrs.geom_names = np.array([ g[1].encode('utf-8')
for g in self.geoms ])
M.attrs.geom_senses = np.array([ g[0].encode('utf-8')
for g in self.geoms ])
# If you don't set a TITLE on M, the file is slightly out of
# spec and R's hdf5load() will segfault(!)
M.attrs.TITLE = "baseline"
def process_geometry(self, sense, geom):
assert sense == '+' or sense == '-'
name = os.path.splitext(os.path.basename(geom.name))[0]
self.geoms.append((sense, name))
sys.stderr.write("Processing {} (crs={})...\n"
.format(name, fiona.crs.to_string(geom.crs)))
# unary_union does not accept generators
inner_boundary = shapely.ops.unary_union([
shapely.geometry.shape(g['geometry'])
for g in geom])
# It is (marginally) more efficient to transform the inner
# boundary to the desired "raw WGS84 lat/long" coordinate
# system after combining it into one shape.
inner_boundary = shapely.ops.transform(
functools.partial(
pyproj.transform,
pyproj.Proj(geom.crs),
pyproj.Proj(proj="latlong", datum="WGS84", ellps="WGS84")),
inner_boundary)
outer_boundary = inner_boundary.buffer(self.fuzz_deg)
inner_boundary_p = shapely.prepared.prep(inner_boundary)
outer_boundary_p = shapely.prepared.prep(outer_boundary)
for i, x in enumerate(self.lon):
for j, y in enumerate(self.lat):
pt = shapely.geometry.Point(x, y)
if inner_boundary_p.contains(pt):
val = 1
elif not outer_boundary_p.contains(pt):
val = 0
else:
# in between
val = 1 - min(1, max(0,
pt.distance(inner_boundary)/self.fuzz_deg))
if sense == '+':
self.mtx[j,i] = min(1, self.mtx[j,i] + val)
else:
self.mtx[j,i] = max(0, self.mtx[j,i] - val)
def process(args):
matrix = GeographicMatrix(args)
for sense, geom in args.shapefile:
matrix.process_geometry(sense, geom)
matrix.write_to(args.output)
def main():
def shapefile(fname):
if not fname:
raise ArgumentTypeError("shapefile name cannot be empty")
if fname[0] == '+':
tag = '+'
fname = fname[1:]
else:
tag = '?'
try:
return (tag, fiona.open(fname, 'r'))
except FionaValueError as e:
raise ArgumentTypeError(
"%s: not a shapefile (%s)" % (fname, str(e)))
except OSError as e:
raise ArgumentTypeError(
"%s: cannot open (%s)" % (fname, e.strerror))
def fixup_shapefile_arg(n, arg):
if arg[0] != '?': return arg
if n == 0: return ('+', arg[1])
return ('-', arg[1])
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('-s', '--south', type=float, default=-60,
help='Southmost latitude for the output matrix. '
'The default is -60, which is south of all major '
'landmasses except Antarctica.')
ap.add_argument('-n', '--north', type=float, default=84,
help='Northmost latitude for the output matrix. '
'The default is 84, which is north of all major '
'landmasses.')
ap.add_argument('-w', '--west', type=float, default=-180,
help='Westmost longitude for the output matrix. '
'The default is -180.')
ap.add_argument('-e', '--east', type=float, default=180,
help='Eastmost longitude for the output matrix. '
'The default is 180.')
ap.add_argument('-r', '--resolution', type=float, default=5000,
help='Grid resolution of the matrix, in meters at '
'the equator. The matrix is NOT projected, so its '
'east-west resolution closer to the poles will be finer.'
'The default is 5km.')
ap.add_argument('-f', '--fuzz', type=float, default=None,
help='Fuzz radius. Points outside the positive geometry '
'by less than this distance will have values between 0 and '
'1. The default is 1.5 times the resolution.')
ap.add_argument('-o', '--output', default=None,
help='Name of output file. The default is to use the '
'name of the first input shapefile, with a ".hdf" suffix.')
ap.add_argument('shapefile', type=shapefile, nargs='+',
help='Shapefiles to process. The first shapefile in the '
'list is always considered positive geometry; subsequent '
'shapefiles are negative geometry unless specified with a '
'leading "+" on the filename.')
args = ap.parse_args()
if not args.shapefile:
ap.error("at least one shapefile must be specified")
if not (-180 <= args.west < args.east <= 180):
ap.error("improper values for --west/--east")
if not (-90 <= args.south < args.north < 90):
ap.error("improper values for --south/--north")
args.shapefile = [fixup_shapefile_arg(n, arg)
for n, arg in enumerate(args.shapefile)]
if args.output is None:
args.output = os.path.splitext(args.shapefile[0][1].name)[0] + '.hdf'
if args.fuzz is None:
args.fuzz = args.resolution * 1.5
process(args)
main()
| mit | -7,904,016,563,273,701,000 | 38.208333 | 80 | 0.55328 | false | 3.955292 | false | false | false |
cxcsds/ciao-contrib | ciao_contrib/caldb.py | 1 | 15200 | #
# Copyright (C) 2010, 2011, 2012, 2014, 2015, 2016, 2019
# Smithsonian Astrophysical Observatory
#
#
# 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
"""Find the version numbers and release dates of the Chandra CALDB.
"""
import os
import copy
import socket
import time
from html.parser import HTMLParser
from urllib.request import urlopen
from urllib.error import URLError
import pycrates
from ciao_contrib import logger_wrapper as lw
__all__ = (
"check_caldb_version",
"get_caldb_dir",
"get_caldb_releases",
"get_caldb_installed",
"get_caldb_installed_version",
"get_caldb_installed_date"
)
lgr = lw.initialize_module_logger('caldb')
v3 = lgr.verbose3
release_notes_url = "https://cxc.cfa.harvard.edu/caldb/downloads/releasenotes.html"
def todate(txt):
"""Convert text to time.
This is intended to convert a time string, as reported by the
CALDB web pages, to a time object.
Parameters
----------
txt : str or None
The time string.
Returns
-------
val : time object or str or None
If the input can be converted to a time object then that
object is returned, otherwise the input is returned unchanged.
"""
if txt is None:
return None
try:
return time.strptime(txt + "UTC", "%Y-%m-%dT%H:%M:%S%Z")
except ValueError:
return txt
# The current version has the main data in a td with class=mainbar
# but this is hopefully going to change RSN for a div (as this comment
# was written a long time ago it obviously hasn't happened).
#
class CALDBReleaseParser(HTMLParser):
"""Extract relevant fields from the CIAO CALDB web page.
Parse the CALDB release-notes HTML page for
release information on the CALDB.
Raises
------
IOError
This can be caused if the result is empty (at least for the
CALDB release column); the page can not be parsed (e.g. it
does not match the expected contents). The error messages
are not 'user friendly' since they may reveal the internal
state of the object to make debugging easier.
Examples
--------
The use is, where h is a string containing the HTML to parse:
>>> p = CALDBReleaseParser()
>>> p.feed(h)
>>> p.close()
and then the p.releases field is a dictionary where the keys are
the various CALDB release types (e.g. CALDB, SDP, CIAO, and L3)
and the values are tuples of (version number, date) where the
version number is a string and the date is a time object.
"""
state = "need-table"
open_mode = {"need-table":
{"tag": "table",
"attribute": ("id", "caldbver"),
"newstate": "check-header"
},
}
close_mode = {"check-header": {"tag": "tr",
"newstate": "store-data"},
"store-data": {"tag": "table",
"newstate": "finished"}
}
store = []
row_store = None
item_store = None
def close(self):
HTMLParser.close(self)
if self.state != "finished":
raise IOError("incorrectly-nested tables; state={}".format(self.state))
st = self.store
def make(i):
return [(s[0], s[i]) for s in st if s[i] is not None]
self.releases = {"CALDB": make(1),
"SDP": make(2),
"CIAO": make(3),
"L3": make(4)}
if len(self.releases["CALDB"]) == 0:
raise IOError("No CALDB release information found!")
def handle_starttag(self, tag, attrs):
if self.state == "store-data":
# Could do the storing via a pseudo state machine as we do with
# finding the table, but just hard code the logic for now
#
if self.row_store is None:
if tag == "tr":
self.row_store = []
else:
raise IOError("A new row has started with the tag: {}".format(tag))
if tag == "td":
if self.item_store is None:
self.item_store = ""
else:
raise IOError("A new item has started but the item_store=[{}]".format(self.item_store))
return
if self.state not in self.open_mode:
return
tbl = self.open_mode[self.state]
if tag != tbl["tag"] or \
("attribute" in tbl and tbl["attribute"] not in attrs):
return
if "newstate" in tbl:
self.state = tbl["newstate"]
def handle_endtag(self, tag):
if self.state == "store-data":
if tag == "td":
item = self.item_store.strip()
if item.lower() in ["n/a", "not released publicly"]:
self.row_store.append(None)
else:
self.row_store.append(item)
self.item_store = None
elif tag == "tr":
r = self.row_store
if len(r) != 5:
raise IOError("Unable to parse row: {0}".format(r))
self.store.append((r[0],
todate(r[1]),
todate(r[2]),
todate(r[3]),
todate(r[4])))
self.row_store = None
if self.state not in self.close_mode:
return
tbl = self.close_mode[self.state]
if tag != tbl["tag"]:
return
self.state = tbl["newstate"]
def handle_data(self, data):
if self.state == "store-data" and self.item_store is not None:
ds = data.strip()
if ds is not None:
if self.item_store == "":
self.item_store = ds
else:
self.item_store += " {0}".format(ds)
def get_caldb_releases(timeout=None):
"""Return information on the CIAO CALDB releases.
Extracts the CIAO CALDB release history from the web page.
Parameters
----------
timeout : optional
The timeout option for the urlopen call. If not set then the
global Python timeout setting will be used. If given then it
is the maximum time to wait in seconds.
Returns
-------
releases : dict
The keys are the names "CALDB", "SDP", "CIAO" or "L3",
and the values are arrays of (version-string, date) tuples.
There is no guarantee that the lists are in descending order
of time or version number.
Raises
------
IOError
Many network errors are converted to an IOError with a
simple error message.
Notes
-----
This routine will only work if the computer is on-line and able to
access the Chandra CALDB pages at
https://cxc.cfa.harvard.edu/caldb/
This call turns off certificate validation for the requests since
there are issues with getting this working on all supported platforms.
It *only* does it for the calls it makes (i.e. it does not turn
off validation of any other requests).
The version-string is "1.2" or "4.2.2" and the date is a time
object.
"""
import ssl
# Note that the SSL context is explicitly
# set to stop verification, because the CIAO 4.12 release has
# seen some issues with certificate validation (in particular
# on Ubuntu and macOS systems).
#
context = ssl._create_unverified_context()
v3("About to download {}".format(release_notes_url))
try:
if timeout is None:
h = urlopen(release_notes_url, context=context)
else:
h = urlopen(release_notes_url, context=context, timeout=timeout)
except URLError as ue:
v3(" - failed with {}".format(ue))
# Probably excessive attempt to make a "nice" error message
#
if hasattr(ue, "reason"):
if hasattr(ue.reason, "errno") and \
ue.reason.errno == socket.EAI_NONAME:
raise IOError("Unable to reach the CALDB site - is the network down?")
else:
raise IOError("Unable to reach the CALDB site - {}".format(ue.reason))
elif hasattr(ue, "getcode"):
cval = ue.getcode()
if cval == 404:
raise IOError("The CALDB site appears to be unreachable.")
else:
raise IOError("The CALDB site returned {}".format(ue))
else:
raise IOError("Unable to access the CALDB site - {}".format(ue))
h = h.read().decode('utf-8')
try:
p = CALDBReleaseParser()
p.feed(h)
p.close()
except IOError:
raise IOError("Unable to parse the CALDB release table.")
# use a deep copy so that the parser can be cleaned up
# in case there's a lot of state squirreled away
# (although have not checked that it actually matters)
return copy.deepcopy(p.releases)
def get_caldb_dir():
"""Return the location of the CIAO CALDB.
Returns
-------
path : str
The location of the CIAO CALDB, as given by the CALDB
environment variable.
Raises
------
IOError
If the CALDB environment variable is not defined or does
not point to a directory.
"""
caldb = os.getenv("CALDB")
if caldb is None:
raise IOError("CALDB environment variable is not defined!")
elif not os.path.isdir(caldb):
raise IOError("CALDB directory does not exist: {}".format(caldb))
else:
return caldb
def get_caldb_installed(caldb=None):
"""What CIAO CALDB is installed (version and release date)?
Parameters
----------
caldb : str, optional
If set, the directory to search in, otherwise the
CALDB environment variable is used.
Returns
-------
version, date
The CIAO CALDB version, as a string, and the release date
of the version (as a date object) of the installed
CIAO CALDB.
See Also
--------
get_caldb_installed_date, get_caldb_installed_version
"""
if caldb is None:
caldb = get_caldb_dir()
fname = os.path.join(caldb,
"docs/chandra/caldb_version/caldb_version.fits")
cr = pycrates.TABLECrate(fname, mode='r')
for cname in ["CALDB_VER", "CALDB_DATE"]:
if not cr.column_exists(cname):
raise IOError("Unable to find the {} column in the CALDB version file.".format(cname))
cversion = pycrates.copy_colvals(cr, "CALDB_VER")[-1]
cdate = pycrates.copy_colvals(cr, "CALDB_DATE")[-1]
cversion = cversion.strip()
cdate = cdate.strip()
return (cversion, todate(cdate))
def get_caldb_installed_version(caldb=None):
"""What CIAO CALDB is installed (version)?
Parameters
----------
caldb : str, optional
If set, the directory to search in, otherwise the
CALDB environment variable is used.
Returns
-------
version : str
The CIAO CALDB version, as a string.
See Also
--------
get_caldb_installed, get_caldb_installed_date
"""
return get_caldb_installed(caldb)[0]
def get_caldb_installed_date(caldb=None):
"""What CIAO CALDB is installed (release date)?
Parameters
----------
caldb : str, optional
If set, the directory to search in, otherwise the
CALDB environment variable is used.
Returns
-------
date
The release date of the version (as a date object) of the
installed CIAO CALDB.
See Also
--------
get_caldb_installed, get_caldb_installed_version
"""
return get_caldb_installed(caldb)[1]
def version_to_tuple(version):
"""Convert CALDB version string to a tuple.
Parameters
----------
version : str
A CALDB version string like '4.4.10',
Returns
-------
version : tuple of int
The tuple of integers representing the input version. The
number of elements in the tuple depends on the input.
"""
toks = version.split('.')
try:
out = [int(t) for t in toks]
except ValueError:
raise ValueError("Invalid version string '{}'".format(version))
return tuple(out)
def check_caldb_version(version=None):
"""Is the locally-installed Chandra CALDB installation up-to-date?
The routine requires that the computer is on-line and able to
access the Chandra CALDB web site: https://cxc.harvard.edu/caldb/
Parameters
----------
version : str, optional
The version to compare to the latest released Chandra CALDB
(as obtained from https://cxc.harvard.edu/caldb/). If not
set then the version from the locally-installed Chandra CALDB
is used. The format for the string is integer values separated
by ".", such as "4.7.2".
Returns
-------
retval : None or (str, str)
If the installation is up to date then the routine returns
None, otherwise it returns the tuple
(version checked against, latest version).
Raises
------
IOError
If the version parameter is given but does not match a CALDB
release.
"""
# Converting the dotted string form (4.2.1 or 3.2.0.1) to
# a tuple of integers means we can just use Python's comparison
# operator and it handles cases like
#
# >>> (4,2,1) > (3,2,0,1)
# True
# >>> (4,2,2) > (4,2,2,2)
# False
#
# We are relying on the CALDB release numbers to be dotted
# integers, with no alphanumerics (i.e. not 4.4.1a)
#
rels = get_caldb_releases()
if version is None:
installed_ver = get_caldb_installed_version()
else:
installed_ver = version
# We check against the CALDB release numbers rather than
# the CALDB ones, since they form the "complete" set.
# Should perhaps be case insensitive but leave that for
# a later revision.
#
if version not in [v[0] for v in rels["CALDB"]]:
raise IOError("The input CALDB version '{}' is unknown!".format(version))
iver = version_to_tuple(installed_ver)
out = [v for (v, d) in rels["CIAO"] if version_to_tuple(v) > iver]
if out == []:
return
out.sort(reverse=True)
return (installed_ver, out[0])
# End
| gpl-3.0 | 4,398,095,165,819,895,300 | 28.287091 | 107 | 0.586447 | false | 3.988454 | false | false | false |
tellproject/helper_scripts | tpcc_server.py | 1 | 1105 | #!/usr/bin/env python
from threaded_ssh import ThreadedClients
from ServerConfig import Tpcc
from ServerConfig import Kudu
from ServerConfig import TellStore
from ServerConfig import General
def hostToIp(host):
return General.infinibandIp[host]
def semicolonReduce(x, y):
return x + ';' + y
cmd = ""
if Tpcc.storage == Kudu:
cmd = "{0}/watch/tpcc/tpcc_kudu -H `hostname` -W {1} --network-threads 8 -s {2} -P {3}".format(Tpcc.builddir, Tpcc.warehouses, Kudu.master, len(Kudu.tservers)*4)
elif Tpcc.storage == TellStore:
Tpcc.rsyncBuild()
cmd = '{0}/watch/tpcc/tpcc_server -W {1} --network-threads 4 -c "{2}" -s "{3}"'.format(Tpcc.builddir, Tpcc.warehouses, General.infinibandIp[TellStore.commitmanager] + ":7242", reduce(semicolonReduce, map(lambda x: hostToIp(x) + ":7241", TellStore.servers)))
client0 = ThreadedClients(Tpcc.servers0, "numactl -m 0 -N 0 {0}".format(cmd), rnd_start=True, root=False)
client1 = ThreadedClients(Tpcc.servers1, "numactl -m 1 -N 1 {0} -p 8712".format(cmd), rnd_start=True, root=False)
client0.start()
client1.start()
client0.join()
client1.join()
| apache-2.0 | 6,247,841,676,958,327,000 | 35.833333 | 261 | 0.711312 | false | 2.675545 | false | false | false |
clearpathrobotics/axis_camera | nodes/teleop.py | 1 | 1321 | #!/usr/bin/python
import rospy
from sensor_msgs.msg import Joy
from axis_camera.msg import Axis
class Teleop:
def __init__(self):
rospy.init_node('axis_ptz_teleop')
self.enable_button = rospy.get_param('~enable_button', 1)
self.axis_pan = rospy.get_param('~axis_pan', 0)
self.axis_tilt = rospy.get_param('~axis_tilt', 1)
self.state = Axis(pan=220)
self.joy = None
self.pub = rospy.Publisher('cmd', Axis)
rospy.Subscriber("joy", Joy, self.joy_callback)
# rospy.Subscriber("state", Axis, self.state_callback)
def spin(self):
self.state.brightness = 5000
self.pub.publish(self.state)
r = rospy.Rate(5)
while not rospy.is_shutdown():
if self.joy != None and self.joy.buttons[self.enable_button] == 1:
#and (rospy.Time.now() - self.joy.header.stamp).to_sec() < 0.2:
self.state.pan += self.joy.axes[axis_pan]*5
self.state.tilt += self.joy.axes[axis_tilt]*5
if self.state.tilt > 85: self.state.tilt = 85
if self.state.tilt < 0: self.state.tilt = 0
self.pub.publish(self.state)
r.sleep()
def joy_callback(self, data):
self.joy = data
if __name__ == "__main__": Teleop().spin()
| bsd-3-clause | 5,746,486,995,024,746,000 | 32.871795 | 79 | 0.570023 | false | 3.387179 | false | false | false |
bswartz/manila | manila/tests/share/drivers/test_service_instance.py | 1 | 106768 | # Copyright (c) 2014 NetApp, Inc.
# Copyright (c) 2015 Mirantis, Inc.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""Unit tests for the instance module."""
import os
import time
import ddt
import mock
import netaddr
from oslo_config import cfg
from oslo_utils import importutils
import six
from manila import exception
from manila.share import configuration
from manila.share import driver # noqa
from manila.share.drivers import service_instance
from manila import test
from manila.tests import fake_compute
from manila.tests import fake_network
from manila.tests import utils as test_utils
CONF = cfg.CONF
def fake_get_config_option(key):
if key == 'driver_handles_share_servers':
return True
elif key == 'service_instance_password':
return None
elif key == 'service_instance_user':
return 'fake_user'
elif key == 'service_network_name':
return 'fake_service_network_name'
elif key == 'service_instance_flavor_id':
return 100
elif key == 'service_instance_name_template':
return 'fake_manila_service_instance_%s'
elif key == 'service_image_name':
return 'fake_service_image_name'
elif key == 'manila_service_keypair_name':
return 'fake_manila_service_keypair_name'
elif key == 'path_to_private_key':
return 'fake_path_to_private_key'
elif key == 'path_to_public_key':
return 'fake_path_to_public_key'
elif key == 'max_time_to_build_instance':
return 500
elif key == 'connect_share_server_to_tenant_network':
return False
elif key == 'service_network_cidr':
return '99.254.0.0/24'
elif key == 'service_network_division_mask':
return 27
elif key == 'service_network_name':
return 'fake_service_network_name'
elif key == 'interface_driver':
return 'i.am.fake.VifDriver'
elif key == 'admin_network_id':
return None
elif key == 'admin_subnet_id':
return None
else:
return mock.Mock()
class FakeServiceInstance(object):
def __init__(self, driver_config=None):
super(FakeServiceInstance, self).__init__()
self.compute_api = service_instance.compute.API()
self.admin_context = service_instance.context.get_admin_context()
self.driver_config = driver_config
def get_config_option(self, key):
return fake_get_config_option(key)
class FakeNetworkHelper(service_instance.BaseNetworkhelper):
@property
def NAME(self):
return service_instance.NEUTRON_NAME
@property
def neutron_api(self):
if not hasattr(self, '_neutron_api'):
self._neutron_api = mock.Mock()
return self._neutron_api
def __init__(self, service_instance_manager):
self.get_config_option = service_instance_manager.get_config_option
def get_network_name(self, network_info):
"""Return name of network."""
return 'fake_network_name'
def setup_connectivity_with_service_instances(self):
"""Nothing to do in fake network helper."""
def setup_network(self, network_info):
"""Combine fake network data."""
return dict()
def teardown_network(self, server_details):
"""Nothing to do in fake network helper."""
@ddt.ddt
class ServiceInstanceManagerTestCase(test.TestCase):
"""Test suite for service instance manager."""
def setUp(self):
super(ServiceInstanceManagerTestCase, self).setUp()
self.instance_id = 'fake_instance_id'
self.config = configuration.Configuration(None)
self.config.safe_get = mock.Mock(side_effect=fake_get_config_option)
self.mock_object(service_instance.compute, 'API', fake_compute.API)
self.mock_object(
service_instance.os.path, 'exists', mock.Mock(return_value=True))
self.mock_object(service_instance, 'NeutronNetworkHelper',
mock.Mock(side_effect=FakeNetworkHelper))
self._manager = service_instance.ServiceInstanceManager(self.config)
self._manager._execute = mock.Mock(return_value=('', ''))
self.mock_object(time, 'sleep')
def test_get_config_option_from_driver_config(self):
username1 = 'fake_username_1_%s' % self.id()
username2 = 'fake_username_2_%s' % self.id()
config_data = dict(
DEFAULT=dict(service_instance_user=username1),
CUSTOM=dict(service_instance_user=username2))
with test_utils.create_temp_config_with_opts(config_data):
self.config = configuration.Configuration(
service_instance.common_opts, config_group='CUSTOM')
self._manager = service_instance.ServiceInstanceManager(
self.config)
result = self._manager.get_config_option('service_instance_user')
self.assertEqual(username2, result)
def test_get_config_option_from_common_config(self):
username = 'fake_username_%s' % self.id()
config_data = dict(DEFAULT=dict(service_instance_user=username))
with test_utils.create_temp_config_with_opts(config_data):
self._manager = service_instance.ServiceInstanceManager()
result = self._manager.get_config_option('service_instance_user')
self.assertEqual(username, result)
def test_get_neutron_network_helper(self):
# Mock it again, because it was called in setUp method.
self.mock_object(service_instance, 'NeutronNetworkHelper')
config_data = dict(DEFAULT=dict(service_instance_user='fake_username',
driver_handles_share_servers=True))
with test_utils.create_temp_config_with_opts(config_data):
self._manager = service_instance.ServiceInstanceManager()
self._manager.network_helper
service_instance.NeutronNetworkHelper.assert_called_once_with(
self._manager)
def test_init_with_driver_config_and_handling_of_share_servers(self):
self.mock_object(service_instance, 'NeutronNetworkHelper')
config_data = dict(CUSTOM=dict(
driver_handles_share_servers=True,
service_instance_user='fake_user'))
opts = service_instance.common_opts + driver.share_opts
with test_utils.create_temp_config_with_opts(config_data):
self.config = configuration.Configuration(opts, 'CUSTOM')
self._manager = service_instance.ServiceInstanceManager(
self.config)
self.assertTrue(
self._manager.get_config_option("driver_handles_share_servers"))
self.assertIsNotNone(self._manager.driver_config)
self.assertTrue(hasattr(self._manager, 'network_helper'))
self.assertTrue(service_instance.NeutronNetworkHelper.called)
def test_init_with_driver_config_and_wo_handling_of_share_servers(self):
self.mock_object(service_instance, 'NeutronNetworkHelper')
config_data = dict(CUSTOM=dict(
driver_handles_share_servers=False,
service_instance_user='fake_user'))
opts = service_instance.common_opts + driver.share_opts
with test_utils.create_temp_config_with_opts(config_data):
self.config = configuration.Configuration(opts, 'CUSTOM')
self._manager = service_instance.ServiceInstanceManager(
self.config)
self.assertIsNotNone(self._manager.driver_config)
self.assertFalse(hasattr(self._manager, 'network_helper'))
self.assertFalse(service_instance.NeutronNetworkHelper.called)
def test_init_with_common_config_and_handling_of_share_servers(self):
self.mock_object(service_instance, 'NeutronNetworkHelper')
config_data = dict(DEFAULT=dict(
service_instance_user='fake_username',
driver_handles_share_servers=True))
with test_utils.create_temp_config_with_opts(config_data):
self._manager = service_instance.ServiceInstanceManager()
self.assertTrue(
self._manager.get_config_option("driver_handles_share_servers"))
self.assertIsNone(self._manager.driver_config)
self.assertTrue(hasattr(self._manager, 'network_helper'))
self.assertTrue(service_instance.NeutronNetworkHelper.called)
def test_init_with_common_config_and_wo_handling_of_share_servers(self):
self.mock_object(service_instance, 'NeutronNetworkHelper')
config_data = dict(DEFAULT=dict(
service_instance_user='fake_username',
driver_handles_share_servers=False))
with test_utils.create_temp_config_with_opts(config_data):
self._manager = service_instance.ServiceInstanceManager()
self.assertEqual(
False,
self._manager.get_config_option("driver_handles_share_servers"))
self.assertIsNone(self._manager.driver_config)
self.assertFalse(hasattr(self._manager, 'network_helper'))
self.assertFalse(service_instance.NeutronNetworkHelper.called)
def test_no_service_user_defined(self):
group_name = 'GROUP_%s' % self.id()
config_data = {group_name: dict()}
with test_utils.create_temp_config_with_opts(config_data):
config = configuration.Configuration(
service_instance.common_opts, config_group=group_name)
self.assertRaises(
exception.ServiceInstanceException,
service_instance.ServiceInstanceManager, config)
def test_get_service_instance_name_using_driver_config(self):
fake_server_id = 'fake_share_server_id_%s' % self.id()
self.mock_object(service_instance, 'NeutronNetworkHelper')
config_data = dict(CUSTOM=dict(
driver_handles_share_servers=True,
service_instance_user='fake_user'))
opts = service_instance.common_opts + driver.share_opts
with test_utils.create_temp_config_with_opts(config_data):
self.config = configuration.Configuration(opts, 'CUSTOM')
self._manager = service_instance.ServiceInstanceManager(
self.config)
result = self._manager._get_service_instance_name(fake_server_id)
self.assertIsNotNone(self._manager.driver_config)
self.assertEqual(
self._manager.get_config_option(
"service_instance_name_template") % "%s_%s" % (
self._manager.driver_config.config_group, fake_server_id),
result)
self.assertTrue(
self._manager.get_config_option("driver_handles_share_servers"))
self.assertTrue(hasattr(self._manager, 'network_helper'))
self.assertTrue(service_instance.NeutronNetworkHelper.called)
def test_get_service_instance_name_using_default_config(self):
fake_server_id = 'fake_share_server_id_%s' % self.id()
config_data = dict(CUSTOM=dict(
service_instance_user='fake_user'))
with test_utils.create_temp_config_with_opts(config_data):
self._manager = service_instance.ServiceInstanceManager()
result = self._manager._get_service_instance_name(fake_server_id)
self.assertIsNone(self._manager.driver_config)
self.assertEqual(
self._manager.get_config_option(
"service_instance_name_template") % fake_server_id, result)
def test__check_server_availability_available_from_start(self):
fake_server = dict(id='fake_server', ip='127.0.0.1')
self.mock_object(service_instance.socket.socket, 'connect')
self.mock_object(service_instance.time, 'sleep')
self.mock_object(service_instance.time, 'time',
mock.Mock(return_value=0))
result = self._manager._check_server_availability(fake_server)
self.assertTrue(result)
service_instance.socket.socket.connect.assert_called_once_with(
(fake_server['ip'], 22))
service_instance.time.time.assert_has_calls([
mock.call(), mock.call()])
service_instance.time.time.assert_has_calls([])
@ddt.data(True, False)
def test__check_server_availability_with_recall(self, is_ok):
fake_server = dict(id='fake_server', ip='fake_ip_address')
self.fake_time = 0
def fake_connect(addr):
if not(is_ok and self.fake_time > 1):
raise service_instance.socket.error
def fake_time():
return self.fake_time
def fake_sleep(time):
self.fake_time += 5
self.mock_object(service_instance.time, 'sleep',
mock.Mock(side_effect=fake_sleep))
self.mock_object(service_instance.socket.socket, 'connect',
mock.Mock(side_effect=fake_connect))
self.mock_object(service_instance.time, 'time',
mock.Mock(side_effect=fake_time))
self._manager.max_time_to_build_instance = 6
result = self._manager._check_server_availability(fake_server)
if is_ok:
self.assertTrue(result)
else:
self.assertFalse(result)
service_instance.socket.socket.connect.assert_has_calls([
mock.call((fake_server['ip'], 22)),
mock.call((fake_server['ip'], 22))])
service_instance.time.time.assert_has_calls([
mock.call(), mock.call(), mock.call()])
service_instance.time.time.assert_has_calls([mock.call()])
def test_get_server_ip_found_in_networks_section(self):
ip = '10.0.0.1'
net_name = self._manager.get_config_option('service_network_name')
fake_server = dict(networks={net_name: [ip]})
result = self._manager._get_server_ip(fake_server, net_name)
self.assertEqual(ip, result)
def test_get_server_ip_found_in_addresses_section(self):
ip = '10.0.0.1'
net_name = self._manager.get_config_option('service_network_name')
fake_server = dict(addresses={net_name: [dict(addr=ip, version=4)]})
result = self._manager._get_server_ip(fake_server, net_name)
self.assertEqual(ip, result)
@ddt.data(
{},
{'networks': {fake_get_config_option('service_network_name'): []}},
{'addresses': {fake_get_config_option('service_network_name'): []}})
def test_get_server_ip_not_found(self, data):
self.assertRaises(
exception.ManilaException,
self._manager._get_server_ip, data,
fake_get_config_option('service_network_name'))
def test_security_group_name_not_specified(self):
self.mock_object(self._manager, 'get_config_option',
mock.Mock(return_value=None))
result = self._manager._get_or_create_security_group(
self._manager.admin_context)
self.assertIsNone(result)
self._manager.get_config_option.assert_called_once_with(
'service_instance_security_group')
def test_security_group_name_from_config_and_sg_exist(self):
name = "fake_sg_name_from_config"
desc = "fake_sg_description"
fake_secgroup = {'id': 'fake_sg_id', 'name': name, 'description': desc}
self.mock_object(self._manager, 'get_config_option',
mock.Mock(return_value=name))
neutron_api = self._manager.network_helper.neutron_api
neutron_api.security_group_list.return_value = {
'security_groups': [fake_secgroup]}
result = self._manager._get_or_create_security_group(
self._manager.admin_context)
self.assertEqual(fake_secgroup, result)
self._manager.get_config_option.assert_called_once_with(
'service_instance_security_group')
neutron_api.security_group_list.assert_called_once_with({"name": name})
@ddt.data(None, 'fake_name')
def test_security_group_creation_with_name_from_config(self, name):
config_name = "fake_sg_name_from_config"
desc = "fake_sg_description"
fake_secgroup = {'id': 'fake_sg_id', 'name': name, 'description': desc}
self.mock_object(self._manager, 'get_config_option',
mock.Mock(return_value=name or config_name))
neutron_api = self._manager.network_helper.neutron_api
neutron_api.security_group_list.return_value = {'security_groups': []}
neutron_api.security_group_create.return_value = {
'security_group': fake_secgroup,
}
result = self._manager._get_or_create_security_group(
context=self._manager.admin_context,
name=name,
description=desc,
)
self.assertEqual(fake_secgroup, result)
if not name:
self._manager.get_config_option.assert_called_once_with(
'service_instance_security_group')
neutron_api.security_group_list.assert_called_once_with(
{"name": name or config_name})
neutron_api.security_group_create.assert_called_once_with(
name or config_name, desc)
def test_security_group_two_sg_in_list(self):
name = "fake_name"
fake_secgroup1 = {'id': 'fake_sg_id1', 'name': name}
fake_secgroup2 = {'id': 'fake_sg_id2', 'name': name}
neutron_api = self._manager.network_helper.neutron_api
neutron_api.security_group_list.return_value = {
'security_groups': [fake_secgroup1, fake_secgroup2]}
self.assertRaises(exception.ServiceInstanceException,
self._manager._get_or_create_security_group,
self._manager.admin_context,
name)
neutron_api.security_group_list.assert_called_once_with(
{"name": name})
@ddt.data(
dict(),
dict(service_port_id='fake_service_port_id'),
dict(public_port_id='fake_public_port_id'),
dict(service_port_id='fake_service_port_id',
public_port_id='fake_public_port_id'),
)
def test_set_up_service_instance(self, update_data):
fake_network_info = {'foo': 'bar', 'server_id': 'fake_server_id'}
fake_server = {
'id': 'fake', 'ip': '1.2.3.4', 'public_address': '1.2.3.4',
'pk_path': None, 'subnet_id': 'fake-subnet-id',
'router_id': 'fake-router-id',
'username': self._manager.get_config_option(
'service_instance_user'),
'admin_ip': 'admin_ip'}
fake_server.update(update_data)
expected_details = fake_server.copy()
expected_details.pop('pk_path')
expected_details['instance_id'] = expected_details.pop('id')
self.mock_object(self._manager, '_create_service_instance',
mock.Mock(return_value=fake_server))
self.mock_object(self._manager, '_check_server_availability')
result = self._manager.set_up_service_instance(
self._manager.admin_context, fake_network_info)
self._manager._create_service_instance.assert_called_once_with(
self._manager.admin_context,
fake_network_info['server_id'], fake_network_info)
self._manager._check_server_availability.assert_called_once_with(
expected_details)
self.assertEqual(expected_details, result)
def test_set_up_service_instance_not_available(self):
fake_network_info = {'foo': 'bar', 'server_id': 'fake_server_id'}
fake_server = {
'id': 'fake', 'ip': '1.2.3.4', 'public_address': '1.2.3.4',
'pk_path': None, 'subnet_id': 'fake-subnet-id',
'router_id': 'fake-router-id',
'username': self._manager.get_config_option(
'service_instance_user'),
'admin_ip': 'admin_ip'}
expected_details = fake_server.copy()
expected_details.pop('pk_path')
expected_details['instance_id'] = expected_details.pop('id')
self.mock_object(self._manager, '_create_service_instance',
mock.Mock(return_value=fake_server))
self.mock_object(self._manager, '_check_server_availability',
mock.Mock(return_value=False))
result = self.assertRaises(
exception.ServiceInstanceException,
self._manager.set_up_service_instance,
self._manager.admin_context, fake_network_info)
self.assertTrue(hasattr(result, 'detail_data'))
self.assertEqual(
{'server_details': expected_details}, result.detail_data)
self._manager._create_service_instance.assert_called_once_with(
self._manager.admin_context,
fake_network_info['server_id'], fake_network_info)
self._manager._check_server_availability.assert_called_once_with(
expected_details)
def test_ensure_server(self):
server_details = {'instance_id': 'fake_inst_id', 'ip': '1.2.3.4'}
fake_server = fake_compute.FakeServer()
self.mock_object(self._manager, '_check_server_availability',
mock.Mock(return_value=True))
self.mock_object(self._manager.compute_api, 'server_get',
mock.Mock(return_value=fake_server))
result = self._manager.ensure_service_instance(
self._manager.admin_context, server_details)
self._manager.compute_api.server_get.assert_called_once_with(
self._manager.admin_context, server_details['instance_id'])
self._manager._check_server_availability.assert_called_once_with(
server_details)
self.assertTrue(result)
def test_ensure_server_not_exists(self):
server_details = {'instance_id': 'fake_inst_id', 'ip': '1.2.3.4'}
self.mock_object(self._manager, '_check_server_availability',
mock.Mock(return_value=True))
self.mock_object(self._manager.compute_api, 'server_get',
mock.Mock(side_effect=exception.InstanceNotFound(
instance_id=server_details['instance_id'])))
result = self._manager.ensure_service_instance(
self._manager.admin_context, server_details)
self._manager.compute_api.server_get.assert_called_once_with(
self._manager.admin_context, server_details['instance_id'])
self.assertFalse(self._manager._check_server_availability.called)
self.assertFalse(result)
def test_ensure_server_exception(self):
server_details = {'instance_id': 'fake_inst_id', 'ip': '1.2.3.4'}
self.mock_object(self._manager, '_check_server_availability',
mock.Mock(return_value=True))
self.mock_object(self._manager.compute_api, 'server_get',
mock.Mock(side_effect=exception.ManilaException))
self.assertRaises(exception.ManilaException,
self._manager.ensure_service_instance,
self._manager.admin_context,
server_details)
self._manager.compute_api.server_get.assert_called_once_with(
self._manager.admin_context, server_details['instance_id'])
self.assertFalse(self._manager._check_server_availability.called)
def test_ensure_server_non_active(self):
server_details = {'instance_id': 'fake_inst_id', 'ip': '1.2.3.4'}
fake_server = fake_compute.FakeServer(status='ERROR')
self.mock_object(self._manager.compute_api, 'server_get',
mock.Mock(return_value=fake_server))
self.mock_object(self._manager, '_check_server_availability',
mock.Mock(return_value=True))
result = self._manager.ensure_service_instance(
self._manager.admin_context, server_details)
self.assertFalse(self._manager._check_server_availability.called)
self.assertFalse(result)
def test_ensure_server_no_instance_id(self):
# Tests that we avoid a KeyError if the share details don't have an
# instance_id key set (so we can't find the share instance).
self.assertFalse(self._manager.ensure_service_instance(
self._manager.admin_context, {'ip': '1.2.3.4'}))
def test_get_key_create_new(self):
keypair_name = self._manager.get_config_option(
'manila_service_keypair_name')
fake_keypair = fake_compute.FakeKeypair(name=keypair_name)
self.mock_object(self._manager.compute_api, 'keypair_list',
mock.Mock(return_value=[]))
self.mock_object(self._manager.compute_api, 'keypair_import',
mock.Mock(return_value=fake_keypair))
result = self._manager._get_key(self._manager.admin_context)
self.assertEqual(
(fake_keypair.name,
os.path.expanduser(self._manager.get_config_option(
'path_to_private_key'))),
result)
self._manager.compute_api.keypair_list.assert_called_once_with(
self._manager.admin_context)
self._manager.compute_api.keypair_import.assert_called_once_with(
self._manager.admin_context, keypair_name, '')
def test_get_key_exists(self):
fake_keypair = fake_compute.FakeKeypair(
name=self._manager.get_config_option(
'manila_service_keypair_name'),
public_key='fake_public_key')
self.mock_object(self._manager.compute_api, 'keypair_list',
mock.Mock(return_value=[fake_keypair]))
self.mock_object(self._manager.compute_api, 'keypair_import',
mock.Mock(return_value=fake_keypair))
self.mock_object(self._manager, '_execute',
mock.Mock(return_value=('fake_public_key', '')))
result = self._manager._get_key(self._manager.admin_context)
self._manager.compute_api.keypair_list.assert_called_once_with(
self._manager.admin_context)
self.assertFalse(self._manager.compute_api.keypair_import.called)
self.assertEqual(
(fake_keypair.name,
os.path.expanduser(self._manager.get_config_option(
'path_to_private_key'))),
result)
def test_get_key_exists_recreate(self):
fake_keypair = fake_compute.FakeKeypair(
name=self._manager.get_config_option(
'manila_service_keypair_name'),
public_key='fake_public_key1')
self.mock_object(self._manager.compute_api, 'keypair_list',
mock.Mock(return_value=[fake_keypair]))
self.mock_object(self._manager.compute_api, 'keypair_import',
mock.Mock(return_value=fake_keypair))
self.mock_object(self._manager.compute_api, 'keypair_delete')
self.mock_object(self._manager, '_execute',
mock.Mock(return_value=('fake_public_key2', '')))
result = self._manager._get_key(self._manager.admin_context)
self._manager.compute_api.keypair_list.assert_called_once_with(
self._manager.admin_context)
self._manager.compute_api.keypair_delete.assert_called_once_with(
self._manager.admin_context, fake_keypair.id)
self._manager.compute_api.keypair_import.assert_called_once_with(
self._manager.admin_context, fake_keypair.name, 'fake_public_key2')
self.assertEqual(
(fake_keypair.name,
os.path.expanduser(self._manager.get_config_option(
'path_to_private_key'))),
result)
def test_get_key_more_than_one_exist(self):
fake_keypair = fake_compute.FakeKeypair(
name=self._manager.get_config_option(
'manila_service_keypair_name'),
public_key='fake_public_key1')
self.mock_object(self._manager.compute_api, 'keypair_list',
mock.Mock(return_value=[fake_keypair, fake_keypair]))
self.assertRaises(
exception.ServiceInstanceException,
self._manager._get_key, self._manager.admin_context)
self._manager.compute_api.keypair_list.assert_called_once_with(
self._manager.admin_context)
def test_get_key_keypath_to_public_not_set(self):
self._manager.path_to_public_key = None
result = self._manager._get_key(self._manager.admin_context)
self.assertEqual((None, None), result)
def test_get_key_keypath_to_private_not_set(self):
self._manager.path_to_private_key = None
result = self._manager._get_key(self._manager.admin_context)
self.assertEqual((None, None), result)
def test_get_key_incorrect_keypath_to_public(self):
def exists_side_effect(path):
return False if path == 'fake_path' else True
self._manager.path_to_public_key = 'fake_path'
os_path_exists_mock = mock.Mock(side_effect=exists_side_effect)
with mock.patch.object(os.path, 'exists', os_path_exists_mock):
with mock.patch.object(os.path, 'expanduser',
mock.Mock(side_effect=lambda value: value)):
result = self._manager._get_key(self._manager.admin_context)
self.assertEqual((None, None), result)
def test_get_key_incorrect_keypath_to_private(self):
def exists_side_effect(path):
return False if path == 'fake_path' else True
self._manager.path_to_private_key = 'fake_path'
os_path_exists_mock = mock.Mock(side_effect=exists_side_effect)
with mock.patch.object(os.path, 'exists', os_path_exists_mock):
with mock.patch.object(os.path, 'expanduser',
mock.Mock(side_effect=lambda value: value)):
result = self._manager._get_key(self._manager.admin_context)
self.assertEqual((None, None), result)
def test_get_service_image(self):
fake_image1 = fake_compute.FakeImage(
name=self._manager.get_config_option('service_image_name'),
status='active')
fake_image2 = fake_compute.FakeImage(
name='service_image_name',
status='error')
fake_image3 = fake_compute.FakeImage(
name='another-image',
status='active')
self.mock_object(self._manager.compute_api, 'image_list',
mock.Mock(return_value=[fake_image1,
fake_image2,
fake_image3]))
result = self._manager._get_service_image(self._manager.admin_context)
self.assertEqual(fake_image1.id, result)
def test_get_service_image_not_found(self):
self.mock_object(self._manager.compute_api, 'image_list',
mock.Mock(return_value=[]))
self.assertRaises(
exception.ServiceInstanceException,
self._manager._get_service_image, self._manager.admin_context)
fake_error_image = fake_compute.FakeImage(
name='service_image_name',
status='error')
self.mock_object(self._manager.compute_api, 'image_list',
mock.Mock(return_value=[fake_error_image]))
self.assertRaises(
exception.ServiceInstanceException,
self._manager._get_service_image, self._manager.admin_context)
def test_get_service_image_ambiguous(self):
fake_image = fake_compute.FakeImage(
name=fake_get_config_option('service_image_name'),
status='active')
fake_images = [fake_image, fake_image]
self.mock_object(self._manager.compute_api, 'image_list',
mock.Mock(return_value=fake_images))
self.assertRaises(
exception.ServiceInstanceException,
self._manager._get_service_image, self._manager.admin_context)
def test__delete_server_not_found(self):
self.mock_object(self._manager.compute_api, 'server_delete')
self.mock_object(
self._manager.compute_api, 'server_get',
mock.Mock(side_effect=exception.InstanceNotFound(
instance_id=self.instance_id)))
self._manager._delete_server(
self._manager.admin_context, self.instance_id)
self.assertFalse(self._manager.compute_api.server_delete.called)
self._manager.compute_api.server_get.assert_called_once_with(
self._manager.admin_context, self.instance_id)
def test__delete_server(self):
def fake_server_get(*args, **kwargs):
ctx = args[0]
if not hasattr(ctx, 'called'):
ctx.called = True
return
else:
raise exception.InstanceNotFound(instance_id=self.instance_id)
self.mock_object(self._manager.compute_api, 'server_delete')
self.mock_object(self._manager.compute_api, 'server_get',
mock.Mock(side_effect=fake_server_get))
self._manager._delete_server(
self._manager.admin_context, self.instance_id)
self._manager.compute_api.server_delete.assert_called_once_with(
self._manager.admin_context, self.instance_id)
self._manager.compute_api.server_get.assert_has_calls([
mock.call(self._manager.admin_context, self.instance_id),
mock.call(self._manager.admin_context, self.instance_id)])
def test__delete_server_found_always(self):
self.fake_time = 0
def fake_time():
return self.fake_time
def fake_sleep(time):
self.fake_time += 1
self.mock_object(self._manager.compute_api, 'server_delete')
self.mock_object(self._manager.compute_api, 'server_get')
self.mock_object(service_instance, 'time')
self.mock_object(
service_instance.time, 'time', mock.Mock(side_effect=fake_time))
self.mock_object(
service_instance.time, 'sleep', mock.Mock(side_effect=fake_sleep))
self.mock_object(self._manager, 'max_time_to_build_instance', 2)
self.assertRaises(
exception.ServiceInstanceException, self._manager._delete_server,
self._manager.admin_context, self.instance_id)
self._manager.compute_api.server_delete.assert_called_once_with(
self._manager.admin_context, self.instance_id)
service_instance.time.sleep.assert_has_calls(
[mock.call(mock.ANY) for i in range(2)])
service_instance.time.time.assert_has_calls(
[mock.call() for i in range(4)])
self._manager.compute_api.server_get.assert_has_calls(
[mock.call(self._manager.admin_context,
self.instance_id) for i in range(3)])
def test_delete_service_instance(self):
fake_server_details = dict(
router_id='foo', subnet_id='bar', instance_id='quuz')
self.mock_object(self._manager, '_delete_server')
self.mock_object(self._manager.network_helper, 'teardown_network')
self._manager.delete_service_instance(
self._manager.admin_context, fake_server_details)
self._manager._delete_server.assert_called_once_with(
self._manager.admin_context, fake_server_details['instance_id'])
self._manager.network_helper.teardown_network.assert_called_once_with(
fake_server_details)
@ddt.data(
*[{'service_config': service_config,
'tenant_config': tenant_config,
'server': server}
for service_config, tenant_config in (
('fake_net_s', 'fake_net_t'),
('fake_net_s', '12.34.56.78'),
('98.76.54.123', 'fake_net_t'),
('98.76.54.123', '12.34.56.78'))
for server in (
{'networks': {
'fake_net_s': ['foo', '98.76.54.123', 'bar'],
'fake_net_t': ['baar', '12.34.56.78', 'quuz']}},
{'addresses': {
'fake_net_s': [
{'addr': 'fake1'},
{'addr': '98.76.54.123'},
{'addr': 'fake2'}],
'fake_net_t': [
{'addr': 'fake3'},
{'addr': '12.34.56.78'},
{'addr': 'fake4'}],
}})])
@ddt.unpack
def test_get_common_server_valid_cases(self, service_config,
tenant_config, server):
self._get_common_server(service_config, tenant_config, server,
'98.76.54.123', '12.34.56.78', True)
@ddt.data(
*[{'service_config': service_config,
'tenant_config': tenant_config,
'server': server}
for service_config, tenant_config in (
('fake_net_s', 'fake'),
('fake', 'fake_net_t'),
('fake', 'fake'),
('98.76.54.123', '12.12.12.1212'),
('12.12.12.1212', '12.34.56.78'),
('12.12.12.1212', '12.12.12.1212'),
('1001::1001', '1001::100G'),
('1001::10G1', '1001::1001'),
)
for server in (
{'networks': {
'fake_net_s': ['foo', '98.76.54.123', 'bar'],
'fake_net_t': ['baar', '12.34.56.78', 'quuz']}},
{'addresses': {
'fake_net_s': [
{'addr': 'fake1'},
{'addr': '98.76.54.123'},
{'addr': 'fake2'}],
'fake_net_t': [
{'addr': 'fake3'},
{'addr': '12.34.56.78'},
{'addr': 'fake4'}],
}})])
@ddt.unpack
def test_get_common_server_invalid_cases(self, service_config,
tenant_config, server):
self._get_common_server(service_config, tenant_config, server,
'98.76.54.123', '12.34.56.78', False)
@ddt.data(
*[{'service_config': service_config,
'tenant_config': tenant_config,
'server': server}
for service_config, tenant_config in (
('fake_net_s', '1001::1002'),
('1001::1001', 'fake_net_t'),
('1001::1001', '1001::1002'))
for server in (
{'networks': {
'fake_net_s': ['foo', '1001::1001'],
'fake_net_t': ['bar', '1001::1002']}},
{'addresses': {
'fake_net_s': [{'addr': 'foo'}, {'addr': '1001::1001'}],
'fake_net_t': [{'addr': 'bar'}, {'addr': '1001::1002'}]}})])
@ddt.unpack
def test_get_common_server_valid_ipv6_address(self, service_config,
tenant_config, server):
self._get_common_server(service_config, tenant_config, server,
'1001::1001', '1001::1002', True)
def _get_common_server(self, service_config, tenant_config,
server, service_address, network_address,
is_valid=True):
fake_instance_id = 'fake_instance_id'
fake_user = 'fake_user'
fake_pass = 'fake_pass'
fake_server = {'id': fake_instance_id}
fake_server.update(server)
expected = {
'backend_details': {
'username': fake_user,
'password': fake_pass,
'pk_path': self._manager.path_to_private_key,
'ip': service_address,
'public_address': network_address,
'instance_id': fake_instance_id,
}
}
def fake_get_config_option(attr):
if attr == 'service_net_name_or_ip':
return service_config
elif attr == 'tenant_net_name_or_ip':
return tenant_config
elif attr == 'service_instance_name_or_id':
return fake_instance_id
elif attr == 'service_instance_user':
return fake_user
elif attr == 'service_instance_password':
return fake_pass
else:
raise exception.ManilaException("Wrong test data provided.")
self.mock_object(
self._manager.compute_api, 'server_get_by_name_or_id',
mock.Mock(return_value=fake_server))
self.mock_object(
self._manager, 'get_config_option',
mock.Mock(side_effect=fake_get_config_option))
if is_valid:
actual = self._manager.get_common_server()
self.assertEqual(expected, actual)
else:
self.assertRaises(
exception.ManilaException,
self._manager.get_common_server)
self.assertTrue(
self._manager.compute_api.server_get_by_name_or_id.called)
def test___create_service_instance_with_sg_success(self):
self.mock_object(service_instance, 'NeutronNetworkHelper',
mock.Mock(side_effect=FakeNetworkHelper))
config_data = dict(DEFAULT=dict(
driver_handles_share_servers=True,
service_instance_user='fake_user'))
with test_utils.create_temp_config_with_opts(config_data):
self._manager = service_instance.ServiceInstanceManager()
server_create = dict(id='fakeid', status='CREATING', networks=dict())
net_name = self._manager.get_config_option("service_network_name")
sg = {'id': 'fakeid', 'name': 'fakename'}
ip_address = 'fake_ip_address'
service_image_id = 'fake_service_image_id'
key_data = 'fake_key_name', 'fake_key_path'
instance_name = 'fake_instance_name'
network_info = dict()
network_data = {'nics': ['fake_nic1', 'fake_nic2']}
network_data['router'] = dict(id='fake_router_id')
server_get = dict(
id='fakeid', status='ACTIVE', networks={net_name: [ip_address]})
network_data.update(dict(
router_id='fake_router_id', subnet_id='fake_subnet_id',
public_port=dict(id='fake_public_port',
fixed_ips=[dict(ip_address=ip_address)]),
service_port=dict(id='fake_service_port',
fixed_ips=[{'ip_address': ip_address}]),
admin_port={'id': 'fake_admin_port',
'fixed_ips': [{'ip_address': ip_address}]}))
self.mock_object(service_instance.time, 'time',
mock.Mock(return_value=5))
self.mock_object(self._manager.network_helper, 'setup_network',
mock.Mock(return_value=network_data))
self.mock_object(self._manager.network_helper, 'get_network_name',
mock.Mock(return_value=net_name))
self.mock_object(self._manager, '_get_service_image',
mock.Mock(return_value=service_image_id))
self.mock_object(self._manager, '_get_key',
mock.Mock(return_value=key_data))
self.mock_object(self._manager, '_get_or_create_security_group',
mock.Mock(return_value=sg))
self.mock_object(self._manager.compute_api, 'server_create',
mock.Mock(return_value=server_create))
self.mock_object(self._manager.compute_api, 'server_get',
mock.Mock(return_value=server_get))
self.mock_object(self._manager.compute_api,
'add_security_group_to_server')
expected = {
'id': server_get['id'],
'status': server_get['status'],
'pk_path': key_data[1],
'public_address': ip_address,
'router_id': network_data.get('router_id'),
'subnet_id': network_data.get('subnet_id'),
'instance_id': server_get['id'],
'ip': ip_address,
'networks': server_get['networks'],
'router_id': network_data['router']['id'],
'public_port_id': 'fake_public_port',
'service_port_id': 'fake_service_port',
'admin_port_id': 'fake_admin_port',
'admin_ip': 'fake_ip_address',
}
result = self._manager._create_service_instance(
self._manager.admin_context, instance_name, network_info)
self.assertEqual(expected, result)
self.assertTrue(service_instance.time.time.called)
self._manager.network_helper.setup_network.assert_called_once_with(
network_info)
self._manager._get_service_image.assert_called_once_with(
self._manager.admin_context)
self._manager._get_key.assert_called_once_with(
self._manager.admin_context)
self._manager._get_or_create_security_group.assert_called_once_with(
self._manager.admin_context)
self._manager.compute_api.server_create.assert_called_once_with(
self._manager.admin_context, name=instance_name,
image=service_image_id, flavor=100,
key_name=key_data[0], nics=network_data['nics'],
availability_zone=service_instance.CONF.storage_availability_zone)
self._manager.compute_api.server_get.assert_called_once_with(
self._manager.admin_context, server_create['id'])
(self._manager.compute_api.add_security_group_to_server.
assert_called_once_with(
self._manager.admin_context, server_get['id'], sg['id']))
self._manager.network_helper.get_network_name.assert_has_calls([])
def test___create_service_instance_neutron_no_admin_ip(self):
self.mock_object(service_instance, 'NeutronNetworkHelper',
mock.Mock(side_effect=FakeNetworkHelper))
config_data = {'DEFAULT': {
'driver_handles_share_servers': True,
'service_instance_user': 'fake_user'}}
with test_utils.create_temp_config_with_opts(config_data):
self._manager = service_instance.ServiceInstanceManager()
server_create = {'id': 'fakeid', 'status': 'CREATING', 'networks': {}}
net_name = self._manager.get_config_option("service_network_name")
sg = {'id': 'fakeid', 'name': 'fakename'}
ip_address = 'fake_ip_address'
service_image_id = 'fake_service_image_id'
key_data = 'fake_key_name', 'fake_key_path'
instance_name = 'fake_instance_name'
network_info = {}
network_data = {
'nics': ['fake_nic1', 'fake_nic2'],
'router_id': 'fake_router_id', 'subnet_id': 'fake_subnet_id',
'public_port': {'id': 'fake_public_port',
'fixed_ips': [{'ip_address': ip_address}]},
'service_port': {'id': 'fake_service_port',
'fixed_ips': [{'ip_address': ip_address}]},
'admin_port': {'id': 'fake_admin_port',
'fixed_ips': []},
'router': {'id': 'fake_router_id'}}
server_get = {
'id': 'fakeid', 'status': 'ACTIVE', 'networks':
{net_name: [ip_address]}}
self.mock_object(service_instance.time, 'time',
mock.Mock(return_value=5))
self.mock_object(self._manager.network_helper, 'setup_network',
mock.Mock(return_value=network_data))
self.mock_object(self._manager.network_helper, 'get_network_name',
mock.Mock(return_value=net_name))
self.mock_object(self._manager, '_get_service_image',
mock.Mock(return_value=service_image_id))
self.mock_object(self._manager, '_get_key',
mock.Mock(return_value=key_data))
self.mock_object(self._manager, '_get_or_create_security_group',
mock.Mock(return_value=sg))
self.mock_object(self._manager.compute_api, 'server_create',
mock.Mock(return_value=server_create))
self.mock_object(self._manager.compute_api, 'server_get',
mock.Mock(return_value=server_get))
self.mock_object(self._manager.compute_api,
'add_security_group_to_server')
self.assertRaises(
exception.AdminIPNotFound, self._manager._create_service_instance,
self._manager.admin_context, instance_name, network_info)
self.assertTrue(service_instance.time.time.called)
self._manager.network_helper.setup_network.assert_called_once_with(
network_info)
self._manager._get_service_image.assert_called_once_with(
self._manager.admin_context)
self._manager._get_key.assert_called_once_with(
self._manager.admin_context)
self._manager._get_or_create_security_group.assert_called_once_with(
self._manager.admin_context)
self._manager.compute_api.server_create.assert_called_once_with(
self._manager.admin_context, name=instance_name,
image=service_image_id, flavor=100,
key_name=key_data[0], nics=network_data['nics'],
availability_zone=service_instance.CONF.storage_availability_zone)
self._manager.compute_api.server_get.assert_called_once_with(
self._manager.admin_context, server_create['id'])
(self._manager.compute_api.add_security_group_to_server.
assert_called_once_with(
self._manager.admin_context, server_get['id'], sg['id']))
self._manager.network_helper.get_network_name.assert_has_calls([])
@ddt.data(
dict(
instance_id_included=False,
mockobj=mock.Mock(side_effect=exception.ServiceInstanceException)),
dict(
instance_id_included=True,
mockobj=mock.Mock(return_value=dict(id='fakeid', status='ERROR'))))
@ddt.unpack
def test___create_service_instance_failed_to_create(
self, instance_id_included, mockobj):
service_image_id = 'fake_service_image_id'
key_data = 'fake_key_name', 'fake_key_path'
instance_name = 'fake_instance_name'
network_info = dict()
network_data = dict(
nics=['fake_nic1', 'fake_nic2'],
router_id='fake_router_id', subnet_id='fake_subnet_id')
self.mock_object(self._manager.network_helper, 'setup_network',
mock.Mock(return_value=network_data))
self.mock_object(self._manager, '_get_service_image',
mock.Mock(return_value=service_image_id))
self.mock_object(self._manager, '_get_key',
mock.Mock(return_value=key_data))
self.mock_object(
self._manager.compute_api, 'server_create', mockobj)
self.mock_object(
self._manager, 'wait_for_instance_to_be_active',
mock.Mock(side_effect=exception.ServiceInstanceException))
try:
self._manager._create_service_instance(
self._manager.admin_context, instance_name, network_info)
except exception.ServiceInstanceException as e:
expected = dict(server_details=dict(
subnet_id=network_data['subnet_id'],
router_id=network_data['router_id']))
if instance_id_included:
expected['server_details']['instance_id'] = 'fakeid'
self.assertEqual(expected, e.detail_data)
else:
raise exception.ManilaException('Expected error was not raised.')
self._manager.network_helper.setup_network.assert_called_once_with(
network_info)
self._manager._get_service_image.assert_called_once_with(
self._manager.admin_context)
self._manager._get_key.assert_called_once_with(
self._manager.admin_context)
self._manager.compute_api.server_create.assert_called_once_with(
self._manager.admin_context, name=instance_name,
image=service_image_id, flavor=100,
key_name=key_data[0], nics=network_data['nics'],
availability_zone=service_instance.CONF.storage_availability_zone)
def test___create_service_instance_failed_to_build(self):
server_create = dict(id='fakeid', status='CREATING', networks=dict())
service_image_id = 'fake_service_image_id'
key_data = 'fake_key_name', 'fake_key_path'
instance_name = 'fake_instance_name'
network_info = dict()
network_data = dict(
nics=['fake_nic1', 'fake_nic2'],
router_id='fake_router_id', subnet_id='fake_subnet_id')
self.mock_object(self._manager.network_helper, 'setup_network',
mock.Mock(return_value=network_data))
self.mock_object(self._manager, '_get_service_image',
mock.Mock(return_value=service_image_id))
self.mock_object(self._manager, '_get_key',
mock.Mock(return_value=key_data))
self.mock_object(self._manager.compute_api, 'server_create',
mock.Mock(return_value=server_create))
self.mock_object(
self._manager, 'wait_for_instance_to_be_active',
mock.Mock(side_effect=exception.ServiceInstanceException))
try:
self._manager._create_service_instance(
self._manager.admin_context, instance_name, network_info)
except exception.ServiceInstanceException as e:
self.assertEqual(
dict(server_details=dict(subnet_id=network_data['subnet_id'],
router_id=network_data['router_id'],
instance_id=server_create['id'])),
e.detail_data)
else:
raise exception.ManilaException('Expected error was not raised.')
self._manager.network_helper.setup_network.assert_called_once_with(
network_info)
self._manager._get_service_image.assert_called_once_with(
self._manager.admin_context)
self._manager._get_key.assert_called_once_with(
self._manager.admin_context)
self._manager.compute_api.server_create.assert_called_once_with(
self._manager.admin_context, name=instance_name,
image=service_image_id, flavor=100,
key_name=key_data[0], nics=network_data['nics'],
availability_zone=service_instance.CONF.storage_availability_zone)
@ddt.data(
dict(name=None, path=None),
dict(name=None, path='/tmp'))
@ddt.unpack
def test__create_service_instance_no_key_and_no_path(self, name, path):
key_data = name, path
self.mock_object(self._manager, '_get_service_image')
self.mock_object(self._manager, '_get_key',
mock.Mock(return_value=key_data))
self.assertRaises(
exception.ServiceInstanceException,
self._manager._create_service_instance,
self._manager.admin_context, 'fake_instance_name', dict())
self._manager._get_service_image.assert_called_once_with(
self._manager.admin_context)
self._manager._get_key.assert_called_once_with(
self._manager.admin_context)
@mock.patch('time.sleep')
@mock.patch('time.time')
def _test_wait_for_instance(self, mock_time, mock_sleep,
server_get_side_eff=None,
expected_try_count=1,
expected_sleep_count=0,
expected_ret_val=None,
expected_exc=None):
mock_server_get = mock.Mock(side_effect=server_get_side_eff)
self.mock_object(self._manager.compute_api, 'server_get',
mock_server_get)
self.fake_time = 0
def fake_time():
return self.fake_time
def fake_sleep(sleep_time):
self.fake_time += sleep_time
# Note(lpetrut): LOG methods can call time.time
mock_time.side_effect = fake_time
mock_sleep.side_effect = fake_sleep
timeout = 3
if expected_exc:
self.assertRaises(
expected_exc,
self._manager.wait_for_instance_to_be_active,
instance_id=mock.sentinel.instance_id,
timeout=timeout)
else:
instance = self._manager.wait_for_instance_to_be_active(
instance_id=mock.sentinel.instance_id,
timeout=timeout)
self.assertEqual(expected_ret_val, instance)
mock_server_get.assert_has_calls(
[mock.call(self._manager.admin_context,
mock.sentinel.instance_id)] * expected_try_count)
mock_sleep.assert_has_calls([mock.call(1)] * expected_sleep_count)
def test_wait_for_instance_timeout(self):
server_get_side_eff = [
exception.InstanceNotFound(
instance_id=mock.sentinel.instance_id),
{'status': 'BUILDING'},
{'status': 'ACTIVE'}]
# Note that in this case, although the status is active, the
# 'networks' field is missing.
self._test_wait_for_instance(
server_get_side_eff=server_get_side_eff,
expected_exc=exception.ServiceInstanceException,
expected_try_count=3,
expected_sleep_count=3)
def test_wait_for_instance_error_state(self):
mock_instance = {'status': 'ERROR'}
self._test_wait_for_instance(
server_get_side_eff=[mock_instance],
expected_exc=exception.ServiceInstanceException,
expected_try_count=1)
def test_wait_for_instance_available(self):
mock_instance = {'status': 'ACTIVE',
'networks': mock.sentinel.networks}
self._test_wait_for_instance(
server_get_side_eff=[mock_instance],
expected_try_count=1,
expected_ret_val=mock_instance)
def test_reboot_server(self):
fake_server = {'instance_id': mock.sentinel.instance_id}
soft_reboot = True
mock_reboot = mock.Mock()
self.mock_object(self._manager.compute_api, 'server_reboot',
mock_reboot)
self._manager.reboot_server(fake_server, soft_reboot)
mock_reboot.assert_called_once_with(self._manager.admin_context,
fake_server['instance_id'],
soft_reboot)
class BaseNetworkHelperTestCase(test.TestCase):
"""Tests Base network helper for service instance."""
def test_instantiate_valid(self):
class FakeNetworkHelper(service_instance.BaseNetworkhelper):
@property
def NAME(self):
return 'fake_NAME'
def __init__(self, service_instance_manager):
self.fake_init = 'fake_init_value'
def get_network_name(self, network_info):
return 'fake_network_name'
def setup_connectivity_with_service_instances(self):
return 'fake_setup_connectivity_with_service_instances'
def setup_network(self, network_info):
return 'fake_setup_network'
def teardown_network(self, server_details):
return 'fake_teardown_network'
instance = FakeNetworkHelper('fake')
attrs = [
'fake_init', 'NAME', 'get_network_name', 'teardown_network',
'setup_connectivity_with_service_instances', 'setup_network',
]
for attr in attrs:
self.assertTrue(hasattr(instance, attr))
self.assertEqual('fake_init_value', instance.fake_init)
self.assertEqual('fake_NAME', instance.NAME)
self.assertEqual(
'fake_network_name', instance.get_network_name('fake'))
self.assertEqual(
'fake_setup_connectivity_with_service_instances',
instance.setup_connectivity_with_service_instances())
self.assertEqual('fake_setup_network', instance.setup_network('fake'))
self.assertEqual(
'fake_teardown_network', instance.teardown_network('fake'))
def test_instantiate_invalid(self):
self.assertRaises(
TypeError, service_instance.BaseNetworkhelper, 'fake')
@ddt.ddt
class NeutronNetworkHelperTestCase(test.TestCase):
"""Tests Neutron network helper for service instance."""
def setUp(self):
super(NeutronNetworkHelperTestCase, self).setUp()
self.mock_object(importutils, 'import_class')
self.fake_manager = FakeServiceInstance()
def _init_neutron_network_plugin(self):
self.mock_object(
service_instance.NeutronNetworkHelper, '_get_service_network_id',
mock.Mock(return_value='fake_service_network_id'))
return service_instance.NeutronNetworkHelper(self.fake_manager)
def test_init_neutron_network_plugin(self):
instance = self._init_neutron_network_plugin()
self.assertEqual(service_instance.NEUTRON_NAME, instance.NAME)
attrs = [
'neutron_api', 'vif_driver', 'service_network_id',
'connect_share_server_to_tenant_network', 'get_config_option']
for attr in attrs:
self.assertTrue(hasattr(instance, attr), "No attr '%s'" % attr)
(service_instance.NeutronNetworkHelper._get_service_network_id.
assert_called_once_with())
self.assertEqual('DEFAULT', instance.neutron_api.config_group_name)
def test_init_neutron_network_plugin_with_driver_config_group(self):
self.fake_manager.driver_config = mock.Mock()
self.fake_manager.driver_config.config_group = (
'fake_config_group')
self.fake_manager.driver_config.network_config_group = None
instance = self._init_neutron_network_plugin()
self.assertEqual('fake_config_group',
instance.neutron_api.config_group_name)
def test_init_neutron_network_plugin_with_network_config_group(self):
self.fake_manager.driver_config = mock.Mock()
self.fake_manager.driver_config.config_group = (
"fake_config_group")
self.fake_manager.driver_config.network_config_group = (
"fake_network_config_group")
instance = self._init_neutron_network_plugin()
self.assertEqual('fake_network_config_group',
instance.neutron_api.config_group_name)
def test_admin_project_id(self):
instance = self._init_neutron_network_plugin()
admin_project_id = 'fake_admin_project_id'
self.mock_class('manila.network.neutron.api.API', mock.Mock())
instance.neutron_api.admin_project_id = admin_project_id
self.assertEqual(admin_project_id, instance.admin_project_id)
def test_get_network_name(self):
network_info = dict(neutron_net_id='fake_neutron_net_id')
network = dict(name='fake_network_name')
instance = self._init_neutron_network_plugin()
self.mock_object(
instance.neutron_api, 'get_network',
mock.Mock(return_value=network))
result = instance.get_network_name(network_info)
self.assertEqual(network['name'], result)
instance.neutron_api.get_network.assert_called_once_with(
network_info['neutron_net_id'])
def test_get_service_network_id_none_exist(self):
service_network_name = fake_get_config_option('service_network_name')
network = dict(id='fake_network_id')
admin_project_id = 'fake_admin_project_id'
self.mock_object(
service_instance.neutron.API, 'get_all_admin_project_networks',
mock.Mock(return_value=[]))
self.mock_object(
service_instance.neutron.API, 'admin_project_id',
mock.Mock(return_value=admin_project_id))
self.mock_object(
service_instance.neutron.API, 'network_create',
mock.Mock(return_value=network))
instance = service_instance.NeutronNetworkHelper(self.fake_manager)
result = instance._get_service_network_id()
self.assertEqual(network['id'], result)
self.assertTrue(service_instance.neutron.API.
get_all_admin_project_networks.called)
service_instance.neutron.API.network_create.assert_has_calls([
mock.call(instance.admin_project_id, service_network_name)])
def test_get_service_network_id_one_exist(self):
service_network_name = fake_get_config_option('service_network_name')
network = dict(id='fake_network_id', name=service_network_name)
admin_project_id = 'fake_admin_project_id'
self.mock_object(
service_instance.neutron.API, 'get_all_admin_project_networks',
mock.Mock(return_value=[network]))
self.mock_object(
service_instance.neutron.API, 'admin_project_id',
mock.Mock(return_value=admin_project_id))
instance = service_instance.NeutronNetworkHelper(self.fake_manager)
result = instance._get_service_network_id()
self.assertEqual(network['id'], result)
self.assertTrue(service_instance.neutron.API.
get_all_admin_project_networks.called)
def test_get_service_network_id_two_exist(self):
service_network_name = fake_get_config_option('service_network_name')
network = dict(id='fake_network_id', name=service_network_name)
self.mock_object(
service_instance.neutron.API, 'get_all_admin_project_networks',
mock.Mock(return_value=[network, network]))
helper = service_instance.NeutronNetworkHelper(self.fake_manager)
self.assertRaises(exception.ManilaException,
lambda: helper.service_network_id)
(service_instance.neutron.API.get_all_admin_project_networks.
assert_has_calls([mock.call()]))
@ddt.data(dict(), dict(subnet_id='foo'), dict(router_id='bar'))
def test_teardown_network_no_service_data(self, server_details):
instance = self._init_neutron_network_plugin()
self.mock_object(
service_instance.neutron.API, 'router_remove_interface')
instance.teardown_network(server_details)
self.assertFalse(
service_instance.neutron.API.router_remove_interface.called)
@ddt.data(
*[dict(server_details=sd, fail=f) for f in (True, False)
for sd in (dict(service_port_id='fake_service_port_id'),
dict(public_port_id='fake_public_port_id'),
dict(service_port_id='fake_service_port_id',
public_port_id='fake_public_port_id'))]
)
@ddt.unpack
def test_teardown_network_with_ports(self, server_details, fail):
instance = self._init_neutron_network_plugin()
self.mock_object(
service_instance.neutron.API, 'router_remove_interface')
if fail:
delete_port_mock = mock.Mock(
side_effect=exception.NetworkException(code=404))
else:
delete_port_mock = mock.Mock()
self.mock_object(instance.neutron_api, 'delete_port', delete_port_mock)
self.mock_object(service_instance.LOG, 'debug')
instance.teardown_network(server_details)
self.assertFalse(instance.neutron_api.router_remove_interface.called)
self.assertEqual(
len(server_details),
len(instance.neutron_api.delete_port.mock_calls))
for k, v in server_details.items():
self.assertIn(
mock.call(v), instance.neutron_api.delete_port.mock_calls)
if fail:
service_instance.LOG.debug.assert_has_calls([
mock.call(mock.ANY, mock.ANY) for sd in server_details
])
else:
service_instance.LOG.debug.assert_has_calls([])
@ddt.data(
dict(service_port_id='fake_service_port_id'),
dict(public_port_id='fake_public_port_id'),
dict(service_port_id='fake_service_port_id',
public_port_id='fake_public_port_id'),
)
def test_teardown_network_with_ports_unhandled_exception(self,
server_details):
instance = self._init_neutron_network_plugin()
self.mock_object(
service_instance.neutron.API, 'router_remove_interface')
delete_port_mock = mock.Mock(
side_effect=exception.NetworkException(code=500))
self.mock_object(
service_instance.neutron.API, 'delete_port', delete_port_mock)
self.mock_object(service_instance.LOG, 'debug')
self.assertRaises(
exception.NetworkException,
instance.teardown_network,
server_details,
)
self.assertFalse(
service_instance.neutron.API.router_remove_interface.called)
service_instance.neutron.API.delete_port.assert_called_once_with(
mock.ANY)
service_instance.LOG.debug.assert_has_calls([])
def test_teardown_network_with_wrong_ports(self):
instance = self._init_neutron_network_plugin()
self.mock_object(
service_instance.neutron.API, 'router_remove_interface')
self.mock_object(
service_instance.neutron.API, 'delete_port')
self.mock_object(service_instance.LOG, 'debug')
instance.teardown_network(dict(foo_id='fake_service_port_id'))
service_instance.neutron.API.router_remove_interface.assert_has_calls(
[])
service_instance.neutron.API.delete_port.assert_has_calls([])
service_instance.LOG.debug.assert_has_calls([])
def test_teardown_network_subnet_is_used(self):
server_details = dict(subnet_id='foo', router_id='bar')
fake_ports = [
{'fixed_ips': [{'subnet_id': server_details['subnet_id']}],
'device_id': 'fake_device_id',
'device_owner': 'compute:foo'},
]
instance = self._init_neutron_network_plugin()
self.mock_object(
service_instance.neutron.API, 'router_remove_interface')
self.mock_object(
service_instance.neutron.API, 'update_subnet')
self.mock_object(
service_instance.neutron.API, 'list_ports',
mock.Mock(return_value=fake_ports))
instance.teardown_network(server_details)
self.assertFalse(
service_instance.neutron.API.router_remove_interface.called)
self.assertFalse(service_instance.neutron.API.update_subnet.called)
service_instance.neutron.API.list_ports.assert_called_once_with(
fields=['fixed_ips', 'device_id', 'device_owner'])
def test_teardown_network_subnet_not_used(self):
server_details = dict(subnet_id='foo', router_id='bar')
fake_ports = [
{'fixed_ips': [{'subnet_id': server_details['subnet_id']}],
'device_id': 'fake_device_id',
'device_owner': 'network:router_interface'},
{'fixed_ips': [{'subnet_id': 'bar' + server_details['subnet_id']}],
'device_id': 'fake_device_id',
'device_owner': 'compute'},
{'fixed_ips': [{'subnet_id': server_details['subnet_id']}],
'device_id': '',
'device_owner': 'compute'},
]
instance = self._init_neutron_network_plugin()
self.mock_object(
service_instance.neutron.API, 'router_remove_interface')
self.mock_object(
service_instance.neutron.API, 'update_subnet')
self.mock_object(
service_instance.neutron.API, 'list_ports',
mock.Mock(return_value=fake_ports))
instance.teardown_network(server_details)
(service_instance.neutron.API.router_remove_interface.
assert_called_once_with('bar', 'foo'))
(service_instance.neutron.API.update_subnet.
assert_called_once_with('foo', ''))
service_instance.neutron.API.list_ports.assert_called_once_with(
fields=['fixed_ips', 'device_id', 'device_owner'])
def test_teardown_network_subnet_not_used_and_get_error_404(self):
server_details = dict(subnet_id='foo', router_id='bar')
fake_ports = [
{'fixed_ips': [{'subnet_id': server_details['subnet_id']}],
'device_id': 'fake_device_id',
'device_owner': 'fake'},
]
instance = self._init_neutron_network_plugin()
self.mock_object(
service_instance.neutron.API, 'router_remove_interface',
mock.Mock(side_effect=exception.NetworkException(code=404)))
self.mock_object(
service_instance.neutron.API, 'update_subnet')
self.mock_object(
service_instance.neutron.API, 'list_ports',
mock.Mock(return_value=fake_ports))
instance.teardown_network(server_details)
(service_instance.neutron.API.router_remove_interface.
assert_called_once_with('bar', 'foo'))
(service_instance.neutron.API.update_subnet.
assert_called_once_with('foo', ''))
service_instance.neutron.API.list_ports.assert_called_once_with(
fields=['fixed_ips', 'device_id', 'device_owner'])
def test_teardown_network_subnet_not_used_get_unhandled_error(self):
server_details = dict(subnet_id='foo', router_id='bar')
fake_ports = [
{'fixed_ips': [{'subnet_id': server_details['subnet_id']}],
'device_id': 'fake_device_id',
'device_owner': 'fake'},
]
instance = self._init_neutron_network_plugin()
self.mock_object(
service_instance.neutron.API, 'router_remove_interface',
mock.Mock(side_effect=exception.NetworkException(code=500)))
self.mock_object(
service_instance.neutron.API, 'update_subnet')
self.mock_object(
service_instance.neutron.API, 'list_ports',
mock.Mock(return_value=fake_ports))
self.assertRaises(
exception.NetworkException,
instance.teardown_network, server_details)
(service_instance.neutron.API.router_remove_interface.
assert_called_once_with('bar', 'foo'))
self.assertFalse(service_instance.neutron.API.update_subnet.called)
service_instance.neutron.API.list_ports.assert_called_once_with(
fields=['fixed_ips', 'device_id', 'device_owner'])
def test_setup_network_and_connect_share_server_to_tenant_net(self):
def fake_create_port(*aargs, **kwargs):
if aargs[1] == 'fake_service_network_id':
return self.service_port
elif aargs[1] == 'fake_tenant_network_id':
return self.public_port
else:
raise exception.ManilaException('Got unexpected data')
admin_project_id = 'fake_admin_project_id'
network_info = dict(
neutron_net_id='fake_tenant_network_id',
neutron_subnet_id='fake_tenant_subnet_id')
cidr = '13.0.0.0/24'
self.service_port = dict(
id='fake_service_port_id',
fixed_ips=[dict(ip_address='fake_service_port_ip_address')])
self.public_port = dict(
id='fake_tenant_port_id',
fixed_ips=[dict(ip_address='fake_public_port_ip_address')])
service_subnet = dict(id='fake_service_subnet')
instance = self._init_neutron_network_plugin()
instance.connect_share_server_to_tenant_network = True
self.mock_object(instance, '_get_service_network_id',
mock.Mock(return_value='fake_service_network_id'))
self.mock_object(
service_instance.neutron.API, 'admin_project_id',
mock.Mock(return_value=admin_project_id))
self.mock_object(
service_instance.neutron.API, 'create_port',
mock.Mock(side_effect=fake_create_port))
self.mock_object(
service_instance.neutron.API, 'subnet_create',
mock.Mock(return_value=service_subnet))
self.mock_object(
instance, 'setup_connectivity_with_service_instances',
mock.Mock(return_value=service_subnet))
self.mock_object(
instance, '_get_cidr_for_subnet', mock.Mock(return_value=cidr))
self.mock_object(
instance, '_get_service_subnet', mock.Mock(return_value=None))
expected = {
'ip_address': self.public_port['fixed_ips'][0]['ip_address'],
'public_port': self.public_port,
'service_port': self.service_port,
'service_subnet': service_subnet,
'ports': [self.public_port, self.service_port],
'nics': [{'port-id': self.public_port['id']},
{'port-id': self.service_port['id']}]}
result = instance.setup_network(network_info)
self.assertEqual(expected, result)
(instance.setup_connectivity_with_service_instances.
assert_called_once_with())
instance._get_service_subnet.assert_called_once_with(mock.ANY)
instance._get_cidr_for_subnet.assert_called_once_with()
self.assertTrue(service_instance.neutron.API.subnet_create.called)
self.assertTrue(service_instance.neutron.API.create_port.called)
def test_setup_network_and_connect_share_server_to_tenant_net_admin(self):
def fake_create_port(*aargs, **kwargs):
if aargs[1] == 'fake_admin_network_id':
return self.admin_port
elif aargs[1] == 'fake_tenant_network_id':
return self.public_port
else:
raise exception.ManilaException('Got unexpected data')
admin_project_id = 'fake_admin_project_id'
network_info = {
'neutron_net_id': 'fake_tenant_network_id',
'neutron_subnet_id': 'fake_tenant_subnet_id'}
self.admin_port = {
'id': 'fake_admin_port_id',
'fixed_ips': [{'ip_address': 'fake_admin_port_ip_address'}]}
self.public_port = {
'id': 'fake_tenant_port_id',
'fixed_ips': [{'ip_address': 'fake_public_port_ip_address'}]}
instance = self._init_neutron_network_plugin()
instance.use_admin_port = True
instance.use_service_network = False
instance.admin_network_id = 'fake_admin_network_id'
instance.admin_subnet_id = 'fake_admin_subnet_id'
instance.connect_share_server_to_tenant_network = True
self.mock_object(
service_instance.neutron.API, 'admin_project_id',
mock.Mock(return_value=admin_project_id))
self.mock_object(
service_instance.neutron.API, 'create_port',
mock.Mock(side_effect=fake_create_port))
self.mock_object(
instance, 'setup_connectivity_with_service_instances')
expected = {
'ip_address': self.public_port['fixed_ips'][0]['ip_address'],
'public_port': self.public_port,
'admin_port': self.admin_port,
'ports': [self.public_port, self.admin_port],
'nics': [{'port-id': self.public_port['id']},
{'port-id': self.admin_port['id']}]}
result = instance.setup_network(network_info)
self.assertEqual(expected, result)
(instance.setup_connectivity_with_service_instances.
assert_called_once_with())
self.assertTrue(service_instance.neutron.API.create_port.called)
@ddt.data(None, exception.NetworkException(code=400))
def test_setup_network_using_router_success(self, return_obj):
admin_project_id = 'fake_admin_project_id'
network_info = dict(
neutron_net_id='fake_tenant_network_id',
neutron_subnet_id='fake_tenant_subnet_id')
cidr = '13.0.0.0/24'
self.admin_port = {
'id': 'fake_admin_port_id',
'fixed_ips': [{'ip_address': 'fake_admin_port_ip_address'}]}
self.service_port = dict(
id='fake_service_port_id',
fixed_ips=[dict(ip_address='fake_service_port_ip_address')])
service_subnet = dict(id='fake_service_subnet')
instance = self._init_neutron_network_plugin()
instance.use_admin_port = True
instance.admin_network_id = 'fake_admin_network_id'
instance.admin_subnet_id = 'fake_admin_subnet_id'
instance.connect_share_server_to_tenant_network = False
self.mock_object(instance, '_get_service_network_id',
mock.Mock(return_value='fake_service_network_id'))
router = dict(id='fake_router_id')
self.mock_object(
service_instance.neutron.API, 'admin_project_id',
mock.Mock(return_value=admin_project_id))
self.mock_object(
service_instance.neutron.API, 'create_port',
mock.Mock(side_effect=[self.service_port, self.admin_port]))
self.mock_object(
service_instance.neutron.API, 'subnet_create',
mock.Mock(return_value=service_subnet))
self.mock_object(
instance, '_get_private_router', mock.Mock(return_value=router))
self.mock_object(
service_instance.neutron.API, 'router_add_interface',
mock.Mock(side_effect=return_obj))
self.mock_object(instance, 'setup_connectivity_with_service_instances')
self.mock_object(
instance, '_get_cidr_for_subnet', mock.Mock(return_value=cidr))
self.mock_object(
instance, '_get_service_subnet', mock.Mock(return_value=None))
expected = {
'ip_address': self.service_port['fixed_ips'][0]['ip_address'],
'service_port': self.service_port,
'service_subnet': service_subnet,
'admin_port': self.admin_port, 'router': router,
'ports': [self.service_port, self.admin_port],
'nics': [{'port-id': self.service_port['id']},
{'port-id': self.admin_port['id']}]}
result = instance.setup_network(network_info)
self.assertEqual(expected, result)
(instance.setup_connectivity_with_service_instances.
assert_called_once_with())
instance._get_service_subnet.assert_called_once_with(mock.ANY)
instance._get_cidr_for_subnet.assert_called_once_with()
self.assertTrue(service_instance.neutron.API.subnet_create.called)
self.assertTrue(service_instance.neutron.API.create_port.called)
instance._get_private_router.assert_called_once_with(
network_info['neutron_net_id'], network_info['neutron_subnet_id'])
(service_instance.neutron.API.router_add_interface.
assert_called_once_with(router['id'], service_subnet['id']))
def test_setup_network_using_router_addon_of_interface_failed(self):
network_info = dict(
neutron_net_id='fake_tenant_network_id',
neutron_subnet_id='fake_tenant_subnet_id')
service_subnet = dict(id='fake_service_subnet')
instance = self._init_neutron_network_plugin()
instance.connect_share_server_to_tenant_network = False
self.mock_object(instance, '_get_service_network_id',
mock.Mock(return_value='fake_service_network_id'))
router = dict(id='fake_router_id')
self.mock_object(
instance, '_get_private_router', mock.Mock(return_value=router))
self.mock_object(
service_instance.neutron.API, 'router_add_interface',
mock.Mock(side_effect=exception.NetworkException(code=500)))
self.mock_object(
instance, '_get_service_subnet',
mock.Mock(return_value=service_subnet))
self.assertRaises(
exception.NetworkException,
instance.setup_network, network_info)
instance._get_service_subnet.assert_called_once_with(mock.ANY)
instance._get_private_router.assert_called_once_with(
network_info['neutron_net_id'], network_info['neutron_subnet_id'])
(service_instance.neutron.API.router_add_interface.
assert_called_once_with(router['id'], service_subnet['id']))
def test_setup_network_using_router_connectivity_verification_fail(self):
admin_project_id = 'fake_admin_project_id'
network_info = dict(
neutron_net_id='fake_tenant_network_id',
neutron_subnet_id='fake_tenant_subnet_id')
cidr = '13.0.0.0/24'
self.service_port = dict(
id='fake_service_port_id',
fixed_ips=[dict(ip_address='fake_service_port_ip_address')])
service_subnet = dict(id='fake_service_subnet')
instance = self._init_neutron_network_plugin()
instance.connect_share_server_to_tenant_network = False
self.mock_object(instance, '_get_service_network_id',
mock.Mock(return_value='fake_service_network_id'))
router = dict(id='fake_router_id')
self.mock_object(
service_instance.neutron.API, 'admin_project_id',
mock.Mock(return_value=admin_project_id))
self.mock_object(
service_instance.neutron.API, 'create_port',
mock.Mock(return_value=self.service_port))
self.mock_object(
service_instance.neutron.API, 'subnet_create',
mock.Mock(return_value=service_subnet))
self.mock_object(service_instance.neutron.API, 'delete_port')
self.mock_object(
instance, '_get_private_router', mock.Mock(return_value=router))
self.mock_object(
service_instance.neutron.API, 'router_add_interface')
self.mock_object(
instance, 'setup_connectivity_with_service_instances',
mock.Mock(side_effect=exception.ManilaException('Fake')))
self.mock_object(
instance, '_get_cidr_for_subnet', mock.Mock(return_value=cidr))
self.mock_object(
instance, '_get_service_subnet', mock.Mock(return_value=None))
self.assertRaises(
exception.ManilaException, instance.setup_network, network_info)
(instance.setup_connectivity_with_service_instances.
assert_called_once_with())
instance._get_service_subnet.assert_called_once_with(mock.ANY)
instance._get_cidr_for_subnet.assert_called_once_with()
self.assertTrue(service_instance.neutron.API.subnet_create.called)
self.assertTrue(service_instance.neutron.API.create_port.called)
instance._get_private_router.assert_called_once_with(
network_info['neutron_net_id'], network_info['neutron_subnet_id'])
(service_instance.neutron.API.router_add_interface.
assert_called_once_with(router['id'], service_subnet['id']))
service_instance.neutron.API.delete_port.assert_has_calls([
mock.call(self.service_port['id'])])
def test__get_cidr_for_subnet_success(self):
expected = (
fake_get_config_option('service_network_cidr').split('/')[0] +
'/' + six.text_type(
fake_get_config_option('service_network_division_mask')))
instance = self._init_neutron_network_plugin()
self.mock_object(
instance, '_get_all_service_subnets', mock.Mock(return_value=[]))
result = instance._get_cidr_for_subnet()
self.assertEqual(expected, result)
instance._get_all_service_subnets.assert_called_once_with()
def test__get_cidr_for_subnet_failure(self):
subnets = []
serv_cidr = netaddr.IPNetwork(
fake_get_config_option('service_network_cidr'))
division_mask = fake_get_config_option('service_network_division_mask')
for subnet in serv_cidr.subnet(division_mask):
subnets.append(dict(cidr=six.text_type(subnet.cidr)))
instance = self._init_neutron_network_plugin()
self.mock_object(
instance, '_get_all_service_subnets',
mock.Mock(return_value=subnets))
self.assertRaises(
exception.ServiceInstanceException,
instance._get_cidr_for_subnet)
instance._get_all_service_subnets.assert_called_once_with()
def test_setup_connectivity_with_service_instances(self):
instance = self._init_neutron_network_plugin()
instance.use_admin_port = True
instance.admin_network_id = 'fake_admin_network_id'
instance.admin_subnet_id = 'fake_admin_subnet_id'
interface_name_service = 'fake_interface_name_service'
interface_name_admin = 'fake_interface_name_admin'
fake_division_mask = fake_get_config_option(
'service_network_division_mask')
fake_subnet_service = fake_network.FakeSubnet(
cidr='10.254.0.0/%s' % fake_division_mask)
fake_subnet_admin = fake_network.FakeSubnet(id='fake_admin_subnet_id',
cidr='10.0.0.0/24')
fake_service_port = fake_network.FakePort(fixed_ips=[
{'subnet_id': fake_subnet_service['id'],
'ip_address': '10.254.0.2'}], mac_address='fake_mac_address')
fake_admin_port = fake_network.FakePort(fixed_ips=[
{'subnet_id': fake_subnet_admin['id'], 'ip_address': '10.0.0.4'}],
mac_address='fake_mac_address')
self.mock_object(instance, '_get_service_port',
mock.Mock(side_effect=[fake_service_port,
fake_admin_port]))
self.mock_object(instance, '_add_fixed_ips_to_service_port',
mock.Mock(return_value=fake_service_port))
self.mock_object(instance.vif_driver, 'get_device_name',
mock.Mock(side_effect=[interface_name_service,
interface_name_admin]))
self.mock_object(instance.neutron_api, 'get_subnet',
mock.Mock(side_effect=[fake_subnet_service,
fake_subnet_admin,
fake_subnet_admin]))
self.mock_object(instance, '_remove_outdated_interfaces')
self.mock_object(instance.vif_driver, 'plug')
device_mock = mock.Mock()
self.mock_object(service_instance.ip_lib, 'IPDevice',
mock.Mock(return_value=device_mock))
instance.setup_connectivity_with_service_instances()
instance._get_service_port.assert_has_calls([
mock.call(instance.service_network_id, None, 'manila-share'),
mock.call('fake_admin_network_id', 'fake_admin_subnet_id',
'manila-admin-share')])
instance.vif_driver.get_device_name.assert_has_calls([
mock.call(fake_service_port), mock.call(fake_admin_port)])
instance.vif_driver.plug.assert_has_calls([
mock.call(interface_name_service, fake_service_port['id'],
fake_service_port['mac_address']),
mock.call(interface_name_admin, fake_admin_port['id'],
fake_admin_port['mac_address'])])
instance.neutron_api.get_subnet.assert_has_calls([
mock.call(fake_subnet_service['id']),
mock.call(fake_subnet_admin['id']),
mock.call(fake_subnet_admin['id'])])
instance.vif_driver.init_l3.assert_has_calls([
mock.call(interface_name_service,
['10.254.0.2/%s' % fake_division_mask]),
mock.call(interface_name_admin, ['10.0.0.4/24'])])
service_instance.ip_lib.IPDevice.assert_has_calls([
mock.call(interface_name_service),
mock.call(interface_name_admin)])
device_mock.route.pullup_route.assert_has_calls([
mock.call(interface_name_service),
mock.call(interface_name_admin)])
instance._remove_outdated_interfaces.assert_called_with(device_mock)
def test__get_set_of_device_cidrs(self):
device = fake_network.FakeDevice('foo')
expected = set(('1.0.0.0/27', '2.0.0.0/27'))
instance = self._init_neutron_network_plugin()
result = instance._get_set_of_device_cidrs(device)
self.assertEqual(expected, result)
def test__get_set_of_device_cidrs_exception(self):
device = fake_network.FakeDevice('foo')
self.mock_object(device.addr, 'list', mock.Mock(
side_effect=Exception('foo does not exist')))
instance = self._init_neutron_network_plugin()
result = instance._get_set_of_device_cidrs(device)
self.assertEqual(set(), result)
def test__remove_outdated_interfaces(self):
device = fake_network.FakeDevice(
'foobarquuz', [dict(ip_version=4, cidr='1.0.0.0/27')])
devices = [fake_network.FakeDevice('foobar')]
instance = self._init_neutron_network_plugin()
self.mock_object(instance.vif_driver, 'unplug')
self.mock_object(
service_instance.ip_lib.IPWrapper, 'get_devices',
mock.Mock(return_value=devices))
instance._remove_outdated_interfaces(device)
instance.vif_driver.unplug.assert_called_once_with('foobar')
def test__get_service_port_none_exist(self):
instance = self._init_neutron_network_plugin()
admin_project_id = 'fake_admin_project_id'
fake_port_values = {'device_id': 'manila-share',
'binding:host_id': 'fake_host'}
self.mock_object(
service_instance.neutron.API, 'admin_project_id',
mock.Mock(return_value=admin_project_id))
fake_service_port = fake_network.FakePort(device_id='manila-share')
self.mock_object(instance.neutron_api, 'list_ports',
mock.Mock(return_value=[]))
self.mock_object(service_instance.socket, 'gethostname',
mock.Mock(return_value='fake_host'))
self.mock_object(instance.neutron_api, 'create_port',
mock.Mock(return_value=fake_service_port))
self.mock_object(instance.neutron_api, 'update_port_fixed_ips',
mock.Mock(return_value=fake_service_port))
result = instance._get_service_port(instance.service_network_id,
None, 'manila-share')
instance.neutron_api.list_ports.assert_called_once_with(
**fake_port_values)
instance.neutron_api.create_port.assert_called_once_with(
instance.admin_project_id, instance.service_network_id,
device_id='manila-share', device_owner='manila:share',
host_id='fake_host', subnet_id=None, port_security_enabled=False)
service_instance.socket.gethostname.assert_called_once_with()
self.assertFalse(instance.neutron_api.update_port_fixed_ips.called)
self.assertEqual(fake_service_port, result)
def test__get_service_port_one_exist_on_same_host(self):
instance = self._init_neutron_network_plugin()
fake_port_values = {'device_id': 'manila-share',
'binding:host_id': 'fake_host'}
fake_service_port = fake_network.FakePort(**fake_port_values)
self.mock_object(service_instance.socket, 'gethostname',
mock.Mock(return_value='fake_host'))
self.mock_object(instance.neutron_api, 'list_ports',
mock.Mock(return_value=[fake_service_port]))
self.mock_object(instance.neutron_api, 'create_port',
mock.Mock(return_value=fake_service_port))
self.mock_object(instance.neutron_api, 'update_port_fixed_ips',
mock.Mock(return_value=fake_service_port))
result = instance._get_service_port(instance.service_network_id,
None, 'manila-share')
instance.neutron_api.list_ports.assert_called_once_with(
**fake_port_values)
self.assertFalse(instance.neutron_api.create_port.called)
self.assertFalse(instance.neutron_api.update_port_fixed_ips.called)
self.assertEqual(fake_service_port, result)
def test__get_service_port_one_exist_on_different_host(self):
instance = self._init_neutron_network_plugin()
admin_project_id = 'fake_admin_project_id'
fake_port = {'device_id': 'manila-share',
'binding:host_id': 'fake_host'}
self.mock_object(
service_instance.neutron.API, 'admin_project_id',
mock.Mock(return_value=admin_project_id))
fake_service_port = fake_network.FakePort(**fake_port)
self.mock_object(instance.neutron_api, 'list_ports',
mock.Mock(return_value=[]))
self.mock_object(service_instance.socket, 'gethostname',
mock.Mock(return_value='fake_host'))
self.mock_object(instance.neutron_api, 'create_port',
mock.Mock(return_value=fake_service_port))
self.mock_object(instance.neutron_api, 'update_port_fixed_ips',
mock.Mock(return_value=fake_service_port))
result = instance._get_service_port(instance.service_network_id,
None, 'manila-share')
instance.neutron_api.list_ports.assert_called_once_with(
**fake_port)
instance.neutron_api.create_port.assert_called_once_with(
instance.admin_project_id, instance.service_network_id,
device_id='manila-share', device_owner='manila:share',
host_id='fake_host', subnet_id=None, port_security_enabled=False)
service_instance.socket.gethostname.assert_called_once_with()
self.assertFalse(instance.neutron_api.update_port_fixed_ips.called)
self.assertEqual(fake_service_port, result)
def test__get_service_port_two_exist_on_same_host(self):
instance = self._init_neutron_network_plugin()
fake_service_port = fake_network.FakePort(**{
'device_id': 'manila-share', 'binding:host_id': 'fake_host'})
self.mock_object(
instance.neutron_api, 'list_ports',
mock.Mock(return_value=[fake_service_port, fake_service_port]))
self.mock_object(service_instance.socket, 'gethostname',
mock.Mock(return_value='fake_host'))
self.mock_object(instance.neutron_api, 'create_port',
mock.Mock(return_value=fake_service_port))
self.assertRaises(
exception.ServiceInstanceException, instance._get_service_port,
instance.service_network_id, None, 'manila-share')
self.assertFalse(instance.neutron_api.create_port.called)
def test__add_fixed_ips_to_service_port(self):
ip_address1 = '13.0.0.13'
subnet_id1 = 'fake_subnet_id1'
subnet_id2 = 'fake_subnet_id2'
port = dict(id='fooport', fixed_ips=[dict(
subnet_id=subnet_id1, ip_address=ip_address1)])
expected = mock.Mock()
network = dict(subnets=[subnet_id1, subnet_id2])
instance = self._init_neutron_network_plugin()
self.mock_object(instance.neutron_api, 'get_network',
mock.Mock(return_value=network))
self.mock_object(instance.neutron_api, 'update_port_fixed_ips',
mock.Mock(return_value=expected))
result = instance._add_fixed_ips_to_service_port(port)
self.assertEqual(expected, result)
instance.neutron_api.get_network.assert_called_once_with(
instance.service_network_id)
instance.neutron_api.update_port_fixed_ips.assert_called_once_with(
port['id'], dict(fixed_ips=[
dict(subnet_id=subnet_id1, ip_address=ip_address1),
dict(subnet_id=subnet_id2)]))
def test__get_private_router_success(self):
instance = self._init_neutron_network_plugin()
network = fake_network.FakeNetwork()
subnet = fake_network.FakeSubnet(gateway_ip='fake_ip')
router = fake_network.FakeRouter(id='fake_router_id')
port = fake_network.FakePort(fixed_ips=[
dict(subnet_id=subnet['id'],
ip_address=subnet['gateway_ip'])],
device_id=router['id'])
self.mock_object(instance.neutron_api, 'get_subnet',
mock.Mock(return_value=subnet))
self.mock_object(instance.neutron_api, 'list_ports',
mock.Mock(return_value=[port]))
self.mock_object(instance.neutron_api, 'show_router',
mock.Mock(return_value=router))
result = instance._get_private_router(network['id'], subnet['id'])
self.assertEqual(router, result)
instance.neutron_api.get_subnet.assert_called_once_with(subnet['id'])
instance.neutron_api.list_ports.assert_called_once_with(
network_id=network['id'])
instance.neutron_api.show_router.assert_called_once_with(router['id'])
def test__get_private_router_no_gateway(self):
instance = self._init_neutron_network_plugin()
subnet = fake_network.FakeSubnet(gateway_ip='')
self.mock_object(instance.neutron_api, 'get_subnet',
mock.Mock(return_value=subnet))
self.assertRaises(
exception.ServiceInstanceException,
instance._get_private_router, 'fake_network_id', subnet['id'])
instance.neutron_api.get_subnet.assert_called_once_with(
subnet['id'])
def test__get_private_router_subnet_is_not_attached_to_the_router(self):
instance = self._init_neutron_network_plugin()
network_id = 'fake_network_id'
subnet = fake_network.FakeSubnet(gateway_ip='fake_ip')
self.mock_object(instance.neutron_api, 'get_subnet',
mock.Mock(return_value=subnet))
self.mock_object(instance.neutron_api, 'list_ports',
mock.Mock(return_value=[]))
self.assertRaises(
exception.ServiceInstanceException,
instance._get_private_router, network_id, subnet['id'])
instance.neutron_api.get_subnet.assert_called_once_with(
subnet['id'])
instance.neutron_api.list_ports.assert_called_once_with(
network_id=network_id)
def test__get_service_subnet_none_found(self):
subnet_name = 'fake_subnet_name'
instance = self._init_neutron_network_plugin()
self.mock_object(instance, '_get_all_service_subnets',
mock.Mock(return_value=[]))
result = instance._get_service_subnet(subnet_name)
self.assertIsNone(result)
instance._get_all_service_subnets.assert_called_once_with()
def test__get_service_subnet_unused_found(self):
subnet_name = 'fake_subnet_name'
subnets = [fake_network.FakeSubnet(id='foo', name=''),
fake_network.FakeSubnet(id='bar', name='quuz')]
instance = self._init_neutron_network_plugin()
self.mock_object(instance.neutron_api, 'update_subnet')
self.mock_object(instance, '_get_all_service_subnets',
mock.Mock(return_value=subnets))
result = instance._get_service_subnet(subnet_name)
self.assertEqual(subnets[0], result)
instance._get_all_service_subnets.assert_called_once_with()
instance.neutron_api.update_subnet.assert_called_once_with(
subnets[0]['id'], subnet_name)
def test__get_service_subnet_one_found(self):
subnet_name = 'fake_subnet_name'
subnets = [fake_network.FakeSubnet(id='foo', name='quuz'),
fake_network.FakeSubnet(id='bar', name=subnet_name)]
instance = self._init_neutron_network_plugin()
self.mock_object(instance, '_get_all_service_subnets',
mock.Mock(return_value=subnets))
result = instance._get_service_subnet(subnet_name)
self.assertEqual(subnets[1], result)
instance._get_all_service_subnets.assert_called_once_with()
def test__get_service_subnet_two_found(self):
subnet_name = 'fake_subnet_name'
subnets = [fake_network.FakeSubnet(id='foo', name=subnet_name),
fake_network.FakeSubnet(id='bar', name=subnet_name)]
instance = self._init_neutron_network_plugin()
self.mock_object(instance, '_get_all_service_subnets',
mock.Mock(return_value=subnets))
self.assertRaises(
exception.ServiceInstanceException,
instance._get_service_subnet, subnet_name)
instance._get_all_service_subnets.assert_called_once_with()
def test__get_all_service_subnets(self):
subnet_id1 = 'fake_subnet_id1'
subnet_id2 = 'fake_subnet_id2'
instance = self._init_neutron_network_plugin()
network = dict(subnets=[subnet_id1, subnet_id2])
self.mock_object(instance.neutron_api, 'get_subnet',
mock.Mock(side_effect=lambda s_id: dict(id=s_id)))
self.mock_object(instance.neutron_api, 'get_network',
mock.Mock(return_value=network))
result = instance._get_all_service_subnets()
self.assertEqual([dict(id=subnet_id1), dict(id=subnet_id2)], result)
instance.neutron_api.get_network.assert_called_once_with(
instance.service_network_id)
instance.neutron_api.get_subnet.assert_has_calls([
mock.call(subnet_id1), mock.call(subnet_id2)])
| apache-2.0 | -2,590,683,383,154,454,500 | 45.300087 | 79 | 0.600845 | false | 3.866725 | true | false | false |
eqrx/mauzr | mauzr/gui/elements/meta.py | 1 | 2003 | """ Meta elements. """
from mauzr.gui import TextMixin, ColorStateMixin, RectBackgroundMixin
from mauzr.gui import BaseElement, ColorState
__author__ = "Alexander Sowitzki"
class Acceptor(TextMixin, RectBackgroundMixin, BaseElement):
""" Acknowledge all states via one click.
:param placement: Center and size of the element.
:type placement: tuple
:param panel: Panel to control.
:type panel: mauzr.gui.panel.Table
"""
def __init__(self, placement, panel):
BaseElement.__init__(self, *placement)
RectBackgroundMixin.__init__(self)
TextMixin.__init__(self, "Clear")
self._panel = panel
def _on_click(self):
# Assume click means acknowledge
for element in self._panel.elements:
element.state_acknowledged = True
@property
def _color(self):
""" Color of the element as tuple. """
return ColorState.INFORMATION.value[0]
class Muter(ColorStateMixin, TextMixin, RectBackgroundMixin, BaseElement):
""" Mute audio notifications.
:param placement: Center and size of the element.
:type placement: tuple
:param panel: Panel to control.
:type panel: mauzr.gui.panel.Table
"""
def __init__(self, placement, panel):
BaseElement.__init__(self, *placement)
RectBackgroundMixin.__init__(self)
TextMixin.__init__(self, "Mute")
conditions = {ColorState.WARNING: lambda v: v,
ColorState.INFORMATION: lambda v: not v}
ColorStateMixin.__init__(self, conditions)
self._muted = False
self._panel = panel
def _on_click(self):
# Assume click means acknowledge
self._muted = not self._muted
self._update_state(self._muted)
self._panel.mute(self._muted)
@property
def _color(self):
""" Color of the element as tuple. """
if self._muted:
return ColorState.WARNING.value[0]
return ColorState.INFORMATION.value[0]
| agpl-3.0 | 1,007,512,086,339,034,500 | 28.895522 | 74 | 0.631553 | false | 3.982107 | false | false | false |
HalShaw/Leetcode | Two Sum II - Input array is sorted.py | 1 | 1388 | class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
if len(numbers)<2:
return None
else:
for i in range(len(numbers)):#自己写的,时间复杂度O(n^2),AC不了
for x in range(1,len(numbers)):
if numbers[i]+numbers[x]!=target:
continue
else:
if i==x:
return[i+1,x+1+1]
else:
return[i+1,x+1]
if __name__ == '__main__':
s=Solution()
print(s.twoSum([5,25,75],100))
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
for i in xrange(len(numbers)):
if i>0 and numbers[i-1]==numbers[i]:#跳过重复元素
continue
low=i+1
high=len(numbers)-1
while(low<=high):
mid=(low+high)/2#二分法查找提速
if target-numbers[i]==numbers[mid]:
return [i+1, mid+1]
elif target-numbers[i]<numbers[mid]:
high=mid-1
else:
low=mid+1 | mit | 7,454,215,357,454,273,000 | 30.833333 | 63 | 0.41991 | false | 3.690608 | false | false | false |
FuegoFro/KeepTalkingBot | src/modules/complicated_wires_cv.py | 1 | 3415 | import cv2
from cv_helpers import extract_color, get_subset, get_dimens, show, get_contours, \
get_center_for_contour, apply_offset_to_single_location
from modules.complicated_wires_common import WireColor
_WIRE_Y_BOUNDARIES = (
64.0,
73.6,
)
_LED_Y_BOUNDARIES = (
13.8,
20.9,
)
_STAR_Y_BOUNDARIES = (
75.5,
86.4,
)
_TOP_X_BOUNDARIES = (
12.7,
22.4,
31.6,
41.2,
51.6,
60.9,
69.7,
)
_BOTTOM_X_BOUNDARIES = (
12.1,
23.3,
35.1,
47.4,
59.7,
69.9,
82.1,
)
_STAR_RATIO_THRESHOLD = 0.03
def _get_wire_color_and_mat_or_none(wire, hue, saturation, value, color):
mat = extract_color(wire, hue, saturation, value)
if mat.any():
return color, mat
else:
return None
def _get_wire_colors_and_positions(im):
colors_and_positions = []
for i in range(len(_BOTTOM_X_BOUNDARIES) - 1):
wire = get_subset(im, _BOTTOM_X_BOUNDARIES[i:i + 2], _WIRE_Y_BOUNDARIES)
wire_colors_and_mats = filter(None, (
_get_wire_color_and_mat_or_none(wire, 354 / 2, (220, 255), (150, 220), WireColor.RED),
_get_wire_color_and_mat_or_none(wire, 37 / 2, (0, 50), (200, 255), WireColor.WHITE),
_get_wire_color_and_mat_or_none(wire, 229 / 2, (150, 200), (75, 215), WireColor.BLUE),
))
if not wire_colors_and_mats:
colors_and_positions.append(None)
continue
wire_colors, mats = zip(*wire_colors_and_mats)
w, h = get_dimens(im)
left = int((w * _BOTTOM_X_BOUNDARIES[i]) / 100.0)
top = int((h * _WIRE_Y_BOUNDARIES[0]) / 100.0)
summed_wires = sum(mats)
structuring_element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15))
summed_wires = cv2.morphologyEx(summed_wires, cv2.MORPH_CLOSE, structuring_element1)
contour = max(get_contours(summed_wires, close_and_open=False), key=cv2.contourArea)
center = get_center_for_contour(contour)
center = apply_offset_to_single_location(center, (left, top))
# show(summed_wires)
colors_and_positions.append((wire_colors, center))
return colors_and_positions
def _get_leds_are_lit(im):
leds_are_lit = []
for i in range(len(_TOP_X_BOUNDARIES) - 1):
led = get_subset(im, _TOP_X_BOUNDARIES[i:i + 2], _LED_Y_BOUNDARIES)
lit_led = extract_color(led, 51 / 2, (40, 90), (220, 255))
leds_are_lit.append(lit_led.any())
# show(lit_led)
return leds_are_lit
def _get_has_stars(im):
has_stars = []
for i in range(len(_BOTTOM_X_BOUNDARIES) - 1):
star = get_subset(im, _BOTTOM_X_BOUNDARIES[i:i + 2], _STAR_Y_BOUNDARIES)
has_star = extract_color(star, 33 / 2, (75, 125), (0, 70))
# show(has_star)
w, h = get_dimens(star)
star_ratio = float(cv2.countNonZero(has_star)) / (w * h)
# print star_ratio
has_stars.append(star_ratio > _STAR_RATIO_THRESHOLD)
return has_stars
def get_complicated_wire_info_for_module(im):
"""
Returns a list (has_led, wire_colors_and_position, has_star) for each position. The
wire_colors_and_position will be a tuple of ((wire_color, ...), (x_pos, y_pos)) if a wire
exists, or None if there is no wire.
"""
leds = _get_leds_are_lit(im)
wires = _get_wire_colors_and_positions(im)
stars = _get_has_stars(im)
return zip(leds, wires, stars)
| mit | -4,617,776,191,764,275,000 | 29.491071 | 98 | 0.59795 | false | 2.765182 | false | false | false |
manjaro/thus | thus/installation/chroot.py | 1 | 4851 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# chroot.py
#
# This file was forked from Cnchi (graphical installer from Antergos)
# Check it at https://github.com/antergos
#
# Copyright © 2013-2015 Antergos (http://antergos.com/)
# Copyright © 2013-2015 Manjaro (http://manjaro.org)
#
# 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., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
""" Chroot related functions. Used in the installation process """
import logging
import os
import subprocess
# When testing, no _() is available
try:
_("")
except NameError as err:
def _(message):
return message
_special_dirs_mounted = False
def get_special_dirs():
""" Get special dirs to be mounted or unmounted """
special_dirs = ["/dev", "/dev/pts", "/proc", "/sys"]
efi = "/sys/firmware/efi/efivars"
if os.path.exists(efi):
special_dirs.append(efi)
return special_dirs
def mount_special_dirs(dest_dir):
""" Mount special directories for our chroot (bind them)"""
"""
There was an error creating the child process for this terminal
grantpt failed: Operation not permitted
"""
global _special_dirs_mounted
# Don't try to remount them
if _special_dirs_mounted:
msg = _("Special dirs are already mounted. Skipping.")
logging.debug(msg)
return
special_dirs = []
special_dirs = get_special_dirs()
for special_dir in special_dirs:
mountpoint = os.path.join(dest_dir, special_dir[1:])
os.makedirs(mountpoint, mode=0o755, exist_ok=True)
# os.chmod(mountpoint, 0o755)
cmd = ["mount", "--bind", special_dir, mountpoint]
logging.debug("Mounting special dir '{0}' to {1}".format(special_dir, mountpoint))
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError as process_error:
txt = "Unable to mount {0}, command {1} failed: {2}".format(mountpoint, process_error.cmd, process_error.output)
logging.warning(txt)
_special_dirs_mounted = True
def umount_special_dirs(dest_dir):
""" Umount special directories for our chroot """
global _special_dirs_mounted
# Do not umount if they're not mounted
if not _special_dirs_mounted:
msg = _("Special dirs are not mounted. Skipping.")
logging.debug(msg)
return
special_dirs = []
special_dirs = get_special_dirs()
for special_dir in reversed(special_dirs):
mountpoint = os.path.join(dest_dir, special_dir[1:])
logging.debug("Unmounting special dir '{0}'".format(mountpoint))
try:
subprocess.check_call(["umount", mountpoint])
except subprocess.CalledProcessError:
logging.debug("Can't unmount. Trying -l to force it.")
try:
subprocess.check_call(["umount", "-l", mountpoint])
except subprocess.CalledProcessError as process_error:
txt = "Unable to unmount {0}, command {1} failed: {2}".format(
mountpoint, process_error.cmd, process_error.output)
logging.warning(txt)
_special_dirs_mounted = False
def run(cmd, dest_dir, timeout=None, stdin=None):
""" Runs command inside the chroot """
full_cmd = ['chroot', dest_dir]
for element in cmd:
full_cmd.append(element)
proc = None
try:
proc = subprocess.Popen(full_cmd,
stdin=stdin,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
outs, errs = proc.communicate(timeout=timeout)
txt = outs.decode().strip()
if len(txt) > 0:
logging.debug(txt)
except subprocess.TimeoutExpired as timeout_error:
if proc:
proc.kill()
proc.communicate()
logging.error("Timeout running the command {0}".format(timeout_error.cmd))
except subprocess.CalledProcessError as process_error:
logging.error("Error running command {0}: {1}".format(process_error.cmd, process_error.output))
except OSError as os_error:
logging.error("Error running command {0}: {1}".format(" ".join(full_cmd), os_error))
| gpl-3.0 | 6,578,615,531,245,678,000 | 33.147887 | 124 | 0.63807 | false | 3.926316 | false | false | false |
yougov/pmxbot | pmxbot/quotes.py | 1 | 7008 | import random
import operator
from . import storage
from .core import command
class Quotes(storage.SelectableStorage):
lib = 'pmx'
@classmethod
def initialize(cls):
cls.store = cls.from_URI()
cls._finalizers.append(cls.finalize)
@classmethod
def finalize(cls):
del cls.store
@staticmethod
def split_num(lookup):
prefix, sep, num = lookup.rpartition(' ')
if not prefix or not num.isdigit():
return lookup, 0
return prefix, int(num)
def lookup(self, rest=''):
rest = rest.strip()
return self.lookup_with_num(*self.split_num(rest))
class SQLiteQuotes(Quotes, storage.SQLiteStorage):
def init_tables(self):
CREATE_QUOTES_TABLE = '''
CREATE TABLE
IF NOT EXISTS quotes (
quoteid INTEGER NOT NULL,
library VARCHAR NOT NULL,
quote TEXT NOT NULL,
PRIMARY KEY (quoteid)
)
'''
CREATE_QUOTES_INDEX = '''
CREATE INDEX
IF NOT EXISTS ix_quotes_library
on quotes(library)
'''
CREATE_QUOTE_LOG_TABLE = '''
CREATE TABLE IF NOT EXISTS quote_log (quoteid varchar, logid INTEGER)
'''
self.db.execute(CREATE_QUOTES_TABLE)
self.db.execute(CREATE_QUOTES_INDEX)
self.db.execute(CREATE_QUOTE_LOG_TABLE)
self.db.commit()
def lookup_with_num(self, thing='', num=0):
lib = self.lib
BASE_SEARCH_SQL = """
SELECT quoteid, quote
FROM quotes
WHERE library = ? %s order by quoteid
"""
thing = thing.strip().lower()
num = int(num)
if thing:
wtf = ' AND %s' % (
' AND '.join(["quote like '%%%s%%'" % x for x in thing.split()])
)
SEARCH_SQL = BASE_SEARCH_SQL % wtf
else:
SEARCH_SQL = BASE_SEARCH_SQL % ''
results = [x[1] for x in self.db.execute(SEARCH_SQL, (lib,)).fetchall()]
n = len(results)
if n > 0:
if num:
i = num - 1
else:
i = random.randrange(n)
quote = results[i]
else:
i = 0
quote = ''
return (quote, i + 1, n)
def add(self, quote):
lib = self.lib
quote = quote.strip()
if not quote:
# Do not add empty quotes
return
ADD_QUOTE_SQL = 'INSERT INTO quotes (library, quote) VALUES (?, ?)'
res = self.db.execute(ADD_QUOTE_SQL, (lib, quote))
quoteid = res.lastrowid
query = 'SELECT id, message FROM LOGS order by datetime desc limit 1'
log_id, log_message = self.db.execute(query).fetchone()
if quote in log_message:
query = 'INSERT INTO quote_log (quoteid, logid) VALUES (?, ?)'
self.db.execute(query, (quoteid, log_id))
self.db.commit()
def __iter__(self):
# Note: also filter on quote not null, for backward compatibility
query = "SELECT quote FROM quotes WHERE library = ? and quote is not null"
for row in self.db.execute(query, [self.lib]):
yield {'text': row[0]}
def export_all(self):
query = """
SELECT quote, library, logid
from quotes
left outer join quote_log on quotes.quoteid = quote_log.quoteid
"""
fields = 'text', 'library', 'log_id'
return (dict(zip(fields, res)) for res in self.db.execute(query))
class MongoDBQuotes(Quotes, storage.MongoDBStorage):
collection_name = 'quotes'
def find_matches(self, thing):
thing = thing.strip().lower()
words = thing.split()
def matches(quote):
quote = quote.lower()
return all(word in quote for word in words)
return [
row
for row in self.db.find(dict(library=self.lib)).sort('_id')
if matches(row['text'])
]
def lookup_with_num(self, thing='', num=0):
by_text = operator.itemgetter('text')
results = list(map(by_text, self.find_matches(thing)))
n = len(results)
if n > 0:
if num:
i = num - 1
else:
i = random.randrange(n)
quote = results[i]
else:
i = 0
quote = ''
return (quote, i + 1, n)
def delete(self, lookup):
"""
If exactly one quote matches, delete it. Otherwise,
raise a ValueError.
"""
lookup, num = self.split_num(lookup)
if num:
result = self.find_matches(lookup)[num - 1]
else:
(result,) = self.find_matches(lookup)
self.db.delete_one(result)
def add(self, quote):
quote = quote.strip()
quote_id = self.db.insert_one(dict(library=self.lib, text=quote))
# see if the quote added is in the last IRC message logged
newest_first = [('_id', storage.pymongo.DESCENDING)]
last_message = self.db.database.logs.find_one(sort=newest_first)
if last_message and quote in last_message['message']:
self.db.update_one(
{'_id': quote_id}, {'$set': dict(log_id=last_message['_id'])}
)
def __iter__(self):
return self.db.find(dict(library=self.lib))
def _build_log_id_map(self):
from . import logging
if not hasattr(logging.Logger, 'log_id_map'):
log_db = self.db.database.logs
logging.Logger.log_id_map = dict(
(logging.MongoDBLogger.extract_legacy_id(rec['_id']), rec['_id'])
for rec in log_db.find(projection=[])
)
return logging.Logger.log_id_map
def import_(self, quote):
log_id_map = self._build_log_id_map()
log_id = quote.pop('log_id', None)
log_id = log_id_map.get(log_id, log_id)
if log_id is not None:
quote['log_id'] = log_id
self.db.insert_one(quote)
@command(aliases='q')
def quote(rest):
"""
If passed with nothing then get a random quote. If passed with some
string then search for that. If prepended with "add:" then add it to the
db, eg "!quote add: drivers: I only work here because of pmxbot!".
Delete an individual quote by prepending "del:" and passing a search
matching exactly one query.
"""
rest = rest.strip()
if rest.startswith('add: ') or rest.startswith('add '):
quote_to_add = rest.split(' ', 1)[1]
Quotes.store.add(quote_to_add)
qt = False
return 'Quote added!'
if rest.startswith('del: ') or rest.startswith('del '):
cmd, sep, lookup = rest.partition(' ')
Quotes.store.delete(lookup)
return 'Deleted the sole quote that matched'
qt, i, n = Quotes.store.lookup(rest)
if not qt:
return
return '(%s/%s): %s' % (i, n, qt)
| mit | 8,421,166,876,933,345,000 | 31.146789 | 82 | 0.540525 | false | 3.869685 | false | false | false |
warriorframework/warriorframework | warrior/WarriorCore/Classes/html_results_class.py | 1 | 10967 | """
Copyright 2017, Fujitsu Network Communications, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import json
import getpass
import Tools
from Framework.Utils import xml_Utils, file_Utils
from Framework.Utils.testcase_Utils import pNote
from Framework.Utils.print_Utils import print_info
from Framework.Utils.xml_Utils import getElementWithTagAttribValueMatch
__author__ = 'Keenan Jabri'
class LineResult:
"""Class that generates html result line items"""
data = {}
html = ''
def __init__(self):
"""Constructor for class LineResult"""
self.keys = ['type', 'name', 'info', 'description', 'timestamp', 'duration', 'status', 'impact', 'onerror', 'msc', 'static',
'dynamic']
def get_info(self, line):
"""gets info for line"""
inf_obj = line.get("info") if line.get("info") else ' '
info = json.dumps(inf_obj)
info = info.replace('}"', ',').replace('"{', '').replace("'", "").replace('"', '')
return info
def set_dynamic_content(self, line):
"""sets content that is subjected to change"""
self.data['dynamic'] = [line.get("keywords"), line.get("passes"), line.get("failures"),
line.get("errors"), line.get("exceptions"), line.get("skipped")]
self.data['timestamp'] = line.get("timestamp")
def set_attributes(self, line, variant, stepcount):
"""sets attributes"""
if 'Keyword' not in variant and 'step' not in variant:
stepcount = ''
result_file = line.get("resultfile") if line.get("resultfile") else line.get("resultsdir") if line.get(
"resultsdir") else ''
status_name = line.get("status") if line.get("status") else ''
self.data = {'nameAttr': variant + 'Record',
'type': variant.replace('Test', '').replace('Keyword', 'step ') + str(stepcount),
'name': line.get("name"),
'info': self.get_info(line),
'description': line.get("description"),
'timestamp': line.get("timestamp"),
'duration': line.get("time"),
'status': '<span class=' + status_name + '>' + status_name + '</span>',
'impact': line.get("impact"),
'onerror': line.get("onerror"),
'msc': '<span style="padding-left:10px; padding-right: 10px;"><a href="' + result_file
+ '"><i class="fa fa-line-chart"> </i></a></span>' + (
'' if variant == 'Keyword' else '<span style="padding-left:10px; padding-right: 10px;"><a href="' + (
line.get("logsdir") if line.get(
"logsdir") else '') + '"><i class="fa fa-book"> </i></a></span>') + (
'<span style="padding-left:10px; padding-right: 10px;"><a href="' + line.get("defects")
+ '"><i class="fa fa-bug"> </i></a></span>' if line.get("defects") else ''),
'static': ['Count', 'Passed', 'Failed', 'Errors', 'Exceptions', 'Skipped']
}
def set_html(self, line, variant, stepcount):
"""sets the html code"""
if self.html == '':
self.set_attributes(line, variant, stepcount)
self.set_dynamic_content(line)
top_level = ''
top_level_next = ''
if not line.get("display") or line.get("display") == 'True':
if self.data['nameAttr'] != 'KeywordRecord':
for elem in self.keys:
if elem == 'dynamic':
for dynamicElem in self.data['dynamic']:
top_level_next += '<td>' + (dynamicElem if dynamicElem else '0') + '</td>'
elif elem == 'static':
for staticElem in self.data['static']:
top_level += '<td>' + (staticElem if staticElem else '') + '</td>'
else:
top_level += '<td rowspan="2"><div>' + (
self.data[elem] if self.data[elem] else '') + '</div></td>'
top_level_next = '<tr>' + top_level_next + '</tr>'
else:
for elem in self.keys:
if elem != 'static' and elem != 'dynamic':
top_level += '<td rowspan="2"><div>' + (
self.data[elem] if self.data[elem] else '') + '</div></td>'
self.html = '<tr name="' + self.data['nameAttr'] + '">' + top_level + '</tr>' + top_level_next
class WarriorHtmlResults:
"""Class that generates html results using the junit result file """
lineObjs = []
lineCount = 0
recount = 0
steps = 0
def __init__(self, junit_file=None):
""" init function"""
self.junit_file = junit_file
self.html_template = "{0}{1}reporting{1}html_results_template.html" \
.format(Tools.__path__[0], os.sep)
self.junit_root = xml_Utils.getRoot(self.junit_file)
def create_line_result(self, line, variant):
""" create new objs"""
temp = LineResult()
temp.set_html(line, variant, self.steps)
self.lineObjs.append(temp)
self.lineCount += 1
def set_line_objs(self):
""" call to create a new obj per item"""
self.lineCount = 0
project_node_list = [self.junit_root]
for project_node in project_node_list:
self.create_line_result(project_node, "Project")
for testsuite_node in project_node.findall("testsuite"):
self.create_line_result(testsuite_node, "Testsuite")
#to add setup result in html file
for setup_node in testsuite_node.findall("Setup"):
self.create_line_result(setup_node, "Setup")
self.steps = 0
for step_node in setup_node.findall("properties"):
for node in step_node.findall("property"):
if node.get('type') == 'keyword':
self.steps += 1
self.create_line_result(node, "Keyword")
for testcase_node in testsuite_node.findall("testcase"):
self.create_line_result(testcase_node, "Testcase")
self.steps = 0
for step_node in testcase_node.findall("properties"):
for node in step_node.findall("property"):
if node.get('type') == 'keyword':
self.steps += 1
self.create_line_result(node, "Keyword")
#to add debug result in html file
for debug_node in testsuite_node.findall("Debug"):
self.create_line_result(debug_node, "Debug")
self.steps = 0
for step_node in debug_node.findall("properties"):
for node in step_node.findall("property"):
if node.get('type') == 'keyword':
self.steps += 1
self.create_line_result(node, "Keyword")
#to add cleanup result in html file
for cleanup_node in testsuite_node.findall("Cleanup"):
self.create_line_result(cleanup_node, "Cleanup")
self.steps = 0
for step_node in cleanup_node.findall("properties"):
for node in step_node.findall("property"):
if node.get('type') == 'keyword':
self.steps += 1
self.create_line_result(node, "Keyword")
def get_path(self):
""" get the html results path """
filename = file_Utils.getNameOnly(os.path.basename(self.junit_file))
filename = filename.split("_junit")[0]
html_filename = filename + ".html"
if hasattr(self, 'givenPath'):
html_results_path = self.givenPath + os.sep + html_filename
else:
results_dir = os.path.dirname(self.junit_file)
html_results_path = results_dir + os.sep + html_filename
return html_results_path
def merge_html(self, dynamic_html):
""" merge html from template and dynamic """
temp = open(self.html_template)
template_html = temp.read().replace('\n', '')
temp.close()
index = template_html.rfind('</table>')
return template_html[:index] + dynamic_html + template_html[index:] + self.get_war_version() + self.get_user()
def get_war_version(self):
""" find the warrior version """
path = self.get_path().split('warriorframework')[0] + 'warriorframework/version.txt'
if os.path.isfile(path):
version = open(path, 'r').read().splitlines()[1].split(':')[1]
return '<div class="version">' + version + '</div>'
return ''
def get_user(self):
""" find the user who executed the testcase """
try:
user = getpass.getuser()
except Exception:
user = "Unknown_user"
return '<div class="user">' + user + '</div>'
def generate_html(self, junitObj, givenPath, print_summary=False):
""" build the html givenPath: added this feature in case of later down the line
calling from outside junit file ( no actual use as of now )
"""
if junitObj:
self.junit_file = junitObj
self.junit_root = xml_Utils.getRoot(self.junit_file)
if givenPath:
self.givenPath = givenPath
self.set_line_objs()
html = ''
for item in self.lineObjs:
html += item.html
html = self.merge_html(html)
elem_file = open(self.get_path(), 'w')
elem_file.write(html)
elem_file.close()
self.lineObjs = []
# Prints result summary at the end of execution
if print_summary is True:
print_info("++++ Results Summary ++++")
print_info("Open the Results summary file given below in a browser to "
"view results summary for this execution")
print_info("Results summary file: {0}".format(self.get_path()))
print_info("+++++++++++++++++++++++++")
| apache-2.0 | 3,793,665,087,416,468,000 | 45.668085 | 133 | 0.529498 | false | 4.200306 | true | false | false |
zhenxuan00/mmdgm | mlp-mmdgm/anglepy/models/GPUVAE_MM_Z_X.py | 1 | 20222 | '''
Code for mmDGM
Author: Chongxuan Li ([email protected])
Co-author: Tianlin Shi
Version = '1.0'
'''
import sys, os
import pdb
import numpy as np
import theano
import theano.tensor as T
import collections as C
import anglepy as ap
import anglepy.ndict as ndict
import color
from anglepy.misc import lazytheanofunc
import math, inspect
#import theano.sandbox.cuda.rng_curand as rng_curand
def shared32(x, name=None, borrow=False):
return theano.shared(np.asarray(x, dtype='float32'), name=name, borrow=borrow)
def cast32(x):
return T.cast(x, dtype='float32')
'''
Fully connected deep variational auto-encoder (VAE_Z_X)
'''
class GPUVAE_MM_Z_X(ap.GPUVAEModel):
def __init__(self, get_optimizer, n_x, n_y, n_hidden_q, n_z, n_hidden_p, nonlinear_q='tanh', nonlinear_p='tanh', type_px='bernoulli', type_qz='gaussianmarg', type_pz='gaussianmarg', prior_sd=1, init_sd=1e-2, var_smoothing=0, n_mixture=50, c=10, ell=1, average_activation = 0.1, sparsity_weight = 3):
self.constr = (__name__, inspect.stack()[0][3], locals())
self.n_x = n_x
self.n_y = n_y
self.n_hidden_q = n_hidden_q
self.n_z = n_z
self.n_hidden_p = n_hidden_p
self.dropout = False
self.nonlinear_q = nonlinear_q
self.nonlinear_p = nonlinear_p
self.type_px = type_px
self.type_qz = type_qz
self.type_pz = type_pz
self.prior_sd = prior_sd
self.var_smoothing = var_smoothing
self.n_mixture = n_mixture
self.c = c
self.ell = ell
self.average_activation = average_activation
self.sparsity_weight = sparsity_weight
if os.environ.has_key('c'):
self.c = float(os.environ['c'])
if os.environ.has_key('ell'):
self.ell = float(os.environ['ell'])
self.sv = 0
if os.environ.has_key('sv'):
self.sv = int(os.environ['sv'])
color.printBlue('apply supervision from layer ' + str(self.sv+1) + ' to end.')
self.super_to_mean = False
if os.environ.has_key('super_to_mean') and bool(int(os.environ['super_to_mean'])) == True:
self.super_to_mean = True
color.printBlue('apply supervision to z_mean.')
self.train_residual = False
if os.environ.has_key('train_residual') and bool(int(os.environ['train_residual'])) == True:
self.train_residual = True
color.printBlue('Train residual wrt prior instead of the whole model.')
self.Lambda = 0
if os.environ.has_key('Lambda'):
self.Lambda = float(os.environ['Lambda'])
self.sigma_square = 1
if os.environ.has_key('sigma_square'):
self.sigma_square = float(os.environ['sigma_square'])
if os.environ.has_key('dropout'):
self.dropout = bool(int(os.environ['dropout']))
color.printBlue('c = ' + str(self.c) + ' , ell = ' + str(self.ell) + ' , sigma_square = ' + str(self.sigma_square))
# Init weights
v, w = self.init_w(1e-2)
for i in v: v[i] = shared32(v[i])
for i in w: w[i] = shared32(w[i])
if not self.super_to_mean:
W = shared32(np.zeros((sum(n_hidden_q[self.sv:])+1, n_y)))
#print 'apply supervision from', self.sv+1, ' to end.'
else:
W = shared32(np.zeros((n_z+1, n_y)))
#print 'apply supervison to z_mean'
self.v = v
self.v['W'] = W
#print 'dimension of the prediction model: ', self.v['W'].get_value().shape
self.w = w
super(GPUVAE_MM_Z_X, self).__init__(get_optimizer)
def factors(self, x, z, A):
v = self.v # parameters of recognition model.
w = self.w # parameters of generative model.
'''
z is unused
x['x'] is the data
The names of dict z[...] may be confusing here: the latent variable z is not included in the dict z[...],
but implicitely computed from epsilon and parameters in w.
z is computed with g(.) from eps and variational parameters
let logpx be the generative model density: log p(x|z) where z=g(.)
let logpz be the prior of Z plus the entropy of q(z|x): logp(z) + H_q(z|x)
So the lower bound L(x) = logpx + logpz
let logpv and logpw be the (prior) density of the parameters
'''
# Compute q(z|x)
hidden_q = [x['x']]
hidden_q_s = [x['x']]
def f_softplus(x): return T.log(T.exp(x) + 1)# - np.log(2)
def f_rectlin(x): return x*(x>0)
def f_rectlin2(x): return x*(x>0) + 0.01 * x
nonlinear = {'tanh': T.tanh, 'sigmoid': T.nnet.sigmoid, 'softplus': f_softplus, 'rectlin': f_rectlin, 'rectlin2': f_rectlin2}
nonlinear_q = nonlinear[self.nonlinear_q]
nonlinear_p = nonlinear[self.nonlinear_p]
#rng = rng_curand.CURAND_RandomStreams(0)
import theano.tensor.shared_randomstreams
rng = theano.tensor.shared_randomstreams.RandomStreams(0)
# TOTAL HACK
#hidden_q.append(nonlinear_q(T.dot(v['scale0'], A) * T.dot(w['out_w'].T, hidden_q[-1]) + T.dot(v['b0'], A)))
#hidden_q.append(nonlinear_q(T.dot(v['scale1'], A) * T.dot(w['w1'].T, hidden_q[-1]) + T.dot(v['b1'], A)))
for i in range(len(self.n_hidden_q)):
hidden_q.append(nonlinear_q(T.dot(v['w'+str(i)], hidden_q[-1]) + T.dot(v['b'+str(i)], A)))
hidden_q_s.append(T.nnet.sigmoid(T.dot(v['w'+str(i)], hidden_q_s[-1]) + T.dot(v['b'+str(i)], A)))
if self.dropout:
hidden_q[-1] *= 2. * (rng.uniform(size=hidden_q[-1].shape, dtype='float32') > .5)
hidden_q_s[-1] *= 2. * (rng.uniform(size=hidden_q_s[-1].shape, dtype='float32') > .5)
'''
print 'mm_model'
for (d, xx) in x.items():
print d
'''
#print 'x', x['mean_prior'].type
#print 'T', (T.dot(v['mean_w'], hidden_q[-1]) + T.dot(v['mean_b'], A)).type
if not self.train_residual:
q_mean = T.dot(v['mean_w'], hidden_q[-1]) + T.dot(v['mean_b'], A)
else:
q_mean = x['mean_prior'] + T.dot(v['mean_w'], hidden_q[-1]) + T.dot(v['mean_b'], A)
#q_mean = T.dot(v['mean_w'], hidden_q[-1]) + T.dot(v['mean_b'], A)
if self.type_qz == 'gaussian' or self.type_qz == 'gaussianmarg':
q_logvar = T.dot(v['logvar_w'], hidden_q[-1]) + T.dot(v['logvar_b'], A)
else: raise Exception()
ell = cast32(self.ell)
self.param_c = shared32(0)
sv = self.sv
a_a = cast32(self.average_activation)
s_w = cast32(self.sparsity_weight)
def activate():
res = 0
if self.super_to_mean:
lenw = len(v['W'].get_value())
res += T.dot(v['W'][:-1,:].T, q_mean)
res += T.dot(v['W'][lenw-1:lenw,:].T, A)
else:
lenw = len(v['W'].get_value())
for (hi, hidden) in enumerate(hidden_q[1+sv:]):
res += T.dot(v['W'][sum(self.n_hidden_q[sv:sv+hi]):sum(self.n_hidden_q[sv:sv+hi+1]),:].T, hidden)
res += T.dot(v['W'][lenw-1:lenw,:].T, A)
return res
predy = T.argmax(activate(), axis=0)
# function for distribution q(z|x)
theanofunc = lazytheanofunc('warn', mode='FAST_RUN')
self.dist_qz['z'] = theanofunc([x['x'], x['mean_prior']] + [A], [q_mean, q_logvar])
self.dist_qz['hidden'] = theanofunc([x['x'], x['mean_prior']] + [A], hidden_q[1:])
self.dist_qz['predy'] = theanofunc([x['x'], x['mean_prior']] + [A], predy)
# compute cost (posterior regularization).
true_resp = (activate() * x['y']).sum(axis=0, keepdims=True)
T.addbroadcast(true_resp, 0)
cost = self.param_c * (ell * (1-x['y']) + activate() - true_resp).max(axis=0).sum() \
+ self.Lambda * (v['W'] * v['W']).sum()
# compute the sparsity penalty
sparsity_penalty = 0
for i in range(1, len(hidden_q_s)):
sparsity_penalty += (a_a*T.log(a_a/(hidden_q_s[i].mean(axis=1))) + (1-a_a)*T.log((1-a_a)/(1-(hidden_q_s[i].mean(axis=1))))).sum(axis=0)
sparsity_penalty *= s_w
# Compute virtual sample
eps = rng.normal(size=q_mean.shape, dtype='float32')
_z = q_mean + T.exp(0.5 * q_logvar) * eps
# Compute log p(x|z)
hidden_p = [_z]
for i in range(len(self.n_hidden_p)):
hidden_p.append(nonlinear_p(T.dot(w['w'+str(i)], hidden_p[-1]) + T.dot(w['b'+str(i)], A)))
if self.dropout:
hidden_p[-1] *= 2. * (rng.uniform(size=hidden_p[-1].shape, dtype='float32') > .5)
if self.type_px == 'bernoulli':
p = T.nnet.sigmoid(T.dot(w['out_w'], hidden_p[-1]) + T.dot(w['out_b'], A))
_logpx = - T.nnet.binary_crossentropy(p, x['x'])
self.dist_px['x'] = theanofunc([_z] + [A], p)
elif self.type_px == 'gaussian':
x_mean = T.dot(w['out_w'], hidden_p[-1]) + T.dot(w['out_b'], A)
x_logvar = T.dot(w['out_logvar_w'], hidden_p[-1]) + T.dot(w['out_logvar_b'], A)
_logpx = ap.logpdfs.normal2(x['x'], x_mean, x_logvar)
self.dist_px['x'] = theanofunc([_z] + [A], [x_mean, x_logvar])
elif self.type_px == 'bounded01':
x_mean = T.nnet.sigmoid(T.dot(w['out_w'], hidden_p[-1]) + T.dot(w['out_b'], A))
x_logvar = T.dot(w['out_logvar_b'], A)
_logpx = ap.logpdfs.normal2(x['x'], x_mean, x_logvar)
# Make it a mixture between uniform and Gaussian
w_unif = T.nnet.sigmoid(T.dot(w['out_unif'], A))
_logpx = T.log(w_unif + (1-w_unif) * T.exp(_logpx))
self.dist_px['x'] = theanofunc([_z] + [A], [x_mean, x_logvar])
else: raise Exception("")
# Note: logpx is a row vector (one element per sample)
logpx = T.dot(shared32(np.ones((1, self.n_x))), _logpx) # logpx = log p(x|z,w)
# log p(z) (prior of z)
if self.type_pz == 'gaussianmarg':
if not self.train_residual:
logpz = -0.5 * (np.log(2 * np.pi * self.sigma_square) + ((q_mean-x['mean_prior'])**2 + T.exp(q_logvar))/self.sigma_square).sum(axis=0, keepdims=True)
else:
logpz = -0.5 * (np.log(2 * np.pi * self.sigma_square) + (q_mean**2 + T.exp(q_logvar))/self.sigma_square).sum(axis=0, keepdims=True)
elif self.type_pz == 'gaussian':
logpz = ap.logpdfs.standard_normal(_z).sum(axis=0, keepdims=True)
elif self.type_pz == 'mog':
pz = 0
for i in range(self.n_mixture):
pz += T.exp(ap.logpdfs.normal2(_z, T.dot(w['mog_mean'+str(i)], A), T.dot(w['mog_logvar'+str(i)], A)))
logpz = T.log(pz).sum(axis=0, keepdims=True) - self.n_z * np.log(float(self.n_mixture))
elif self.type_pz == 'laplace':
logpz = ap.logpdfs.standard_laplace(_z).sum(axis=0, keepdims=True)
elif self.type_pz == 'studentt':
logpz = ap.logpdfs.studentt(_z, T.dot(T.exp(w['logv']), A)).sum(axis=0, keepdims=True)
else:
raise Exception("Unknown type_pz")
# loq q(z|x) (entropy of z)
if self.type_qz == 'gaussianmarg':
logqz = - 0.5 * (np.log(2 * np.pi) + 1 + q_logvar).sum(axis=0, keepdims=True)
elif self.type_qz == 'gaussian':
logqz = ap.logpdfs.normal2(_z, q_mean, q_logvar).sum(axis=0, keepdims=True)
else: raise Exception()
# [new part] Fisher divergence of latent variables
if self.var_smoothing > 0:
dlogq_dz = T.grad(logqz.sum(), _z) # gives error when using gaussianmarg instead of gaussian
dlogp_dz = T.grad((logpx + logpz).sum(), _z)
FD = 0.5 * ((dlogq_dz - dlogp_dz)**2).sum(axis=0, keepdims=True)
# [end new part]
logqz -= self.var_smoothing * FD
# Note: logpv and logpw are a scalars
if True:
def f_prior(_w, prior_sd=self.prior_sd):
return ap.logpdfs.normal(_w, 0, prior_sd).sum()
else:
def f_prior(_w, prior_sd=self.prior_sd):
return ap.logpdfs.standard_laplace(_w / prior_sd).sum()
return logpx, logpz, logqz, cost, sparsity_penalty
# Generate epsilon from prior
def gen_eps(self, n_batch):
z = {'eps': np.random.standard_normal(size=(self.n_z, n_batch)).astype('float32')}
return z
# Generate variables
def gen_xz_prior(self, x, z, mean_prior, sigma_square, n_batch):
x, z = ndict.ordereddicts((x, z))
A = np.ones((1, n_batch)).astype(np.float32)
for i in z: z[i] = z[i].astype(np.float32)
for i in x: x[i] = x[i].astype(np.float32)
tmp = np.random.standard_normal(size=(self.n_z, n_batch)).astype(np.float32)
z['z'] = tmp * np.sqrt(sigma_square) + mean_prior
if self.type_px == 'bernoulli':
x['x'] = self.dist_px['x'](*([z['z']] + [A]))
elif self.type_px == 'bounded01' or self.type_px == 'gaussian':
x_mean, x_logvar = self.dist_px['x'](*([z['z']] + [A]))
if not x.has_key('x'):
x['x'] = np.random.normal(x_mean, np.exp(x_logvar/2))
if self.type_px == 'bounded01':
x['x'] = np.maximum(np.zeros(x['x'].shape), x['x'])
x['x'] = np.minimum(np.ones(x['x'].shape), x['x'])
else: raise Exception("")
return x
# Generate variables
def gen_xz(self, x, z, n_batch):
x, z = ndict.ordereddicts((x, z))
A = np.ones((1, n_batch)).astype(np.float32)
for i in z: z[i] = z[i].astype(np.float32)
for i in x: x[i] = x[i].astype(np.float32)
_z = {}
# If x['x'] was given but not z['z']: generate z ~ q(z|x)
if x.has_key('x') and not z.has_key('z'):
q_mean, q_logvar = self.dist_qz['z'](*([x['x'], x['mean_prior']] + [A]))
q_hidden = self.dist_qz['hidden'](*([x['x'], x['mean_prior']] + [A]))
predy = self.dist_qz['predy'](*([x['x'], x['mean_prior']] + [A]))
_z['mean'] = q_mean
_z['logvar'] = q_logvar
_z['hidden'] = q_hidden
_z['predy'] = predy
# Require epsilon
if not z.has_key('eps'):
eps = self.gen_eps(n_batch)['eps']
z['z'] = q_mean + np.exp(0.5 * q_logvar) * eps
elif not z.has_key('z'):
if self.type_pz in ['gaussian','gaussianmarg']:
z['z'] = np.random.standard_normal(size=(self.n_z, n_batch)).astype(np.float32)
elif self.type_pz == 'laplace':
z['z'] = np.random.laplace(size=(self.n_z, n_batch)).astype(np.float32)
elif self.type_pz == 'studentt':
z['z'] = np.random.standard_t(np.dot(np.exp(self.w['logv'].get_value()), A)).astype(np.float32)
elif self.type_pz == 'mog':
i = np.random.randint(self.n_mixture)
loc = np.dot(self.w['mog_mean'+str(i)].get_value(), A)
scale = np.dot(np.exp(.5*self.w['mog_logvar'+str(i)].get_value()), A)
z['z'] = np.random.normal(loc=loc, scale=scale).astype(np.float32)
else:
raise Exception('Unknown type_pz')
# Generate from p(x|z)
if self.type_px == 'bernoulli':
p = self.dist_px['x'](*([z['z']] + [A]))
_z['x'] = p
if not x.has_key('x'):
x['x'] = np.random.binomial(n=1,p=p)
elif self.type_px == 'bounded01' or self.type_px == 'gaussian':
x_mean, x_logvar = self.dist_px['x'](*([z['z']] + [A]))
_z['x'] = x_mean
if not x.has_key('x'):
x['x'] = np.random.normal(x_mean, np.exp(x_logvar/2))
if self.type_px == 'bounded01':
x['x'] = np.maximum(np.zeros(x['x'].shape), x['x'])
x['x'] = np.minimum(np.ones(x['x'].shape), x['x'])
else: raise Exception("")
return x, z, _z
def gen_xz_prior11(self, x, z, mean_prior, sigma_square, n_batch):
x, z = ndict.ordereddicts((x, z))
A = np.ones((1, n_batch)).astype(np.float32)
z['z'] = mean_prior.astype(np.float32)
if self.type_px == 'bernoulli':
x['x'] = self.dist_px['x'](*([z['z']] + [A]))
elif self.type_px == 'bounded01' or self.type_px == 'gaussian':
x_mean, x_logvar = self.dist_px['x'](*([z['z']] + [A]))
if not x.has_key('x'):
x['x'] = np.random.normal(x_mean, np.exp(x_logvar/2))
if self.type_px == 'bounded01':
x['x'] = np.maximum(np.zeros(x['x'].shape), x['x'])
x['x'] = np.minimum(np.ones(x['x'].shape), x['x'])
else: raise Exception("")
return x
def variables(self):
z = {}
# Define observed variables 'x'
x = {'x': T.fmatrix('x'), 'mean_prior': T.fmatrix('mean_prior'), 'y': T.fmatrix('y'), }
#x = {'x': T.fmatrix('x'), 'y': T.fmatrix('y'), }
return x, z
def init_w(self, std=1e-2):
def rand(size):
if len(size) == 2 and size[1] > 1:
return np.random.normal(0, 1, size=size) / np.sqrt(size[1])
return np.random.normal(0, std, size=size)
v = {}
#v['scale0'] = np.ones((self.n_hidden_q[0], 1))
#v['scale1'] = np.ones((self.n_hidden_q[0], 1))
v['w0'] = rand((self.n_hidden_q[0], self.n_x))
v['b0'] = rand((self.n_hidden_q[0], 1))
for i in range(1, len(self.n_hidden_q)):
v['w'+str(i)] = rand((self.n_hidden_q[i], self.n_hidden_q[i-1]))
v['b'+str(i)] = rand((self.n_hidden_q[i], 1))
v['mean_w'] = rand((self.n_z, self.n_hidden_q[-1]))
v['mean_b'] = rand((self.n_z, 1))
if self.type_qz in ['gaussian','gaussianmarg']:
v['logvar_w'] = np.zeros((self.n_z, self.n_hidden_q[-1]))
v['logvar_b'] = np.zeros((self.n_z, 1))
w = {}
if self.type_pz == 'mog':
for i in range(self.n_mixture):
w['mog_mean'+str(i)] = rand((self.n_z, 1))
w['mog_logvar'+str(i)] = rand((self.n_z, 1))
if self.type_pz == 'studentt':
w['logv'] = np.zeros((self.n_z, 1))
if len(self.n_hidden_p) > 0:
w['w0'] = rand((self.n_hidden_p[0], self.n_z))
w['b0'] = rand((self.n_hidden_p[0], 1))
for i in range(1, len(self.n_hidden_p)):
w['w'+str(i)] = rand((self.n_hidden_p[i], self.n_hidden_p[i-1]))
w['b'+str(i)] = rand((self.n_hidden_p[i], 1))
w['out_w'] = rand((self.n_x, self.n_hidden_p[-1]))
w['out_b'] = np.zeros((self.n_x, 1))
if self.type_px == 'gaussian':
w['out_logvar_w'] = rand((self.n_x, self.n_hidden_p[-1]))
w['out_logvar_b'] = np.zeros((self.n_x, 1))
if self.type_px == 'bounded01':
w['out_logvar_b'] = np.zeros((self.n_x, 1))
w['out_unif'] = np.zeros((self.n_x, 1))
else:
w['out_w'] = rand((self.n_x, self.n_z))
w['out_b'] = np.zeros((self.n_x, 1))
if self.type_px == 'gaussian':
w['out_logvar_w'] = rand((self.n_x, self.n_z))
w['out_logvar_b'] = np.zeros((self.n_x, 1))
if self.type_px == 'bounded01':
w['out_logvar_b'] = np.zeros((self.n_x, 1))
w['out_unif'] = np.zeros((self.n_x, 1))
return v, w
| mit | 6,343,238,090,610,356,000 | 42.676026 | 303 | 0.500198 | false | 2.963365 | false | false | false |
erggo/Harpy | harpia/amara/saxtools.py | 2 | 22115 | #Python 2.3 or higher required
from xml import sax
from xml.dom import EMPTY_NAMESPACE as NULL_NAMESPACE
from xml.dom import EMPTY_PREFIX as NULL_PREFIX
from xml.dom import XML_NAMESPACE
from xml.dom import Node
from Ft.Xml import Domlette
START_DOCUMENT = 1
END_DOCUMENT = 2
START_ELEMENT = 3
END_ELEMENT = 4
CHARACTER_DATA = 10
COMMENT = 11
PI = 12
#
# namespace_mixin is a utility that helps manage namespace prefix mappings
#
class namespace_mixin:
def __init__(self):
self._ns_prefix = {XML_NAMESPACE: [u'xml'], NULL_NAMESPACE: [NULL_PREFIX]}
self._prefix_ns = {u'xml': [XML_NAMESPACE], NULL_PREFIX: [NULL_NAMESPACE]}
return
def startPrefixMapping(self, prefix, uri):
self._ns_prefix.setdefault(uri, []).append(prefix)
self._prefix_ns.setdefault(prefix, []).append(uri)
return
def endPrefixMapping(self, prefix):
uri = self._prefix_ns[prefix].pop()
prefix = self._ns_prefix[uri].pop()
#assert prefix == uri
return
def name_to_qname(self, name):
#print self._ns_prefix
#print self._prefix_ns
uri, local = name
prefix = self._ns_prefix[uri][-1]
qname = ( prefix and ( prefix + u':' ) or '') + local
return qname
#
# Tenorsax framework: helps linerarize SAX logic
#
class tenorsax(namespace_mixin, sax.ContentHandler):
def __init__(self, consumer):
namespace_mixin.__init__(self)
self.consumer = consumer
self.dispatcher = consumer.top_dispatcher
self.curr_gen = None
return
def startElementNS(self, name, qname, attributes):
(ns, local) = name
qname = self.name_to_qname(name)
#print "Start element", (name, qname)
self.consumer.event = (START_ELEMENT, ns, local)
self.consumer.params = attributes
self.curr_gen = tenorsax.event_loop_body(self.dispatcher, self.curr_gen, self.consumer.event)
return
def endElementNS(self, name, qname):
(ns, local) = name
qname = self.name_to_qname(name)
#print "end element", (name, qname)
self.consumer.event = (END_ELEMENT, ns, local)
self.consumer.params = None
self.curr_gen = tenorsax.event_loop_body(self.dispatcher, self.curr_gen, self.consumer.event)
return
def characters(self, text):
#print "characters", text
self.consumer.event = (CHARACTER_DATA,)
self.consumer.params = text
self.curr_gen = tenorsax.event_loop_body(self.dispatcher, self.curr_gen, self.consumer.event)
return
def event_loop_body(dispatcher, curr_gen, event):
if curr_gen:
curr_gen = tenorsax.execute_delegate(curr_gen)
else:
curr_gen = tenorsax.check_for_delegate(dispatcher, event)
return curr_gen
event_loop_body = staticmethod(event_loop_body)
def execute_delegate(curr_gen):
try:
curr_gen.next()
except StopIteration:
curr_gen = None
return curr_gen
execute_delegate = staticmethod(execute_delegate)
def check_for_delegate(dispatcher, event):
if event[0] == START_ELEMENT:
end_condition = (END_ELEMENT,) + event[1:]
else:
end_condition = None
curr_gen = None
delegate_generator = dispatcher.get(event)
if delegate_generator:
#Fire up the generator
curr_gen = delegate_generator(end_condition)
try:
curr_gen.next()
except StopIteration:
print "immediate end"
#Immediate generator termination
curr_gen = None
return curr_gen
check_for_delegate = staticmethod(check_for_delegate)
#
#
#
from xml import sax
from xml.dom import XML_NAMESPACE, XMLNS_NAMESPACE
from xml.dom import EMPTY_NAMESPACE as NULL_NAMESPACE
from xml.dom import EMPTY_PREFIX as NULL_PREFIX
from Ft.Xml.Xslt import parser as XPatternParser
from Ft.Xml.Xslt.XPatterns import Patterns
from Ft.Xml.Xslt.XPatterns import Pattern
from Ft.Xml.Xslt.XPatterns import DocumentNodeTest
from Ft.Xml.XPath.ParsedNodeTest import LocalNameTest
from Ft.Xml.XPath.ParsedNodeTest import NamespaceTest
from Ft.Xml.XPath.ParsedNodeTest import QualifiedNameTest
from Ft.Xml.XPath.ParsedNodeTest import PrincipalTypeTest
DUMMY_DOCELEM = u'dummy'
START_STATE = 0
TOP = -1
ANY = '?'
#Used to figure out whether a wildcard event is user-specified,
#Or added internally
EXPLICIT, IMPLICIT = (True, False)
class xpattern_state_machine:
"""
A simple state machine that interprets XPatterns
A state is "live" when it represents the successful completion
of an XPattern.
"""
PARSER = XPatternParser.new()
def __init__(self, repr_xp, xp, nss):
self._state_table = {START_STATE: {}}
self._live_states = {}
self._ignored_subtree_states = []
self._substate_depth = 0
newest_state = START_STATE
last_state = START_STATE
for subpat in xp.patterns:
steps = subpat.steps[:]
steps.reverse()
for (step_count, (axis_type, node_test, ancestor)) in enumerate(steps):
if isinstance(node_test, DocumentNodeTest):
start_event = (1, None, None)
end_event = (0, None, None)
elif isinstance(node_test, LocalNameTest):
if node_test.nodeType == Node.ELEMENT_NODE:
start_event = (1, None, node_test._name)
end_event = (0, None, node_test._name)
else:
continue
elif isinstance(node_test, QualifiedNameTest):
if node_test.nodeType == Node.ELEMENT_NODE:
ns = nss[node_test._prefix]
start_event = (1, ns, node_test._localName)
end_event = (0, ns, node_test._localName)
else:
continue
elif isinstance(node_test, PrincipalTypeTest):
if node_test.nodeType == Node.ELEMENT_NODE:
start_event = (1, ANY, EXPLICIT)
end_event = (0, ANY, EXPLICIT)
else:
continue
elif isinstance(node_test, NamespaceTest):
if node_test.nodeType == Node.ELEMENT_NODE:
ns = nss[node_test._prefix]
start_event = (1, ns, ANY)
end_event = (0, ns, ANY)
else:
continue
else:
import sys; print >> sys.stderr, "Pattern step not supported:", (axis_type, node_test, ancestor), "Node test class", node_test.__class__
continue
if self._state_table[last_state].has_key(start_event):
top_state = self._state_table[last_state][start_event]
else:
newest_state += 1
top_state = newest_state
self._state_table[top_state] = {}
self._state_table[last_state][start_event] = top_state
self._state_table[top_state][end_event] = last_state
last_state = top_state
complete_state = top_state #The state representing completion of an XPattern
if step_count and not ancestor:
#Insert a state, which handles any child element
#Not explicitly matching some other state (so that
#/a/b/c is not a mistaken match for XPattern /a/c)
start_event = (1, ANY, IMPLICIT)
end_event = (0, ANY, IMPLICIT)
newest_state += 1
self._state_table[newest_state] = {}
self._state_table[parent_start_element_event][start_event] = newest_state
self._state_table[newest_state][end_event] = parent_start_element_event
self._ignored_subtree_states.append(newest_state)
parent_start_element_event = top_state
self._live_states[top_state] = repr_xp
#print self._state_table
#print self._live_states
self._state = START_STATE
self.entering_xpatterns = []
self.leaving_xpatterns = []
self.current_xpatterns = []
self.tree_depth = 0
self.depth_marks = []
return
def event(self, is_start, ns, local):
"""
Register an event and effect ant state transitions
found in the state table
"""
#We only have a chunk ready for the handler in
#the explicit case below
self.entering_xpatterns = []
self.leaving_xpatterns = []
self.tree_depth += is_start and 1 or -1
#print "event", (is_start, ns, local), self._state, self.tree_depth, self.depth_marks
#An end event is never significant unless we know we're expecting it
if not is_start and self.depth_marks and self.tree_depth != self.depth_marks[-1]:
return self._state
lookup_from = self._state_table[self._state]
#FIXME: second part should be an element node test "*", should not match, say, start document
if not lookup_from.has_key((is_start, ns, local)) and (ns, local) == (None, None):
return self._state
if lookup_from.has_key((is_start, ns, local)) or lookup_from.has_key((is_start, ns, ANY)):
try:
new_state = lookup_from[(is_start, ns, local)]
except KeyError:
new_state = lookup_from[(is_start, ns, ANY)]
if (new_state in self._live_states):
#Entering a defined XPattern chunk
self.entering_xpatterns.append(self._live_states[new_state])
self.current_xpatterns.append(self._live_states[new_state])
elif (self._state in self._live_states):
#Leaving a defined XPattern chunk
self.leaving_xpatterns.append(self.current_xpatterns.pop())
if is_start:
self.depth_marks.append(self.tree_depth - 1)
else:
self.depth_marks.pop()
self._state = new_state
elif lookup_from.has_key((is_start, ANY, EXPLICIT)):
new_state = lookup_from[(is_start, ANY, EXPLICIT)]
if (new_state in self._live_states):
#Entering a defined XPattern chunk
self.entering_xpatterns.append(self._live_states[new_state])
self.current_xpatterns.append(self._live_states[new_state])
elif (self._state in self._live_states):
#Leaving a defined XPattern chunk
self.leaving_xpatterns.append(self.current_xpatterns.pop())
self._state = new_state
if is_start:
self.depth_marks.append(self.tree_depth - 1)
else:
self.depth_marks.pop()
elif lookup_from.has_key((is_start, ANY, IMPLICIT)):
new_state = lookup_from[(is_start, ANY, IMPLICIT)]
self._state = new_state
if is_start:
self.depth_marks.append(self.tree_depth - 1)
else:
self.depth_marks.pop()
#print self.entering_xpatterns,self.leaving_xpatterns,self.current_xpatterns
return self._state
def status(self):
"""
1 if currently within an XPattern, 0 if not
Calling code might also want to just check
self.current_xpatterns directly
"""
return not not self.current_xpatterns
class xpattern_state_manager:
"""
And aggregation of multiple state machines, one for each registered pattern
"""
PARSER = XPatternParser.new()
def __init__(self, xpatterns, nss):
if not hasattr(xpatterns[0], "match"):
self._xpatterns = [ (p, self.PARSER.parse(p)) for p in xpatterns ]
else:
self._xpatterns = [ (repr(xp), self.PARSER.parse(p)) for p in xpatterns ]
self._machines = [ xpattern_state_machine(repr_xp, xp, nss) for repr_xp, xp in self._xpatterns ]
return
def event(self, is_start, ns, local):
for machine in self._machines:
machine.event(is_start, ns, local)
#FIXME: Slow and clumsy
self.entering_xpatterns = []
self.leaving_xpatterns = []
self.current_xpatterns = []
for m in self._machines:
self.entering_xpatterns.extend(m.entering_xpatterns)
self.leaving_xpatterns.extend(m.leaving_xpatterns)
self.current_xpatterns.extend(m.current_xpatterns)
#print "manager event", (self.entering_xpatterns, self.leaving_xpatterns, self.current_xpatterns)
return
def status(self):
"""
1 if currently within an XPattern, 0 if not
Calling code might also want to just check
self.current_xpatterns directly
"""
return not not self.current_xpatterns
class sax2dom_chunker(namespace_mixin, sax.ContentHandler):
"""
Note: Ignores nodes prior to the document element, such as PIs and
text nodes. Collapses CDATA sections into plain text
Only designed to work if you set the feature
sax.handler.feature_namespaces
to 1 on the parser you use.
xpatterns - list of XPatterns. Only portions of the
tree within these patterns will be instantiated as DOM (as
chunks fed to chunk_consumer in sequence)
If None (the default, a DOM node will be created representing
the entire tree.
nss - a dictionary of prefix -> namespace name mappings used to
interpret XPatterns
chunk_consumer - a callable object taking a DOM node. It will be
invoked as each DOM chunk is prepared.
domimpl - DOM implemention to build, e.g. mindom (the default)
or cDomlette or pxdom (if you have the right third-party
packages installed).
owner_doc - for advanced uses, if you want to use an existing
DOM document object as the owner of all created nodes.
"""
def __init__(self,
xpatterns=None,
nss=None,
chunk_consumer=None,
domimpl=Domlette.implementation,
owner_doc=None,
):
namespace_mixin.__init__(self)
nss = nss or {}
#HINT: To use minidom
#domimpl = xml.dom.minidom.getDOMImplementation()
self._impl = domimpl
if isinstance(xpatterns, str) or isinstance(xpatterns, unicode) :
xpatterns = [xpatterns]
#print xpatterns
if owner_doc:
self._owner_doc = owner_doc
else:
try:
dt = self._impl.createDocumentType(DUMMY_DOCELEM, None, u'')
except AttributeError:
#Domlette doesn't need createDocumentType
dt = None
self._owner_doc = self._impl.createDocument(
DUMMY_DOCELEM, DUMMY_DOCELEM, dt)
#Create a docfrag to hold all the generated nodes.
root_node = self._owner_doc.createDocumentFragment()
self._nodeStack = [ root_node ]
self.state_machine = xpattern_state_manager(xpatterns, nss)
self._chunk_consumer = chunk_consumer
return
def get_root_node(self):
"""
Only useful if the user does not register trim paths
If so, then after SAX processing the user can call this
method to retrieve resulting DOM representing the entire
document
"""
return self._nodeStack[0]
#Overridden ContentHandler methods
def startDocument(self):
self.state_machine.event(1, None, None)
return
def endDocument(self):
self.state_machine.event(0, None, None)
return
def startElementNS(self, name, qname, attribs):
(ns, local) = name
qname = self.name_to_qname(name)
self.state_machine.event(1, ns, local)
if not self.state_machine.status():
return
new_element = self._owner_doc.createElementNS(ns, qname or local)
#No, "for aname in attributes" not possible because
#AttributeListImpl diesn't play by those rules :-(
for ((attr_ns, lname), value) in attribs.items():
if attr_ns is not None:
attr_qname = attribs.getQNameByName((attr_ns, lname))
else:
attr_qname = lname
attr = self._owner_doc.createAttributeNS(
attr_ns, attr_qname)
attr_qname = attribs.getQNameByName((attr_ns, lname))
attr.value = value
new_element.setAttributeNodeNS(attr)
self._nodeStack.append(new_element)
return
def endElementNS(self, name, qname):
(ns, local) = name
qname = self.name_to_qname(name)
self.state_machine.event(0, ns, local)
if not self.state_machine.status():
if (self._chunk_consumer and
self.state_machine.leaving_xpatterns):
#Complete the element being closed because it
#Is the last bit of a DOM to be fed to the consumer
new_element = self._nodeStack[TOP]
del self._nodeStack[TOP]
self._nodeStack[TOP].appendChild(new_element)
#Feed the consumer
self._chunk_consumer(self._nodeStack[0])
#Start all over with a new doc frag so the old
#One's memory can be reclaimed
root_node = self._owner_doc.createDocumentFragment()
self._nodeStack = [ root_node ]
return
new_element = self._nodeStack[TOP]
del self._nodeStack[TOP]
self._nodeStack[TOP].appendChild(new_element)
return
def processingInstruction(self, target, data):
if self.state_machine.status():
pi = self._owner_doc.createProcessingInstruction(
target, data)
self._nodeStack[TOP].appendChild(pi)
return
def characters(self, chars):
if self.state_machine.status():
new_text = self._owner_doc.createTextNode(chars)
self._nodeStack[TOP].appendChild(new_text)
return
#Overridden LexicalHandler methods
def comment(self, text):
if self.state_machine.status():
new_comment = self._owner_doc.createComment(text)
self._nodeStack[TOP].appendChild(new_comment)
return
from xml.sax.saxutils import XMLFilterBase
#FIXME: Set up to use actual PyXML if available
from harpia.amara.pyxml_standins import *
class normalize_text_filter(XMLFilterBase, LexicalHandler):
"""
SAX filter to ensure that contiguous white space nodes are
delivered merged into a single node
"""
def __init__(self, *args):
XMLFilterBase.__init__(self, *args)
self._accumulator = []
return
def _complete_text_node(self):
if self._accumulator:
XMLFilterBase.characters(self, ''.join(self._accumulator))
self._accumulator = []
return
def startDocument(self):
XMLFilterBase.startDocument(self)
return
def endDocument(self):
XMLFilterBase.endDocument(self)
return
def startElement(self, name, attrs):
self._complete_text_node()
XMLFilterBase.startElement(self, name, attrs)
return
def startElementNS(self, name, qname, attrs):
self._complete_text_node()
#A bug in Python 2.3 means that we can't just defer to parent, which is broken
#XMLFilterBase.startElementNS(self, name, qname, attrs)
self._cont_handler.startElementNS(name, qname, attrs)
return
def endElement(self, name):
self._complete_text_node()
XMLFilterBase.endElement(self, name)
return
def endElementNS(self, name, qname):
self._complete_text_node()
XMLFilterBase.endElementNS(self, name, qname)
return
def processingInstruction(self, target, body):
self._complete_text_node()
XMLFilterBase.processingInstruction(self, target, body)
return
def comment(self, body):
self._complete_text_node()
#No such thing as an XMLFilterBase.comment :-(
#XMLFilterBase.comment(self, body)
self._cont_handler.comment(body)
return
def characters(self, text):
self._accumulator.append(text)
return
def ignorableWhitespace(self, ws):
self._accumulator.append(text)
return
#Must be overridden because of a bug in Python 2.0 through 2.4
#And even still in PyXML 0.8.4. Missing "return"
def resolveEntity(self, publicId, systemId):
return self._ent_handler.resolveEntity(publicId, systemId)
# Enhancement suggested by James Kew:
# Override XMLFilterBase.parse to connect the LexicalHandler
# Can only do this by setting the relevant property
# May throw SAXNotSupportedException
def parse(self, source):
#import inspect; import pprint; pprint.pprint(inspect.stack())
self._parent.setProperty(property_lexical_handler, self)
# Delegate to XMLFilterBase for the rest
XMLFilterBase.parse(self, source)
return
#
# From xml.dom
#
#ELEMENT_NODE = 1
#ATTRIBUTE_NODE = 2
#TEXT_NODE = 3
#CDATA_SECTION_NODE = 4
#ENTITY_REFERENCE_NODE = 5
#ENTITY_NODE = 6
#PROCESSING_INSTRUCTION_NODE = 7
#COMMENT_NODE = 8
#DOCUMENT_NODE = 9
#DOCUMENT_TYPE_NODE = 10
#DOCUMENT_FRAGMENT_NODE = 11
#NOTATION_NODE = 12
| gpl-3.0 | 5,785,131,844,268,594,000 | 36.610544 | 156 | 0.589193 | false | 4.091582 | true | false | false |
georgistanev/django-dash | src/dash/contrib/plugins/video/dash_widgets.py | 1 | 1797 | __author__ = 'Artur Barseghyan <[email protected]>'
__copyright__ = 'Copyright (c) 2013 Artur Barseghyan'
__license__ = 'GPL 2.0/LGPL 2.1'
__all__ = (
'BaseVideoWidget', 'Video1x1Widget', 'Video2x2Widget', 'Video3x3Widget',
'Video4x4Widget', 'Video5x5Widget'
)
from django.template.loader import render_to_string
from dash.base import BaseDashboardPluginWidget
# **********************************************************************
# *********************** Base Video widget plugin *********************
# **********************************************************************
class BaseVideoWidget(BaseDashboardPluginWidget):
"""
Base video plugin widget.
"""
media_css = (
'css/dash_plugin_video.css',
)
def render(self, request=None):
context = {'plugin': self.plugin}
return render_to_string('video/render.html', context)
# **********************************************************************
# ************************** Specific widgets **************************
# **********************************************************************
class Video1x1Widget(BaseVideoWidget):
"""
Video plugin 1x1 widget.
"""
plugin_uid = 'video_1x1'
class Video2x2Widget(BaseVideoWidget):
"""
Video plugin 2x2 widget.
"""
plugin_uid = 'video_2x2'
cols = 2
rows = 2
class Video3x3Widget(BaseVideoWidget):
"""
Video plugin 3x3 widget.
"""
plugin_uid = 'video_3x3'
cols = 3
rows = 3
class Video4x4Widget(BaseVideoWidget):
"""
Video plugin 4x4 widget.
"""
plugin_uid = 'video_4x4'
cols = 4
rows = 4
class Video5x5Widget(BaseVideoWidget):
"""
Video plugin 5x5 widget.
"""
plugin_uid = 'video_5x5'
cols = 5
rows = 5
| gpl-2.0 | -6,775,300,280,484,336,000 | 23.616438 | 76 | 0.49527 | false | 3.77521 | false | false | false |
nviel/geostat | ForbRecord.py | 1 | 1470 | #!/usr/bin/python
# -*- coding: utf-8 -*-
class ForbRecord:
def __init__(self,line='',hit=0, key='', ref=''):
if line != '':
(h,self.key,ref) = line.split('|',2)
self.hit = int(h)
self.ref = set(ref.split())
return
if key != '':
self.key = key
if ref != '':
self.ref = set(ref.split())
if hit == 0:
self.hit = 1
else:
self.hit = hit
return
else:
self.ref = set()
self.hit = hit
return
self.key = ''
self.hit = 0
self.ref = set()
def __repr__(self):
line=str(self.hit)+"|"+self.key+"|"
if len(self.ref)>0:
for ref in self.ref:
line+= ref + " "
return line[:-1]
else:
return line
def __add__(self,other):
result = ForbRecord()
if self.key =='':
if other.key =='':
return result
result.key = other.key
if self.key != other.key:
pass # fixme: grosse erreur, mais je ne sais pas la remonter... (il faudrait que j'apprenne le python un jour)
result.hit = self.hit + other.hit
result.ref = self.ref | other.ref
#print(self)
#print(other)
#print(result)
#print("--------")
return result
def __cmp__(self,other):
return cmp(self.hit,other.hit)
if __name__ == '__main__':
r1 = ForbRecord('173|laclef|nico fred')
r2 = ForbRecord(key='laclef', ref='nico toto')
print(r1)
print(r2)
print(r1+r2)
| mit | -4,623,617,808,017,423,000 | 20.617647 | 116 | 0.509524 | false | 3.107822 | false | false | false |
rovest/UlyssesReportAndMarkdown | md_split2ulysses_xcall.py | 1 | 2495 | #coding: utf-8
'''
python3
md_split2ulysses_xcall.py
2017-04-07 at 09:55 EDT
Will take Markdown file as input or from clipboard and split it to Ulysses sheets
at chosen heading levels.
A new Ulysses group for these sheets will be created at root level.
'''
import subprocess
import json
import sys
import re
import urllib.parse
SPLIT_LEVEL = 2
ACCESS_TOKEN = "5a5887277e324caabb4e9229c79141b3"
XCALLAPP = "/Applications/xcall.app/Contents/MacOS/xcall"
X_NEW_GROUP = "ulysses://x-callback-url/new-group?name={name}"
X_NEW_SHEET = "ulysses://x-callback-url/new-sheet?groupId={id}&index={index}&text={text}"
arg1 = ""
if len(sys.argv) > 1:
if sys.argv[1] != "":
arg1 = sys.argv[1]
def main():
if arg1 == "":
md_text = read_from_clipboard()
else:
md_text = read_file(arg1)
md_lines = md_text.splitlines()
title = re.sub(r'^#+ ', '', md_lines[0])
group_id = new_ul_group(title)
pattern = '#' + '#?' * (SPLIT_LEVEL - 1) + " "
break_points = []
index = 1
for line in md_lines[1:]:
if re.match(pattern, line):
print(line)
break_points.append(index)
index += 1
break_points.append(len(md_lines))
start = 0
index = 0
for end in break_points:
print(str(index) + '. ' + md_lines[start])
new_sheet(md_lines[start:end], group_id, index)
start = end
index += 1
# View result group in Ulysses:
url = "ulysses://x-callback-url/open-group?id=" + group_id
subprocess.call(["open", url])
# NOTE! subprocess.call() with "open" does not wait! So should only be used as last command!
def new_ul_group(title):
print('New group = Splitted: ' + title)
gr_name = urllib.parse.quote('Splitted: ' + title[:20])
url = X_NEW_GROUP.format(name=gr_name)
args = XCALLAPP + ' -url "' + url + '"'
output = subprocess.check_output(args, shell=True)
ret_dict = json.loads(output.decode('UTF-8'))
return ret_dict['targetId']
def new_sheet(chunk, group_id, index):
md_text = '\n'.join(chunk)
url = X_NEW_SHEET.format(id=group_id, index=index, text=urllib.parse.quote(md_text))
args = XCALLAPP + ' -url "' + url + '"'
ret_code = subprocess.call(args, shell=True)
if ret_code != 0:
print('Error: ' + str(ret_code) + ': ' + chunk[1])
def read_from_clipboard():
return subprocess.check_output(
'pbpaste', env={'LANG': 'en_US.UTF-8'}).decode('utf-8')
if __name__ == '__main__':
main()
| mit | 4,419,663,919,681,229,000 | 28.011628 | 96 | 0.612425 | false | 2.973778 | false | false | false |
thenetcircle/dino | dino/rest/resources/rooms_for_users.py | 1 | 2462 | from datetime import datetime
from dino.exceptions import NoSuchRoomException
from flask import request
import logging
from dino.utils import b64e
from dino.utils.decorators import timeit
from dino.rest.resources.base import BaseResource
from dino import environ
logger = logging.getLogger(__name__)
class RoomsForUsersResource(BaseResource):
def __init__(self):
super(RoomsForUsersResource, self).__init__()
self.last_cleared = datetime.utcnow()
self.request = request
def _do_get(self, user_id):
output = list()
channel_ids = dict()
channel_names = dict()
rooms = environ.env.db.rooms_for_user(user_id)
for room_id, room_name in rooms.items():
try:
if room_id in channel_ids:
channel_id = channel_ids[room_id]
else:
channel_id = environ.env.db.channel_for_room(room_id)
channel_ids[room_id] = channel_id
if channel_id in channel_names:
channel_name = channel_names[channel_id]
else:
channel_name = environ.env.db.get_channel_name(channel_id)
channel_names[channel_id] = channel_name
output.append({
'room_id': room_id,
'room_name': b64e(room_name),
'channel_id': channel_id,
'channel_name': b64e(channel_name)
})
except NoSuchRoomException:
# can ignore, already deleted or old cache value
pass
return output
def do_get_with_params(self, user_id):
return self._do_get(user_id)
@timeit(logger, 'on_rest_rooms_for_users')
def do_get(self):
is_valid, msg, json = self.validate_json(self.request, silent=False)
if not is_valid:
logger.error('invalid json: %s' % msg)
return dict()
if 'users' not in json:
return dict()
logger.debug('GET request: %s' % str(json))
output = dict()
for user in json['users']:
output[user] = self.do_get_with_params(user)
return output
def _get_lru_method(self):
return self.do_get_with_params
def _get_last_cleared(self):
return self.last_cleared
def _set_last_cleared(self, last_cleared):
self.last_cleared = last_cleared
| apache-2.0 | 1,053,603,811,281,318,700 | 29.395062 | 78 | 0.565394 | false | 3.914149 | false | false | false |
twz915/django | tests/forms_tests/field_tests/test_floatfield.py | 15 | 3657 | from django.forms import FloatField, NumberInput, ValidationError
from django.test import SimpleTestCase
from django.utils import formats, translation
from . import FormFieldAssertionsMixin
class FloatFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
def test_floatfield_1(self):
f = FloatField()
self.assertWidgetRendersTo(f, '<input step="any" type="number" name="f" id="id_f" required />')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean('')
with self.assertRaisesMessage(ValidationError, "'This field is required.'"):
f.clean(None)
self.assertEqual(1.0, f.clean('1'))
self.assertIsInstance(f.clean('1'), float)
self.assertEqual(23.0, f.clean('23'))
self.assertEqual(3.1400000000000001, f.clean('3.14'))
self.assertEqual(3.1400000000000001, f.clean(3.14))
self.assertEqual(42.0, f.clean(42))
with self.assertRaisesMessage(ValidationError, "'Enter a number.'"):
f.clean('a')
self.assertEqual(1.0, f.clean('1.0 '))
self.assertEqual(1.0, f.clean(' 1.0'))
self.assertEqual(1.0, f.clean(' 1.0 '))
with self.assertRaisesMessage(ValidationError, "'Enter a number.'"):
f.clean('1.0a')
self.assertIsNone(f.max_value)
self.assertIsNone(f.min_value)
with self.assertRaisesMessage(ValidationError, "'Enter a number.'"):
f.clean('Infinity')
with self.assertRaisesMessage(ValidationError, "'Enter a number.'"):
f.clean('NaN')
with self.assertRaisesMessage(ValidationError, "'Enter a number.'"):
f.clean('-Inf')
def test_floatfield_2(self):
f = FloatField(required=False)
self.assertIsNone(f.clean(''))
self.assertIsNone(f.clean(None))
self.assertEqual(1.0, f.clean('1'))
self.assertIsNone(f.max_value)
self.assertIsNone(f.min_value)
def test_floatfield_3(self):
f = FloatField(max_value=1.5, min_value=0.5)
self.assertWidgetRendersTo(
f,
'<input step="any" name="f" min="0.5" max="1.5" type="number" id="id_f" required />',
)
with self.assertRaisesMessage(ValidationError, "'Ensure this value is less than or equal to 1.5.'"):
f.clean('1.6')
with self.assertRaisesMessage(ValidationError, "'Ensure this value is greater than or equal to 0.5.'"):
f.clean('0.4')
self.assertEqual(1.5, f.clean('1.5'))
self.assertEqual(0.5, f.clean('0.5'))
self.assertEqual(f.max_value, 1.5)
self.assertEqual(f.min_value, 0.5)
def test_floatfield_widget_attrs(self):
f = FloatField(widget=NumberInput(attrs={'step': 0.01, 'max': 1.0, 'min': 0.0}))
self.assertWidgetRendersTo(
f,
'<input step="0.01" name="f" min="0.0" max="1.0" type="number" id="id_f" required />',
)
def test_floatfield_localized(self):
"""
A localized FloatField's widget renders to a text input without any
number input specific attributes.
"""
f = FloatField(localize=True)
self.assertWidgetRendersTo(f, '<input id="id_f" name="f" type="text" required />')
def test_floatfield_changed(self):
f = FloatField()
n = 4.35
self.assertFalse(f.has_changed(n, '4.3500'))
with translation.override('fr'), self.settings(USE_L10N=True):
f = FloatField(localize=True)
localized_n = formats.localize_input(n) # -> '4,35' in French
self.assertFalse(f.has_changed(n, localized_n))
| bsd-3-clause | -4,090,251,715,257,690,000 | 42.023529 | 111 | 0.613344 | false | 3.664329 | true | false | false |
miketheman/fullstack | site-cookbooks/fullstack/files/default/webapp.py | 1 | 2087 | #!/usr/bin/env python
'''
This application is a simple implemnetation of a word counter.
It leverages the bottle micro-framework, as well as pymongo.
'''
import time
from bottle import route, run, response, request, template
from bson.json_util import default
import pymongo
from pymongo.uri_parser import parse_uri
import json
from statsd import statsd
try:
import local_settings as config
except ImportError:
# make default config: non-replset connection
# directly to mongo on localhost
class config(object):
mongo_uri = 'mongodb://localhost'
mongo_uri = getattr(config, 'mongo_uri', 'mongodb://localhost')
uri_components = parse_uri(mongo_uri)
if 'replicaSet' in uri_components['options']:
conn = pymongo.ReplicaSetConnection(mongo_uri)
else:
conn = pymongo.Connection(mongo_uri)
db = conn.test
@route('/insert/:name')
@statsd.timed('fullstack.insert.time', sample_rate=0.5)
def insert(name):
doc = {'name': name}
db.phrases.update(doc, {"$inc":{"count": 1}}, upsert=True)
# TODO: Figure out a better place for this - some sort of setup url?
db.phrases.ensure_index('name')
db.phrases.ensure_index('count')
return json.dumps(doc, default=default)
@route('/get')
@route('/get/:name')
@statsd.timed('fullstack.get.time', sample_rate=0.5)
def get(name=None):
query = {}
if name is not None:
query['name'] = name
response.set_header('Content-Type', 'application/json')
return json.dumps(list(db.phrases.find(query)), default=default)
@route('/toplist')
@statsd.timed('fullstack.toplist.time', sample_rate=0.5)
def toplist(name=None):
# TODO: Figure out a better place for this - some sort of setup url?
db.phrases.ensure_index('name')
db.phrases.ensure_index('count')
query = db.phrases.find({}, ['count', 'name']).sort('count', -1).limit(10)
return template('toplist', toplist=list(query))
# This is because I hate seeing errors for no reason.
@route('/favicon.ico')
def favicon():
return
if __name__ == '__main__':
run(host='localhost', port=8080, reloader=True) | mit | -2,513,415,409,055,776,000 | 27.60274 | 78 | 0.690944 | false | 3.328549 | false | false | false |
dchaplinsky/declarations.com.ua | declarations_site/landings/models.py | 1 | 12334 | from itertools import chain
import hashlib
from django.db import models
from django.contrib.postgres.fields import JSONField, ArrayField
from django.core.serializers.json import DjangoJSONEncoder
from django.urls import reverse
from django.utils.translation import gettext as _, get_language
from dateutil.parser import parse as dt_parse
from elasticsearch.serializer import JSONSerializer
from elasticsearch_dsl import Q
from ckeditor.fields import RichTextField
from easy_thumbnails.fields import ThumbnailerImageField
from translitua import translit
from catalog.elastic_models import NACPDeclaration
from catalog.models import Region
class DeclarationsManager(models.Manager):
def create_declarations(self, person, declarations):
existing_ids = self.filter(person=person).values_list(
"declaration_id", flat=True
)
for d in declarations:
if d._id in existing_ids:
continue
self.create(
person=person,
declaration_id=d._id,
year=d.intro.declaration_year,
corrected=getattr(d.intro, "corrected", False),
doc_type=getattr(d.intro, "doc_type", "Щорічна"),
obj_ids=list(getattr(d, "obj_ids", [])),
user_declarant_id=getattr(d.intro, "user_declarant_id", None),
source=d.api_response(
fields=[
"guid",
"infocard",
"raw_source",
"unified_source",
"related_entities",
"guid",
"aggregated_data",
]
),
)
class LandingPage(models.Model):
BODY_TYPES = {
"city_council": _("Міська рада"),
"regional_council": _("Обласна рада"),
"other": _("Інше"),
}
slug = models.SlugField("Ідентифікатор сторінки", primary_key=True, max_length=100)
title = models.CharField("Заголовок сторінки", max_length=200)
description = RichTextField("Опис сторінки", blank=True)
title_en = models.CharField("Заголовок сторінки [en]", max_length=200, blank=True)
description_en = RichTextField("Опис сторінки [en]", blank=True)
image = ThumbnailerImageField(blank=True, upload_to="landings")
region = models.ForeignKey(Region, blank=True, null=True, on_delete=models.SET_NULL)
body_type = models.CharField(
"Тип держоргану",
blank=True,
null=True,
choices=BODY_TYPES.items(),
max_length=30,
)
keywords = models.TextField(
"Ключові слова для пошуку в деклараціях (по одному запиту на рядок)", blank=True
)
def pull_declarations(self):
for p in self.persons.select_related("body").prefetch_related("declarations"):
p.pull_declarations()
def get_summary(self):
persons = {}
min_years = []
max_years = []
for p in self.persons.select_related("body").prefetch_related("declarations"):
summary = p.get_summary()
if "min_year" in summary:
min_years.append(summary["min_year"])
if "max_year" in summary:
max_years.append(summary["max_year"])
persons[p.pk] = summary
return {
"max_year": max(max_years),
"min_year": min(min_years),
"persons": persons,
}
def __str__(self):
return "%s (%s)" % (self.title, self.slug)
def get_absolute_url(self):
return reverse("landing_page_details", kwargs={"pk": self.pk})
class Meta:
verbose_name = "Лендінг-сторінка"
verbose_name_plural = "Лендінг-сторінки"
class Person(models.Model):
body = models.ForeignKey(
"LandingPage",
verbose_name="Лендінг-сторінка",
related_name="persons",
on_delete=models.CASCADE,
)
name = models.CharField("Ім'я особи", max_length=200)
extra_keywords = models.CharField(
"Додаткові ключові слова для пошуку",
max_length=200,
blank=True,
help_text="Ключові слова для додаткового звуження пошуку",
)
def __str__(self):
return "%s (знайдено декларацій: %s)" % (self.name, self.declarations.count())
def get_absolute_url(self):
return reverse(
"landing_page_person", kwargs={"body_id": self.body_id, "pk": self.pk}
)
def pull_declarations(self):
def get_search_clause(kwd):
if "область" not in kwd:
return Q(
"multi_match",
query=kwd,
operator="or",
minimum_should_match=1,
fields=[
"general.post.region",
"general.post.office",
"general.post.post",
"general.post.actual_region",
],
)
else:
return Q(
"multi_match",
query=kwd,
fields=["general.post.region", "general.post.actual_region"],
)
search_clauses = [
get_search_clause(x)
for x in filter(None, map(str.strip, self.body.keywords.split("\n")))
]
q = "{} {}".format(self.name, self.extra_keywords)
if search_clauses:
for sc in search_clauses:
first_pass = (
NACPDeclaration.search()
.query(
"bool",
must=[
Q(
"match",
general__full_name={"query": q, "operator": "and"},
)
],
should=[sc],
minimum_should_match=1,
)[:100]
.execute()
)
if first_pass:
break
else:
first_pass = (
NACPDeclaration.search()
.query(
"bool",
must=[
Q("match", general__full_name={"query": q, "operator": "and"})
],
)[:100]
.execute()
)
Declaration.objects.create_declarations(self, first_pass)
user_declarant_ids = set(
filter(
None,
self.declarations.exclude(exclude=True).values_list(
"user_declarant_id", flat=True
),
)
)
if user_declarant_ids:
second_pass = NACPDeclaration.search().filter(
"terms", **{"intro.user_declarant_id": list(user_declarant_ids)}
)
second_pass = second_pass.execute()
if not user_declarant_ids or not second_pass:
obj_ids_to_find = set(
chain(
*self.declarations.exclude(exclude=True).values_list(
"obj_ids", flat=True
)
)
)
second_pass = NACPDeclaration.search().query(
"bool",
must=[
Q("match", general__full_name={"query": q, "operator": "or"}),
Q("match", obj_ids=" ".join(list(obj_ids_to_find)[:512])),
],
should=[],
minimum_should_match=0,
)[:100]
second_pass = second_pass.execute()
Declaration.objects.create_declarations(self, second_pass)
@staticmethod
def get_flags(aggregated_data):
res = []
for f, flag in NACPDeclaration.ENABLED_FLAGS.items():
if str(aggregated_data.get(f, "false")).lower() == "true":
res.append(
{
"flag": f,
"text": flag["name"],
"description": flag["description"],
}
)
return res
def get_summary(self):
result = {"name": self.name, "id": self.pk, "documents": {}}
years = {}
for d in self.declarations.exclude(doc_type="Форма змін").exclude(exclude=True):
if d.year in years:
if dt_parse(d.source["infocard"]["created_date"]) > dt_parse(
years[d.year].source["infocard"]["created_date"]
):
years[d.year] = d
else:
years[d.year] = d
for k in sorted(years.keys()):
result["documents"][k] = {
"aggregated_data": years[k].source["aggregated_data"],
"flags": self.get_flags(years[k].source["aggregated_data"]),
"year": k,
"infocard": years[k].source["infocard"],
}
if years:
result["min_year"] = min(years.keys())
result["max_year"] = max(years.keys())
return result
def get_nodes(self):
language = get_language()
persons = set()
companies = set()
name = self.name
if language == "en":
name = translit(name)
for d in self.declarations.exclude(doc_type="Форма змін").exclude(exclude=True):
persons |= set(d.source["related_entities"]["people"]["family"])
companies |= set(d.source["related_entities"]["companies"]["owned"])
companies |= set(d.source["related_entities"]["companies"]["related"])
nodes = [{"data": {"id": "root", "label": name}, "classes": ["root", "person"]}]
edges = []
for p in persons:
id_ = hashlib.sha256(p.encode("utf-8")).hexdigest()
if language == "en":
p = translit(p)
nodes.append({"data": {"id": id_, "label": p}, "classes": ["person"]})
edges.append({"data": {"source": "root", "target": id_}})
for c in companies:
id_ = hashlib.sha256(c.encode("utf-8")).hexdigest()
nodes.append({"data": {"id": id_, "label": c}, "classes": ["company"]})
edges.append({"data": {"source": "root", "target": id_}})
return {"nodes": nodes, "edges": edges}
class Meta:
verbose_name = "Фокус-персона"
verbose_name_plural = "Фокус-персони"
class Declaration(models.Model):
person = models.ForeignKey(
"Person",
verbose_name="Персона",
related_name="declarations",
on_delete=models.CASCADE,
)
declaration_id = models.CharField("Ідентифікатор декларації", max_length=60)
user_declarant_id = models.IntegerField(
"Ідентифікатор декларанта", null=True, default=None
)
year = models.IntegerField("Рік подання декларації")
corrected = models.BooleanField("Уточнена декларація")
exclude = models.BooleanField("Ігнорувати цей документ", default=False)
doc_type = models.CharField("Тип документу", max_length=50)
source = JSONField("Машиночитний вміст", default=dict, encoder=DjangoJSONEncoder)
obj_ids = ArrayField(
models.CharField(max_length=50),
verbose_name="Ідентифікатори з декларації",
default=list,
)
objects = DeclarationsManager()
class Meta:
verbose_name = "Декларація фокус-персони"
verbose_name_plural = "Декларація фокус-персони"
index_together = [["year", "corrected", "doc_type", "exclude"]]
unique_together = [["person", "declaration_id"]]
ordering = ["-year", "-corrected"]
| mit | -1,422,018,491,001,332,500 | 32.20904 | 88 | 0.514886 | false | 3.72733 | false | false | false |
ang2ara/elearning | nusa/settings.py | 1 | 4445 | """
Django settings for nusa project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'lxg(cfz*_vxmt0%!+vbinb^)0l_t5k_&kvq2*oq9^^al-tt-+t'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# The Django sites framework is required
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
# ... include the providers you want to enable:
#'allauth.socialaccount.providers.amazon',
#'allauth.socialaccount.providers.angellist',
#'allauth.socialaccount.providers.bitbucket',
#'allauth.socialaccount.providers.bitly',
#'allauth.socialaccount.providers.coinbase',
#'allauth.socialaccount.providers.dropbox',
'allauth.socialaccount.providers.facebook',
#'allauth.socialaccount.providers.flickr',
#'allauth.socialaccount.providers.feedly',
#'allauth.socialaccount.providers.github',
#'allauth.socialaccount.providers.google',
#'allauth.socialaccount.providers.hubic',
#'allauth.socialaccount.providers.instagram',
#'allauth.socialaccount.providers.linkedin',
#'allauth.socialaccount.providers.linkedin_oauth2',
#'allauth.socialaccount.providers.openid',
#'allauth.socialaccount.providers.persona',
#'allauth.socialaccount.providers.soundcloud',
#'allauth.socialaccount.providers.stackexchange',
#'allauth.socialaccount.providers.tumblr',
#'allauth.socialaccount.providers.twitch',
#'allauth.socialaccount.providers.twitter',
#'allauth.socialaccount.providers.vimeo',
#'allauth.socialaccount.providers.vk',
#'allauth.socialaccount.providers.weibo',
#'allauth.socialaccount.providers.xing',
'elearning',
)
SITE_ID = 1
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
TEMPLATE_CONTEXT_PROCESSORS = (
# Required by allauth template tags
"django.core.context_processors.request",
# allauth specific context processors
"allauth.account.context_processors.account",
"allauth.socialaccount.context_processors.socialaccount",
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.media',
)
AUTHENTICATION_BACKENDS = (
# Needed to login by username in Django admin, regardless of `allauth`
"django.contrib.auth.backends.ModelBackend",
# `allauth` specific authentication methods, such as login by e-mail
"allauth.account.auth_backends.AuthenticationBackend",
)
ROOT_URLCONF = 'nusa.urls'
WSGI_APPLICATION = 'nusa.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/dev/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/dev/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = 'D:/django/elearning/elearning/media/'
MEDIA_URL = '/media/'
#setting auth
ACCOUNT_AUTHENTICATION_METHOD = "username"
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_EMAIL_VERIFICATION = "optional"
ACCOUNT_EMAIL_SUBJECT_PREFIX = "[q4ts]"
ACCOUNT_PASSWORD_MIN_LENGTH = 6
| lgpl-3.0 | 2,634,240,403,403,597,300 | 28.437086 | 74 | 0.732958 | false | 3.596278 | false | false | false |
rthouvenin/meteography | meteography/django/broadcaster/forecast.py | 1 | 2965 | # -*- coding: utf-8 -*-
from datetime import datetime
from sklearn.neighbors import DistanceMetric
from django.utils.timezone import utc
from meteography.neighbors import NearestNeighbors
from meteography.django.broadcaster.models import Prediction
from meteography.django.broadcaster.storage import webcam_fs
def make_prediction(webcam, params, timestamp):
"""
Make a prediction using NearestNeighbors algorithm.
Parameters
----------
webcam : Webcam instance
The source of pictures
params : PredictionParams instance
The parameters to use to compute the prediction
timestamp : int
The Unix-Epoch-timestamp (UTC) of when the prediction is made
Return
------
Prediction instance
"""
cam_id = webcam.webcam_id
result = None
with webcam_fs.get_dataset(cam_id) as dataset:
ex_set = dataset.get_set(params.name)
new_input = dataset.make_input(ex_set, timestamp)
if new_input is not None and len(ex_set.input) > 0:
neighbors = NearestNeighbors()
neighbors.fit(ex_set.input)
output_ref = neighbors.predict(new_input)
output = dataset.output_img(ex_set, output_ref)
# FIXME reference existing image (data and file)
imgpath = webcam_fs.prediction_path(cam_id, params.name, timestamp)
result = Prediction(params=params, path=imgpath)
result.comp_date = datetime.fromtimestamp(timestamp, utc)
result.sci_bytes = output
result.create()
return result
def update_prediction(prediction, real_pic, metric_name='euclidean'):
"""
Update a prediction after receiving the actual picture from the webcam.
Parameters
----------
prediction : Prediction
The model object of the prediction to update
real_pic : Picture
The model object of the actual picture received
Return
------
float : the prediction error
"""
pred_pic = prediction.as_picture()
cam_id = prediction.params.webcam.webcam_id
if metric_name == 'wminkowski-pca':
with webcam_fs.get_dataset(cam_id) as dataset:
if 'pca' not in dataset.imgset.feature_sets:
raise ValueError("""wminkowski-pca cannnot be used
without a PCA feature set""")
pca_extractor = dataset.imgset.feature_sets['pca'].extractor
weights = pca_extractor.pca.explained_variance_ratio_
pred_data = pca_extractor.extract(pred_pic.pixels)
real_data = pca_extractor.extract(real_pic.pixels)
metric = DistanceMetric.get_metric('wminkowski', p=2, w=weights)
else:
pred_data = pred_pic.pixels
real_data = real_pic.pixels
metric = DistanceMetric.get_metric(metric_name)
error = metric.pairwise([pred_data], [real_data])[0]
prediction.error = error
prediction.save()
return error
| mit | 5,971,376,574,569,990,000 | 33.476744 | 79 | 0.648229 | false | 4.112344 | false | false | false |
mgraupe/acq4 | acq4/util/ColorMapper/CMTemplate.py | 4 | 3370 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file './acq4/util/ColorMapper/CMTemplate.ui'
#
# Created: Tue Dec 24 01:49:16 2013
# by: PyQt4 UI code generator 4.10
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(264, 249)
self.gridLayout = QtGui.QGridLayout(Form)
self.gridLayout.setMargin(0)
self.gridLayout.setHorizontalSpacing(0)
self.gridLayout.setVerticalSpacing(1)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setSpacing(0)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label = QtGui.QLabel(Form)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout.addWidget(self.label)
self.fileCombo = QtGui.QComboBox(Form)
self.fileCombo.setEditable(True)
self.fileCombo.setMaxVisibleItems(20)
self.fileCombo.setObjectName(_fromUtf8("fileCombo"))
self.horizontalLayout.addWidget(self.fileCombo)
self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 3)
self.saveBtn = FeedbackButton(Form)
self.saveBtn.setObjectName(_fromUtf8("saveBtn"))
self.gridLayout.addWidget(self.saveBtn, 1, 0, 1, 1)
self.saveAsBtn = FeedbackButton(Form)
self.saveAsBtn.setObjectName(_fromUtf8("saveAsBtn"))
self.gridLayout.addWidget(self.saveAsBtn, 1, 1, 1, 1)
self.deleteBtn = FeedbackButton(Form)
self.deleteBtn.setObjectName(_fromUtf8("deleteBtn"))
self.gridLayout.addWidget(self.deleteBtn, 1, 2, 1, 1)
self.tree = TreeWidget(Form)
self.tree.setRootIsDecorated(False)
self.tree.setObjectName(_fromUtf8("tree"))
self.gridLayout.addWidget(self.tree, 2, 0, 1, 3)
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.label.setText(_translate("Form", "Color Scheme:", None))
self.saveBtn.setText(_translate("Form", "Save", None))
self.saveAsBtn.setText(_translate("Form", "Save As..", None))
self.deleteBtn.setText(_translate("Form", "Delete", None))
self.tree.headerItem().setText(0, _translate("Form", "arg", None))
self.tree.headerItem().setText(1, _translate("Form", "op", None))
self.tree.headerItem().setText(2, _translate("Form", "min", None))
self.tree.headerItem().setText(3, _translate("Form", "max", None))
self.tree.headerItem().setText(4, _translate("Form", "colors", None))
self.tree.headerItem().setText(5, _translate("Form", "remove", None))
from acq4.pyqtgraph import FeedbackButton, TreeWidget
| mit | -2,164,891,471,097,324,300 | 42.766234 | 92 | 0.675074 | false | 3.740289 | false | false | false |
craigtracey/nova-docker | novadocker/tests/virt/docker/test_network.py | 3 | 3612 | # Copyright 2014 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.
import uuid
from nova import exception
from nova import test
from nova import utils
from nova.tests import utils as test_utils
from nova.openstack.common import processutils
from novadocker.virt.docker import network
import mock
class NetworkTestCase(test.NoDBTestCase):
@mock.patch.object(utils, 'execute')
def test_teardown_delete_network(self, utils_mock):
id = "second-id"
utils_mock.return_value = ("first-id\nsecond-id\nthird-id\n", None)
network.teardown_network(id)
utils_mock.assert_called_with('ip', 'netns', 'delete', id,
run_as_root=True)
@mock.patch.object(utils, 'execute')
def test_teardown_network_not_in_list(self, utils_mock):
utils_mock.return_value = ("first-id\nsecond-id\nthird-id\n", None)
network.teardown_network("not-in-list")
utils_mock.assert_called_with('ip', '-o', 'netns', 'list')
@mock.patch.object(network, 'LOG')
@mock.patch.object(utils, 'execute',
side_effect=processutils.ProcessExecutionError)
def test_teardown_network_fails(self, utils_mock, log_mock):
# Call fails but method should not fail.
# Error will be caught and logged.
utils_mock.return_value = ("first-id\nsecond-id\nthird-id\n", None)
id = "third-id"
network.teardown_network(id)
log_mock.warning.assert_called_with(mock.ANY, id)
def test_find_gateway(self):
instance = {'uuid': uuid.uuid4()}
network_info = test_utils.get_test_network_info()
first_net = network_info[0]['network']
first_net['subnets'][0]['gateway']['address'] = '10.0.0.1'
self.assertEqual('10.0.0.1', network.find_gateway(instance, first_net))
def test_cannot_find_gateway(self):
instance = {'uuid': uuid.uuid4()}
network_info = test_utils.get_test_network_info()
first_net = network_info[0]['network']
first_net['subnets'] = []
self.assertRaises(exception.InstanceDeployFailure,
network.find_gateway, instance, first_net)
def test_find_fixed_ip(self):
instance = {'uuid': uuid.uuid4()}
network_info = test_utils.get_test_network_info()
first_net = network_info[0]['network']
first_net['subnets'][0]['cidr'] = '10.0.0.0/24'
first_net['subnets'][0]['ips'][0]['type'] = 'fixed'
first_net['subnets'][0]['ips'][0]['address'] = '10.0.1.13'
self.assertEqual('10.0.1.13/24', network.find_fixed_ip(instance,
first_net))
def test_cannot_find_fixed_ip(self):
instance = {'uuid': uuid.uuid4()}
network_info = test_utils.get_test_network_info()
first_net = network_info[0]['network']
first_net['subnets'] = []
self.assertRaises(exception.InstanceDeployFailure,
network.find_fixed_ip, instance, first_net)
| apache-2.0 | 1,277,902,536,624,382,000 | 40.517241 | 79 | 0.629845 | false | 3.659574 | true | false | false |
wscullin/spack | var/spack/repos/builtin/packages/mrbayes/package.py | 3 | 2955 | ##############################################################################
# Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, [email protected], All rights reserved.
# LLNL-CODE-647188
#
# For details, see https://github.com/llnl/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version 2.1, February 1999.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser 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
##############################################################################
from spack import *
class Mrbayes(AutotoolsPackage):
"""MrBayes is a program for Bayesian inference and model choice across a
wide range of phylogenetic and evolutionary models. MrBayes uses Markov
chain Monte Carlo (MCMC) methods to estimate the posterior distribution
of model parameters."""
homepage = "http://mrbayes.sourceforge.net"
url = "https://downloads.sourceforge.net/project/mrbayes/mrbayes/3.2.6/mrbayes-3.2.6.tar.gz"
version('3.2.6', '95f9822f24be47b976bf87540b55d1fe')
variant('mpi', default=True, description='Enable MPI parallel support')
variant('beagle', default=True, description='Enable BEAGLE library for speed benefits')
variant('sse', default=True, description='Enable SSE in order to substantially speed up execution')
depends_on('autoconf', type='build')
depends_on('automake', type='build')
depends_on('libtool', type='build')
depends_on('m4', type='build')
depends_on('libbeagle', when='+beagle')
depends_on('mpi', when='+mpi')
configure_directory = 'src'
def configure_args(self):
args = []
if '~beagle' in self.spec:
args.append('--with-beagle=no')
else:
args.append('--with-beagle=%s' % self.spec['libbeagle'].prefix)
if '~sse' in self.spec:
args.append('--enable-sse=no')
else:
args.append('--enable-sse=yes')
if '~mpi' in self.spec:
args.append('--enable-mpi=no')
else:
args.append('--enable-mpi=yes')
return args
def install(self, spec, prefix):
mkdirp(prefix.bin)
with working_dir('src'):
install('mb', prefix.bin)
| lgpl-2.1 | 1,541,369,795,507,201,300 | 40.041667 | 103 | 0.643993 | false | 3.817829 | false | false | false |
danielfrg/jupyterhub-kubernetes_spawner | kubernetes_spawner/swagger_client/apis/apiv_api.py | 1 | 850227 | # coding: utf-8
"""
ApivApi.py
Copyright 2015 SmartBear Software
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from __future__ import absolute_import
import sys
import os
# python 2 and python 3 compatibility library
from six import iteritems
from ..configuration import Configuration
from ..api_client import ApiClient
class ApivApi(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not config.api_client:
config.api_client = ApiClient()
self.api_client = config.api_client
def get_api_resources(self, **kwargs):
"""
get available resources
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_api_resources(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_api_resources" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/yaml'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_component_status(self, **kwargs):
"""
list objects of kind ComponentStatus
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_component_status(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1ComponentStatusList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_component_status" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/componentstatuses'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ComponentStatusList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_component_status(self, name, **kwargs):
"""
read the specified ComponentStatus
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_component_status(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the ComponentStatus (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ComponentStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_component_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_component_status`")
resource_path = '/api/v1/componentstatuses/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ComponentStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_endpoints(self, **kwargs):
"""
list or watch objects of kind Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_endpoints(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1EndpointsList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_endpoints" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/endpoints'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1EndpointsList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_event(self, **kwargs):
"""
list or watch objects of kind Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_event(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1EventList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_event" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/events'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1EventList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_limit_range(self, **kwargs):
"""
list or watch objects of kind LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_limit_range(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1LimitRangeList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_limit_range" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/limitranges'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1LimitRangeList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_namespace(self, **kwargs):
"""
list or watch objects of kind Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_namespace(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1NamespaceList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_namespace" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/namespaces'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1NamespaceList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_namespace(self, body, **kwargs):
"""
create a Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_namespace(body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Namespace body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_namespace" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_namespace`")
resource_path = '/api/v1/namespaces'.replace('{format}', 'json')
method = 'POST'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Namespace',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_namespace(self, **kwargs):
"""
delete collection of Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_namespace(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_namespace" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/namespaces'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_binding(self, body, namespace, **kwargs):
"""
create a Binding
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_binding(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Binding body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Binding
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_binding" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_binding`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_binding`")
resource_path = '/api/v1/namespaces/{namespace}/bindings'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Binding',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_endpoints(self, namespace, **kwargs):
"""
list or watch objects of kind Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_endpoints(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1EndpointsList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_endpoints" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_endpoints`")
resource_path = '/api/v1/namespaces/{namespace}/endpoints'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1EndpointsList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_endpoints(self, body, namespace, **kwargs):
"""
create a Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_endpoints(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Endpoints body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Endpoints
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_endpoints" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_endpoints`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_endpoints`")
resource_path = '/api/v1/namespaces/{namespace}/endpoints'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Endpoints',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_endpoints(self, namespace, **kwargs):
"""
delete collection of Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_endpoints(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_endpoints" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_endpoints`")
resource_path = '/api/v1/namespaces/{namespace}/endpoints'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_endpoints(self, namespace, name, **kwargs):
"""
read the specified Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_endpoints(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Endpoints (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1Endpoints
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_endpoints" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_endpoints`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_endpoints`")
resource_path = '/api/v1/namespaces/{namespace}/endpoints/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Endpoints',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_endpoints(self, body, namespace, name, **kwargs):
"""
replace the specified Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_endpoints(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Endpoints body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Endpoints (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Endpoints
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_endpoints" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_endpoints`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_endpoints`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_endpoints`")
resource_path = '/api/v1/namespaces/{namespace}/endpoints/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Endpoints',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_endpoints(self, body, namespace, name, **kwargs):
"""
delete a Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_endpoints(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Endpoints (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_endpoints" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_endpoints`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_endpoints`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_endpoints`")
resource_path = '/api/v1/namespaces/{namespace}/endpoints/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_endpoints(self, body, namespace, name, **kwargs):
"""
partially update the specified Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_endpoints(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Endpoints (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Endpoints
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_endpoints" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_endpoints`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_endpoints`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_endpoints`")
resource_path = '/api/v1/namespaces/{namespace}/endpoints/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Endpoints',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_event(self, namespace, **kwargs):
"""
list or watch objects of kind Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_event(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1EventList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_event" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_event`")
resource_path = '/api/v1/namespaces/{namespace}/events'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1EventList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_event(self, body, namespace, **kwargs):
"""
create a Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_event(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Event body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Event
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_event" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_event`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_event`")
resource_path = '/api/v1/namespaces/{namespace}/events'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Event',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_event(self, namespace, **kwargs):
"""
delete collection of Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_event(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_event" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_event`")
resource_path = '/api/v1/namespaces/{namespace}/events'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_event(self, namespace, name, **kwargs):
"""
read the specified Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_event(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Event (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1Event
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_event" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_event`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_event`")
resource_path = '/api/v1/namespaces/{namespace}/events/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Event',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_event(self, body, namespace, name, **kwargs):
"""
replace the specified Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_event(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Event body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Event (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Event
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_event" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_event`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_event`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_event`")
resource_path = '/api/v1/namespaces/{namespace}/events/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Event',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_event(self, body, namespace, name, **kwargs):
"""
delete a Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_event(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Event (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_event" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_event`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_event`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_event`")
resource_path = '/api/v1/namespaces/{namespace}/events/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_event(self, body, namespace, name, **kwargs):
"""
partially update the specified Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_event(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Event (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Event
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_event" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_event`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_event`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_event`")
resource_path = '/api/v1/namespaces/{namespace}/events/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Event',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_limit_range(self, namespace, **kwargs):
"""
list or watch objects of kind LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_limit_range(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1LimitRangeList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_limit_range" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_limit_range`")
resource_path = '/api/v1/namespaces/{namespace}/limitranges'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1LimitRangeList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_limit_range(self, body, namespace, **kwargs):
"""
create a LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_limit_range(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1LimitRange body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1LimitRange
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_limit_range" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_limit_range`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_limit_range`")
resource_path = '/api/v1/namespaces/{namespace}/limitranges'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1LimitRange',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_limit_range(self, namespace, **kwargs):
"""
delete collection of LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_limit_range(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_limit_range" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_limit_range`")
resource_path = '/api/v1/namespaces/{namespace}/limitranges'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_limit_range(self, namespace, name, **kwargs):
"""
read the specified LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_limit_range(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the LimitRange (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1LimitRange
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_limit_range" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_limit_range`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_limit_range`")
resource_path = '/api/v1/namespaces/{namespace}/limitranges/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1LimitRange',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_limit_range(self, body, namespace, name, **kwargs):
"""
replace the specified LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_limit_range(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1LimitRange body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the LimitRange (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1LimitRange
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_limit_range" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_limit_range`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_limit_range`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_limit_range`")
resource_path = '/api/v1/namespaces/{namespace}/limitranges/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1LimitRange',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_limit_range(self, body, namespace, name, **kwargs):
"""
delete a LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_limit_range(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the LimitRange (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_limit_range" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_limit_range`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_limit_range`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_limit_range`")
resource_path = '/api/v1/namespaces/{namespace}/limitranges/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_limit_range(self, body, namespace, name, **kwargs):
"""
partially update the specified LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_limit_range(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the LimitRange (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1LimitRange
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_limit_range" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_limit_range`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_limit_range`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_limit_range`")
resource_path = '/api/v1/namespaces/{namespace}/limitranges/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1LimitRange',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_persistent_volume_claim(self, namespace, **kwargs):
"""
list or watch objects of kind PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_persistent_volume_claim(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1PersistentVolumeClaimList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeClaimList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_persistent_volume_claim(self, body, namespace, **kwargs):
"""
create a PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_persistent_volume_claim(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1PersistentVolumeClaim body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_persistent_volume_claim`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeClaim',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_persistent_volume_claim(self, namespace, **kwargs):
"""
delete collection of PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_persistent_volume_claim(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_persistent_volume_claim(self, namespace, name, **kwargs):
"""
read the specified PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_persistent_volume_claim(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PersistentVolumeClaim (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_persistent_volume_claim`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeClaim',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_persistent_volume_claim(self, body, namespace, name, **kwargs):
"""
replace the specified PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_persistent_volume_claim(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1PersistentVolumeClaim body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PersistentVolumeClaim (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_persistent_volume_claim`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_persistent_volume_claim`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeClaim',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_persistent_volume_claim(self, body, namespace, name, **kwargs):
"""
delete a PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_persistent_volume_claim(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PersistentVolumeClaim (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_persistent_volume_claim`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_persistent_volume_claim`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_persistent_volume_claim(self, body, namespace, name, **kwargs):
"""
partially update the specified PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_persistent_volume_claim(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PersistentVolumeClaim (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_persistent_volume_claim`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_persistent_volume_claim`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeClaim',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_persistent_volume_claim_status(self, body, namespace, name, **kwargs):
"""
replace status of the specified PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_persistent_volume_claim_status(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1PersistentVolumeClaim body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PersistentVolumeClaim (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PersistentVolumeClaim
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_persistent_volume_claim_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_persistent_volume_claim_status`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_persistent_volume_claim_status`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_persistent_volume_claim_status`")
resource_path = '/api/v1/namespaces/{namespace}/persistentvolumeclaims/{name}/status'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeClaim',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_pod(self, namespace, **kwargs):
"""
list or watch objects of kind Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_pod(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1PodList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_pod`")
resource_path = '/api/v1/namespaces/{namespace}/pods'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PodList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_pod(self, body, namespace, **kwargs):
"""
create a Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_pod(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Pod body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_pod`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_pod`")
resource_path = '/api/v1/namespaces/{namespace}/pods'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Pod',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_pod(self, namespace, **kwargs):
"""
delete collection of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_pod(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_pod`")
resource_path = '/api/v1/namespaces/{namespace}/pods'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_pod(self, namespace, name, **kwargs):
"""
read the specified Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_pod(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_pod`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Pod',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_pod(self, body, namespace, name, **kwargs):
"""
replace the specified Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_pod(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Pod body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_pod`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_pod`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Pod',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_pod(self, body, namespace, name, **kwargs):
"""
delete a Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_pod(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_pod`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_pod`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_pod(self, body, namespace, name, **kwargs):
"""
partially update the specified Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_pod(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_pod`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_pod`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Pod',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_get_namespaced_pod_attach(self, namespace, name, **kwargs):
"""
connect GET requests to attach of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_get_namespaced_pod_attach(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param bool stdin: Stdin if true, redirects the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Stdout if true indicates that stdout is to be redirected for the attach call. Defaults to true.
:param bool stderr: Stderr if true indicates that stderr is to be redirected for the attach call. Defaults to true.
:param bool tty: TTY if true indicates that a tty will be allocated for the attach call. This is passed through the container runtime so the tty is allocated on the worker node by the container runtime. Defaults to false.
:param str container: The container in which to execute the command. Defaults to only container if there is only one container in the pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'stdin', 'stdout', 'stderr', 'tty', 'container']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_pod_attach" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_pod_attach`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_get_namespaced_pod_attach`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/attach'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'stdin' in params:
query_params['stdin'] = params['stdin']
if 'stdout' in params:
query_params['stdout'] = params['stdout']
if 'stderr' in params:
query_params['stderr'] = params['stderr']
if 'tty' in params:
query_params['tty'] = params['tty']
if 'container' in params:
query_params['container'] = params['container']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_post_namespaced_pod_attach(self, namespace, name, **kwargs):
"""
connect POST requests to attach of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_post_namespaced_pod_attach(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param bool stdin: Stdin if true, redirects the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Stdout if true indicates that stdout is to be redirected for the attach call. Defaults to true.
:param bool stderr: Stderr if true indicates that stderr is to be redirected for the attach call. Defaults to true.
:param bool tty: TTY if true indicates that a tty will be allocated for the attach call. This is passed through the container runtime so the tty is allocated on the worker node by the container runtime. Defaults to false.
:param str container: The container in which to execute the command. Defaults to only container if there is only one container in the pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'stdin', 'stdout', 'stderr', 'tty', 'container']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_pod_attach" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_attach`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_attach`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/attach'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'stdin' in params:
query_params['stdin'] = params['stdin']
if 'stdout' in params:
query_params['stdout'] = params['stdout']
if 'stderr' in params:
query_params['stderr'] = params['stderr']
if 'tty' in params:
query_params['tty'] = params['tty']
if 'container' in params:
query_params['container'] = params['container']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_binding_binding(self, body, namespace, name, **kwargs):
"""
create binding of a Binding
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_binding_binding(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Binding body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Binding (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Binding
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_binding_binding" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_binding_binding`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_binding_binding`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `create_namespaced_binding_binding`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/binding'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Binding',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_get_namespaced_pod_exec(self, namespace, name, **kwargs):
"""
connect GET requests to exec of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_get_namespaced_pod_exec(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param bool stdin: Redirect the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Redirect the standard output stream of the pod for this call. Defaults to true.
:param bool stderr: Redirect the standard error stream of the pod for this call. Defaults to true.
:param bool tty: TTY if true indicates that a tty will be allocated for the exec call. Defaults to false.
:param str container: Container in which to execute the command. Defaults to only container if there is only one container in the pod.
:param str command: Command is the remote command to execute. argv array. Not executed within a shell.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'stdin', 'stdout', 'stderr', 'tty', 'container', 'command']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_pod_exec" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_pod_exec`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_get_namespaced_pod_exec`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/exec'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'stdin' in params:
query_params['stdin'] = params['stdin']
if 'stdout' in params:
query_params['stdout'] = params['stdout']
if 'stderr' in params:
query_params['stderr'] = params['stderr']
if 'tty' in params:
query_params['tty'] = params['tty']
if 'container' in params:
query_params['container'] = params['container']
if 'command' in params:
query_params['command'] = params['command']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_post_namespaced_pod_exec(self, namespace, name, **kwargs):
"""
connect POST requests to exec of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_post_namespaced_pod_exec(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param bool stdin: Redirect the standard input stream of the pod for this call. Defaults to false.
:param bool stdout: Redirect the standard output stream of the pod for this call. Defaults to true.
:param bool stderr: Redirect the standard error stream of the pod for this call. Defaults to true.
:param bool tty: TTY if true indicates that a tty will be allocated for the exec call. Defaults to false.
:param str container: Container in which to execute the command. Defaults to only container if there is only one container in the pod.
:param str command: Command is the remote command to execute. argv array. Not executed within a shell.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'stdin', 'stdout', 'stderr', 'tty', 'container', 'command']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_pod_exec" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_exec`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_exec`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/exec'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'stdin' in params:
query_params['stdin'] = params['stdin']
if 'stdout' in params:
query_params['stdout'] = params['stdout']
if 'stderr' in params:
query_params['stderr'] = params['stderr']
if 'tty' in params:
query_params['tty'] = params['tty']
if 'container' in params:
query_params['container'] = params['container']
if 'command' in params:
query_params['command'] = params['command']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_pod_log(self, namespace, name, **kwargs):
"""
read log of the specified Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_pod_log(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str container: The container for which to stream logs. Defaults to only container if there is one container in the pod.
:param bool follow: Follow the log stream of the pod. Defaults to false.
:param bool previous: Return previous terminated container logs. Defaults to false.
:param int since_seconds: A relative time in seconds before the current time from which to show logs. If this value precedes the time a pod was started, only logs since the pod start will be returned. If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified.
:param str since_time: An RFC3339 timestamp from which to show logs. If this value preceeds the time a pod was started, only logs since the pod start will be returned. If this value is in the future, no logs will be returned. Only one of sinceSeconds or sinceTime may be specified.
:param bool timestamps: If true, add an RFC3339 or RFC3339Nano timestamp at the beginning of every line of log output. Defaults to false.
:param int tail_lines: If set, the number of lines from the end of the logs to show. If not specified, logs are shown from the creation of the container or sinceSeconds or sinceTime
:param int limit_bytes: If set, the number of bytes to read from the server before terminating the log output. This may not display a complete final line of logging, and may return slightly more or slightly less than the specified limit.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'container', 'follow', 'previous', 'since_seconds', 'since_time', 'timestamps', 'tail_lines', 'limit_bytes']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_pod_log" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_pod_log`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_pod_log`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/log'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'container' in params:
query_params['container'] = params['container']
if 'follow' in params:
query_params['follow'] = params['follow']
if 'previous' in params:
query_params['previous'] = params['previous']
if 'since_seconds' in params:
query_params['sinceSeconds'] = params['since_seconds']
if 'since_time' in params:
query_params['sinceTime'] = params['since_time']
if 'timestamps' in params:
query_params['timestamps'] = params['timestamps']
if 'tail_lines' in params:
query_params['tailLines'] = params['tail_lines']
if 'limit_bytes' in params:
query_params['limitBytes'] = params['limit_bytes']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Pod',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_get_namespaced_pod_portforward(self, namespace, name, **kwargs):
"""
connect GET requests to portforward of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_get_namespaced_pod_portforward(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_pod_portforward" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_pod_portforward`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_get_namespaced_pod_portforward`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/portforward'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_post_namespaced_pod_portforward(self, namespace, name, **kwargs):
"""
connect POST requests to portforward of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_post_namespaced_pod_portforward(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_pod_portforward" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_portforward`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_portforward`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/portforward'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_get_namespaced_pod_proxy(self, namespace, name, **kwargs):
"""
connect GET requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_get_namespaced_pod_proxy(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_pod_proxy" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_pod_proxy`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_get_namespaced_pod_proxy`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_head_namespaced_pod_proxy(self, namespace, name, **kwargs):
"""
connect HEAD requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_head_namespaced_pod_proxy(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_head_namespaced_pod_proxy" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_head_namespaced_pod_proxy`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_head_namespaced_pod_proxy`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy'.replace('{format}', 'json')
method = 'HEAD'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_put_namespaced_pod_proxy(self, namespace, name, **kwargs):
"""
connect PUT requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_put_namespaced_pod_proxy(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_put_namespaced_pod_proxy" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_put_namespaced_pod_proxy`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_put_namespaced_pod_proxy`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_post_namespaced_pod_proxy(self, namespace, name, **kwargs):
"""
connect POST requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_post_namespaced_pod_proxy(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_pod_proxy" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_proxy`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_proxy`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_delete_namespaced_pod_proxy(self, namespace, name, **kwargs):
"""
connect DELETE requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_delete_namespaced_pod_proxy(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_delete_namespaced_pod_proxy" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_delete_namespaced_pod_proxy`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_delete_namespaced_pod_proxy`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_options_namespaced_pod_proxy(self, namespace, name, **kwargs):
"""
connect OPTIONS requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_options_namespaced_pod_proxy(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_options_namespaced_pod_proxy" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_options_namespaced_pod_proxy`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_options_namespaced_pod_proxy`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy'.replace('{format}', 'json')
method = 'OPTIONS'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_get_namespaced_pod_proxy_1(self, namespace, name, path2, **kwargs):
"""
connect GET requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_get_namespaced_pod_proxy_1(namespace, name, path2, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path2: path to the resource (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path2', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_get_namespaced_pod_proxy_1" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_get_namespaced_pod_proxy_1`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_get_namespaced_pod_proxy_1`")
# verify the required parameter 'path2' is set
if ('path2' not in params) or (params['path2'] is None):
raise ValueError("Missing the required parameter `path2` when calling `connect_get_namespaced_pod_proxy_1`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path2' in params:
path_params['path'] = params['path2']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_head_namespaced_pod_proxy_2(self, namespace, name, path2, **kwargs):
"""
connect HEAD requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_head_namespaced_pod_proxy_2(namespace, name, path2, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path2: path to the resource (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path2', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_head_namespaced_pod_proxy_2" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_head_namespaced_pod_proxy_2`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_head_namespaced_pod_proxy_2`")
# verify the required parameter 'path2' is set
if ('path2' not in params) or (params['path2'] is None):
raise ValueError("Missing the required parameter `path2` when calling `connect_head_namespaced_pod_proxy_2`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}'.replace('{format}', 'json')
method = 'HEAD'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path2' in params:
path_params['path'] = params['path2']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_put_namespaced_pod_proxy_3(self, namespace, name, path2, **kwargs):
"""
connect PUT requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_put_namespaced_pod_proxy_3(namespace, name, path2, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path2: path to the resource (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path2', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_put_namespaced_pod_proxy_3" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_put_namespaced_pod_proxy_3`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_put_namespaced_pod_proxy_3`")
# verify the required parameter 'path2' is set
if ('path2' not in params) or (params['path2'] is None):
raise ValueError("Missing the required parameter `path2` when calling `connect_put_namespaced_pod_proxy_3`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path2' in params:
path_params['path'] = params['path2']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_post_namespaced_pod_proxy_4(self, namespace, name, path2, **kwargs):
"""
connect POST requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_post_namespaced_pod_proxy_4(namespace, name, path2, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path2: path to the resource (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path2', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_post_namespaced_pod_proxy_4" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_post_namespaced_pod_proxy_4`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_post_namespaced_pod_proxy_4`")
# verify the required parameter 'path2' is set
if ('path2' not in params) or (params['path2'] is None):
raise ValueError("Missing the required parameter `path2` when calling `connect_post_namespaced_pod_proxy_4`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path2' in params:
path_params['path'] = params['path2']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_delete_namespaced_pod_proxy_5(self, namespace, name, path2, **kwargs):
"""
connect DELETE requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_delete_namespaced_pod_proxy_5(namespace, name, path2, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path2: path to the resource (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path2', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_delete_namespaced_pod_proxy_5" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_delete_namespaced_pod_proxy_5`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_delete_namespaced_pod_proxy_5`")
# verify the required parameter 'path2' is set
if ('path2' not in params) or (params['path2'] is None):
raise ValueError("Missing the required parameter `path2` when calling `connect_delete_namespaced_pod_proxy_5`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path2' in params:
path_params['path'] = params['path2']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def connect_options_namespaced_pod_proxy_6(self, namespace, name, path2, **kwargs):
"""
connect OPTIONS requests to proxy of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.connect_options_namespaced_pod_proxy_6(namespace, name, path2, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path2: path to the resource (required)
:param str path: Path is the URL path to use for the current proxy request to pod.
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path2', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method connect_options_namespaced_pod_proxy_6" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `connect_options_namespaced_pod_proxy_6`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `connect_options_namespaced_pod_proxy_6`")
# verify the required parameter 'path2' is set
if ('path2' not in params) or (params['path2'] is None):
raise ValueError("Missing the required parameter `path2` when calling `connect_options_namespaced_pod_proxy_6`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/proxy/{path}'.replace('{format}', 'json')
method = 'OPTIONS'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path2' in params:
path_params['path'] = params['path2']
query_params = {}
if 'path' in params:
query_params['path'] = params['path']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_pod_status(self, body, namespace, name, **kwargs):
"""
replace status of the specified Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_pod_status(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Pod body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Pod
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_pod_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_pod_status`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_pod_status`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_pod_status`")
resource_path = '/api/v1/namespaces/{namespace}/pods/{name}/status'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Pod',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_pod_template(self, namespace, **kwargs):
"""
list or watch objects of kind PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_pod_template(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1PodTemplateList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_pod_template" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_pod_template`")
resource_path = '/api/v1/namespaces/{namespace}/podtemplates'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PodTemplateList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_pod_template(self, body, namespace, **kwargs):
"""
create a PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_pod_template(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1PodTemplate body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PodTemplate
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_pod_template" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_pod_template`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_pod_template`")
resource_path = '/api/v1/namespaces/{namespace}/podtemplates'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PodTemplate',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_pod_template(self, namespace, **kwargs):
"""
delete collection of PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_pod_template(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_pod_template" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_pod_template`")
resource_path = '/api/v1/namespaces/{namespace}/podtemplates'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_pod_template(self, namespace, name, **kwargs):
"""
read the specified PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_pod_template(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PodTemplate (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1PodTemplate
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_pod_template" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_pod_template`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_pod_template`")
resource_path = '/api/v1/namespaces/{namespace}/podtemplates/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PodTemplate',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_pod_template(self, body, namespace, name, **kwargs):
"""
replace the specified PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_pod_template(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1PodTemplate body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PodTemplate (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PodTemplate
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_pod_template" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_pod_template`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_pod_template`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_pod_template`")
resource_path = '/api/v1/namespaces/{namespace}/podtemplates/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PodTemplate',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_pod_template(self, body, namespace, name, **kwargs):
"""
delete a PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_pod_template(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PodTemplate (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_pod_template" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_pod_template`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_pod_template`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_pod_template`")
resource_path = '/api/v1/namespaces/{namespace}/podtemplates/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_pod_template(self, body, namespace, name, **kwargs):
"""
partially update the specified PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_pod_template(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PodTemplate (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PodTemplate
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_pod_template" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_pod_template`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_pod_template`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_pod_template`")
resource_path = '/api/v1/namespaces/{namespace}/podtemplates/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PodTemplate',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_replication_controller(self, namespace, **kwargs):
"""
list or watch objects of kind ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_replication_controller(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1ReplicationControllerList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_replication_controller" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_replication_controller`")
resource_path = '/api/v1/namespaces/{namespace}/replicationcontrollers'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ReplicationControllerList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_replication_controller(self, body, namespace, **kwargs):
"""
create a ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_replication_controller(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1ReplicationController body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_replication_controller" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_replication_controller`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_replication_controller`")
resource_path = '/api/v1/namespaces/{namespace}/replicationcontrollers'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ReplicationController',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_replication_controller(self, namespace, **kwargs):
"""
delete collection of ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_replication_controller(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_replication_controller" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_replication_controller`")
resource_path = '/api/v1/namespaces/{namespace}/replicationcontrollers'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_replication_controller(self, namespace, name, **kwargs):
"""
read the specified ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_replication_controller(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ReplicationController (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_replication_controller" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_replication_controller`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_replication_controller`")
resource_path = '/api/v1/namespaces/{namespace}/replicationcontrollers/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ReplicationController',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_replication_controller(self, body, namespace, name, **kwargs):
"""
replace the specified ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_replication_controller(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1ReplicationController body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ReplicationController (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_replication_controller" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_replication_controller`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_replication_controller`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_replication_controller`")
resource_path = '/api/v1/namespaces/{namespace}/replicationcontrollers/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ReplicationController',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_replication_controller(self, body, namespace, name, **kwargs):
"""
delete a ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_replication_controller(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ReplicationController (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_replication_controller" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_replication_controller`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_replication_controller`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_replication_controller`")
resource_path = '/api/v1/namespaces/{namespace}/replicationcontrollers/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_replication_controller(self, body, namespace, name, **kwargs):
"""
partially update the specified ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_replication_controller(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ReplicationController (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_replication_controller" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_replication_controller`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_replication_controller`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_replication_controller`")
resource_path = '/api/v1/namespaces/{namespace}/replicationcontrollers/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ReplicationController',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_replication_controller_status(self, body, namespace, name, **kwargs):
"""
replace status of the specified ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_replication_controller_status(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1ReplicationController body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ReplicationController (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ReplicationController
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_replication_controller_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_replication_controller_status`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_replication_controller_status`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_replication_controller_status`")
resource_path = '/api/v1/namespaces/{namespace}/replicationcontrollers/{name}/status'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ReplicationController',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_resource_quota(self, namespace, **kwargs):
"""
list or watch objects of kind ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_resource_quota(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1ResourceQuotaList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_resource_quota" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_resource_quota`")
resource_path = '/api/v1/namespaces/{namespace}/resourcequotas'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ResourceQuotaList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_resource_quota(self, body, namespace, **kwargs):
"""
create a ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_resource_quota(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1ResourceQuota body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_resource_quota" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_resource_quota`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_resource_quota`")
resource_path = '/api/v1/namespaces/{namespace}/resourcequotas'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ResourceQuota',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_resource_quota(self, namespace, **kwargs):
"""
delete collection of ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_resource_quota(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_resource_quota" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_resource_quota`")
resource_path = '/api/v1/namespaces/{namespace}/resourcequotas'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_resource_quota(self, namespace, name, **kwargs):
"""
read the specified ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_resource_quota(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ResourceQuota (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_resource_quota" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_resource_quota`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_resource_quota`")
resource_path = '/api/v1/namespaces/{namespace}/resourcequotas/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ResourceQuota',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_resource_quota(self, body, namespace, name, **kwargs):
"""
replace the specified ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_resource_quota(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1ResourceQuota body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ResourceQuota (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_resource_quota" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_resource_quota`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_resource_quota`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_resource_quota`")
resource_path = '/api/v1/namespaces/{namespace}/resourcequotas/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ResourceQuota',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_resource_quota(self, body, namespace, name, **kwargs):
"""
delete a ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_resource_quota(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ResourceQuota (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_resource_quota" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_resource_quota`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_resource_quota`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_resource_quota`")
resource_path = '/api/v1/namespaces/{namespace}/resourcequotas/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_resource_quota(self, body, namespace, name, **kwargs):
"""
partially update the specified ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_resource_quota(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ResourceQuota (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_resource_quota" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_resource_quota`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_resource_quota`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_resource_quota`")
resource_path = '/api/v1/namespaces/{namespace}/resourcequotas/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ResourceQuota',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_resource_quota_status(self, body, namespace, name, **kwargs):
"""
replace status of the specified ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_resource_quota_status(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1ResourceQuota body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ResourceQuota (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ResourceQuota
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_resource_quota_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_resource_quota_status`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_resource_quota_status`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_resource_quota_status`")
resource_path = '/api/v1/namespaces/{namespace}/resourcequotas/{name}/status'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ResourceQuota',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_secret(self, namespace, **kwargs):
"""
list or watch objects of kind Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_secret(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1SecretList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_secret" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_secret`")
resource_path = '/api/v1/namespaces/{namespace}/secrets'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1SecretList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_secret(self, body, namespace, **kwargs):
"""
create a Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_secret(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Secret body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Secret
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_secret" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_secret`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_secret`")
resource_path = '/api/v1/namespaces/{namespace}/secrets'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Secret',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_secret(self, namespace, **kwargs):
"""
delete collection of Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_secret(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_secret" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_secret`")
resource_path = '/api/v1/namespaces/{namespace}/secrets'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_secret(self, namespace, name, **kwargs):
"""
read the specified Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_secret(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Secret (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1Secret
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_secret" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_secret`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_secret`")
resource_path = '/api/v1/namespaces/{namespace}/secrets/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Secret',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_secret(self, body, namespace, name, **kwargs):
"""
replace the specified Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_secret(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Secret body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Secret (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Secret
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_secret" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_secret`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_secret`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_secret`")
resource_path = '/api/v1/namespaces/{namespace}/secrets/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Secret',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_secret(self, body, namespace, name, **kwargs):
"""
delete a Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_secret(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Secret (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_secret" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_secret`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_secret`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_secret`")
resource_path = '/api/v1/namespaces/{namespace}/secrets/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_secret(self, body, namespace, name, **kwargs):
"""
partially update the specified Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_secret(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Secret (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Secret
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_secret" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_secret`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_secret`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_secret`")
resource_path = '/api/v1/namespaces/{namespace}/secrets/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Secret',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_service_account(self, namespace, **kwargs):
"""
list or watch objects of kind ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_service_account(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1ServiceAccountList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_service_account" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_service_account`")
resource_path = '/api/v1/namespaces/{namespace}/serviceaccounts'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ServiceAccountList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_service_account(self, body, namespace, **kwargs):
"""
create a ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_service_account(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1ServiceAccount body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ServiceAccount
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_service_account" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_service_account`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_service_account`")
resource_path = '/api/v1/namespaces/{namespace}/serviceaccounts'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ServiceAccount',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_service_account(self, namespace, **kwargs):
"""
delete collection of ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_service_account(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_service_account" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `deletecollection_namespaced_service_account`")
resource_path = '/api/v1/namespaces/{namespace}/serviceaccounts'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_service_account(self, namespace, name, **kwargs):
"""
read the specified ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_service_account(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ServiceAccount (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1ServiceAccount
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_service_account" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_service_account`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_service_account`")
resource_path = '/api/v1/namespaces/{namespace}/serviceaccounts/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ServiceAccount',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_service_account(self, body, namespace, name, **kwargs):
"""
replace the specified ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_service_account(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1ServiceAccount body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ServiceAccount (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ServiceAccount
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_service_account" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_service_account`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_service_account`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_service_account`")
resource_path = '/api/v1/namespaces/{namespace}/serviceaccounts/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ServiceAccount',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_service_account(self, body, namespace, name, **kwargs):
"""
delete a ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_service_account(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ServiceAccount (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_service_account" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_service_account`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_service_account`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_service_account`")
resource_path = '/api/v1/namespaces/{namespace}/serviceaccounts/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_service_account(self, body, namespace, name, **kwargs):
"""
partially update the specified ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_service_account(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ServiceAccount (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1ServiceAccount
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_service_account" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_service_account`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_service_account`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_service_account`")
resource_path = '/api/v1/namespaces/{namespace}/serviceaccounts/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ServiceAccount',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_service(self, namespace, **kwargs):
"""
list or watch objects of kind Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_service(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1ServiceList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `list_namespaced_service`")
resource_path = '/api/v1/namespaces/{namespace}/services'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ServiceList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_service(self, body, namespace, **kwargs):
"""
create a Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_service(body, namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Service body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_service`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `create_namespaced_service`")
resource_path = '/api/v1/namespaces/{namespace}/services'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Service',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_service(self, namespace, name, **kwargs):
"""
read the specified Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_service(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `read_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_service`")
resource_path = '/api/v1/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Service',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_service(self, body, namespace, name, **kwargs):
"""
replace the specified Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_service(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Service body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_service`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `replace_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_service`")
resource_path = '/api/v1/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Service',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_service(self, namespace, name, **kwargs):
"""
delete a Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_service(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `delete_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_service`")
resource_path = '/api/v1/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_service(self, body, namespace, name, **kwargs):
"""
partially update the specified Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_service(body, namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Service
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'namespace', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_service`")
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `patch_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_service`")
resource_path = '/api/v1/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Service',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_namespace(self, name, **kwargs):
"""
read the specified Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_namespace(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_namespace" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_namespace`")
resource_path = '/api/v1/namespaces/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Namespace',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_namespace(self, body, name, **kwargs):
"""
replace the specified Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_namespace(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Namespace body: (required)
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_namespace" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_namespace`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_namespace`")
resource_path = '/api/v1/namespaces/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Namespace',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_namespace(self, body, name, **kwargs):
"""
delete a Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_namespace(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_namespace" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_namespace`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_namespace`")
resource_path = '/api/v1/namespaces/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_namespace(self, body, name, **kwargs):
"""
partially update the specified Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_namespace(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_namespace" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_namespace`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_namespace`")
resource_path = '/api/v1/namespaces/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Namespace',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_namespace_finalize(self, body, name, **kwargs):
"""
replace finalize of the specified Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_namespace_finalize(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Namespace body: (required)
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_namespace_finalize" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_namespace_finalize`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_namespace_finalize`")
resource_path = '/api/v1/namespaces/{name}/finalize'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Namespace',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_namespace_status(self, body, name, **kwargs):
"""
replace status of the specified Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_namespace_status(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Namespace body: (required)
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Namespace
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_namespace_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_namespace_status`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_namespace_status`")
resource_path = '/api/v1/namespaces/{name}/status'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Namespace',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_node(self, **kwargs):
"""
list or watch objects of kind Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_node(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1NodeList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_node" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/nodes'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1NodeList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_node(self, body, **kwargs):
"""
create a Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_node(body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Node body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_node`")
resource_path = '/api/v1/nodes'.replace('{format}', 'json')
method = 'POST'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Node',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_node(self, **kwargs):
"""
delete collection of Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_node(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_node" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/nodes'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_node(self, name, **kwargs):
"""
read the specified Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_node(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_node`")
resource_path = '/api/v1/nodes/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Node',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_node(self, body, name, **kwargs):
"""
replace the specified Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_node(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Node body: (required)
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_node`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_node`")
resource_path = '/api/v1/nodes/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Node',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_node(self, body, name, **kwargs):
"""
delete a Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_node(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_node`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_node`")
resource_path = '/api/v1/nodes/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_node(self, body, name, **kwargs):
"""
partially update the specified Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_node(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_node`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_node`")
resource_path = '/api/v1/nodes/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Node',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_node_status(self, body, name, **kwargs):
"""
replace status of the specified Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_node_status(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1Node body: (required)
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1Node
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_node_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_node_status`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_node_status`")
resource_path = '/api/v1/nodes/{name}/status'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1Node',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_persistent_volume_claim(self, **kwargs):
"""
list or watch objects of kind PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_persistent_volume_claim(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1PersistentVolumeClaimList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/persistentvolumeclaims'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeClaimList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_namespaced_persistent_volume(self, **kwargs):
"""
list or watch objects of kind PersistentVolume
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_namespaced_persistent_volume(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1PersistentVolumeList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_namespaced_persistent_volume" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/persistentvolumes'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolumeList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def create_namespaced_persistent_volume(self, body, **kwargs):
"""
create a PersistentVolume
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_namespaced_persistent_volume(body, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1PersistentVolume body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method create_namespaced_persistent_volume" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `create_namespaced_persistent_volume`")
resource_path = '/api/v1/persistentvolumes'.replace('{format}', 'json')
method = 'POST'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolume',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def deletecollection_namespaced_persistent_volume(self, **kwargs):
"""
delete collection of PersistentVolume
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.deletecollection_namespaced_persistent_volume(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method deletecollection_namespaced_persistent_volume" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/persistentvolumes'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def read_namespaced_persistent_volume(self, name, **kwargs):
"""
read the specified PersistentVolume
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.read_namespaced_persistent_volume(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool export: Should this value be exported. Export strips fields that a user can not specify.
:param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'pretty', 'export', 'exact']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method read_namespaced_persistent_volume" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `read_namespaced_persistent_volume`")
resource_path = '/api/v1/persistentvolumes/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'export' in params:
query_params['export'] = params['export']
if 'exact' in params:
query_params['exact'] = params['exact']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolume',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_persistent_volume(self, body, name, **kwargs):
"""
replace the specified PersistentVolume
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_persistent_volume(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1PersistentVolume body: (required)
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_persistent_volume" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_persistent_volume`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_persistent_volume`")
resource_path = '/api/v1/persistentvolumes/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolume',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def delete_namespaced_persistent_volume(self, body, name, **kwargs):
"""
delete a PersistentVolume
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_namespaced_persistent_volume(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1DeleteOptions body: (required)
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: UnversionedStatus
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_namespaced_persistent_volume" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `delete_namespaced_persistent_volume`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `delete_namespaced_persistent_volume`")
resource_path = '/api/v1/persistentvolumes/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='UnversionedStatus',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def patch_namespaced_persistent_volume(self, body, name, **kwargs):
"""
partially update the specified PersistentVolume
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.patch_namespaced_persistent_volume(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param UnversionedPatch body: (required)
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method patch_namespaced_persistent_volume" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `patch_namespaced_persistent_volume`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `patch_namespaced_persistent_volume`")
resource_path = '/api/v1/persistentvolumes/{name}'.replace('{format}', 'json')
method = 'PATCH'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolume',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def replace_namespaced_persistent_volume_status(self, body, name, **kwargs):
"""
replace status of the specified PersistentVolume
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.replace_namespaced_persistent_volume_status(body, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param V1PersistentVolume body: (required)
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V1PersistentVolume
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['body', 'name', 'pretty']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method replace_namespaced_persistent_volume_status" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError("Missing the required parameter `body` when calling `replace_namespaced_persistent_volume_status`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `replace_namespaced_persistent_volume_status`")
resource_path = '/api/v1/persistentvolumes/{name}/status'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
header_params = {}
form_params = {}
files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PersistentVolume',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_pod(self, **kwargs):
"""
list or watch objects of kind Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_pod(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1PodList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_pod" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/pods'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PodList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_pod_template(self, **kwargs):
"""
list or watch objects of kind PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_pod_template(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1PodTemplateList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_pod_template" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/podtemplates'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1PodTemplateList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_get_namespaced_pod(self, namespace, name, **kwargs):
"""
proxy GET requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_get_namespaced_pod(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_get_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_get_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_get_namespaced_pod`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_head_namespaced_pod(self, namespace, name, **kwargs):
"""
proxy HEAD requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_head_namespaced_pod(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_head_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_head_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_head_namespaced_pod`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'HEAD'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_put_namespaced_pod(self, namespace, name, **kwargs):
"""
proxy PUT requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_put_namespaced_pod(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_put_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_put_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_put_namespaced_pod`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_post_namespaced_pod(self, namespace, name, **kwargs):
"""
proxy POST requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_post_namespaced_pod(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_post_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_post_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_post_namespaced_pod`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_delete_namespaced_pod(self, namespace, name, **kwargs):
"""
proxy DELETE requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_delete_namespaced_pod(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_delete_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_delete_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_delete_namespaced_pod`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_options_namespaced_pod(self, namespace, name, **kwargs):
"""
proxy OPTIONS requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_options_namespaced_pod(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_options_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_options_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_options_namespaced_pod`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'OPTIONS'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_get_namespaced_pod_7(self, namespace, name, path, **kwargs):
"""
proxy GET requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_get_namespaced_pod_7(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_get_namespaced_pod_7" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_get_namespaced_pod_7`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_get_namespaced_pod_7`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_get_namespaced_pod_7`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}/{path}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_head_namespaced_pod_8(self, namespace, name, path, **kwargs):
"""
proxy HEAD requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_head_namespaced_pod_8(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_head_namespaced_pod_8" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_head_namespaced_pod_8`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_head_namespaced_pod_8`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_head_namespaced_pod_8`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}/{path}'.replace('{format}', 'json')
method = 'HEAD'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_put_namespaced_pod_9(self, namespace, name, path, **kwargs):
"""
proxy PUT requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_put_namespaced_pod_9(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_put_namespaced_pod_9" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_put_namespaced_pod_9`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_put_namespaced_pod_9`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_put_namespaced_pod_9`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}/{path}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_post_namespaced_pod_10(self, namespace, name, path, **kwargs):
"""
proxy POST requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_post_namespaced_pod_10(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_post_namespaced_pod_10" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_post_namespaced_pod_10`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_post_namespaced_pod_10`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_post_namespaced_pod_10`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}/{path}'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_delete_namespaced_pod_11(self, namespace, name, path, **kwargs):
"""
proxy DELETE requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_delete_namespaced_pod_11(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_delete_namespaced_pod_11" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_delete_namespaced_pod_11`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_delete_namespaced_pod_11`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_delete_namespaced_pod_11`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}/{path}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_options_namespaced_pod_12(self, namespace, name, path, **kwargs):
"""
proxy OPTIONS requests to Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_options_namespaced_pod_12(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_options_namespaced_pod_12" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_options_namespaced_pod_12`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_options_namespaced_pod_12`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_options_namespaced_pod_12`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/pods/{name}/{path}'.replace('{format}', 'json')
method = 'OPTIONS'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_get_namespaced_service(self, namespace, name, **kwargs):
"""
proxy GET requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_get_namespaced_service(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_get_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_get_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_get_namespaced_service`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_head_namespaced_service(self, namespace, name, **kwargs):
"""
proxy HEAD requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_head_namespaced_service(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_head_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_head_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_head_namespaced_service`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'HEAD'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_put_namespaced_service(self, namespace, name, **kwargs):
"""
proxy PUT requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_put_namespaced_service(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_put_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_put_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_put_namespaced_service`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_post_namespaced_service(self, namespace, name, **kwargs):
"""
proxy POST requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_post_namespaced_service(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_post_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_post_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_post_namespaced_service`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_delete_namespaced_service(self, namespace, name, **kwargs):
"""
proxy DELETE requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_delete_namespaced_service(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_delete_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_delete_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_delete_namespaced_service`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_options_namespaced_service(self, namespace, name, **kwargs):
"""
proxy OPTIONS requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_options_namespaced_service(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_options_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_options_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_options_namespaced_service`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'OPTIONS'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_get_namespaced_service_13(self, namespace, name, path, **kwargs):
"""
proxy GET requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_get_namespaced_service_13(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_get_namespaced_service_13" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_get_namespaced_service_13`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_get_namespaced_service_13`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_get_namespaced_service_13`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}/{path}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_head_namespaced_service_14(self, namespace, name, path, **kwargs):
"""
proxy HEAD requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_head_namespaced_service_14(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_head_namespaced_service_14" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_head_namespaced_service_14`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_head_namespaced_service_14`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_head_namespaced_service_14`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}/{path}'.replace('{format}', 'json')
method = 'HEAD'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_put_namespaced_service_15(self, namespace, name, path, **kwargs):
"""
proxy PUT requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_put_namespaced_service_15(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_put_namespaced_service_15" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_put_namespaced_service_15`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_put_namespaced_service_15`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_put_namespaced_service_15`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}/{path}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_post_namespaced_service_16(self, namespace, name, path, **kwargs):
"""
proxy POST requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_post_namespaced_service_16(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_post_namespaced_service_16" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_post_namespaced_service_16`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_post_namespaced_service_16`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_post_namespaced_service_16`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}/{path}'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_delete_namespaced_service_17(self, namespace, name, path, **kwargs):
"""
proxy DELETE requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_delete_namespaced_service_17(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_delete_namespaced_service_17" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_delete_namespaced_service_17`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_delete_namespaced_service_17`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_delete_namespaced_service_17`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}/{path}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_options_namespaced_service_18(self, namespace, name, path, **kwargs):
"""
proxy OPTIONS requests to Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_options_namespaced_service_18(namespace, name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_options_namespaced_service_18" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `proxy_options_namespaced_service_18`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_options_namespaced_service_18`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_options_namespaced_service_18`")
resource_path = '/api/v1/proxy/namespaces/{namespace}/services/{name}/{path}'.replace('{format}', 'json')
method = 'OPTIONS'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_get_namespaced_node(self, name, **kwargs):
"""
proxy GET requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_get_namespaced_node(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_get_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_get_namespaced_node`")
resource_path = '/api/v1/proxy/nodes/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_head_namespaced_node(self, name, **kwargs):
"""
proxy HEAD requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_head_namespaced_node(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_head_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_head_namespaced_node`")
resource_path = '/api/v1/proxy/nodes/{name}'.replace('{format}', 'json')
method = 'HEAD'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_put_namespaced_node(self, name, **kwargs):
"""
proxy PUT requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_put_namespaced_node(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_put_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_put_namespaced_node`")
resource_path = '/api/v1/proxy/nodes/{name}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_post_namespaced_node(self, name, **kwargs):
"""
proxy POST requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_post_namespaced_node(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_post_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_post_namespaced_node`")
resource_path = '/api/v1/proxy/nodes/{name}'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_delete_namespaced_node(self, name, **kwargs):
"""
proxy DELETE requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_delete_namespaced_node(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_delete_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_delete_namespaced_node`")
resource_path = '/api/v1/proxy/nodes/{name}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_options_namespaced_node(self, name, **kwargs):
"""
proxy OPTIONS requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_options_namespaced_node(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_options_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_options_namespaced_node`")
resource_path = '/api/v1/proxy/nodes/{name}'.replace('{format}', 'json')
method = 'OPTIONS'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_get_namespaced_node_19(self, name, path, **kwargs):
"""
proxy GET requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_get_namespaced_node_19(name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_get_namespaced_node_19" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_get_namespaced_node_19`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_get_namespaced_node_19`")
resource_path = '/api/v1/proxy/nodes/{name}/{path}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_head_namespaced_node_20(self, name, path, **kwargs):
"""
proxy HEAD requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_head_namespaced_node_20(name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_head_namespaced_node_20" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_head_namespaced_node_20`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_head_namespaced_node_20`")
resource_path = '/api/v1/proxy/nodes/{name}/{path}'.replace('{format}', 'json')
method = 'HEAD'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_put_namespaced_node_21(self, name, path, **kwargs):
"""
proxy PUT requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_put_namespaced_node_21(name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_put_namespaced_node_21" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_put_namespaced_node_21`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_put_namespaced_node_21`")
resource_path = '/api/v1/proxy/nodes/{name}/{path}'.replace('{format}', 'json')
method = 'PUT'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_post_namespaced_node_22(self, name, path, **kwargs):
"""
proxy POST requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_post_namespaced_node_22(name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_post_namespaced_node_22" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_post_namespaced_node_22`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_post_namespaced_node_22`")
resource_path = '/api/v1/proxy/nodes/{name}/{path}'.replace('{format}', 'json')
method = 'POST'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_delete_namespaced_node_23(self, name, path, **kwargs):
"""
proxy DELETE requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_delete_namespaced_node_23(name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_delete_namespaced_node_23" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_delete_namespaced_node_23`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_delete_namespaced_node_23`")
resource_path = '/api/v1/proxy/nodes/{name}/{path}'.replace('{format}', 'json')
method = 'DELETE'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def proxy_options_namespaced_node_24(self, name, path, **kwargs):
"""
proxy OPTIONS requests to Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.proxy_options_namespaced_node_24(name, path, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:param str path: path to the resource (required)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'path']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method proxy_options_namespaced_node_24" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `proxy_options_namespaced_node_24`")
# verify the required parameter 'path' is set
if ('path' not in params) or (params['path'] is None):
raise ValueError("Missing the required parameter `path` when calling `proxy_options_namespaced_node_24`")
resource_path = '/api/v1/proxy/nodes/{name}/{path}'.replace('{format}', 'json')
method = 'OPTIONS'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'path' in params:
path_params['path'] = params['path']
query_params = {}
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_replication_controller(self, **kwargs):
"""
list or watch objects of kind ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_replication_controller(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1ReplicationControllerList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_replication_controller" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/replicationcontrollers'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ReplicationControllerList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_resource_quota(self, **kwargs):
"""
list or watch objects of kind ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_resource_quota(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1ResourceQuotaList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_resource_quota" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/resourcequotas'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ResourceQuotaList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_secret(self, **kwargs):
"""
list or watch objects of kind Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_secret(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1SecretList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_secret" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/secrets'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1SecretList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_service_account(self, **kwargs):
"""
list or watch objects of kind ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_service_account(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1ServiceAccountList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_service_account" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/serviceaccounts'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ServiceAccountList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def list_service(self, **kwargs):
"""
list or watch objects of kind Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_service(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: V1ServiceList
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method list_service" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/services'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='V1ServiceList',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_endpoints_list(self, **kwargs):
"""
watch individual changes to a list of Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_endpoints_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_endpoints_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/endpoints'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_event_list(self, **kwargs):
"""
watch individual changes to a list of Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_event_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_event_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/events'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_limit_range_list(self, **kwargs):
"""
watch individual changes to a list of LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_limit_range_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_limit_range_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/limitranges'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_namespace_list(self, **kwargs):
"""
watch individual changes to a list of Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_namespace_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_namespace_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/namespaces'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_endpoints_list(self, namespace, **kwargs):
"""
watch individual changes to a list of Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_endpoints_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_endpoints_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_endpoints_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/endpoints'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_endpoints(self, namespace, name, **kwargs):
"""
watch changes to an object of kind Endpoints
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_endpoints(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Endpoints (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_endpoints" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_endpoints`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_endpoints`")
resource_path = '/api/v1/watch/namespaces/{namespace}/endpoints/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_event_list(self, namespace, **kwargs):
"""
watch individual changes to a list of Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_event_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_event_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_event_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/events'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_event(self, namespace, name, **kwargs):
"""
watch changes to an object of kind Event
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_event(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Event (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_event" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_event`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_event`")
resource_path = '/api/v1/watch/namespaces/{namespace}/events/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_limit_range_list(self, namespace, **kwargs):
"""
watch individual changes to a list of LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_limit_range_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_limit_range_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_limit_range_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/limitranges'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_limit_range(self, namespace, name, **kwargs):
"""
watch changes to an object of kind LimitRange
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_limit_range(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the LimitRange (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_limit_range" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_limit_range`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_limit_range`")
resource_path = '/api/v1/watch/namespaces/{namespace}/limitranges/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_persistent_volume_claim_list(self, namespace, **kwargs):
"""
watch individual changes to a list of PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_persistent_volume_claim_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_persistent_volume_claim_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_persistent_volume_claim_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/persistentvolumeclaims'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_persistent_volume_claim(self, namespace, name, **kwargs):
"""
watch changes to an object of kind PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_persistent_volume_claim(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PersistentVolumeClaim (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_persistent_volume_claim" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_persistent_volume_claim`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_persistent_volume_claim`")
resource_path = '/api/v1/watch/namespaces/{namespace}/persistentvolumeclaims/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_pod_list(self, namespace, **kwargs):
"""
watch individual changes to a list of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_pod_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_pod_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_pod_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/pods'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_pod(self, namespace, name, **kwargs):
"""
watch changes to an object of kind Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_pod(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Pod (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_pod" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_pod`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_pod`")
resource_path = '/api/v1/watch/namespaces/{namespace}/pods/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_pod_template_list(self, namespace, **kwargs):
"""
watch individual changes to a list of PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_pod_template_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_pod_template_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_pod_template_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/podtemplates'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_pod_template(self, namespace, name, **kwargs):
"""
watch changes to an object of kind PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_pod_template(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the PodTemplate (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_pod_template" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_pod_template`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_pod_template`")
resource_path = '/api/v1/watch/namespaces/{namespace}/podtemplates/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_replication_controller_list(self, namespace, **kwargs):
"""
watch individual changes to a list of ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_replication_controller_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_replication_controller_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_replication_controller_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/replicationcontrollers'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_replication_controller(self, namespace, name, **kwargs):
"""
watch changes to an object of kind ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_replication_controller(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ReplicationController (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_replication_controller" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_replication_controller`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_replication_controller`")
resource_path = '/api/v1/watch/namespaces/{namespace}/replicationcontrollers/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_resource_quota_list(self, namespace, **kwargs):
"""
watch individual changes to a list of ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_resource_quota_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_resource_quota_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_resource_quota_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/resourcequotas'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_resource_quota(self, namespace, name, **kwargs):
"""
watch changes to an object of kind ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_resource_quota(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ResourceQuota (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_resource_quota" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_resource_quota`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_resource_quota`")
resource_path = '/api/v1/watch/namespaces/{namespace}/resourcequotas/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_secret_list(self, namespace, **kwargs):
"""
watch individual changes to a list of Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_secret_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_secret_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_secret_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/secrets'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_secret(self, namespace, name, **kwargs):
"""
watch changes to an object of kind Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_secret(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Secret (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_secret" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_secret`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_secret`")
resource_path = '/api/v1/watch/namespaces/{namespace}/secrets/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_service_account_list(self, namespace, **kwargs):
"""
watch individual changes to a list of ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_service_account_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_service_account_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_service_account_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/serviceaccounts'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_service_account(self, namespace, name, **kwargs):
"""
watch changes to an object of kind ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_service_account(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the ServiceAccount (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_service_account" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_service_account`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_service_account`")
resource_path = '/api/v1/watch/namespaces/{namespace}/serviceaccounts/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_service_list(self, namespace, **kwargs):
"""
watch individual changes to a list of Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_service_list(namespace, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_service_list" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_service_list`")
resource_path = '/api/v1/watch/namespaces/{namespace}/services'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_service(self, namespace, name, **kwargs):
"""
watch changes to an object of kind Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_service(namespace, name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param str name: name of the Service (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_service" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError("Missing the required parameter `namespace` when calling `watch_namespaced_service`")
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_service`")
resource_path = '/api/v1/watch/namespaces/{namespace}/services/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_namespace(self, name, **kwargs):
"""
watch changes to an object of kind Namespace
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_namespace(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Namespace (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_namespace" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_namespace`")
resource_path = '/api/v1/watch/namespaces/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_node_list(self, **kwargs):
"""
watch individual changes to a list of Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_node_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_node_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/nodes'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_node(self, name, **kwargs):
"""
watch changes to an object of kind Node
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_node(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the Node (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_node" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_node`")
resource_path = '/api/v1/watch/nodes/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_persistent_volume_claim_list(self, **kwargs):
"""
watch individual changes to a list of PersistentVolumeClaim
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_persistent_volume_claim_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_persistent_volume_claim_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/persistentvolumeclaims'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_persistent_volume_list(self, **kwargs):
"""
watch individual changes to a list of PersistentVolume
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_persistent_volume_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_persistent_volume_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/persistentvolumes'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_namespaced_persistent_volume(self, name, **kwargs):
"""
watch changes to an object of kind PersistentVolume
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_namespaced_persistent_volume(name, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str name: name of the PersistentVolume (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_namespaced_persistent_volume" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError("Missing the required parameter `name` when calling `watch_namespaced_persistent_volume`")
resource_path = '/api/v1/watch/persistentvolumes/{name}'.replace('{format}', 'json')
method = 'GET'
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_pod_list(self, **kwargs):
"""
watch individual changes to a list of Pod
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_pod_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_pod_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/pods'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_pod_template_list(self, **kwargs):
"""
watch individual changes to a list of PodTemplate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_pod_template_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_pod_template_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/podtemplates'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_replication_controller_list(self, **kwargs):
"""
watch individual changes to a list of ReplicationController
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_replication_controller_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_replication_controller_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/replicationcontrollers'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_resource_quota_list(self, **kwargs):
"""
watch individual changes to a list of ResourceQuota
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_resource_quota_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_resource_quota_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/resourcequotas'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_secret_list(self, **kwargs):
"""
watch individual changes to a list of Secret
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_secret_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_secret_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/secrets'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_service_account_list(self, **kwargs):
"""
watch individual changes to a list of ServiceAccount
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_service_account_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_service_account_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/serviceaccounts'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
def watch_service_list(self, **kwargs):
"""
watch individual changes to a list of Service
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.watch_service_list(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str pretty: If 'true', then the output is pretty printed.
:param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything.
:param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything.
:param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion.
:param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history.
:param int timeout_seconds: Timeout for the list/watch call.
:return: JsonWatchEvent
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['pretty', 'label_selector', 'field_selector', 'watch', 'resource_version', 'timeout_seconds']
all_params.append('callback')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method watch_service_list" % key
)
params[key] = val
del params['kwargs']
resource_path = '/api/v1/watch/services'.replace('{format}', 'json')
method = 'GET'
path_params = {}
query_params = {}
if 'pretty' in params:
query_params['pretty'] = params['pretty']
if 'label_selector' in params:
query_params['labelSelector'] = params['label_selector']
if 'field_selector' in params:
query_params['fieldSelector'] = params['field_selector']
if 'watch' in params:
query_params['watch'] = params['watch']
if 'resource_version' in params:
query_params['resourceVersion'] = params['resource_version']
if 'timeout_seconds' in params:
query_params['timeoutSeconds'] = params['timeout_seconds']
header_params = {}
form_params = {}
files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = []
response = self.api_client.call_api(resource_path, method,
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=files,
response_type='JsonWatchEvent',
auth_settings=auth_settings,
callback=params.get('callback'))
return response
| apache-2.0 | -1,206,368,449,628,720,000 | 41.895263 | 322 | 0.549097 | false | 5.059851 | false | false | false |
btenaglia/hpc-historias-clinicas | hpc-historias-clinicas/ayudantes/views.py | 1 | 1147 | # -*- coding: utf-8 -*-
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from django.contrib import messages
from braces.views import LoginRequiredMixin
from .models import Ayudantes
class AyudantesMixin(object):
@property
def success_msg(self):
return NotImplemented
def get_success_url(self):
messages.success(self.request, self.success_msg)
return super(AyudantesMixin, self).get_success_url()
class AyudantesListView(LoginRequiredMixin, ListView):
"""
Lista todos los ayudantes
"""
model = Ayudantes
class AyudantesCreateView(LoginRequiredMixin, AyudantesMixin, CreateView):
"""
Creacion de medico
"""
model = Ayudantes
success_msg = 'El ayudante se agregó correctamente.'
class AyudantesUpdateView(LoginRequiredMixin, AyudantesMixin, UpdateView):
"""
Modificacion de un ayudante
"""
model = Ayudantes
success_msg = 'El ayudante se editó correctamente.'
class AyudantesDeleteView(LoginRequiredMixin, DeleteView):
"""
Eliminar un ayudante
"""
model = Ayudantes
success_url = '/ayudantes/' | bsd-3-clause | -2,561,103,147,593,230,000 | 22.875 | 77 | 0.708297 | false | 3.309249 | false | false | false |
tjcsl/ion | intranet/apps/eighth/views/admin/hybrid.py | 1 | 11270 | import logging
from typing import Optional
from formtools.wizard.views import SessionWizardView
from django import http
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect, render, reverse
from ....auth.decorators import eighth_admin_required
from ....users.models import Group
from ...forms.admin.activities import HybridActivitySelectionForm
from ...forms.admin.blocks import HybridBlockSelectionForm
from ...models import EighthBlock, EighthScheduledActivity, EighthSignup, EighthSponsor
from ...tasks import eighth_admin_signup_group_task_hybrid
from ...utils import get_start_date
logger = logging.getLogger(__name__)
@eighth_admin_required
def activities_without_attendance_view(request):
blocks_set = set()
for b in EighthBlock.objects.filter(
eighthscheduledactivity__in=EighthScheduledActivity.objects.filter(activity__name="z - Hybrid Sticky")
).filter(date__gte=get_start_date(request)):
blocks_set.add((str(b.date), b.block_letter[0]))
blocks = sorted(list(blocks_set))
block_id = request.GET.get("block", None)
block = None
if block_id is not None:
try:
block_id = tuple(block_id.split(","))
block = EighthBlock.objects.filter(date=block_id[0], block_letter__contains=block_id[1])
except (EighthBlock.DoesNotExist, ValueError):
pass
context = {"blocks": blocks, "chosen_block": block_id, "hybrid_blocks": block}
if block is not None:
start_date = get_start_date(request)
scheduled_activities = None
for b in block:
if scheduled_activities is not None:
scheduled_activities = scheduled_activities | b.eighthscheduledactivity_set.filter(
block__date__gte=start_date, attendance_taken=False
).order_by(
"-activity__special", "activity__name"
) # float special to top
else:
scheduled_activities = b.eighthscheduledactivity_set.filter(block__date__gte=start_date, attendance_taken=False).order_by(
"-activity__special", "activity__name"
) # float special to top
context["scheduled_activities"] = scheduled_activities
if request.POST.get("take_attendance_zero", False) is not False:
zero_students = scheduled_activities.filter(members=None)
signups = EighthSignup.objects.filter(scheduled_activity__in=zero_students)
logger.debug(zero_students)
if signups.count() == 0:
zero_students.update(attendance_taken=True)
messages.success(request, "Took attendance for {} empty activities.".format(zero_students.count()))
else:
messages.error(request, "Apparently there were actually {} signups. Maybe one is no longer empty?".format(signups.count()))
return redirect("/eighth/admin/hybrid/no_attendance?block={},{}".format(block_id[0], block_id[1]))
if request.POST.get("take_attendance_cancelled", False) is not False:
cancelled = scheduled_activities.filter(cancelled=True)
signups = EighthSignup.objects.filter(scheduled_activity__in=cancelled)
logger.debug(cancelled)
logger.debug(signups)
signups.update(was_absent=True)
cancelled.update(attendance_taken=True)
messages.success(
request, "Took attendance for {} cancelled activities. {} students marked absent.".format(cancelled.count(), signups.count())
)
return redirect("/eighth/admin/hybrid/no_attendance?block={},{}".format(block_id[0], block_id[1]))
context["admin_page_title"] = "Hybrid Activities That Haven't Taken Attendance"
return render(request, "eighth/admin/activities_without_attendance_hybrid.html", context)
@eighth_admin_required
def list_sponsor_view(request):
block_id = request.GET.get("block", None)
block = None
blocks_set = set()
for b in EighthBlock.objects.filter(
eighthscheduledactivity__in=EighthScheduledActivity.objects.filter(activity__name="z - Hybrid Sticky").filter(
block__date__gte=get_start_date(request)
)
):
blocks_set.add((str(b.date), b.block_letter[0]))
blocks = sorted(list(blocks_set))
if block_id is not None:
try:
block_id = tuple(block_id.split(","))
block = EighthBlock.objects.filter(date=block_id[0], block_letter__contains=block_id[1])
except (EighthBlock.DoesNotExist, ValueError):
pass
context = {"blocks": blocks, "chosen_block": block_id, "hybrid_blocks": block}
if block is not None:
acts = EighthScheduledActivity.objects.filter(block__in=block)
lst = {}
for sponsor in EighthSponsor.objects.all():
lst[sponsor] = []
for act in acts.prefetch_related("sponsors").prefetch_related("rooms"):
for sponsor in act.get_true_sponsors():
lst[sponsor].append(act)
lst = sorted(lst.items(), key=lambda x: x[0].name)
context["sponsor_list"] = lst
context["admin_page_title"] = "Hybrid Sponsor Schedule List"
return render(request, "eighth/admin/list_sponsors_hybrid.html", context)
class EighthAdminSignUpGroupWizard(SessionWizardView):
FORMS = [("block", HybridBlockSelectionForm), ("activity", HybridActivitySelectionForm)]
TEMPLATES = {"block": "eighth/admin/sign_up_group.html", "activity": "eighth/admin/sign_up_group.html"}
def get_template_names(self):
return [self.TEMPLATES[self.steps.current]]
def get_form_kwargs(self, step=None):
kwargs = {}
if step == "block":
kwargs.update({"exclude_before_date": get_start_date(self.request)})
if step == "activity":
block = self.get_cleaned_data_for_step("block")["block"]
kwargs.update({"block": block})
labels = {"block": "Select a block", "activity": "Select an activity"}
kwargs.update({"label": labels[step]})
return kwargs
def get_context_data(self, form, **kwargs):
context = super().get_context_data(form=form, **kwargs)
block = self.get_cleaned_data_for_step("block")
if block:
context.update({"block_obj": (block["block"][2:12], block["block"][16])})
context.update({"admin_page_title": "Sign Up Group", "hybrid": True})
return context
def done(self, form_list, **kwargs):
form_list = list(form_list)
block = form_list[0].cleaned_data["block"]
block_set = EighthBlock.objects.filter(date=block[2:12], block_letter__contains=block[16])
virtual_block = block_set.filter(block_letter__contains="V")[0]
person_block = block_set.filter(block_letter__contains="P")[0]
activity = form_list[1].cleaned_data["activity"]
scheduled_activity_virtual = EighthScheduledActivity.objects.get(block=virtual_block, activity=activity)
scheduled_activity_person = EighthScheduledActivity.objects.get(block=person_block, activity=activity)
try:
group = Group.objects.get(id=kwargs["group_id"])
except Group.DoesNotExist as e:
raise http.Http404 from e
return redirect(
reverse("eighth_admin_signup_group_action_hybrid", args=[group.id, scheduled_activity_virtual.id, scheduled_activity_person.id])
)
eighth_admin_signup_group_hybrid_view = eighth_admin_required(EighthAdminSignUpGroupWizard.as_view(EighthAdminSignUpGroupWizard.FORMS))
def eighth_admin_signup_group_action_hybrid(request, group_id, schact_virtual_id, schact_person_id):
scheduled_activity_virtual = get_object_or_404(EighthScheduledActivity, id=schact_virtual_id)
scheduled_activity_person = get_object_or_404(EighthScheduledActivity, id=schact_person_id)
group = get_object_or_404(Group, id=group_id)
users = group.user_set.all()
if not users.exists():
messages.info(request, "The group you have selected has no members.")
return redirect("eighth_admin_dashboard")
if "confirm" in request.POST:
if request.POST.get("run_in_background"):
eighth_admin_signup_group_task_hybrid.delay(
user_id=request.user.id, group_id=group_id, schact_virtual_id=schact_virtual_id, schact_person_id=schact_person_id
)
messages.success(request, "Group members are being signed up in the background.")
return redirect("eighth_admin_dashboard")
else:
eighth_admin_perform_group_signup(
group_id=group_id, schact_virtual_id=schact_virtual_id, schact_person_id=schact_person_id, request=request
)
messages.success(request, "Successfully signed up group for activity.")
return redirect("eighth_admin_dashboard")
return render(
request,
"eighth/admin/sign_up_group.html",
{
"admin_page_title": "Confirm Group Signup",
"hybrid": True,
"scheduled_activity_virtual": scheduled_activity_virtual,
"scheduled_activity_person": scheduled_activity_person,
"group": group,
"users_num": users.count(),
},
)
def eighth_admin_perform_group_signup(*, group_id: int, schact_virtual_id: int, schact_person_id: int, request: Optional[http.HttpRequest]):
"""Performs sign up of all users in a specific group up for a
specific scheduled activity.
Args:
group_id: The ID of the group that should be signed up for the activity.
schact_virtual_id: The ID of the EighthScheduledActivity all the virtual users in the group
should be signed up for.
schact_person_id: The ID of the EighthScheduledActivity all the in-person users in the group
should be signed up for.
request: If possible, the request object associated with the operation.
"""
# We assume these exist
scheduled_activity_virtual = EighthScheduledActivity.objects.get(id=schact_virtual_id)
scheduled_activity_person = EighthScheduledActivity.objects.get(id=schact_person_id)
group = Group.objects.get(id=group_id)
is_P1_block = "P1" in scheduled_activity_person.block.block_letter
virtual_group = Group.objects.get(name="virtual").user_set.all()
person_group = Group.objects.get(name="in-person").user_set.all()
if is_P1_block:
virtual_group = virtual_group.union(Group.objects.get(name="in-person (l-z)").user_set.all())
person_group = person_group.union(Group.objects.get(name="in-person (a-k)").user_set.all())
else:
virtual_group = virtual_group.union(Group.objects.get(name="in-person (a-k)").user_set.all())
person_group = person_group.union(Group.objects.get(name="in-person (l-z)").user_set.all())
for user in group.user_set.all():
if user in virtual_group:
scheduled_activity_virtual.add_user(user, request=request, force=True, no_after_deadline=True)
elif user in person_group:
scheduled_activity_person.add_user(user, request=request, force=True, no_after_deadline=True)
| gpl-2.0 | -1,466,880,286,373,412,900 | 43.196078 | 141 | 0.65732 | false | 3.690242 | false | false | false |
LarsFronius/ansible | lib/ansible/plugins/callback/foreman.py | 20 | 7129 | # -*- coding: utf-8 -*-
# (C) 2015, 2016 Daniel Lobato <[email protected]>
# 2016 Guido Günther <[email protected]>
#
# 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/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from datetime import datetime
from collections import defaultdict
import json
import time
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
from ansible.plugins.callback import CallbackBase
class CallbackModule(CallbackBase):
"""
This callback will report facts and reports to Foreman https://theforeman.org/
It makes use of the following environment variables:
FOREMAN_URL: URL to the Foreman server
FOREMAN_SSL_CERT: X509 certificate to authenticate to Foreman if
https is used
FOREMAN_SSL_KEY: the corresponding private key
FOREMAN_SSL_VERIFY: whether to verify the Foreman certificate
It can be set to '1' to verify SSL certificates using the
installed CAs or to a path pointing to a CA bundle. Set to '0'
to disable certificate checking.
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'notification'
CALLBACK_NAME = 'foreman'
CALLBACK_NEEDS_WHITELIST = True
FOREMAN_URL = os.getenv('FOREMAN_URL', "http://localhost:3000")
FOREMAN_SSL_CERT = (os.getenv('FOREMAN_SSL_CERT',
"/etc/foreman/client_cert.pem"),
os.getenv('FOREMAN_SSL_KEY',
"/etc/foreman/client_key.pem"))
FOREMAN_SSL_VERIFY = os.getenv('FOREMAN_SSL_VERIFY', "1")
FOREMAN_HEADERS = {
"Content-Type": "application/json",
"Accept": "application/json"
}
TIME_FORMAT = "%Y-%m-%d %H:%M:%S %f"
def __init__(self):
super(CallbackModule, self).__init__()
self.items = defaultdict(list)
self.start_time = int(time.time())
if HAS_REQUESTS:
requests_major = int(requests.__version__.split('.')[0])
if requests_major >= 2:
self.ssl_verify = self._ssl_verify()
else:
self._disable_plugin('The `requests` python module is too old.')
else:
self._disable_plugin('The `requests` python module is not installed.')
def _disable_plugin(self, msg):
self.disabled = True
self._display.warning(msg + ' Disabling the Foreman callback plugin.')
def _ssl_verify(self):
if self.FOREMAN_SSL_VERIFY.lower() in ["1", "true", "on"]:
verify = True
elif self.FOREMAN_SSL_VERIFY.lower() in ["0", "false", "off"]:
requests.packages.urllib3.disable_warnings()
self._display.warning("SSL verification of %s disabled" %
self.FOREMAN_URL)
verify = False
else: # Set ta a CA bundle:
verify = self.FOREMAN_SSL_VERIFY
return verify
def send_facts(self, host, data):
"""
Sends facts to Foreman, to be parsed by foreman_ansible fact
parser. The default fact importer should import these facts
properly.
"""
data["_type"] = "ansible"
data["_timestamp"] = datetime.now().strftime(self.TIME_FORMAT)
facts = {"name": host,
"facts": data,
}
requests.post(url=self.FOREMAN_URL + '/api/v2/hosts/facts',
data=json.dumps(facts),
headers=self.FOREMAN_HEADERS,
cert=self.FOREMAN_SSL_CERT,
verify=self.ssl_verify)
def _build_log(self, data):
logs = []
for entry in data:
source, msg = entry
if 'failed' in msg:
level = 'err'
else:
level = 'notice' if 'changed' in msg and msg['changed'] else 'info'
logs.append({"log": {
'sources': {'source': source},
'messages': {'message': json.dumps(msg)},
'level': level
}})
return logs
def send_reports(self, stats):
"""
Send reports to Foreman to be parsed by its config report
importer. THe data is in a format that Foreman can handle
without writing another report importer.
"""
status = defaultdict(lambda: 0)
metrics = {}
for host in stats.processed.keys():
sum = stats.summarize(host)
status["applied"] = sum['changed']
status["failed"] = sum['failures'] + sum['unreachable']
status["skipped"] = sum['skipped']
log = self._build_log(self.items[host])
metrics["time"] = {"total": int(time.time()) - self.start_time}
now = datetime.now().strftime(self.TIME_FORMAT)
report = {
"report": {
"host": host,
"reported_at": now,
"metrics": metrics,
"status": status,
"logs": log,
}
}
# To be changed to /api/v2/config_reports in 1.11. Maybe we
# could make a GET request to get the Foreman version & do
# this automatically.
requests.post(url=self.FOREMAN_URL + '/api/v2/reports',
data=json.dumps(report),
headers=self.FOREMAN_HEADERS,
cert=self.FOREMAN_SSL_CERT,
verify=self.ssl_verify)
self.items[host] = []
def append_result(self, result):
name = result._task.get_name()
host = result._host.get_name()
self.items[host].append((name, result._result))
# Ansible callback API
def v2_runner_on_failed(self, result, ignore_errors=False):
self.append_result(result)
def v2_runner_on_unreachable(self, result):
self.append_result(result)
def v2_runner_on_async_ok(self, result, jid):
self.append_result(result)
def v2_runner_on_async_failed(self, result, jid):
self.append_result(result)
def v2_playbook_on_stats(self, stats):
self.send_reports(stats)
def v2_runner_on_ok(self, result):
res = result._result
module = result._task.action
if module == 'setup':
host = result._host.get_name()
self.send_facts(host, res)
else:
self.append_result(result)
| gpl-3.0 | 2,600,363,873,120,758,000 | 35 | 83 | 0.574214 | false | 4.03624 | false | false | false |
GeorgiMateev/twitter-user-gender-classification | notebooks/twitter/get_users_data.py | 1 | 1231 | import twitter
# Authentication parameters - fill manually! You need to create a Twitter app in dev.twitter.com
# in order to be given these OAUTH2 parameters for the authentication (mandatory) to your app
# Reference: https://aaronparecki.com/oauth-2-simplified/#creating-an-app (general example, but applies for twitter)
api = twitter.Api(
consumer_key='<consumer_key>',
consumer_secret='<consumer_secret>',
access_token_key='<access_token_key>',
access_token_secret='<access_token_secret>')
names_found_file = open('firstnames.txt', 'w')
names_found_file.write('#<first_name_if_found>=<username>')
sample = 0
for line in open('test/usernames.txt', 'r'):
try:
names_found_file.write(api.GetUser(screen_name='@' + line).__getattribute__('name') + '=' + line)
sample = sample + 1
names_found_file.flush()
# Verbose output for debugging
print(api.GetUser(screen_name='@' + line).__getattribute__('name') + '=' + line)
print(sample)
except:
names_found_file.write('=' + line)
sample = sample + 1
names_found_file.flush()
# Verbose outputfor debugging
print('=' + line)
print(sample)
names_found_file.close() | mit | 7,175,335,983,324,748,000 | 35.235294 | 116 | 0.651503 | false | 3.631268 | false | false | false |
ValliereMagic/TomatoPython | Main.py | 1 | 2974 | import pickle
import sqlite3
import Fruit
class Main:
def __init__(self):
self.fruit_list = Fruit.FruitList()
self.sqlite_db = None
self.run()
@staticmethod
def print_instructions():
print("Enter the number of an option to complete a task: \n",
"1.) Add a new fruit to the system \n",
"2.) Remove a fruit from the system \n",
"3.) Print all the fruits that exist in the system \n",
"4.) Print the description of a specific fruit \n",
"5.) Print the Instructions again \n",
"6.) Close the program")
@staticmethod
def connect_db():
rv = sqlite3.connect("db/tomato.db")
rv.row_factory = sqlite3.Row
return rv
def get_db(self):
if self.sqlite_db is None:
self.sqlite_db = self.connect_db()
return self.sqlite_db
def close_db(self, error=None):
if error:
print(error)
if self.sqlite_db is not None:
self.sqlite_db.close()
def init_db(self):
db = self.get_db()
with open("db/schema.sql", "r") as f:
db.cursor().executescript(f.read())
db.commit()
print("Database Initialized.")
@staticmethod
def serialize_object(obj):
return pickle.dumps(obj)
@staticmethod
def deserialize_object(bytes_obj):
return pickle.loads(bytes_obj)
def load_from_db(self):
try:
db = self.get_db()
cursor = db.execute("SELECT data FROM tomatoes ORDER BY id")
data = cursor.fetchone()
self.fruit_list = self.deserialize_object(data[0])
print("Loaded FruitList from database.")
except (TypeError, sqlite3.OperationalError):
self.init_db()
def dump_to_db(self):
db = self.get_db()
data = self.serialize_object(self.fruit_list)
db.execute("INSERT OR REPLACE INTO tomatoes (id, data) VALUES (?, ?)", [0, data])
db.commit()
print("FruitList saved to database.")
def run(self):
self.load_from_db()
self.print_instructions()
name_prompt = "Name of the fruit: \n"
while True:
try:
option = int(input())
except ValueError:
option = None
print("Invalid input")
if option == 1:
self.fruit_list.create_fruit()
self.dump_to_db()
elif option == 2:
self.fruit_list.remove_fruit(input(name_prompt))
self.dump_to_db()
elif option == 3:
print(self.fruit_list)
elif option == 4:
self.fruit_list.describe_fruit(input(name_prompt))
elif option == 5:
self.print_instructions()
elif option == 6:
break
if __name__ == '__main__':
Main()
| gpl-3.0 | 501,980,693,978,030,700 | 25.087719 | 89 | 0.5269 | false | 3.944297 | false | false | false |
rwgdrummer/maskgen | plugins/Crop/__init__.py | 1 | 1197 | import numpy
from maskgen.image_wrap import ImageWrapper
import cv2
def transform(img,source,target,**kwargs):
pixelWidth = int(kwargs['pixel_width'])
pixelHeight = int(kwargs['pixel_height'])
x = int(kwargs['crop_x'])
y = int(kwargs['crop_y'])
cv_image = numpy.array(img)
new_img = cv_image[y:-(pixelHeight-y), x:-(pixelWidth-x),:]
ImageWrapper(new_img).save(target)
return None,None
def suffix():
return None
def operation():
return {
'category': 'Transform',
'name': 'TransformCrop',
'description':'Crop',
'software':'OpenCV',
'version':cv2.__version__,
'arguments':{'crop_x': {'type': "int[0:100000]", 'description':'upper left corner vertical position'},
'crop_y': {'type': "int[0:100000]", 'description':'upper left corner horizontal position'},
'pixel_width': {'type': "int[0:100000]", 'description':'amount of pixels to remove horizontal'},
'pixel_height': {'type': "int[0:100000]", 'description':'amount of pixels to remove vertically'}},
'transitions': [
'image.image'
]
}
| bsd-3-clause | -7,159,309,722,363,650,000 | 36.40625 | 121 | 0.573935 | false | 3.911765 | false | false | false |
redmatter/combine | combine/manifest.py | 1 | 1719 | # Copyright (c) 2010 John Reese
# Licensed under the MIT license
import yaml
from combine import CombineError
MANIFEST_FORMAT = 1
class Manifest:
def __init__(self):
self.properties = {"manifest-format": MANIFEST_FORMAT}
self.actions = []
def __getitem__(self, key):
return self.properties[key]
def __contains__(self, key):
return key in self.properties
def add_property(self, name, value):
self.properties[name] = value
def add_action(self, action):
self.actions.append(action)
def to_dict(self):
"""
Generate a dictionary representation of the Manifest object.
"""
return dict(self.properties, actions=self.actions)
@classmethod
def from_dict(cls, data):
"""
Given a dictionary object, generate a new Manifest object.
"""
format = data["manifest-format"]
if (format > MANIFEST_FORMAT or format < 0):
raise CombineError("Unsupported manifest format")
mft = Manifest()
for key, value in data.items():
if key == "actions":
for action in value:
mft.add_action(dict(action))
else:
mft.add_property(key, value)
return mft
def to_yaml(self):
"""
Generate a YAML data string representing the Manifest object.
"""
str = yaml.safe_dump(self.to_dict(), default_flow_style=False)
return str
@classmethod
def from_yaml(cls, str):
"""
Given a string of YAML data, generate a new Manifest object.
"""
data = yaml.safe_load(str)
return cls.from_dict(data)
| mit | 3,079,288,446,139,151,400 | 22.875 | 70 | 0.577661 | false | 4.244444 | false | false | false |
kfarr2/django-local-settings | local_settings/loader.py | 1 | 4233 | import os
import re
from collections import Mapping, OrderedDict, Sequence
from six import string_types
from .base import Base
from .exc import SettingsFileNotFoundError
from .types import LocalSetting
from .util import NO_DEFAULT as PLACEHOLDER
class Loader(Base):
def __init__(self, file_name=None, section=None, extender=None):
super(Loader, self).__init__(file_name, section, extender)
if not os.path.exists(self.file_name):
raise SettingsFileNotFoundError(file_name)
# Registry of local settings with a value in the settings file
self.registry = {}
def read_file(self):
"""Read settings from specified ``section`` of config file."""
parser = self._make_parser()
with open(self.file_name) as fp:
parser.read_file(fp)
extends = parser[self.section].get('extends')
settings = OrderedDict()
if extends:
extends = self._parse_setting(extends, expand_vars=True)
if isinstance(extends, str):
extends = [extends]
for e in reversed(extends):
settings.update(self.__class__(e, extender=self).read_file())
settings_from_file = parser[self.section]
for k in settings:
if k in settings_from_file:
del settings[k]
settings.update(settings_from_file)
return settings
def load(self, base_settings):
"""Merge local settings from file with ``base_settings``.
Returns a new OrderedDict containing the base settings and the
loaded settings. Ordering is:
- base settings
- settings from extended file(s), if any
- settings from file
When a setting is overridden, it gets moved to the end.
"""
if not os.path.exists(self.file_name):
self.print_warning(
'Local settings file `{0}` not found'.format(self.file_name))
return
is_upper = lambda k: k == k.upper()
settings = OrderedDict((k, v) for (k, v) in base_settings.items() if is_upper(k))
for k, v in self.read_file().items():
names = k.split('.')
v = self._parse_setting(v, expand_vars=True)
obj = settings
for name, next_name in zip(names[:-1], names[1:]):
next_name = self._convert_name(next_name)
next_is_seq = isinstance(next_name, int)
default = [PLACEHOLDER] * (next_name + 1) if next_is_seq else {}
if isinstance(obj, Mapping):
if name not in obj:
obj[name] = default
elif isinstance(obj, Sequence):
name = int(name)
while name >= len(obj):
obj.append(PLACEHOLDER)
if obj[name] is PLACEHOLDER:
obj[name] = default
obj = obj[name]
name = self._convert_name(names[-1])
try:
curr_v = obj[name]
except (KeyError, IndexError):
pass
else:
if isinstance(curr_v, LocalSetting):
curr_v.value = v
self.registry[curr_v] = name
obj[name] = v
settings.move_to_end(names[0])
settings.pop('extends', None)
self._do_interpolation(settings, settings)
return settings
def _do_interpolation(self, v, settings):
if isinstance(v, string_types):
v = v.format(**settings)
elif isinstance(v, Mapping):
for k in v:
v[k] = self._do_interpolation(v[k], settings)
elif isinstance(v, Sequence):
v = v.__class__(self._do_interpolation(item, settings) for item in v)
return v
def _convert_name(self, name):
"""Convert ``name`` to int if it looks like an int.
Otherwise, return it as is.
"""
if re.search('^\d+$', name):
if len(name) > 1 and name[0] == '0':
# Don't treat strings beginning with "0" as ints
return name
return int(name)
return name
| mit | -1,325,149,308,229,342,700 | 35.808696 | 89 | 0.544767 | false | 4.288754 | false | false | false |
WmHHooper/aima-python | submissions/aardvark/myCSPs.py | 1 | 1655 | import csp
rgb = ['R', 'G', 'B']
d2 = { 'A' : rgb, 'B' : rgb, 'C' : ['R'], 'D' : rgb,}
v2 = d2.keys()
n2 = {'A' : ['B', 'C', 'D'],
'B' : ['A', 'C', 'D'],
'C' : ['A', 'B'],
'D' : ['A', 'B'],}
def constraints(A, a, B, b):
if A == B: # e.g. NSW == NSW
return True
if a == b: # e.g. WA = G and SA = G
return False
return True
c2 = csp.CSP(v2, d2, n2, constraints)
c2.label = 'Really Lame'
myCSPs = [
{
'csp' : c2,
# 'select_unassigned_variable': csp.mrv,
# 'order_domain_values': csp.lcv,
# 'inference': csp.mac,
# 'inference': csp.forward_checking,
},
{
'csp' : c2,
'select_unassigned_variable': csp.mrv,
# 'order_domain_values': csp.lcv,
# 'inference': csp.mac,
# 'inference': csp.forward_checking,
},
{
'csp' : c2,
# 'select_unassigned_variable': csp.mrv,
'order_domain_values': csp.lcv,
# 'inference': csp.mac,
# 'inference': csp.forward_checking,
},
{
'csp' : c2,
# 'select_unassigned_variable': csp.mrv,
# 'order_domain_values': csp.lcv,
'inference': csp.mac,
# 'inference': csp.forward_checking,
},
{
'csp' : c2,
# 'select_unassigned_variable': csp.mrv,
# 'order_domain_values': csp.lcv,
# 'inference': csp.mac,
'inference': csp.forward_checking,
},
{
'csp' : c2,
'select_unassigned_variable': csp.mrv,
'order_domain_values': csp.lcv,
'inference': csp.mac,
# 'inference': csp.forward_checking,
},
]
| mit | 2,727,498,772,143,534,000 | 22.985507 | 53 | 0.470695 | false | 2.772194 | false | false | false |
gg7/diamond | src/diamond/handler/test/testtsdb.py | 1 | 17036 | #!/usr/bin/python
# coding=utf-8
##########################################################################
from test import unittest
from mock import Mock
import configobj
from diamond.handler.tsdb import TSDBHandler
import diamond.handler.tsdb as mod
from diamond.metric import Metric
# These two methods are used for overriding the TSDBHandler._connect method.
# Please check the Test class' setUp and tearDown methods
def fake_connect(self):
# used for 'we can connect' tests
m = Mock()
self.socket = m
if '__sockets_created' not in self.config:
self.config['__sockets_created'] = [m]
else:
self.config['__sockets_created'].append(m)
def fake_bad_connect(self):
# used for 'we can not connect' tests
self.socket = None
class TestTSDBdHandler(unittest.TestCase):
def setUp(self):
self.__connect_method = mod.TSDBHandler
mod.TSDBHandler._connect = fake_connect
def tearDown(self):
# restore the override
mod.TSDBHandler._connect = self.__connect_method
def test_single_gauge(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
metric = Metric('servers.myhostname.cpu.cpu_count',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = ('put cpu.cpu_count 1234567 123 hostname=myhostname\n')
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_with_single_tag_no_space_in_front(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = 'myTag=myValue'
metric = Metric('servers.myhostname.cpu.cpu_count',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.cpu_count 1234567 123 hostname=myhostname '
expected_data += 'myTag=myValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_with_single_tag_space_in_front(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ' myTag=myValue'
metric = Metric('servers.myhostname.cpu.cpu_count',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.cpu_count 1234567 123 hostname=myhostname '
expected_data += 'myTag=myValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_with_multiple_tag_no_space_in_front(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = 'myTag=myValue mySecondTag=myOtherValue'
metric = Metric('servers.myhostname.cpu.cpu_count',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.cpu_count 1234567 123 hostname=myhostname '
expected_data += 'myTag=myValue mySecondTag=myOtherValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_with_multiple_tag_space_in_front(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ' myTag=myValue mySecondTag=myOtherValue'
metric = Metric('servers.myhostname.cpu.cpu_count',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.cpu_count 1234567 123 hostname=myhostname '
expected_data += 'myTag=myValue mySecondTag=myOtherValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_with_multiple_tag_no_space_in_front_comma(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue', 'mySecondTag=myOtherValue']
metric = Metric('servers.myhostname.cpu.cpu_count',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.cpu_count 1234567 123 hostname=myhostname '
expected_data += 'myFirstTag=myValue mySecondTag=myOtherValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_with_multiple_tag_no_space_in_front_comma_and_space(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue',
'mySecondTag=myOtherValue myThirdTag=yetAnotherVal']
metric = Metric('servers.myhostname.cpu.cpu_count',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.cpu_count 1234567 123 hostname=myhostname '
expected_data += 'myFirstTag=myValue mySecondTag=myOtherValue '
expected_data += 'myThirdTag=yetAnotherVal\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_cpu_metrics_taghandling_default(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
metric = Metric('servers.myhostname.cpu.cpu0.user',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.user 1234567 123 hostname=myhostname '
expected_data += 'myFirstTag=myValue cpuId=cpu0\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_cpu_metrics_taghandling_deactivate_so_old_values(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
config['cleanMetrics'] = False
metric = Metric('servers.myhostname.cpu.cpu0.user',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.cpu0.user 1234567 123 hostname=myhostname '
expected_data += 'myFirstTag=myValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_cpu_metrics_taghandling_aggregate_default(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
metric = Metric('servers.myhostname.cpu.total.user',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.user 1234567 123 hostname=myhostname '
expected_data += 'myFirstTag=myValue cpuId=cpu0\n'
handler = TSDBHandler(config)
handler.process(metric)
assert not handler.socket.sendall.called, "should not process"
def test_cpu_metrics_taghandling_aggregate_deactivate_so_old_values1(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
config['cleanMetrics'] = False
metric = Metric('servers.myhostname.cpu.total.user',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.total.user 1234567 123 hostname=myhostname'
expected_data += ' myFirstTag=myValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_cpu_metrics_taghandling_aggregate_deactivate_so_old_values2(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
config['cleanMetrics'] = True
config['skipAggregates'] = False
metric = Metric('servers.myhostname.cpu.total.user',
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put cpu.user 1234567 123 hostname=myhostname '
expected_data += 'myFirstTag=myValue cpuId=total\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_haproxy_metrics_taghandling_default(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
metricName = 'servers.myhostname.'
metricName += 'haproxy.SOME-BACKEND.SOME-SERVER.bin'
metric = Metric(metricName,
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put haproxy.bin 1234567 123 hostname=myhostname '
expected_data += 'myFirstTag=myValue server=SOME-SERVER '
expected_data += 'backend=SOME-BACKEND\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_haproxy_metrics_taghandling_deactivate(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
config['cleanMetrics'] = False
metricName = 'servers.myhostname.'
metricName += 'haproxy.SOME-BACKEND.SOME-SERVER.bin'
metric = Metric(metricName,
123, raw_value=123, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put haproxy.SOME-BACKEND.SOME-SERVER.bin 1234567 '
expected_data += '123 hostname=myhostname '
expected_data += 'myFirstTag=myValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_diskspace_metrics_taghandling_default(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
metricName = 'servers.myhostname.'
metricName += 'diskspace.MOUNT_POINT.byte_percentfree'
metric = Metric(metricName,
80, raw_value=80, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put diskspace.byte_percentfree 1234567 80 '
expected_data += 'hostname=myhostname '
expected_data += 'myFirstTag=myValue mountpoint=MOUNT_POINT\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_diskspace_metrics_taghandling_deactivate(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
config['cleanMetrics'] = False
metricName = 'servers.myhostname.'
metricName += 'diskspace.MOUNT_POINT.byte_percentfree'
metric = Metric(metricName,
80, raw_value=80, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put diskspace.MOUNT_POINT.byte_percentfree 1234567'
expected_data += ' 80 hostname=myhostname '
expected_data += 'myFirstTag=myValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_iostat_metrics_taghandling_default(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
metricName = 'servers.myhostname.'
metricName += 'iostat.DEV.io_in_progress'
metric = Metric(metricName,
80, raw_value=80, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put iostat.io_in_progress 1234567 80 '
expected_data += 'hostname=myhostname '
expected_data += 'myFirstTag=myValue device=DEV\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_iostat_metrics_taghandling_deactivate(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
config['cleanMetrics'] = False
metricName = 'servers.myhostname.'
metricName += 'iostat.DEV.io_in_progress'
metric = Metric(metricName,
80, raw_value=80, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put iostat.DEV.io_in_progress 1234567'
expected_data += ' 80 hostname=myhostname '
expected_data += 'myFirstTag=myValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_network_metrics_taghandling_default(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
metricName = 'servers.myhostname.'
metricName += 'network.IF.rx_packets'
metric = Metric(metricName,
80, raw_value=80, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put network.rx_packets 1234567 80 '
expected_data += 'hostname=myhostname '
expected_data += 'myFirstTag=myValue interface=IF\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_network_metrics_taghandling_deactivate(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue']
config['cleanMetrics'] = False
metricName = 'servers.myhostname.'
metricName += 'network.IF.rx_packets'
metric = Metric(metricName,
80, raw_value=80, timestamp=1234567,
host='myhostname', metric_type='GAUGE')
expected_data = 'put network.IF.rx_packets 1234567'
expected_data += ' 80 hostname=myhostname '
expected_data += 'myFirstTag=myValue\n'
handler = TSDBHandler(config)
handler.process(metric)
handler.socket.sendall.assert_called_with(expected_data)
def test_with_invalid_tag(self):
config = configobj.ConfigObj()
config['host'] = 'localhost'
config['port'] = '9999'
config['tags'] = ['myFirstTag=myValue',
'mySecondTag=myOtherValue,myThirdTag=yetAnotherVal']
try:
TSDBHandler(config)
fail("Expected an exception")
except Exception, e:
assert(e)
| mit | 3,479,828,976,782,790,700 | 38.526682 | 80 | 0.582472 | false | 4.102095 | true | false | false |
vivanov1410/pifarmer-python | api.py | 1 | 2797 | import json
import time
from datetime import datetime
import requests
from cache import *
class BaseApi:
def __init__(self, environment='development'):
self.base_url = 'http://pifarm-api.herokuapp.com/v1' if environment == 'development' else 'http://pifarm.apphb.com/v1'
self.sessionToken = None
self._cache = None
class OnlineApi(BaseApi):
def connect(self, device_id, serial_number):
url = '{0}/auth/login-device'.format(self.base_url)
headers = {'content-type': 'application/json'}
payload = {'deviceId': device_id, 'serialNumber': serial_number}
response = requests.post(url, data=json.dumps(payload), headers=headers)
if response.status_code == requests.codes.ok:
data = response.json()
self.sessionToken = data['sessionToken']
device_model = {'id': data['id'], 'name': data['name'], 'description': data['description'], 'serial_number': data['serialNumber']}
return device_model
else:
response.raise_for_status()
def heartbeat(self, device):
url = '{0}/devices/{1}/stats'.format(self.base_url, device.id)
headers = {'content-type': 'application/json', 'Authorization': 'Bearer ' + self.sessionToken}
payload = {'uptime': device.stats.uptime,
'temperature': {'cpu': device.stats.cpu_temperature, 'gpu': device.stats.gpu_temperature},
'memory': {'total': device.stats.memory_total, 'used': device.stats.memory_used},
'hdd': {'total': device.stats.hdd_total, 'used': device.stats.hdd_used},
'at': str(datetime.utcnow())}
response = requests.post(url, data=json.dumps(payload), headers=headers)
if response.status_code == requests.codes.ok:
return True
else:
response.raise_for_status()
class OfflineApi(BaseApi):
def connect(self, device_id, serial_number):
self._cache = Cache()
device_model = {'id': device_id, 'name': 'n/a', 'description': 'n/a', 'serial_number': serial_number}
return device_model
def heartbeat(self, device):
stats = device.stats
reading = StatisticsReading(device_id=device.id,
uptime=stats.uptime,
cpu_temperature=stats.cpu_temperature,
gpu_temperature=stats.gpu_temperature,
memory_total=stats.memory_total,
memory_used=stats.memory_used,
hdd_total=stats.hdd_total,
hdd_used=stats.hdd_used,
at=time.time())
reading.save()
| gpl-3.0 | -5,987,170,202,995,076,000 | 42.030769 | 142 | 0.567036 | false | 4.089181 | false | false | false |
laysakura/shellstreaming | example/03_CountWindow.py | 1 | 1526 | # -*- coding: utf-8 -*-
from shellstreaming import api
from shellstreaming.istream import IncInt
from shellstreaming.operator import CountWindow
from shellstreaming.ostream import LocalFile
OUTPUT_FILE = '/tmp/03_CountWindow.txt'
def main():
incint_stream = api.IStream(IncInt, max_records=6)
incint_win = api.Operator([incint_stream], CountWindow, 3, slide_size=1, fixed_to=['localhost'])
api.OStream(incint_win, LocalFile, OUTPUT_FILE, output_format='json', fixed_to=['localhost'])
def test():
import json
with open(OUTPUT_FILE) as f:
# 1st window event
assert(int(json.loads(next(f))['num']) == 0)
# 2nd window event
assert(int(json.loads(next(f))['num']) == 0)
assert(int(json.loads(next(f))['num']) == 1)
# 3rd window event
assert(int(json.loads(next(f))['num']) == 0)
assert(int(json.loads(next(f))['num']) == 1)
assert(int(json.loads(next(f))['num']) == 2)
# 4th window event
assert(int(json.loads(next(f))['num']) == 1)
assert(int(json.loads(next(f))['num']) == 2)
assert(int(json.loads(next(f))['num']) == 3)
# 5th window event
assert(int(json.loads(next(f))['num']) == 2)
assert(int(json.loads(next(f))['num']) == 3)
assert(int(json.loads(next(f))['num']) == 4)
# 6th window event
assert(int(json.loads(next(f))['num']) == 3)
assert(int(json.loads(next(f))['num']) == 4)
assert(int(json.loads(next(f))['num']) == 5)
| apache-2.0 | 7,349,580,398,508,393,000 | 32.173913 | 100 | 0.589122 | false | 3.139918 | false | false | false |
andrewyoung1991/abjad | abjad/tools/scoretools/test/test_scoretools_Rest___copy__.py | 2 | 1144 | # -*- encoding: utf-8 -*-
from abjad import *
import copy
def test_scoretools_Rest___copy___01():
r'''Copy rest.
'''
rest_1 = Rest((1, 4))
rest_2 = copy.copy(rest_1)
assert isinstance(rest_1, Rest)
assert isinstance(rest_2, Rest)
assert format(rest_1) == format(rest_2)
assert rest_1 is not rest_2
def test_scoretools_Rest___copy___02():
r'''Copy rest with LilyPond multiplier.
'''
rest_1 = Rest('r4')
attach(Multiplier(1, 2), rest_1)
rest_2 = copy.copy(rest_1)
assert isinstance(rest_1, Rest)
assert isinstance(rest_2, Rest)
assert format(rest_1) == format(rest_2)
assert rest_1 is not rest_2
def test_scoretools_Rest___copy___03():
r'''Copy rest with LilyPond grob overrides and LilyPond context settings.
'''
rest_1 = Rest((1, 4))
override(rest_1).staff.note_head.color = 'red'
override(rest_1).accidental.color = 'red'
set_(rest_1).tuplet_full_length = True
rest_2 = copy.copy(rest_1)
assert isinstance(rest_1, Rest)
assert isinstance(rest_2, Rest)
assert format(rest_1) == format(rest_2)
assert rest_1 is not rest_2 | gpl-3.0 | -4,571,919,088,271,024,000 | 23.891304 | 77 | 0.627622 | false | 3.058824 | false | false | false |
wtsi-hgi/serapis | serapis/controller/db/data_access.py | 1 | 83791 |
#################################################################################
#
# Copyright (c) 2013 Genome Research Ltd.
#
# Author: Irina Colgiu <[email protected]>
#
# 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 abc
import logging
from bson.objectid import ObjectId
from serapis.com import constants, utils
from serapis.controller import exceptions
from serapis.controller.db import models
from serapis.controller.logic import models_utils
from mongoengine.queryset import DoesNotExist
from mongoengine.errors import OperationError
#################################################################################
class DataAccess(object):
pass
class SubmissionDataAccess(DataAccess):
@classmethod
def build_submission_update_dict(cls, update_dict, submission):
update_db_dict = dict()
for (field_name, field_val) in update_dict.items():
if field_name == 'files_list':
pass
# elif field_name == 'hgi_project_list' and field_val:
# for prj in field_val:
# if not utils.is_hgi_project(prj):
# raise ValueError("This project name is not according to HGI_project rules -- "+str(constants.REGEX_HGI_PROJECT))
# if getattr(submission, 'hgi_project_list'):
# hgi_projects = submission.hgi_project_list
# hgi_projects.extend(field_val)
# else:
# hgi_projects = field_val
# update_db_dict['set__hgi_project_list'] = hgi_projects
elif field_name == 'hgi_project' and field_val != None:
#for prj in field_val:
if not utils.is_hgi_project(field_val):
raise ValueError("This project name is not according to HGI_project rules -- "+str(constants.REGEX_HGI_PROJECT))
update_db_dict['set__hgi_project'] = field_val
elif field_name == '_is_uploaded_as_serapis' and field_val != None:
update_db_dict['set__upload_as_serapis'] = field_val
# File-related metadata:
elif field_name == 'data_subtype_tags':
if getattr(submission, 'data_subtype_tags'):
subtypes_dict = submission.data_subtype_tags
subtypes_dict.update(field_val)
else:
subtypes_dict = field_val
update_db_dict['set__data_subtype_tags'] = subtypes_dict
elif field_name == 'data_type':
update_db_dict['set__data_type'] = field_val
# TODO: put here the logic around inserting a ref genome
elif field_name == 'file_reference_genome_id':
models.ReferenceGenome.objects(md5=field_val).get() # Check that the id exists in the RefGenome coll, throw exc
update_db_dict['set__file_reference_genome_id'] = field_val
# This should be tested if it's ok...
elif field_name == 'library_metadata':
update_db_dict['set__abstract_library'] = field_val
elif field_name == 'study':
update_db_dict['set__study'] = field_val
elif field_name == 'irods_collection':
update_db_dict['set__irods_collection'] = field_val
elif field_name == 'file_type':
update_db_dict['set__file_type'] = field_val
elif field_name == 'sanger_user_id':
update_db_dict['set__sanger_user_id'] = field_val
else:
logging.error("ERROR: KEY not in Submission class declaration!!!!! %s", field_name)
return update_db_dict
@classmethod
def update_submission(cls, update_dict, submission_id, submission=None, nr_retries=constants.MAX_DBUPDATE_RETRIES):
''' Updates an existing submission or creates a new submission
if no submission_id is provided.
Returns -- 0 if nothing was changed, 1 if the update has happened
Throws:
ValueError - if the data in update_dict is not correct
'''
if submission_id == None:
return 0
elif not submission:
submission = cls.retrieve_submission(submission_id)
i, upd = 0, 0
while i < nr_retries and upd == 0:
update_db_dict = cls.build_submission_update_dict(update_dict, submission)
upd = models.Submission.objects(id=submission.id, version=submission.version).update_one(**update_db_dict)
logging.info("Updating submission...updated? %s", upd)
i+=1
return upd
@classmethod
def insert_submission(cls, submission_data, user_id):
''' Inserts a submission in the DB, but the submission
won't have the files_list set, as the files are created
after the submission exists.
'''
submission = models.Submission()
submission.sanger_user_id = user_id
submission.submission_date = utils.get_today_date()
submission.save()
if cls.update_submission(submission_data, submission.id, submission) == 1:
return submission.id
submission.delete()
return None
@classmethod
def insert_submission_date(cls, submission_id, date):
if date != None:
return models.Submission.objects(id=submission_id).update_one(set__submission_date=date)
return None
# !!! This is not ATOMIC!!!!
@classmethod
def delete_submission(cls, submission_id, submission=None):
if not submission:
submission = cls.retrieve_submission(submission_id)
# 2. Delete the files and the submission
models.Submission.objects(id=submission_id).delete()
for file_id in submission.files_list:
FileDataAccess.delete_submitted_file(file_id)
return True
@classmethod
def update_submission_file_list(cls, submission_id, files_list, submission=None):
if not submission:
submission = cls.retrieve_submission(submission_id)
if not files_list:
return cls.delete_submission(submission_id, submission)
upd_dict = {"inc__version" : 1, "set__files_list" : files_list}
return models.Submission.objects(id=submission_id).update_one(**upd_dict)
@classmethod
def retrieve_all_user_submissions(cls, user_id):
return models.Submission.objects.filter(sanger_user_id=user_id)
@classmethod
def retrieve_all_submissions(cls):
return models.Submission.objects()
@classmethod
def retrieve_submission(cls, subm_id):
return models.Submission.objects(_id=ObjectId(subm_id)).get()
@classmethod
def retrieve_all_file_ids_for_submission(cls, subm_id):
return models.Submission.objects(id=ObjectId(subm_id)).only('files_list').get().files_list
@classmethod
def retrieve_all_files_for_submission(cls, subm_id):
return models.SubmittedFile.objects(submission_id=str(subm_id))
#return [f for f in files]
@classmethod
def retrieve_submission_date(cls, file_id, submission_id=None):
if submission_id == None:
submission_id = FileDataAccess.retrieve_submission_id(file_id)
return models.Submission.objects(id=ObjectId(submission_id)).only('submission_date').get().submission_date
# TODO: if no obj can be found => get() throws an ugly exception!
@classmethod
def retrieve_submission_upload_as_serapis_flag(cls, submission_id):
if not submission_id:
return None
return models.Submission.objects(id=ObjectId(submission_id)).only('_is_uploaded_as_serapis').get()._is_uploaded_as_serapis
@classmethod
def retrieve_only_submission_fields(cls, submission_id, fields_list):
if not submission_id:
return None
for field in fields_list:
if not field in models.Submission._fields:
raise ValueError(message="Not all fields given as parameter exist as fields of a Submission type.")
return models.Submission.objects(id=ObjectId(submission_id)).only(*fields_list).get()
class FileDataAccess(DataAccess):
@classmethod
def update_entity(cls, entity_json, crt_ent, sender):
has_changed = False
for key in entity_json:
old_val = getattr(crt_ent, key)
if key in constants.ENTITY_META_FIELDS or key == None:
continue
elif old_val == None or old_val == 'unspecified':
setattr(crt_ent, key, entity_json[key])
crt_ent.last_updates_source[key] = sender
has_changed = True
continue
else:
if hasattr(crt_ent, key) and entity_json[key] == getattr(crt_ent, key):
continue
if key not in crt_ent.last_updates_source:
crt_ent.last_updates_source[key] = constants.INIT_SOURCE
priority_comparison = utils.compare_sender_priority(crt_ent.last_updates_source[key], sender)
if priority_comparison >= 0:
setattr(crt_ent, key, entity_json[key])
crt_ent.last_updates_source[key] = sender
has_changed = True
return has_changed
@classmethod
def check_if_list_has_new_entities(cls, old_entity_list, new_entity_list):
''' old_entity_list = list of entity objects
new_entity_list = json list of entities
'''
if len(new_entity_list) == 0:
return False
if len(old_entity_list) == 0 and len(new_entity_list) > 0:
return True
for new_json_entity in new_entity_list:
found = False
for old_entity in old_entity_list:
if models_utils.EntityModelUtilityFunctions.check_if_entities_are_equal(old_entity, new_json_entity):
found = True
break
if not found:
return True
return False
@classmethod
def retrieve_submitted_file(cls, file_id):
return models.SubmittedFile.objects(_id=ObjectId(file_id)).get()
@classmethod
def retrieve_submitted_file_by_submission(cls, submission_id, submission_file_id):
# indexes = models.SubmittedFile.objects._collection.index_information()
# print "INDEXES::::", [str(i) for i in indexes]
return models.SubmittedFile.objects(submission_id=submission_id, file_id=submission_file_id).get()
# Works, turned off for testing:
#return models.SubmittedFile.objects(submission_id=submission_id, file_id=submission_file_id).hint([('submission_id', 1)]).get()
# SFile.objects(submission_id='000').hint([('_cls', 1), ('submission_id', 1)])
#return models.SubmittedFile.objects(submission_id=submission_id, file_id=submission_file_id).get()
#.hint([('_id', 1)])
#hint(['_cls_1_submission_id']) _cls_1_submission_id_1
#self.assertEqual(BlogPost.objects.hint([('tags', 1)]).count(), 10)
# self.assertEqual(BlogPost.objects.hint([('ZZ', 1)]).count(), 10)
@classmethod
def retrieve_sample_list(cls, file_id):
return models.SubmittedFile.objects(id=ObjectId(file_id)).only('sample_list').get().sample_list
@classmethod
def retrieve_library_list(cls, file_id):
return models.SubmittedFile.objects(id=ObjectId(file_id)).only('library_list').get().library_list
@classmethod
def retrieve_study_list(cls, file_id):
return models.SubmittedFile.objects(id=ObjectId(file_id)).only('study_list').get().study_list
@classmethod
def retrieve_version(cls, file_id):
''' Returns the list of versions for this file (e.g. [9,1,0,1]).'''
return models.SubmittedFile.objects(id=ObjectId(file_id)).only('version').get().version
@classmethod
def retrieve_SFile_fields_only(cls, file_id, list_of_field_names):
''' Returns a SubmittedFile object which has only the mentioned fields
retrieved from DB - from efficiency reasons. The rest of the fields
are set to None or default values.'''
return models.SubmittedFile.objects(id=ObjectId(file_id)).only(*list_of_field_names).get()
@classmethod
def retrieve_sample_by_name(cls, sample_name, file_id, submitted_file=None):
if submitted_file == None:
sample_list = cls.retrieve_sample_list(file_id)
else:
sample_list = submitted_file.sample_list
return models_utils.EntityModelUtilityFunctions.get_entity_by_field('name', sample_name, sample_list)
@classmethod
def retrieve_library_by_name(cls, lib_name, file_id, submitted_file=None):
if submitted_file == None:
library_list = cls.retrieve_library_list(file_id)
else:
library_list = submitted_file.library_list
return models_utils.EntityModelUtilityFunctions.get_entity_by_field('name', lib_name, library_list)
@classmethod
def retrieve_study_by_name(cls, study_name, file_id, submitted_file=None):
if submitted_file == None:
study_list = cls.retrieve_study_list(file_id)
else:
study_list = submitted_file.study_list
return models_utils.EntityModelUtilityFunctions.get_entity_by_field('name', study_name, study_list)
@classmethod
def retrieve_sample_by_id(cls, sample_id, file_id, submitted_file=None):
if submitted_file == None:
sample_list = cls.retrieve_sample_list(file_id)
else:
sample_list = submitted_file.sample_list
return models_utils.EntityModelUtilityFunctions.get_entity_by_field('internal_id', int(sample_id), sample_list)
@classmethod
def retrieve_library_by_id(cls, lib_id, file_id, submitted_file=None):
if submitted_file == None:
library_list = cls.retrieve_library_list(file_id)
else:
library_list = submitted_file.library_list
return models_utils.EntityModelUtilityFunctions.get_entity_by_field('internal_id', int(lib_id), library_list)
@classmethod
def retrieve_study_by_id(cls, study_id, file_id, submitted_file=None):
if submitted_file == None:
study_list = cls.retrieve_study_list(file_id)
print("STUDY LIST: ", study_list)
else:
study_list = submitted_file.study_list
return models_utils.EntityModelUtilityFunctions.get_entity_by_field('internal_id', int(study_id), study_list)
@classmethod
def retrieve_submission_id(cls, file_id):
return models.SubmittedFile.objects(id=ObjectId(file_id)).only('submission_id').get().submission_id
@classmethod
def retrieve_sanger_user_id(cls, file_id):
#subm_id = models.SubmittedFile.objects(id=ObjectId(file_id)).only('submission_id').get().submission_id
subm_id = cls.retrieve_submission_id(file_id)
return models.Submission.objects(id=ObjectId(subm_id)).only('sanger_user_id').get().sanger_user_id
@classmethod
def retrieve_client_file_path(cls, file_id):
return models.SubmittedFile.objects(id=file_id).only('file_path_client').get().file_path_client
@classmethod
def retrieve_file_md5(cls, file_id):
return models.SubmittedFile.objects(id=file_id).only('md5').get().md5
@classmethod
def retrieve_index_md5(cls, file_id):
return models.SubmittedFile.objects(id=file_id).only('index_file_md5').get().index_file_md5
@classmethod
def retrieve_tasks_dict(cls, file_id):
return models.SubmittedFile.objects(id=file_id).only('tasks').get().tasks
#################### AUXILIARY FUNCTIONS - RELATED TO FILE VERSION ############
@classmethod
def get_file_version(cls, file_id, submitted_file=None):
if submitted_file == None:
version = cls.retrieve_version(file_id)
return version[0]
return submitted_file.version[0]
@classmethod
def get_sample_version(cls, file_id, submitted_file=None):
if submitted_file == None:
version = cls.retrieve_version(file_id)
return version[1]
return submitted_file.version[1]
@classmethod
def get_library_version(cls, file_id, submitted_file=None):
if submitted_file == None:
version = cls.retrieve_version(file_id)
return version[2]
return submitted_file.version[2]
@classmethod
def get_study_version(cls, file_id, submitted_file=None):
if submitted_file == None:
version = cls.retrieve_version(file_id)
return version[3]
return submitted_file.version[3]
@classmethod
def get_entity_list_version(cls, entity_type, file_id, submitted_file=None):
if entity_type not in constants.LIST_OF_ENTITY_TYPES:
return None
if entity_type == constants.SAMPLE_TYPE:
return cls.get_sample_version(file_id, submitted_file)
elif entity_type == constants.STUDY_TYPE:
return cls.get_study_version(file_id, submitted_file)
elif entity_type == constants.LIBRARY_TYPE:
return cls.get_library_version(file_id, submitted_file)
#------------------------ SEARCH ENTITY ---------------------------------
@classmethod
def search_JSONEntity_in_list(cls, entity_json, entity_list):
''' Searches for the JSON entity within the entity list.
Returns:
- the entity if it was found
- None if not
Throws:
exceptions.NoIdentifyingFieldsProvidedException -- if the entity_json doesn't contain
any field to identify it.
'''
if entity_list == None or len(entity_list) == 0:
return None
has_ids = models_utils.EntityModelUtilityFunctions.check_if_JSONEntity_has_identifying_fields(entity_json) # This throws an exception if the json entity doesn't have any ids
if not has_ids:
raise exceptions.NoIdentifyingFieldsProvidedException(faulty_expression=entity_json)
for ent in entity_list:
if models_utils.EntityModelUtilityFunctions.check_if_entities_are_equal(ent, entity_json) == True:
return ent
return None
@classmethod
def search_JSONLibrary_in_list(cls, lib_json, lib_list):
return cls.search_JSONEntity_in_list(lib_json, lib_list)
@classmethod
def search_JSONSample_in_list(cls, sample_json, sample_list):
return cls.search_JSONEntity_in_list(sample_json, sample_list)
@classmethod
def search_JSONStudy_in_list(cls, study_json, study_list):
return cls.search_JSONEntity_in_list(study_json, study_list)
@classmethod
def search_JSONLibrary(cls, lib_json, file_id, submitted_file=None):
if submitted_file == None:
submitted_file = cls.retrieve_submitted_file(file_id)
return cls.search_JSONEntity_in_list(lib_json, submitted_file.library_list)
@classmethod
def search_JSONSample(cls, sample_json, file_id, submitted_file=None):
if submitted_file == None:
submitted_file = cls.retrieve_submitted_file(file_id)
return cls.search_JSONEntity_in_list(sample_json, submitted_file.sample_list)
@classmethod
def search_JSONStudy(cls, study_json, file_id, submitted_file=None):
if submitted_file == None:
submitted_file = cls.retrieve_submitted_file(file_id)
return cls.search_JSONEntity_in_list(study_json, submitted_file.study_list)
@classmethod
def search_JSON_entity(cls, entity_json, entity_type, file_id, submitted_file=None):
if submitted_file == None:
submitted_file = cls.retrieve_submitted_file(file_id)
if entity_type == constants.STUDY_TYPE:
return cls.search_JSONEntity_in_list(entity_json, submitted_file.study_list)
elif entity_type == constants.LIBRARY_TYPE:
return cls.search_JSONEntity_in_list(entity_json, submitted_file.library_list)
elif entity_type == constants.SAMPLE_TYPE:
return cls.search_JSONEntity_in_list(entity_json, submitted_file.sample_list)
return None
# ------------------------ INSERTS & UPDATES -----------------------------
# Hackish way of putting the attributes of the abstract lib, in each lib inserted:
@classmethod
def __update_lib_from_abstract_lib__(cls, library, abstract_lib):
if not library:
return None
for field in models.AbstractLibrary._fields:
if hasattr(abstract_lib, field) and getattr(abstract_lib, field) not in [None, "unspecified"]:
setattr(library, field, getattr(abstract_lib, field))
return library
@classmethod
def insert_JSONentity_in_filemeta(cls, entity_json, entity_type, sender, submitted_file):
if submitted_file == None or not entity_json or not entity_type:
return False
if entity_type not in constants.LIST_OF_ENTITY_TYPES:
return False
if cls.search_JSON_entity(entity_json, entity_type, submitted_file.id, submitted_file) == None:
#library = cls.json2library(library_json, sender)
entity = models_utils.EntityModelUtilityFunctions.json2entity(entity_json, sender, entity_type)
#library = cls.__update_lib_from_abstract_lib__(library, submitted_file.abstract_library)
#submitted_file.library_list.append(library)
if entity_type == constants.LIBRARY_TYPE:
submitted_file.library_list.append(entity)
elif entity_type == constants.SAMPLE_TYPE:
submitted_file.sample_list.append(entity)
elif entity_type == constants.STUDY_TYPE:
submitted_file.study_list.append(entity)
return True
return False
@classmethod
def insert_library_in_SFObj(cls, library_json, sender, submitted_file):
if submitted_file == None or not library_json:
return False
if cls.search_JSONLibrary(library_json, submitted_file.id, submitted_file) == None:
library = models_utils.EntityModelUtilityFunctions.json2library(library_json, sender)
library = cls.__update_lib_from_abstract_lib__(library, submitted_file.abstract_library)
submitted_file.library_list.append(library)
return True
return False
@classmethod
def insert_sample_in_SFObj(cls, sample_json, sender, submitted_file):
if submitted_file == None:
return False
if cls.search_JSONSample(sample_json, submitted_file.id, submitted_file) == None:
sample = models_utils.EntityModelUtilityFunctions.json2sample(sample_json, sender)
submitted_file.sample_list.append(sample)
return True
return False
@classmethod
def insert_study_in_SFObj(cls, study_json, sender, submitted_file):
if submitted_file == None:
return False
if cls.search_JSONStudy(study_json, submitted_file.id, submitted_file) == None:
study = models_utils.EntityModelUtilityFunctions.json2study(study_json, sender)
submitted_file.study_list.append(study)
return True
return False
##########################
@classmethod
def insert_JSONentity_in_db(cls, entity_json, entity_type, sender, file_id, submitted_file):
if entity_type not in constants.LIST_OF_ENTITY_TYPES:
return False
if entity_type == constants.SAMPLE_TYPE:
return cls.insert_sample_in_db(entity_json, sender, file_id)
elif entity_type == constants.LIBRARY_TYPE:
return cls.insert_library_in_db(entity_json, sender, file_id)
elif entity_type == constants.STUDY_TYPE:
return cls.insert_study_in_db(entity_json, sender, file_id)
return False
@classmethod
def insert_library_in_db(cls, library_json, sender, file_id):
submitted_file = cls.retrieve_submitted_file(file_id)
inserted = cls.insert_library_in_SFObj(library_json, sender, submitted_file)
if inserted == True:
library_version = cls.get_library_version(submitted_file.id, submitted_file)
return models.SubmittedFile.objects(id=file_id, version__2=library_version).update_one(inc__version__2=1, inc__version__0=1, set__library_list=submitted_file.library_list)
return 0
@classmethod
def insert_sample_in_db(cls, sample_json, sender, file_id):
''' Inserts in the DB the updated document with the new
sample inserted in the sample list.
Returns:
1 -- if the insert in the DB was successfully
0 -- if not
'''
submitted_file = cls.retrieve_submitted_file(file_id)
inserted = cls.insert_sample_in_SFObj(sample_json, sender, submitted_file)
if inserted == True:
sample_version = cls.get_sample_version(submitted_file.id, submitted_file)
return models.SubmittedFile.objects(id=file_id, version__1=sample_version).update_one(inc__version__1=1, inc__version__0=1, set__sample_list=submitted_file.entity_set)
return 0
@classmethod
def insert_study_in_db(cls, study_json, sender, file_id):
submitted_file = cls.retrieve_submitted_file(file_id)
inserted = cls.insert_study_in_SFObj(study_json, sender, submitted_file)
logging.info("IN STUDY INSERT --> HAS THE STUDY BEEN INSERTED? %s", inserted)
#print "HAS THE STUDY BEEN INSERTED????==============", inserted
if inserted == True:
study_version = cls.get_study_version(submitted_file.id, submitted_file)
return models.SubmittedFile.objects(id=file_id, version__3=study_version).update_one(inc__version__3=1, inc__version__0=1, set__study_list=submitted_file.study_list)
return 0
#---------------------------------------------------------------
@classmethod
# def update_library_in_SFObj(cls, library_json, sender, submitted_file):
# if submitted_file == None:
# return False
# crt_library = cls.search_JSONEntity_in_list(library_json, submitted_file.library_list)
# if crt_library == None:
# raise exceptions.ResourceNotFoundError(library_json)
# #return False
# return cls.update_entity(library_json, crt_library, sender)
#
# @classmethod
# def update_sample_in_SFObj(cls, sample_json, sender, submitted_file):
# if submitted_file == None:
# return False
# crt_sample = cls.search_JSONEntity_in_list(sample_json, submitted_file.sample_list)
# if crt_sample == None:
# raise exceptions.ResourceNotFoundError(sample_json)
# #return False
# return cls.update_entity(sample_json, crt_sample, sender)
# @classmethod
# def update_study_in_SFObj(cls, study_json, sender, submitted_file):
# if submitted_file == None:
# return False
# crt_study = cls.search_JSONEntity_in_list(study_json, submitted_file.study_list)
# if crt_study == None:
# raise exceptions.ResourceNotFoundError(study_json)
# #return False
# return cls.update_entity(study_json, crt_study, sender)
#---------------------------------------------------------------
@classmethod
def update_library_in_db(cls, library_json, sender, file_id, library_id=None):
''' Throws:
- DoesNotExist exception -- if the file being queried does not exist in the DB
- exceptions.NoIdentifyingFieldsProvidedException -- if the library_id isn't provided
neither as a parameter, nor in the library_json
'''
if library_id == None and models_utils.EntityModelUtilityFunctions.check_if_JSONEntity_has_identifying_fields(library_json) == False:
raise exceptions.NoIdentifyingFieldsProvidedException()
submitted_file = cls.retrieve_submitted_file(file_id)
if library_id != None:
library_json['internal_id'] = int(library_id)
has_changed = cls.update_library_in_SFObj(library_json, sender, submitted_file)
if has_changed == True:
lib_list_version = cls.get_library_version(submitted_file.id, submitted_file)
return models.SubmittedFile.objects(id=file_id, version__2=lib_list_version).update_one(inc__version__2=1, inc__version__0=1, set__library_list=submitted_file.library_list)
return 0
@classmethod
def update_sample_in_db(cls, sample_json, sender, file_id, sample_id=None):
''' Updates the metadata for a sample in the DB.
Throws:
- DoesNotExist exception -- if the file being queried does not exist in the DB
- exceptions.NoIdentifyingFieldsProvidedException -- if the sample_id isn't provided
neither as a parameter, nor in the sample_json
'''
if sample_id == None and models_utils.EntityModelUtilityFunctions.check_if_JSONEntity_has_identifying_fields(sample_json) == False:
raise exceptions.NoIdentifyingFieldsProvidedException()
submitted_file = cls.retrieve_submitted_file(file_id)
if sample_id != None:
sample_json['internal_id'] = int(sample_id)
has_changed = cls.update_sample_in_SFObj(sample_json, sender, submitted_file)
if has_changed == True:
sample_list_version = cls.get_sample_version(submitted_file.id, submitted_file)
return models.SubmittedFile.objects(id=file_id, version__1=sample_list_version).update_one(inc__version__1=1, inc__version__0=1, set__sample_list=submitted_file.entity_set)
return 0
@classmethod
def update_study_in_db(cls, study_json, sender, file_id, study_id=None):
''' Throws:
- DoesNotExist exception -- if the file being queried does not exist in the DB
- exceptions.NoIdentifyingFieldsProvidedException -- if the study_id isn't provided
neither as a parameter, nor in the study_json
'''
if study_id == None and models_utils.EntityModelUtilityFunctions.check_if_JSONEntity_has_identifying_fields(study_json) == False:
raise exceptions.NoIdentifyingFieldsProvidedException()
submitted_file = cls.retrieve_submitted_file(file_id)
if study_id != None:
study_json['internal_id'] = int(study_id)
has_changed = cls.update_study_in_SFObj(study_json, sender, submitted_file)
if has_changed == True:
lib_list_version = cls.get_study_version(submitted_file.id, submitted_file)
return models.SubmittedFile.objects(id=file_id, version__3=lib_list_version).update_one(inc__version__3=1, inc__version__0=1, set__study_list=submitted_file.study_list)
return 0
#------------------------------------------------------------------------------------
@classmethod
def insert_or_update_library_in_SFObj(cls, library_json, sender, submitted_file):
if submitted_file == None or library_json == None:
return False
lib_found = cls.search_JSONEntity_in_list(library_json, submitted_file.library_list)
if not lib_found:
return cls.insert_library_in_SFObj(library_json, sender, submitted_file)
else:
return cls.update_entity(library_json, lib_found, sender)
# return cls.update_library_in_SFObj(library_json, sender, submitted_file)
@classmethod
def insert_or_update_sample_in_SFObj(cls, sample_json, sender, submitted_file):
if submitted_file == None or sample_json == None:
return False
sample_found = cls.search_JSONEntity_in_list(sample_json, submitted_file.entity_set)
if sample_found == None:
return cls.insert_sample_in_SFObj(sample_json, sender, submitted_file)
else:
return cls.update_entity(sample_json, sample_found, sender)
# return cls.update_sample_in_SFObj(sample_json, sender, submitted_file)
@classmethod
def insert_or_update_study_in_SFObj(cls, study_json, sender, submitted_file):
if submitted_file == None or study_json == None:
return False
study_found = cls.search_JSONEntity_in_list(study_json, submitted_file.study_list)
if study_found == None:
return cls.insert_study_in_SFObj(study_json, sender, submitted_file)
else:
return cls.update_entity(study_json, study_found, sender)
# return cls.update_study_in_SFObj(study_json, sender, submitted_file)
#--------------------------------------------------------------------------------
@classmethod
def insert_or_update_library_in_db(cls, library_json, sender, file_id):
submitted_file = cls.retrieve_submitted_file(file_id)
# done = False
# lib_exists = cls.search_JSONEntity_in_list(library_json, submitted_file.library_list)
# if lib_exists == None:
# done = cls.insert_library_in_SFObj(library_json, sender, submitted_file)
# else:
# done = cls.update_library_in_SFObj(library_json, sender, submitted_file)
done = cls.insert_or_update_library_in_SFObj(library_json, sender, submitted_file)
if done == True:
lib_list_version = cls.get_library_version(submitted_file.id, submitted_file)
return models.SubmittedFile.objects(id=file_id, version__2=lib_list_version).update_one(inc__version__2=1, inc__version__0=1, set__library_list=submitted_file.library_list)
@classmethod
def insert_or_update_sample_in_db(cls, sample_json, sender, file_id):
submitted_file = cls.retrieve_submitted_file(file_id)
# done = False
# sample_exists = cls.search_JSONEntity_in_list(sample_json, submitted_file.entity_set)
# if sample_exists == None:
# done = cls.insert_sample_in_db(sample_json, sender, file_id)
# else:
# done = cls.update_sample_in_db(sample_json, sender, file_id)
done = cls.insert_or_update_sample_in_SFObj(sample_json, sender, submitted_file)
if done == True:
sample_list_version = cls.get_sample_version(submitted_file.id, submitted_file)
return models.SubmittedFile.objects(id=file_id, version__1=sample_list_version).update_one(inc__version__1=1, inc__version__0=1, set__sample_list=submitted_file.entity_set)
@classmethod
def insert_or_update_study_in_db(cls, study_json, sender, file_id):
submitted_file = cls.retrieve_submitted_file(file_id)
# done = False
# study_exists = cls.search_JSONEntity_in_list(study_json, submitted_file.study_list)
# if study_exists == None:
# done = cls.insert_study_in_db(study_json, sender, file_id)
# else:
# done = cls.update_study_in_db(study_json, sender, file_id)
done = cls.insert_or_update_study_in_SFObj(study_json, sender, submitted_file)
if done == True:
study_list_version = cls.get_study_version(submitted_file.id, submitted_file)
return models.SubmittedFile.objects(id=file_id, version__3=study_list_version).update_one(inc__version__3=1, inc__version__0=1, set__study_list=submitted_file.study_list)
#---------------------------------------------------------------------------------
@classmethod
def update_library_list(cls, library_list, sender, submitted_file):
if submitted_file == None:
return False
if not hasattr(submitted_file, 'library_list') or not getattr(submitted_file, 'library_list'):
submitted_file.library_list = library_list
print("IT enters this fct --- update_library_list in data_access.FileDataAccess......................................")
return True
for library in library_list:
cls.insert_or_update_library_in_SFObj(library, sender, submitted_file)
return True
@classmethod
def update_sample_list(cls, sample_list, sender, submitted_file):
if submitted_file == None:
return False
if not hasattr(submitted_file, 'entity_set') or not getattr(submitted_file, 'entity_set'):
submitted_file.entity_set = sample_list
print("UPDATING SAMPLES LIST WITH update_sample_list...................................")
return True
for sample in sample_list:
cls.insert_or_update_sample_in_SFObj(sample, sender, submitted_file)
return True
@classmethod
def update_study_list(cls, study_list, sender, submitted_file):
if submitted_file == None:
return False
if not hasattr(submitted_file, 'study_list') or not getattr(submitted_file, 'study_list'):
submitted_file.study_list = study_list
print("Using this fct for updating study........................")
return True
for study in study_list:
cls.insert_or_update_study_in_SFObj(study, sender, submitted_file)
return True
#-------------------------------------------------------------
# @classmethod
# def update_and_save_library_list(cls, library_list, sender, file_id):
# if library_list == None or len(library_list) == 0:
# return False
# for library in library_list:
# upsert = cls.insert_or_update_library_in_db(library, sender, file_id)
# return True
#
# @classmethod
# def update_and_save_sample_list(cls, entity_set, sender, file_id):
# if entity_set == None or len(entity_set) == 0:
# return False
# for sample in entity_set:
# upsert = cls.insert_or_update_sample_in_db(sample, sender, file_id)
# return True
#
# @classmethod
# def update_and_save_study_list(cls, study_list, sender, file_id):
# if study_list == None or len(study_list) == 0:
# return False
# for study in study_list:
# upsert = cls.insert_or_update_study_in_db(study, sender, file_id)
# return True
@classmethod
def __upd_list_of_primary_types__(cls, crt_list, update_list_json):
if len(update_list_json) == 0:
return
crt_set = set(crt_list)
new_set = set(update_list_json)
res = crt_set.union(new_set)
crt_list = list(res)
return crt_list
@classmethod
def build_update_dict(cls, file_updates, update_source, file_id, submitted_file):
if not file_updates:
return None
update_db_dict = dict()
for (field_name, field_val) in file_updates.items():
if field_val == 'null' or not field_val:
pass
if field_name in models.SubmittedFile._fields:
if field_name in ['submission_id',
'id',
'_id',
'version',
'file_type',
'irods_coll', # TODO: make it updatable by user, if file not yet submitted to permanent irods coll
'file_path_client',
'last_updates_source',
'file_mdata_status',
'file_submission_status',
'missing_mandatory_fields_dict']:
pass
elif field_name == 'library_list':
# Crappy way of doing this - to be rewritten -- if I don't "patch" the library, it won't have the attributes from abstract
if len(field_val) > 0:
#was_updated = cls.update_library_list(field_val, update_source, submitted_file)
update_db_dict['set__library_list'] = submitted_file.library_list
update_db_dict['inc__version__2'] = 1
#update_db_dict['inc__version__0'] = 1
# #was_updated = cls.update_library_list(field_val, update_source, submitted_file)
# update_db_dict['set__library_list'] = file_updates['library_list']
# update_db_dict['inc__version__2'] = 1
update_db_dict['inc__version__0'] = 1
# #logging.info("UPDATE FILE TO SUBMIT --- UPDATING LIBRARY LIST.................................%s ", was_updated)
elif field_name == 'sample_list':
if len(field_val) > 0:
#was_updated = cls.update_sample_list(field_val, update_source, submitted_file)
update_db_dict['set__sample_list'] = file_updates['sample_list']
update_db_dict['inc__version__1'] = 1
update_db_dict['inc__version__0'] = 1
#logging.info("UPDATE FILE TO SUBMIT ---UPDATING SAMPLE LIST -- was it updated? %s", was_updated)
elif field_name == 'study_list':
if len(field_val) > 0:
#was_updated = cls.update_study_list(field_val, update_source, submitted_file)
update_db_dict['set__study_list'] = file_updates['study_list']
update_db_dict['inc__version__3'] = 1
update_db_dict['inc__version__0'] = 1
#logging.info("UPDATING STUDY LIST - was it updated? %s", was_updated)
# Fields that only the workers' PUT req are allowed to modify - donno how to distinguish...
elif field_name == 'missing_entities_error_dict':
if field_val:
for entity_categ, entities in field_val.items():
update_db_dict['add_to_set__missing_entities_error_dict__'+entity_categ] = entities
update_db_dict['inc__version__0'] = 1
elif field_name == 'not_unique_entity_error_dict':
if field_val:
for entity_categ, entities in field_val.items():
#update_db_dict['push_all__not_unique_entity_error_dict'] = entities
update_db_dict['add_to_set__not_unique_entity_error_dict__'+entity_categ] = entities
update_db_dict['inc__version__0'] = 1
elif field_name == 'header_has_mdata':
if update_source == constants.PARSE_HEADER_TASK:
update_db_dict['set__header_has_mdata'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'md5':
if update_source == constants.CALC_MD5_TASK:
update_db_dict['set__md5'] = field_val
update_db_dict['inc__version__0'] = 1
logging.debug("UPDATING md5")
elif field_name == 'index_file':
if update_source == constants.CALC_MD5_TASK:
if 'md5' in field_val:
update_db_dict['set__index_file__md5'] = field_val['md5']
update_db_dict['inc__version__0'] = 1
else:
raise exceptions.MetadataProblemException("Calc md5 task did not return a dict with an md5 field in it!!!")
#elif field_name == 'hgi_project_list':
elif field_name == 'hgi_project':
if update_source == constants.EXTERNAL_SOURCE:
#for prj in field_val:
if not utils.is_hgi_project(field_val):
raise ValueError("This project name is not according to HGI_project rules -- "+str(constants.REGEX_HGI_PROJECT))
# if getattr(submitted_file, 'hgi_project'):
# hgi_projects = submitted_file.hgi_project
# hgi_projects.extend(field_val)
# else:
# hgi_projects = field_val
update_db_dict['set__hgi_project'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'data_type':
if update_source == constants.EXTERNAL_SOURCE:
update_db_dict['set__data_type'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'data_subtype_tags':
if update_source in [constants.EXTERNAL_SOURCE, constants.PARSE_HEADER_TASK]:
# if getattr(submitted_file, 'data_subtype_tags') != None:
# subtypes_dict = submitted_file.data_subtype_tags
# subtypes_dict.update(field_val)
# else:
subtypes_dict = field_val
update_db_dict['set__data_subtype_tags'] = subtypes_dict
update_db_dict['inc__version__0'] = 1
elif field_name == 'abstract_library':
if update_source == constants.EXTERNAL_SOURCE:
update_db_dict['set__abstract_library'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'file_reference_genome_id':
if update_source == constants.EXTERNAL_SOURCE:
models.ReferenceGenome.objects(md5=field_val).get() # Check that the id exists in the RefGenome coll, throw exc
update_db_dict['set__file_reference_genome_id'] = str(field_val)
update_db_dict['inc__version__0'] = 1
elif field_name == 'security_level':
update_db_dict['set__security_level'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'pmid_list':
update_db_dict['set__pmid_list'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name != None and field_name != "null":
logging.info("Key in VARS+++++++++++++++++++++++++====== but not in the special list: %s", field_name)
elif field_name == 'reference_genome':
#ref_gen = ReferenceGenomeDataAccess.get_or_insert_reference_genome(field_val) # field_val should be a path
ref_gen = ReferenceGenomeDataAccess.retrieve_reference_by_path(field_val)
if not ref_gen:
raise exceptions.ResourceNotFoundException(field_val, "Reference genome not in the DB.")
update_db_dict['set__file_reference_genome_id'] = ref_gen.md5
else:
logging.error("KEY ERROR RAISED!!! KEY = %s, VALUE = %s", field_name, field_val)
# file_specific_upd_dict = None
# if submitted_file.file_type == constants.BAM_FILE:
# file_specific_upd_dict = cls.build_bam_file_update_dict(file_updates, update_source, file_id, submitted_file)
# elif submitted_file.file_type == constants.VCF_FILE:
# file_specific_upd_dict = cls.build_vcf_file_update_dict(file_updates, update_source, file_id, submitted_file)
# if file_specific_upd_dict:
# update_db_dict.update(file_specific_upd_dict)
return update_db_dict
@classmethod
def build_patch_dict(cls, file_updates, update_source, file_id, submitted_file):
if not file_updates:
return None
update_db_dict = dict()
for (field_name, field_val) in file_updates.items():
if field_val == 'null' or not field_val:
pass
if field_name in submitted_file._fields:
if field_name in ['submission_id',
'id',
'_id',
'version',
'file_type',
'irods_coll', # TODO: make it updateble by user, if file not yet submitted to permanent irods coll
'file_path_client',
'last_updates_source',
'file_mdata_status',
'file_submission_status',
'missing_mandatory_fields_dict']:
pass
elif field_name == 'library_list':
if len(field_val) > 0:
was_updated = cls.update_library_list(field_val, update_source, submitted_file)
update_db_dict['set__library_list'] = submitted_file.library_list
update_db_dict['inc__version__2'] = 1
update_db_dict['inc__version__0'] = 1
logging.info("UPDATE FILE TO SUBMIT --- UPDATING LIBRARY LIST.................................%s ", was_updated)
elif field_name == 'sample_list':
if len(field_val) > 0:
was_updated = cls.update_sample_list(field_val, update_source, submitted_file)
update_db_dict['set__sample_list'] = submitted_file.sample_list
update_db_dict['inc__version__1'] = 1
update_db_dict['inc__version__0'] = 1
logging.info("UPDATE FILE TO SUBMIT ---UPDATING SAMPLE LIST -- was it updated? %s", was_updated)
elif field_name == 'study_list':
if len(field_val) > 0:
was_updated = cls.update_study_list(field_val, update_source, submitted_file)
update_db_dict['set__study_list'] = submitted_file.study_list
update_db_dict['inc__version__3'] = 1
update_db_dict['inc__version__0'] = 1
logging.info("UPDATING STUDY LIST - was it updated? %s", was_updated)
# Fields that only the workers' PUT req are allowed to modify - donno how to distinguish...
elif field_name == 'missing_entities_error_dict':
if field_val:
for entity_categ, entities in field_val.items():
update_db_dict['add_to_set__missing_entities_error_dict__'+entity_categ] = entities
update_db_dict['inc__version__0'] = 1
elif field_name == 'not_unique_entity_error_dict':
if field_val:
for entity_categ, entities in field_val.items():
#update_db_dict['push_all__not_unique_entity_error_dict'] = entities
update_db_dict['add_to_set__not_unique_entity_error_dict__'+entity_categ] = entities
update_db_dict['inc__version__0'] = 1
elif field_name == 'header_has_mdata':
if update_source == constants.PARSE_HEADER_TASK:
update_db_dict['set__header_has_mdata'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'md5':
if update_source == constants.CALC_MD5_TASK:
update_db_dict['set__md5'] = field_val
update_db_dict['inc__version__0'] = 1
logging.debug("UPDATING md5")
elif field_name == 'index_file':
if update_source == constants.CALC_MD5_TASK:
if 'md5' in field_val:
update_db_dict['set__index_file__md5'] = field_val['md5']
update_db_dict['inc__version__0'] = 1
else:
raise exceptions.MetadataProblemException("Calc md5 task did not return a dict with an md5 field in it!!!")
#elif field_name == 'hgi_project_list':
elif field_name == 'hgi_project':
if update_source == constants.EXTERNAL_SOURCE:
#for prj in field_val:
if not utils.is_hgi_project(field_val):
raise ValueError("This project name is not according to HGI_project rules -- "+str(constants.REGEX_HGI_PROJECT))
# if getattr(submitted_file, 'hgi_project'):
# hgi_projects = submitted_file.hgi_project
# hgi_projects.extend(field_val)
# else:
# hgi_projects = field_val
update_db_dict['set__hgi_project'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'data_type':
if update_source == constants.EXTERNAL_SOURCE:
update_db_dict['set__data_type'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'data_subtype_tags':
if update_source in [constants.EXTERNAL_SOURCE, constants.PARSE_HEADER_TASK]:
if getattr(submitted_file, 'data_subtype_tags') != None:
subtypes_dict = submitted_file.data_subtype_tags
subtypes_dict.update(field_val)
else:
subtypes_dict = field_val
update_db_dict['set__data_subtype_tags'] = subtypes_dict
update_db_dict['inc__version__0'] = 1
elif field_name == 'abstract_library':
if update_source == constants.EXTERNAL_SOURCE:
update_db_dict['set__abstract_library'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'file_reference_genome_id':
if update_source == constants.EXTERNAL_SOURCE:
models.ReferenceGenome.objects(md5=field_val).get() # Check that the id exists in the RefGenome coll, throw exc
update_db_dict['set__file_reference_genome_id'] = str(field_val)
update_db_dict['inc__version__0'] = 1
elif field_name == 'security_level':
update_db_dict['set__security_level'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'pmid_list':
update_db_dict['set__pmid_list'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'irods_test_run_report':
update_db_dict['set__irods_test_run_report'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name == 'irods_tests_status':
update_db_dict['set__irods_tests_status'] = field_val
update_db_dict['inc__version__0'] = 1
elif field_name != None and field_name != "null":
logging.info("Key in VARS+++++++++++++++++++++++++====== but not in the special list: %s", field_name)
elif field_name == 'reference_genome':
#ref_gen = ReferenceGenomeDataAccess.get_or_insert_reference_genome(field_val) # field_val should be a path
ref_gen = ReferenceGenomeDataAccess.retrieve_reference_by_path(field_val)
if not ref_gen:
raise exceptions.ResourceNotFoundException(field_val, "Reference genome not in the DB.")
update_db_dict['set__file_reference_genome_id'] = ref_gen.md5
else:
logging.error("KEY ERROR RAISED!!! KEY = %s, VALUE = %s", field_name, field_val)
# file_specific_upd_dict = None
# if submitted_file.file_type == constants.BAM_FILE:
# file_specific_upd_dict = cls.build_bam_file_update_dict(file_updates, update_source, file_id, submitted_file)
# elif submitted_file.file_type == constants.VCF_FILE:
# file_specific_upd_dict = cls.build_vcf_file_update_dict(file_updates, update_source, file_id, submitted_file)
# if file_specific_upd_dict:
# update_db_dict.update(file_specific_upd_dict)
return update_db_dict
@classmethod
def save_task_patches(cls, file_id, file_updates, update_source, task_id=None, task_status=None, errors=None, nr_retries=constants.MAX_DBUPDATE_RETRIES):
upd, i = 0, 0
db_update_dict = {}
if task_id:
db_update_dict = {"set__tasks_dict__"+task_id+"__status" : task_status}
if errors:
for e in errors:
db_update_dict['add_to_set__file_error_log'] = e
while i < nr_retries:
submitted_file = cls.retrieve_submitted_file(file_id)
field_updates = cls.build_patch_dict(file_updates, update_source, file_id, submitted_file)
if field_updates:
db_update_dict.update(field_updates)
db_update_dict['inc__version__0'] = 1
if len(db_update_dict) > 0:
logging.info("UPDATE FILE TO SUBMIT - FILE ID: %s and UPD DICT: %s", str(file_id),str(db_update_dict))
try:
upd = models.SubmittedFile.objects(id=file_id, version__0=cls.get_file_version(submitted_file.id, submitted_file)).update_one(**db_update_dict)
except Exception as e:
print("This exception has been thrown:", str(e))
logging.info("ATOMIC UPDATE RESULT from :%s, NR TRY = %s, WAS THE FILE UPDATED? %s", update_source, i, upd)
if upd == 1:
break
i+=1
return upd
@classmethod
def save_task_updates(cls, file_id, file_updates, update_source, task_id=None, task_status=None, errors=None, nr_retries=constants.MAX_DBUPDATE_RETRIES):
upd, i = 0, 0
db_update_dict = {}
if task_id:
db_update_dict = {"set__tasks_dict__"+task_id+"__status" : task_status}
if errors:
for e in errors:
db_update_dict['add_to_set__file_error_log'] = e
while i < nr_retries:
submitted_file = cls.retrieve_submitted_file(file_id)
field_updates = cls.build_update_dict(file_updates, update_source, file_id, submitted_file)
if field_updates:
db_update_dict.update(field_updates)
db_update_dict['inc__version__0'] = 1
if len(db_update_dict) > 0:
logging.info("UPDATE FILE TO SUBMIT - FILE ID: %s and UPD DICT: %s", str(file_id),str(db_update_dict))
try:
upd = models.SubmittedFile.objects(id=file_id, version__0=cls.get_file_version(submitted_file.id, submitted_file)).update_one(**db_update_dict)
except OperationError as e:
print("Operation error caught---: ", str(e))
logging.error("File duplicate in database %s", str(file_id))
print("MESSAGE of the exception:::::", e.message)
print("ARGS of the exception: ::::::::::", e.args)
error_message = "File duplicate in database file_id = %s" % str(file_id)
raise exceptions.FileAlreadySubmittedException(file_id=str(file_id), message=error_message)
logging.info("ATOMIC UPDATE RESULT from :%s, NR TRY = %s, WAS THE FILE UPDATED? %s", update_source, i, upd)
if upd == 1:
break
i+=1
return upd
@classmethod
def update_data_subtype_tags(cls, file_id, subtype_tags_dict):
return models.SubmittedFile.objects(id=file_id).update_one(set__data_subtype_tags=subtype_tags_dict, inc__version__0=1)
@classmethod
def update_file_ref_genome(cls, file_id, ref_genome_key): # the ref genome key is the md5
return models.SubmittedFile.objects(id=file_id).update_one(set__file_reference_genome_id=ref_genome_key, inc__version__0=1)
@classmethod
def update_file_data_type(cls, file_id, data_type):
return models.SubmittedFile.objects(id=file_id).update_one(set__data_type=data_type, inc__version__0=1)
@classmethod
def update_file_abstract_library(cls, file_id, abstract_lib):
return models.SubmittedFile.objects(id=file_id, abstract_library=None).update_one(set__abstract_library=abstract_lib, inc__version__0=1)
@classmethod
def update_file_submission_status(cls, file_id, status):
upd_dict = {'set__file_submission_status' : status, 'inc__version__0' : 1}
return models.SubmittedFile.objects(id=file_id).update_one(**upd_dict)
@classmethod
def build_file_statuses_updates_dict(cls, file_id, statuses_dict):
if not statuses_dict:
return 0
upd_dict = dict()
for k,v in list(statuses_dict.items()):
upd_dict['set__'+k] = v
upd_dict['inc__version__0'] = 1
return upd_dict
@classmethod
def update_file_statuses(cls, file_id, statuses_dict):
upd_dict = cls.build_file_statuses_updates_dict(file_id, statuses_dict)
return models.SubmittedFile.objects(id=file_id).update_one(**upd_dict)
@classmethod
def update_file_mdata_status(cls, file_id, status):
upd_dict = {'set__file_mdata_status' : status, 'inc__version__0' : 1}
return models.SubmittedFile.objects(id=file_id).update_one(**upd_dict)
@classmethod
def build_file_error_log_update_dict(cls, error_log, file_id=None, submitted_file=None):
if file_id == None and submitted_file == None:
return None
if submitted_file == None:
submitted_file = cls.retrieve_submitted_file(file_id)
old_error_log = submitted_file.file_error_log
if type(error_log) == list:
old_error_log.extend(error_log)
elif type(error_log) == str or type(error_log) == str:
old_error_log.append(error_log)
logging.error("IN UPDATE ERROR LOG LIST ------------------- PRINT ERROR LOG LIST:::::::::::: %s", ' '.join(str(it) for it in error_log))
upd_dict = {'set__file_error_log' : old_error_log, 'inc__version__0' : 1}
return upd_dict
@classmethod
def save_update_dict(cls, file_id, file_version, updates_dict, nr_retries=constants.MAX_DBUPDATE_RETRIES):
i = 0
upd = 0
while i < nr_retries and upd == 0:
i+=1
upd = models.SubmittedFile.objects(id=file_id, version__0=file_version).update_one(**updates_dict)
print("UPD ------------ from save_update_dict: ", str(upd))
return upd
@classmethod
def update_file_error_log(cls, error_log, file_id=None, submitted_file=None):
upd_dict = cls.build_file_error_log_update_dict(error_log, file_id, submitted_file)
return models.SubmittedFile.objects(id=submitted_file.id, version__0=cls.get_file_version(None, submitted_file)).update_one(**upd_dict)
@classmethod
def add_task_to_file(cls, file_id, task_id, task_type, task_status, nr_retries=constants.MAX_DBUPDATE_RETRIES):
upd_dict = {'set__tasks_dict__'+task_id : {'type' : task_type, 'status' : task_status}, 'inc__version__0' : 1}
upd = 0
while nr_retries > 0 and upd == 0:
upd = models.SubmittedFile.objects(id=file_id).update_one(**upd_dict)
logging.info("ADDING NEW TASK TO TASKS dict %s", upd)
return upd
@classmethod
def update_task_status(cls, file_id, task_id, task_status, errors=None, nr_retries=constants.MAX_DBUPDATE_RETRIES):
upd_dict = {'set__tasks_dict__'+task_id+'__status' : task_status, 'inc__version__0' : 1}
if errors:
for e in errors:
upd_dict['add_to_set__file_error_log'] = e
upd = 0
while nr_retries > 0 and upd == 0:
upd = models.SubmittedFile.objects(id=file_id).update_one(**upd_dict)
logging.info("UPDATING TASKS dict %s", upd)
return upd
# - 2nd elem of the list = version of the list of samples mdata
# - 3rd elem of the list = version of the list of libraries mdata
# - 4th elem of the list = version of the list of studies mdata
# Possible PROBLEM: here I update without taking into account the version of the file. If there was an update in the meantime,
# this can lead to loss of information
@classmethod
def update_file_from_dict(cls, file_id, update_dict, update_type_list=[constants.FILE_FIELDS_UPDATE], nr_retries=constants.MAX_DBUPDATE_RETRIES):
db_upd_dict = {}
for upd_type in update_type_list:
if upd_type == constants.FILE_FIELDS_UPDATE:
db_upd_dict['inc__version__0'] = 1
elif upd_type == constants.SAMPLE_UPDATE:
db_upd_dict['inc__version__1'] = 1
elif upd_type == constants.LIBRARY_UPDATE:
db_upd_dict['inc__version__2'] = 1
elif upd_type == constants.STUDY_UPDATE:
db_upd_dict['inc__version__3'] = 1
else:
logging.error("Update file fields -- Different updates than the 4 type acccepted? %s", update_type_list)
for upd_field, val in list(update_dict.items()):
db_upd_dict['set__'+upd_field] = val
upd, i = 0, 0
while i < nr_retries and upd == 0:
upd = models.SubmittedFile.objects(id=file_id).update_one(**db_upd_dict)
return upd
# PB: I am not keeping track of submission's version...
# PB: I am not returning an error code/ Exception if the hgi-project name is incorrect!!!
@classmethod
def insert_hgi_project(cls, subm_id, project):
if utils.is_hgi_project(project):
upd_dict = {'set__hgi_project' : project}
return models.Submission.objects(id=subm_id).update_one(**upd_dict)
# upd_dict = {'add_to_set__hgi_project_list' : project}
# return models.Submission.objects(id=subm_id).update_one(**upd_dict)
@classmethod
def delete_library(cls, library_id, file_id, file_obj=None):
if not file_obj:
file_obj = cls.retrieve_SFile_fields_only(file_id, ['library_list', 'version'])
new_list = []
found = False
for lib in file_obj.library_list:
if lib.internal_id != int(library_id):
new_list.append(lib)
else:
found = True
if found == True:
return models.SubmittedFile.objects(id=file_id, version__2=cls.get_library_version(file_obj.id, file_obj)).update_one(inc__version__2=1, inc__version__0=1, set__library_list=new_list)
else:
raise exceptions.ResourceNotFoundException(library_id)
#sample_id,file_id, file_obj)
@classmethod
def delete_sample(cls, sample_id, file_id, file_obj=None):
if not file_obj:
file_obj = cls.retrieve_SFile_fields_only(file_id, ['sample_list', 'version'])
new_list = []
found = False
for sample in file_obj.entity_set:
if sample.internal_id != int(sample_id):
new_list.append(sample)
else:
found = True
if found == True:
return models.SubmittedFile.objects(id=file_id, version__1=cls.get_sample_version(file_obj.id, file_obj)).update_one(inc__version__1=1, inc__version__0=1, set__sample_list=new_list)
else:
raise exceptions.ResourceNotFoundException(sample_id)
@classmethod
def delete_study(cls, study_id, file_id, file_obj=None):
if not file_obj:
file_obj = cls.retrieve_SFile_fields_only(file_id, ['study_list', 'version'])
new_list = []
found = False
for study in file_obj.study_list:
if study.internal_id != int(study_id):
new_list.append(study)
else:
found = True
if found == True:
return models.SubmittedFile.objects(id=file_id, version__3=cls.get_study_version(file_obj.id, file_obj)).update_one(inc__version__3=1, inc__version__0=1, set__study_list=new_list)
else:
raise exceptions.ResourceNotFoundException(study_id)
@classmethod
def delete_submitted_file(cls, file_id, submitted_file=None):
if submitted_file == None:
submitted_file = models.SubmittedFile.objects(id=file_id)
submitted_file.delete()
return True
# file_specific_upd_dict = None
# if submitted_file.file_type == constants.BAM_FILE:
# file_specific_upd_dict = cls.build_bam_file_update_dict(file_updates, update_source, file_id, submitted_file)
# elif submitted_file.file_type == constants.VCF_FILE:
# file_specific_upd_dict = cls.build_vcf_file_update_dict(file_updates, update_source, file_id, submitted_file)
# if file_specific_upd_dict:
# update_db_dict.update(file_specific_upd_dict)
# return update_db_dict
class BAMFileDataAccess(FileDataAccess):
@classmethod
def build_dict_of_updates(cls, file_updates, update_source, file_id, submitted_file):
if not file_updates:
return None
update_db_dict = {}
for (field_name, field_val) in file_updates.items():
if field_val == 'null' or not field_val:
pass
if field_name in submitted_file._fields:
if field_name in ['submission_id',
'id',
'_id',
'version',
'file_type',
'irods_coll', # TODO: make it updateble by user, if file not yet submitted to permanent irods coll
'file_path_client',
'last_updates_source',
'file_mdata_status',
'file_submission_status',
'missing_mandatory_fields_dict']:
pass
elif field_name == 'seq_centers':
if update_source in [constants.PARSE_HEADER_TASK, constants.EXTERNAL_SOURCE]:
updated_list = cls.__upd_list_of_primary_types__(submitted_file.seq_centers, field_val)
update_db_dict['set__seq_centers'] = updated_list
#update_db_dict['inc__version__0'] = 1
elif field_name == 'run_list':
if update_source in [constants.PARSE_HEADER_TASK, constants.EXTERNAL_SOURCE]:
updated_list = cls.__upd_list_of_primary_types__(submitted_file.run_list, field_val)
update_db_dict['set__run_list'] = updated_list
#update_db_dict['inc__version__0'] = 1
elif field_name == 'platform_list':
if update_source in [constants.PARSE_HEADER_TASK, constants.EXTERNAL_SOURCE]:
updated_list = cls.__upd_list_of_primary_types__(submitted_file.platform_list, field_val)
update_db_dict['set__platform_list'] = updated_list
elif field_name == 'seq_date_list':
if update_source in [constants.PARSE_HEADER_TASK, constants.EXTERNAL_SOURCE]:
updated_list = cls.__upd_list_of_primary_types__(submitted_file.seq_date_list, field_val)
update_db_dict['set__seq_date_list'] = updated_list
elif field_name == 'library_well_list':
if update_source in [constants.PARSE_HEADER_TASK, constants.EXTERNAL_SOURCE]:
updated_list = cls.__upd_list_of_primary_types__(submitted_file.library_well_list, field_val)
update_db_dict['set__library_well_list'] = updated_list
elif field_name == 'multiplex_lib_list':
if update_source in [constants.PARSE_HEADER_TASK, constants.EXTERNAL_SOURCE]:
updated_list = cls.__upd_list_of_primary_types__(submitted_file.multiplex_lib_list, field_val)
update_db_dict['set__multiplex_lib_list'] = updated_list
return update_db_dict
@classmethod
def build_patch_dict(cls, file_updates, update_source, file_id, submitted_file):
general_file_patches = super(BAMFileDataAccess, cls).build_patch_dict(file_updates, update_source, file_id, submitted_file)
file_specific_patches = cls.build_dict_of_updates(file_updates, update_source, file_id, submitted_file)
general_file_patches.update(file_specific_patches)
return general_file_patches
@classmethod
def build_update_dict(cls, file_updates, update_source, file_id, submitted_file):
general_file_updates = super(BAMFileDataAccess, cls).build_update_dict(file_updates, update_source, file_id, submitted_file) or {}
file_specific_updates = cls.build_dict_of_updates(file_updates, update_source, file_id, submitted_file)
general_file_updates.update(file_specific_updates)
return general_file_updates
class VCFFileDataAccess(FileDataAccess):
@classmethod
def build_dict_of_updates(cls, file_updates, update_source, file_id, submitted_file):
if not file_updates:
return {}
update_db_dict = {}
for (field_name, field_val) in file_updates.items():
if field_val == 'null' or not field_val:
pass
elif field_name == 'used_samtools':
update_db_dict['set__used_samtools'] = field_val
elif field_name == 'file_format':
update_db_dict['set__file_format'] = field_val
return update_db_dict
@classmethod
def build_patch_dict(cls, file_updates, update_source, file_id, submitted_file):
if not file_updates:
return {}
general_updates_dict = super(VCFFileDataAccess, cls).build_patch_dict(file_updates, update_source, file_id, submitted_file)
file_specific_upd_dict = cls.build_dict_of_updates(file_updates, update_source, file_id, submitted_file)
general_updates_dict.update(file_specific_upd_dict)
return general_updates_dict
@classmethod
def build_update_dict(cls, file_updates, update_source, file_id, submitted_file):
if not file_updates:
return {}
general_updates_dict = super(VCFFileDataAccess, cls).build_update_dict(file_updates, update_source, file_id, submitted_file)
file_specif_upd_dict = cls.build_dict_of_updates(file_updates, update_source, file_id, submitted_file)
general_updates_dict.update(file_specif_upd_dict)
return general_updates_dict
class ReferenceGenomeDataAccess(DataAccess):
# @classmethod
# def insert_reference_genome(cls, ref_dict):
# ref_genome = models.ReferenceGenome()
# if 'name' in ref_dict:
# #ref_name = ref_dict['name']
# ref_genome.name = ref_dict['name']
# if 'path' in ref_dict:
# ref_genome.paths = [ref_dict['path']]
# else:
# raise exceptions.NotEnoughInformationProvided(msg="You must provide both the name and the path for the reference genome.")
# md5 = utils.calculate_md5(ref_dict['path'])
# ref_genome.md5 = md5
# print "REF GENOME TO BE INSERTED::::::::::::", vars(ref_genome)
# ref_genome.save()
# return ref_genome
#
@classmethod
def insert_into_db(cls, ref_genome_dict):
ref_gen = models.ReferenceGenome()
if 'name' in ref_genome_dict:
ref_gen.name = ref_genome_dict['name']
print("NAME: ", ref_gen.name)
if 'path' in ref_genome_dict:
ref_gen.paths = [ref_genome_dict['path']]
print("PATHS: ", ref_gen.paths)
ref_gen.md5 = utils.calculate_md5(ref_genome_dict['path'])
print("REF GEN BEFORE ADDING IT: ;:::::::::::::::", vars(ref_gen))
ref_gen.save()
return ref_gen
#def insert_reference_genome(ref_dict):
# ref_genome = models.ReferenceGenome()
# if 'name' in ref_dict:
# #ref_name = ref_dict['name']
# ref_genome.name = ref_dict['name']
# if 'path' in ref_dict:
# if not type(ref_dict['path']) == list:
# ref_genome.paths = [ref_dict['path']]
# else:
# ref_genome.paths = ref_dict
# else:
# raise exceptions.NotEnoughInformationProvided(msg="You must provide both the name and the path for the reference genome.")
## ref_genome.name = ref_name
## ref_genome.paths = path_list
##
# for path in ref_genome.paths:
# md5 = calculate_md5(path)
# ref_genome.md5 = md5
# ref_genome.save()
# return ref_genome
@classmethod
def retrieve_all(cls):
return models.ReferenceGenome.objects()
@classmethod
def retrieve_reference_by_path(cls, path):
try:
return models.ReferenceGenome.objects(paths__in=[path]).hint([('paths', 1)]).get()
except DoesNotExist:
return None
@classmethod
def retrieve_reference_by_md5(cls, md5):
try:
found = models.ReferenceGenome.objects.get(pk=md5)
return found
except DoesNotExist:
return None
@classmethod
def retrieve_reference_by_id(cls, ref_id):
return cls.retrieve_reference_by_md5(ref_id)
@classmethod
def retrieve_reference_by_name(cls, canonical_name):
try:
return models.ReferenceGenome.objects(name=canonical_name).get()
except DoesNotExist:
return None
# NOT USED< I THINK
@classmethod
def retrieve_reference_genome(cls, ref_gen_dict):
if not ref_gen_dict:
raise exceptions.NoIdentifyingFieldsProvidedException("No identifying fields provided for the reference genome.")
ref_gen_id_by_name, ref_gen_id_by_path = None, None
if 'name' in ref_gen_dict:
ref_gen_id_by_name = cls.retrieve_reference_by_name(ref_gen_dict['name'])
if 'path' in ref_gen_dict:
ref_gen_id_by_path = cls.retrieve_reference_by_path(ref_gen_dict['path'])
if ref_gen_id_by_name and ref_gen_id_by_path and ref_gen_id_by_name != ref_gen_id_by_path:
raise exceptions.InformationConflictException(msg="The reference genome name "+ref_gen_dict['name'] +"and the path "+ref_gen_dict['path']+" corresponds to different entries in our DB.")
if ref_gen_id_by_name:
return ref_gen_id_by_name.id
if ref_gen_id_by_path:
return ref_gen_id_by_path.id
return None
@classmethod
def update(cls, ref_id, ref_dict):
old_ref = cls.retrieve_reference_by_id(ref_id)
update_dict = {}
if 'name' in ref_dict and old_ref.name != ref_dict['name']:
update_dict['set__name'] = ref_dict['name']
if 'path' in ref_dict:
paths = old_ref.paths
paths.append(ref_dict['path'])
paths = list(set(paths))
if paths != old_ref.paths:
update_dict['set__paths'] = paths
if update_dict:
update_dict['inc__version'] = 1
updated = models.ReferenceGenome.objects(md5=ref_id, version=old_ref.version).update_one(**update_dict)
return updated
return None
# for (field_name, field_val) in file_updates.iteritems():
# if field_val == 'null' or not field_val:
# pass
# if field_name in submitted_file._fields:
#
#
# @classmethod
# def get_or_insert_reference_genome(cls, file_path):
# ''' This function receives a path identifying
# a reference file and retrieves it from the database
# or inserts it if it's not there.
# Parameters: a path(string)
# Throws:
# - TooMuchInformationProvided exception - when the dict has more than a field
# - NotEnoughInformationProvided - when the dict is empty
# '''
# if not file_path:
# raise exceptions.NotEnoughInformationProvided(msg="ERROR: the path of the reference genome must be provided.")
# ref_gen = cls.retrieve_reference_by_path(file_path)
# if ref_gen:
# return ref_gen
# return cls.insert_reference_genome({'path' : file_path})
#
#
# @classmethod
# def get_or_insert_reference_genome_path_and_name(cls, data):
# ''' This function receives a dictionary with data identifying
# a reference genome and retrieves it from the data base.
# Parameters: a dictionary
# Throws:
# - TooMuchInformationProvided exception - when the dict has more than a field
# - NotEnoughInformationProvided - when the dict is empty
# '''
# if not 'name' in data and not 'path' in data:
# raise exceptions.NotEnoughInformationProvided(msg="ERROR: either the name or the path of the reference genome must be provided.")
# ref_gen = cls.retrieve_reference_genome(data)
# if ref_gen:
# return ref_gen
# return cls.insert_reference_genome(data)
#
| agpl-3.0 | 4,441,826,606,016,935,000 | 48.87619 | 197 | 0.578022 | false | 3.909986 | false | false | false |
nismod/energy_demand | tests/read_write/test_narrative_related.py | 1 | 3498 | from energy_demand.read_write.narrative_related import crit_dim_var
from collections import OrderedDict
class TestCritDimensionsVar:
def test_crit_in_list(self):
crit_in_list = [
{'sig_midpoint': 0, 'value_by': 5, 'diffusion_choice': 'linear',
'fueltype_replace': 0, 'regional_specific': False,
'base_yr': 2015, 'value_ey': 5, 'sig_steepness': 1,
'end_yr': 2050, 'fueltype_new': 0}]
actual = crit_dim_var(crit_in_list)
expected = True
print("AC ULT " + str(actual))
assert actual == expected
def test_nested_dict_in_list(self):
nested_dict_in_list = [{'key': {'nested_dict': 'a value'}}]
actual = crit_dim_var(nested_dict_in_list)
expected = False
print("AC ULT " + str(actual))
assert actual == expected
def test_nested_dict(self):
nested_dict = {'key': {'nested_dict': 'a value'}}
actual = crit_dim_var(nested_dict)
expected = False
assert actual == expected
nested_dict = {'another_key': {}, 'key': []}
actual = crit_dim_var(nested_dict)
expected = True
assert actual == expected
def test_crit_list(self):
a_list = []
actual = crit_dim_var(a_list)
expected = True
assert actual == expected
the_bug = {'enduse': [], 'diffusion_type': 'linear', 'default_value': 15.5,
'name': 'ss_t_base_heating', 'sector': True,
'regional_specific': False,
'description': 'Base temperature',
'scenario_value': 15.5}
actual = crit_dim_var(the_bug)
expected = True
assert actual == expected
def test_crit_dim_var_ordered(self):
the_bug = OrderedDict()
the_bug['a'] = {'diffusion_type': 'linear', 'default_value': 15.5,
'name': 'ss_t_base_heating', 'sector': True,
'regional_specific': False,
'description': 'Base temperature',
'scenario_value': 15.5,
'enduse': []}
the_bug['b'] = 'vakye'
actual = crit_dim_var(the_bug)
expected = False
assert actual == expected
def test_crit_dim_var_buggy(self):
fixture = [
{'sig_steepness': 1,
'sector': 'dummy_sector',
'diffusion_choice': 'linear',
'sig_midpoint': 0,
'regional_specific': True,
'base_yr': 2015,
'value_ey': 0.05,
'value_by': 0.05,
'regional_vals_ey': {'W06000023': 0.05, 'W06000010': 0.05},
'regional_vals_by': {'W06000023': 0.05, 'W06000010': 0.05},
'end_yr': 2030,
'enduse': [],
'default_by': 0.05
},
{'sig_steepness': 1,
'sector': 'dummy_sector',
'diffusion_choice': 'linear',
'sig_midpoint': 0,
'regional_specific': True,
'base_yr': 2030,
'value_ey': 0.05,
'value_by': 0.05,
'regional_vals_ey': {'W06000023': 0.05, 'W06000010': 0.05},
'regional_vals_by': {'W06000023': 0.05, 'W06000010': 0.05},
'end_yr': 2050,
'enduse': [],
'default_by': 0.05
}
]
actual = crit_dim_var(fixture)
expected = True
assert actual == expected
| mit | 2,737,258,833,728,051,000 | 32.314286 | 83 | 0.493711 | false | 3.591376 | true | false | false |
dndtools/dndtools | dndtools/dnd/mobile/mobile_dispatcher.py | 4 | 1401 | # -*- coding: utf-8 -*-
import re
from django.core.urlresolvers import reverse
class MobileDispatcher(object):
def __init__(self):
# TODO autodispatch
self.dispatch_methods = {}
for method_name in dir(self):
m = re.match(r'^_dispatch_(.*)$', method_name)
if m:
dispatch_method = getattr(self, method_name)
if hasattr(dispatch_method, '__call__'):
self.dispatch_methods[m.group(1)] = dispatch_method
pass
def dispatch(self, view_func_name, args, kwargs):
if view_func_name in self.dispatch_methods:
return self.dispatch_methods[view_func_name](args, kwargs)
return None
@staticmethod
def _dispatch_feat_index(args, kwargs):
return reverse('feat_index_mobile')
@staticmethod
def _dispatch_feat_category_list(args, kwargs):
return reverse('feat_detail_mobile')
@staticmethod
def _dispatch_feat_category_detail(args, kwargs):
return reverse('feat_category_detail_mobile', kwargs=kwargs)
@staticmethod
def _dispatch_feats_in_rulebook(args, kwargs):
return reverse('feats_in_rulebook_mobile', kwargs={'rulebook_id': kwargs['rulebook_id']})
@staticmethod
def _dispatch_feat_detail(args, kwargs):
return reverse('feat_detail_mobile', kwargs={'feat_id': kwargs['feat_id']}) | mit | -834,625,915,420,921,500 | 29.478261 | 97 | 0.624554 | false | 4.037464 | false | false | false |
jkleckner/ansible | setup.py | 5 | 1396 | #!/usr/bin/env python
import os
import sys
from glob import glob
sys.path.insert(0, os.path.abspath('lib'))
from ansible import __version__, __author__
from distutils.core import setup
# find library modules
from ansible.constants import DEFAULT_MODULE_PATH
dirs=os.listdir("./library/")
data_files = []
for i in dirs:
data_files.append((os.path.join(DEFAULT_MODULE_PATH, i), glob('./library/' + i + '/*')))
setup(name='ansible',
version=__version__,
description='Radically simple IT automation',
author=__author__,
author_email='[email protected]',
url='http://ansibleworks.com/',
license='GPLv3',
install_requires=['paramiko', 'jinja2', "PyYAML"],
package_dir={ 'ansible': 'lib/ansible' },
packages=[
'ansible',
'ansible.utils',
'ansible.inventory',
'ansible.inventory.vars_plugins',
'ansible.playbook',
'ansible.runner',
'ansible.runner.action_plugins',
'ansible.runner.lookup_plugins',
'ansible.runner.connection_plugins',
'ansible.runner.filter_plugins',
'ansible.callback_plugins',
'ansible.module_utils'
],
scripts=[
'bin/ansible',
'bin/ansible-playbook',
'bin/ansible-pull',
'bin/ansible-doc',
'bin/ansible-galaxy'
],
data_files=data_files
)
| gpl-3.0 | -2,027,185,799,533,219,000 | 27.489796 | 92 | 0.604585 | false | 3.84573 | false | false | false |
jindaxia/you-get | src/you_get/extractors/dilidili.py | 2 | 2738 | #!/usr/bin/env python
__all__ = ['dilidili_download']
from ..common import *
#----------------------------------------------------------------------
def dilidili_parser_data_to_stream_types(typ ,vid ,hd2 ,sign):
"""->list"""
parse_url = 'http://player.005.tv/parse.php?xmlurl=null&type={typ}&vid={vid}&hd={hd2}&sign={sign}'.format(typ = typ, vid = vid, hd2 = hd2, sign = sign)
html = get_html(parse_url)
info = re.search(r'(\{[^{]+\})(\{[^{]+\})(\{[^{]+\})(\{[^{]+\})(\{[^{]+\})', html).groups()
info = [i.strip('{}').split('->') for i in info]
info = {i[0]: i [1] for i in info}
stream_types = []
for i in zip(info['deft'].split('|'), info['defa'].split('|')):
stream_types.append({'id': str(i[1][-1]), 'container': 'mp4', 'video_profile': i[0]})
return stream_types
#----------------------------------------------------------------------
def dilidili_parser_data_to_download_url(typ ,vid ,hd2 ,sign):
"""->str"""
parse_url = 'http://player.005.tv/parse.php?xmlurl=null&type={typ}&vid={vid}&hd={hd2}&sign={sign}'.format(typ = typ, vid = vid, hd2 = hd2, sign = sign)
html = get_html(parse_url)
return match1(html, r'<file><!\[CDATA\[(.+)\]\]></file>')
#----------------------------------------------------------------------
def dilidili_download(url, output_dir = '.', merge = False, info_only = False, **kwargs):
if re.match(r'http://www.dilidili.com/watch/\w+', url):
html = get_html(url)
title = match1(html, r'<title>(.+)丨(.+)</title>') #title
# player loaded via internal iframe
frame_url = re.search(r'<iframe (.+)src="(.+)\" f(.+)</iframe>', html).group(2)
#https://player.005.tv:60000/?vid=a8760f03fd:a04808d307&v=yun&sign=a68f8110cacd892bc5b094c8e5348432
html = get_html(frame_url)
match = re.search(r'(.+?)var video =(.+?);', html)
vid = match1(html, r'var vid="(.+)"')
hd2 = match1(html, r'var hd2="(.+)"')
typ = match1(html, r'var typ="(.+)"')
sign = match1(html, r'var sign="(.+)"')
# here s the parser...
stream_types = dilidili_parser_data_to_stream_types(typ, vid, hd2, sign)
#get best
best_id = max([i['id'] for i in stream_types])
url = dilidili_parser_data_to_download_url(typ, vid, best_id, sign)
type_ = ''
size = 0
type_, ext, size = url_info(url)
print_info(site_info, title, type_, size)
if not info_only:
download_urls([url], title, ext, total_size=None, output_dir=output_dir, merge=merge)
site_info = "dilidili"
download = dilidili_download
download_playlist = playlist_not_supported('dilidili')
| mit | -8,038,797,522,279,569,000 | 41.092308 | 155 | 0.51133 | false | 3.067265 | false | false | false |
littlezz/IslandCollection | core/islands/koukuko.py | 1 | 1292 | from .base import BaseIsland
from core.islands.mixins import NextPageJsonParameterMixin
from urllib import parse
__author__ = 'zz'
class KoukokuIsland(NextPageJsonParameterMixin, BaseIsland):
"""
光驱岛
"""
_island_name = 'kukuku'
_island_netloc = 'kukuku.cc'
_static_root = 'http://static.koukuko.com/h/'
json_data = True
def get_tips(self, pd):
return [thread for thread in pd['data']['threads']]
def get_div_link(self, tip):
thread_id = tip['id']
suffix = 't' + '/' + str(thread_id)
return parse.urljoin(self.root_url, suffix)
def get_div_content_text(self, tip):
return tip['content']
def get_div_response_num(self, tip):
return tip['replyCount']
def get_div_image(self, tip):
thumb = tip['thumb']
return self.complete_image_link(thumb)
@staticmethod
def init_start_url(start_url):
if '.json' not in start_url:
parts = parse.urlsplit(start_url)
path = parts.path + '.json'
return parse.urlunsplit((parts.scheme, parts.netloc, path, parts.query, parts.fragment))
class OldKoukukoIsland(KoukokuIsland):
"""
旧光驱岛域名
"""
_island_netloc = 'h.koukuko.com'
_island_name = 'old_koukuko'
| mit | -627,006,767,951,967,000 | 25.541667 | 100 | 0.61617 | false | 3.06988 | false | false | false |
GNOME/pygobject | tests/test_iochannel.py | 1 | 16023 | # -*- Mode: Python -*-
import os
import unittest
import tempfile
import os.path
import shutil
import warnings
try:
import fcntl
except ImportError:
fcntl = None
from gi.repository import GLib
from gi import PyGIDeprecationWarning
class IOChannel(unittest.TestCase):
def setUp(self):
self.workdir = tempfile.mkdtemp()
self.testutf8 = os.path.join(self.workdir, 'testutf8.txt')
with open(self.testutf8, 'wb') as f:
f.write(u'''hello ♥ world
second line
À demain!'''.encode('UTF-8'))
self.testlatin1 = os.path.join(self.workdir, 'testlatin1.txt')
with open(self.testlatin1, 'wb') as f:
f.write(b'''hell\xf8 world
second line
\xc0 demain!''')
self.testout = os.path.join(self.workdir, 'testout.txt')
def tearDown(self):
shutil.rmtree(self.workdir)
def test_file_readline_utf8(self):
ch = GLib.IOChannel(filename=self.testutf8)
self.assertEqual(ch.get_encoding(), 'UTF-8')
self.assertTrue(ch.get_close_on_unref())
self.assertEqual(ch.readline(), 'hello ♥ world\n')
self.assertEqual(ch.get_buffer_condition(), GLib.IOCondition.IN)
self.assertEqual(ch.readline(), 'second line\n')
self.assertEqual(ch.readline(), '\n')
self.assertEqual(ch.readline(), 'À demain!')
self.assertEqual(ch.get_buffer_condition(), 0)
self.assertEqual(ch.readline(), '')
ch.shutdown(True)
def test_file_readline_latin1(self):
ch = GLib.IOChannel(filename=self.testlatin1, mode='r')
ch.set_encoding('latin1')
self.assertEqual(ch.get_encoding(), 'latin1')
self.assertEqual(ch.readline(), 'hellø world\n')
self.assertEqual(ch.readline(), 'second line\n')
self.assertEqual(ch.readline(), '\n')
self.assertEqual(ch.readline(), 'À demain!')
ch.shutdown(True)
def test_file_iter(self):
items = []
ch = GLib.IOChannel(filename=self.testutf8)
for item in ch:
items.append(item)
self.assertEqual(len(items), 4)
self.assertEqual(items[0], 'hello ♥ world\n')
ch.shutdown(True)
def test_file_readlines(self):
ch = GLib.IOChannel(filename=self.testutf8)
lines = ch.readlines()
# Note, this really ought to be 4, but the static bindings add an extra
# empty one
self.assertGreaterEqual(len(lines), 4)
self.assertLessEqual(len(lines), 5)
self.assertEqual(lines[0], 'hello ♥ world\n')
self.assertEqual(lines[3], 'À demain!')
if len(lines) == 4:
self.assertEqual(lines[4], '')
def test_file_read(self):
ch = GLib.IOChannel(filename=self.testutf8)
with open(self.testutf8, 'rb') as f:
self.assertEqual(ch.read(), f.read())
ch = GLib.IOChannel(filename=self.testutf8)
with open(self.testutf8, 'rb') as f:
self.assertEqual(ch.read(10), f.read(10))
ch = GLib.IOChannel(filename=self.testutf8)
with open(self.testutf8, 'rb') as f:
self.assertEqual(ch.read(max_count=15), f.read(15))
def test_seek(self):
ch = GLib.IOChannel(filename=self.testutf8)
ch.seek(2)
self.assertEqual(ch.read(3), b'llo')
ch.seek(2, 0) # SEEK_SET
self.assertEqual(ch.read(3), b'llo')
ch.seek(1, 1) # SEEK_CUR, skip the space
self.assertEqual(ch.read(3), b'\xe2\x99\xa5')
ch.seek(2, 2) # SEEK_END
# FIXME: does not work currently
# self.assertEqual(ch.read(2), b'n!')
# invalid whence value
self.assertRaises(ValueError, ch.seek, 0, 3)
ch.shutdown(True)
def test_file_write(self):
ch = GLib.IOChannel(filename=self.testout, mode='w')
ch.set_encoding('latin1')
ch.write('hellø world\n')
ch.shutdown(True)
ch = GLib.IOChannel(filename=self.testout, mode='a')
ch.set_encoding('latin1')
ch.write('À demain!')
ch.shutdown(True)
with open(self.testout, 'rb') as f:
self.assertEqual(f.read().decode('latin1'), u'hellø world\nÀ demain!')
def test_file_writelines(self):
ch = GLib.IOChannel(filename=self.testout, mode='w')
ch.writelines(['foo', 'bar\n', 'baz\n', 'end'])
ch.shutdown(True)
with open(self.testout, 'r') as f:
self.assertEqual(f.read(), 'foobar\nbaz\nend')
def test_buffering(self):
writer = GLib.IOChannel(filename=self.testout, mode='w')
writer.set_encoding(None)
self.assertTrue(writer.get_buffered())
self.assertGreater(writer.get_buffer_size(), 10)
reader = GLib.IOChannel(filename=self.testout, mode='r')
# does not get written immediately on buffering
writer.write('abc')
self.assertEqual(reader.read(), b'')
writer.flush()
self.assertEqual(reader.read(), b'abc')
# does get written immediately without buffering
writer.set_buffered(False)
writer.write('def')
self.assertEqual(reader.read(), b'def')
# writes after buffer overflow
writer.set_buffer_size(10)
writer.write('0123456789012')
self.assertTrue(reader.read().startswith(b'012'))
writer.flush()
reader.read() # ignore bits written after flushing
# closing flushes
writer.set_buffered(True)
writer.write('ghi')
writer.shutdown(True)
self.assertEqual(reader.read(), b'ghi')
reader.shutdown(True)
@unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
def test_fd_read(self):
(r, w) = os.pipe()
ch = GLib.IOChannel(filedes=r)
ch.set_encoding(None)
ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
self.assertNotEqual(ch.get_flags() | GLib.IOFlags.NONBLOCK, 0)
self.assertEqual(ch.read(), b'')
os.write(w, b'\x01\x02')
self.assertEqual(ch.read(), b'\x01\x02')
# now test blocking case, after closing the write end
ch.set_flags(GLib.IOFlags(ch.get_flags() & ~GLib.IOFlags.NONBLOCK))
os.write(w, b'\x03\x04')
os.close(w)
self.assertEqual(ch.read(), b'\x03\x04')
ch.shutdown(True)
@unittest.skipUnless(fcntl, "no fcntl")
def test_fd_write(self):
(r, w) = os.pipe()
fcntl.fcntl(r, fcntl.F_SETFL, fcntl.fcntl(r, fcntl.F_GETFL) | os.O_NONBLOCK)
ch = GLib.IOChannel(filedes=w, mode='w')
ch.set_encoding(None)
ch.set_buffered(False)
ch.write(b'\x01\x02')
self.assertEqual(os.read(r, 10), b'\x01\x02')
# now test blocking case, after closing the write end
fcntl.fcntl(r, fcntl.F_SETFL, fcntl.fcntl(r, fcntl.F_GETFL) & ~os.O_NONBLOCK)
ch.write(b'\x03\x04')
ch.shutdown(True)
self.assertEqual(os.read(r, 10), b'\x03\x04')
os.close(r)
@unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
def test_deprecated_method_add_watch_no_data(self):
(r, w) = os.pipe()
ch = GLib.IOChannel(filedes=r)
ch.set_encoding(None)
ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
cb_reads = []
def cb(channel, condition):
self.assertEqual(channel, ch)
self.assertEqual(condition, GLib.IOCondition.IN)
cb_reads.append(channel.read())
if len(cb_reads) == 2:
ml.quit()
return True
# io_add_watch() method is deprecated, use GLib.io_add_watch
with warnings.catch_warnings(record=True) as warn:
warnings.simplefilter('always')
ch.add_watch(GLib.IOCondition.IN, cb, priority=GLib.PRIORITY_HIGH)
self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
def write():
os.write(w, b'a')
GLib.idle_add(lambda: os.write(w, b'b') and False)
ml = GLib.MainLoop()
GLib.idle_add(write)
GLib.timeout_add(2000, ml.quit)
ml.run()
self.assertEqual(cb_reads, [b'a', b'b'])
@unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
def test_deprecated_method_add_watch_data_priority(self):
(r, w) = os.pipe()
ch = GLib.IOChannel(filedes=r)
ch.set_encoding(None)
ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
cb_reads = []
def cb(channel, condition, data):
self.assertEqual(channel, ch)
self.assertEqual(condition, GLib.IOCondition.IN)
self.assertEqual(data, 'hello')
cb_reads.append(channel.read())
if len(cb_reads) == 2:
ml.quit()
return True
ml = GLib.MainLoop()
# io_add_watch() method is deprecated, use GLib.io_add_watch
with warnings.catch_warnings(record=True) as warn:
warnings.simplefilter('always')
id = ch.add_watch(GLib.IOCondition.IN, cb, 'hello', priority=GLib.PRIORITY_HIGH)
self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
self.assertEqual(ml.get_context().find_source_by_id(id).priority,
GLib.PRIORITY_HIGH)
def write():
os.write(w, b'a')
GLib.idle_add(lambda: os.write(w, b'b') and False)
GLib.idle_add(write)
GLib.timeout_add(2000, ml.quit)
ml.run()
self.assertEqual(cb_reads, [b'a', b'b'])
@unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
def test_add_watch_no_data(self):
(r, w) = os.pipe()
ch = GLib.IOChannel(filedes=r)
ch.set_encoding(None)
ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
cb_reads = []
def cb(channel, condition):
self.assertEqual(channel, ch)
self.assertEqual(condition, GLib.IOCondition.IN)
cb_reads.append(channel.read())
if len(cb_reads) == 2:
ml.quit()
return True
id = GLib.io_add_watch(ch, GLib.PRIORITY_HIGH, GLib.IOCondition.IN, cb)
ml = GLib.MainLoop()
self.assertEqual(ml.get_context().find_source_by_id(id).priority,
GLib.PRIORITY_HIGH)
def write():
os.write(w, b'a')
GLib.idle_add(lambda: os.write(w, b'b') and False)
GLib.idle_add(write)
GLib.timeout_add(2000, ml.quit)
ml.run()
self.assertEqual(cb_reads, [b'a', b'b'])
@unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
def test_add_watch_with_data(self):
(r, w) = os.pipe()
ch = GLib.IOChannel(filedes=r)
ch.set_encoding(None)
ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
cb_reads = []
def cb(channel, condition, data):
self.assertEqual(channel, ch)
self.assertEqual(condition, GLib.IOCondition.IN)
self.assertEqual(data, 'hello')
cb_reads.append(channel.read())
if len(cb_reads) == 2:
ml.quit()
return True
id = GLib.io_add_watch(ch, GLib.PRIORITY_HIGH, GLib.IOCondition.IN, cb, 'hello')
ml = GLib.MainLoop()
self.assertEqual(ml.get_context().find_source_by_id(id).priority,
GLib.PRIORITY_HIGH)
def write():
os.write(w, b'a')
GLib.idle_add(lambda: os.write(w, b'b') and False)
GLib.idle_add(write)
GLib.timeout_add(2000, ml.quit)
ml.run()
self.assertEqual(cb_reads, [b'a', b'b'])
@unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
def test_add_watch_with_multi_data(self):
(r, w) = os.pipe()
ch = GLib.IOChannel(filedes=r)
ch.set_encoding(None)
ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
cb_reads = []
def cb(channel, condition, data1, data2, data3):
self.assertEqual(channel, ch)
self.assertEqual(condition, GLib.IOCondition.IN)
self.assertEqual(data1, 'a')
self.assertEqual(data2, 'b')
self.assertEqual(data3, 'c')
cb_reads.append(channel.read())
if len(cb_reads) == 2:
ml.quit()
return True
id = GLib.io_add_watch(ch, GLib.PRIORITY_HIGH, GLib.IOCondition.IN, cb,
'a', 'b', 'c')
ml = GLib.MainLoop()
self.assertEqual(ml.get_context().find_source_by_id(id).priority,
GLib.PRIORITY_HIGH)
def write():
os.write(w, b'a')
GLib.idle_add(lambda: os.write(w, b'b') and False)
GLib.idle_add(write)
GLib.timeout_add(2000, ml.quit)
ml.run()
self.assertEqual(cb_reads, [b'a', b'b'])
@unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
def test_deprecated_add_watch_no_data(self):
(r, w) = os.pipe()
ch = GLib.IOChannel(filedes=r)
ch.set_encoding(None)
ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
cb_reads = []
def cb(channel, condition):
self.assertEqual(channel, ch)
self.assertEqual(condition, GLib.IOCondition.IN)
cb_reads.append(channel.read())
if len(cb_reads) == 2:
ml.quit()
return True
with warnings.catch_warnings(record=True) as warn:
warnings.simplefilter('always')
id = GLib.io_add_watch(ch, GLib.IOCondition.IN, cb, priority=GLib.PRIORITY_HIGH)
self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
ml = GLib.MainLoop()
self.assertEqual(ml.get_context().find_source_by_id(id).priority,
GLib.PRIORITY_HIGH)
def write():
os.write(w, b'a')
GLib.idle_add(lambda: os.write(w, b'b') and False)
GLib.idle_add(write)
GLib.timeout_add(2000, ml.quit)
ml.run()
self.assertEqual(cb_reads, [b'a', b'b'])
@unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
def test_deprecated_add_watch_with_data(self):
(r, w) = os.pipe()
ch = GLib.IOChannel(filedes=r)
ch.set_encoding(None)
ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
cb_reads = []
def cb(channel, condition, data):
self.assertEqual(channel, ch)
self.assertEqual(condition, GLib.IOCondition.IN)
self.assertEqual(data, 'hello')
cb_reads.append(channel.read())
if len(cb_reads) == 2:
ml.quit()
return True
with warnings.catch_warnings(record=True) as warn:
warnings.simplefilter('always')
id = GLib.io_add_watch(ch, GLib.IOCondition.IN, cb, 'hello',
priority=GLib.PRIORITY_HIGH)
self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
ml = GLib.MainLoop()
self.assertEqual(ml.get_context().find_source_by_id(id).priority,
GLib.PRIORITY_HIGH)
def write():
os.write(w, b'a')
GLib.idle_add(lambda: os.write(w, b'b') and False)
GLib.idle_add(write)
GLib.timeout_add(2000, ml.quit)
ml.run()
self.assertEqual(cb_reads, [b'a', b'b'])
def test_backwards_compat_flags(self):
with warnings.catch_warnings():
warnings.simplefilter('ignore', PyGIDeprecationWarning)
self.assertEqual(GLib.IOCondition.IN, GLib.IO_IN)
self.assertEqual(GLib.IOFlags.NONBLOCK, GLib.IO_FLAG_NONBLOCK)
self.assertEqual(GLib.IOFlags.IS_SEEKABLE, GLib.IO_FLAG_IS_SEEKABLE)
self.assertEqual(GLib.IOStatus.NORMAL, GLib.IO_STATUS_NORMAL)
| lgpl-2.1 | -5,494,967,302,935,756,000 | 32.696842 | 92 | 0.579345 | false | 3.392539 | true | false | false |
glaudsonml/kurgan-ai | agents/agentBruteForce.py | 1 | 4898 | #!/usr/bin/env python3
'''
Brute Force Attack Agent
'''
import sys,os
import validators
import re, random
from furl import *
from urllib.parse import urlparse
import time, signal
from multiprocessing import Process
import threading
import stomp
import re
from daemonize import Daemonize
from os.path import basename
from os.path import basename
current_dir = os.path.basename(os.getcwd())
if current_dir == "agents":
sys.path.append('../')
if current_dir == "Kurgan-Framework":
sys.path.append('./')
from libs.STOMP import STOMP_Connector
from libs.FIPA import FIPAMessage
from libs.Transport import Transport
import libs.Utils as utl
import config as cf
from actions.bruteforceAction import BruteForceAction
AGENT_NAME="AgentBruteForce"
AGENT_ID="6"
def agent_status():
mAgent = Transport()
mAction = BruteForceAction()
mAction.set_mAgent(mAgent)
ret = mAction.requestInfo('request','All','agent-status','*')
mAction.receive_pkg(mAgent)
def get_infra():
mAgent = Transport()
mAction = BruteForceAction()
mAction.set_mAgent(mAgent)
toAgent = "AgentWebInfra"
ret = mAction.requestInfo('request',toAgent,'agent-status','*')
mAction.receive_pkg(mAgent)
def get_url_base():
mAgent = Transport()
mAction = BruteForceAction()
toAgent = "MasterAgent"
mAction.set_mAgent(mAgent)
ret = mAction.requestInfo('request',toAgent,'base-url-target','*')
mAction.receive_pkg(mAgent)
def run_bruteforce():
mAgent = Transport()
mAction = BruteForceAction()
toAgent = "MasterAgent"
mAction.set_mAgent(mAgent)
ret = mAction.requestInfo('request',toAgent,'run-bruteforce','*')
mAction.receive_pkg(mAgent)
def agent_quit():
mAction = BruteForceAction()
mAgent = Transport()
mAction.set_mAgent(mAgent)
mAction.deregister()
sys.exit(0)
def handler(signum, frame):
print("Exiting of execution...", signum);
agent_quit()
def runAgent():
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)
print("Loading " + AGENT_NAME + " ...\n")
mAgent = Transport()
mAction = BruteForceAction()
mAction.set_mAgent(mAgent)
mAction.registerAgent()
fm = FIPAMessage()
agent_id=[]
while True:
time.sleep(1)
rcv = mAgent.receive_data_from_agents()
if not len(rcv) == 0:
fm.parse_pkg(rcv)
match = re.search("(agent-name(.)+)(\(\w+\))", rcv)
if match:
field = match.group(3).lstrip()
match2 = re.search("\w+",field)
if match2:
agt_id = match2.group(0)
if agt_id in agent_id:
continue
else:
print("agentID: ", agt_id)
agent_id.append(agt_id)
print(rcv)
mAction.add_available_agent(agt_id)
break
else:
print(rcv)
print("Available Agents: ", mAction.get_available_agents())
mAgent = Transport()
mAction = BruteForceAction()
mAction.set_mAgent(mAgent)
mAction.cfp("run-bruteforce", "*")
msg_id=[]
while True:
time.sleep(1)
rcv = mAgent.receive_data_from_agents()
if not len(rcv) == 0:
fm.parse_pkg(rcv)
match = re.search("message-id:(.\w+\-\w+)", rcv)
if match:
message_id = match.group(1).lstrip()
if message_id in msg_id:
continue
else:
msg_id.append(message_id)
#print(rcv)
mAgent.zera_buff()
break
else:
continue
#print(rcv)
p = Process(target= get_url_base())
p.start()
p.join(3)
def show_help():
print("Kurgan MultiAgent Framework version ", cf.VERSION)
print("Usage: python3 " + __file__ + " <background|foreground>")
print("\nExample:\n")
print("python3 " + __file__ + " background")
exit(0)
def run(background=False):
if background == True:
pid = os.fork()
if pid:
p = basename(sys.argv[0])
myname, file_extension = os.path.splitext(p)
pidfile = '/tmp/%s.pid' % myname
daemon = Daemonize(app=myname, pid=pidfile, action=runAgent)
daemon.start()
print("Agent Loaded.")
else:
runAgent()
def main(args):
if args[0] == "foreground":
run(background=False)
else:
if args[0] == "background":
run(background=True)
else:
show_help()
exit
exit
if __name__ == '__main__':
if len(sys.argv) == 1:
show_help()
else:
main(sys.argv[1:]) | apache-2.0 | 4,952,029,758,148,651,000 | 25.197861 | 72 | 0.564516 | false | 3.572575 | false | false | false |
daishoui/MyGithub | taskCode/ForSY2/test2.py | 1 | 2938 | #--*-- coding: utf-8 --*--
def readLinesFromFile(filename):
f = open(filename)
lines = f.readlines()
f.close()
return lines
def writeLinesToFile(filename, lines):
f = open(filename,'w')
for line in lines:
f.write(str(line[0]) + ' ' + str(line[1]) + ' ' + str(line[2]) + '\n')
f.close()
def thirdColumnMerge(lines):
'''
由第三列元素是否相同合并列表
如[[0,1,'A'],[2,3,'A'],[3,4,'A'],[5,6,'B']]
合并成:[[0,4,'A'],[5,6,'B']]
'''
newLines = []
t = lines[0][:]
for line in lines:
if t[2] != line[2]:
newLines.append(t)
t = line[:]
else:
t[1] = line[1]
return newLines
def useTimeInfListFilter(lines, timeInfList = []):
'''
过滤
'''
Lines_new = []
wt = 0
for line in lines:
l = float(line[0])
r = float(line[1])
while wt < len(timeInfList):
if timeInfList[wt][0] <= l and timeInfList[wt][1] <= l:
wt += 1
elif timeInfList[wt][0] > l:
if r <= timeInfList[wt][0]:
Lines_new.append([l,r,line[2]])
break
elif r <= timeInfList[wt][1]:
Lines_new.append([l,timeInfList[wt][0],line[2]])
break
else:
Lines_new.append([l,timeInfList[wt][0],line[2]])
l = timeInfList[wt][1]
wt += 1
else:
if r <= timeInfList[wt][1]:
break
else:
l = timeInfList[wt][1]
wt += 1
return Lines_new
timeInfList = [] #用于存储全部时间信息列表
for line in readLinesFromFile('changchun_2.asr'):
data = line.split()
if(data[-1] == 'sil'):
timeInfList.append([float(data[1])/100.0,(float(data[2])+float(data[1]))/100.0])
#print(timeInfList)
timeInfList.append([100000.0,100000.0]) #增加结束标志
segLines = readLinesFromFile('changchun_2.seg')
#去掉所有所有第三列为'0'的
segLines = [d.split() for d in segLines if d.split()[-1] != '0']
#使用时间信息列表过滤segLines得到segLines_new
segLines_new = useTimeInfListFilter(segLines, timeInfList)
#print(segLines_new)
#合并
segLines = thirdColumnMerge(segLines_new)
#print(segLines)
writeLinesToFile('segLines.txt',segLines)
textGridLines = readLinesFromFile('changchun_2.TextGrid')
#去掉所有所有第三列为'""'的
textGridLines = [d.split() for d in textGridLines if d.split()[-1] != '""']
#print(textGridLines)
#使用时间信息列表过滤textGridLines得到textGridLines_new
textGridLines_new = useTimeInfListFilter(textGridLines, timeInfList)
#print(textGridLines_new)
#合并
textGridLines = thirdColumnMerge(textGridLines_new)
#print(textGridLines)
writeLinesToFile('textGridLines.txt',textGridLines)
| gpl-3.0 | -1,871,335,639,390,152,400 | 27.183673 | 88 | 0.55286 | false | 2.859213 | false | false | false |
mike-perdide/pcoords-gui | pcoordsgui/main_window.py | 1 | 17909 | #!/usr/bin/env python
#
######################
# Frontend for Pcoords
######################
# (C) 2008 Sebastien Tricaud
# 2009 Victor Amaducci
# 2009 Gabriel Cavalcante
# 2012 Julien Miotte
import sys
# QT
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QMainWindow
# Pcoords
import pcoords
# UI
from pcoordsgui import axisgui, export
from pcoordsgui import line_graphics_item
from pcoordsgui.pcoords_graphics_scene import myScene
from pcoordsgui.build_graphic_dialog import Buildpanel
from pcoordsgui.set_width_dialog import buildWidthPanel
from pcoordsgui.select_axis_id_dialog import buildSelectIdPanel
from pcoordsgui.about_dialog import buildAboutPanel
from pcoordsgui.main_window_ui import Ui_MainWindow
# check for psyco
try:
import psyco
psyco.full()
except ImportError:
print 'Running without psyco (http://psyco.sourceforge.net/).'
class MainWindow(QMainWindow):
"""Describes the pcoords main window."""
def __init__(self, pcvfile=None, filters=None, parent=None):
"""Initialization method."""
QMainWindow.__init__(self, parent)
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.scene = QtGui.QGraphicsScene()
self.comboboxes = {}
self.image = 0
self.comboList = []
self.buttonChange = []
self.axes_number = 0
self.filters = None
if pcvfile:
self.setPcvFile(pcvfile, filters=filters)
else:
self.openPcvFile()
self.exporter = export.ExportGraph()
self.connectSignals()
self.show()
def setPcvFile(self, pcvfile, filters=None):
self.image = pcoords.Image(str(pcvfile), filters)
self.setWindowTitle("Pcoords Frontend [%s]" % pcvfile)
if filters:
self.filters = filters
self.destroyComboBoxes()
self.paint_ImageView()
def connectSignals(self):
"""Connect the objects to the slots."""
ui = self.ui
ui.actionSave.triggered.connect(self.exportToPGDL)
ui.actionExport_png.triggered.connect(self.exportToPNG)
ui.action_Build.triggered.connect(self.Buildgraphic)
ui.action_Open.triggered.connect(self.openPcvFile)
ui.action_Quit.triggered.connect(self.close)
ui.zoomButtonPlus.clicked.connect(self.plusZoom)
ui.zoomButtonLess.clicked.connect(self.plusZoom)
ui.axisIncreaseButton.clicked.connect(self.increaseAxisDialog)
ui.setWidthButton.clicked.connect(self.changeWidthDialog)
ui.QCheckAntiAliasing.clicked.connect(self.antiAliasing)
ui.actionUndo.triggered.connect(self.undoProcess)
ui.actionRedo.triggered.connect(self.redoProcess)
ui.action_About.triggered.connect(self.showCredits)
ui.actionZoomin.triggered.connect(self.plusZoom)
ui.actionZoomout.triggered.connect(self.lessZoom)
ui.actionLine_width.triggered.connect(self.changeWidthDialog)
ui.actionViewLayers.toggled.connect(self.viewLayers)
ui.actionViewTable.toggled.connect(self.viewTable)
def Buildgraphic(self):
"""Shows the buildpanel."""
test = Buildpanel(self)
test.show()
def openPcvFile(self):
"""Opens the PCV file with a QFileDialog."""
self.setPcvFile(get_pcv_filename())
def antiAliasing(self):
"""Activate or deactivate the anti-aliasing."""
graphics_view = self.ui.graphicsView
is_checked = self.ui.QCheckAntiAliasing.isChecked()
graphics_view.setRenderHint(QtGui.QPainter.Antialiasing, is_checked)
def destroyComboBoxes(self):
for each in self.comboList:
each.close()
for each in self.buttonChange:
each.Close()
def showCredits(self):
"""Show the credits in the about dialog."""
panel = buildAboutPanel(pcoords.Version(), self)
panel.show()
del panel
def viewLayers(self, checked):
"""Display the layers box."""
if checked:
self.ui.LayersBox.show()
else:
self.ui.LayersBox.hide()
def viewTable(self, checked):
if checked:
self.ui.tableWidget.show()
else:
self.ui.tableWidget.hide()
def sortLayers(self):
self.ui.layersTreeWidget.sortItems(2, 0)
def redoProcess(self):
try:
if self.scene.countUndo < 0:
QtGui.QMessageBox.information(
self, self.trUtf8("Redo"),
self.trUtf8("There isn't Statement to Redo!")
)
else:
statementList = self.scene.listUndoStatement
cmd = str(statementList[self.scene.countUndo])
strList = cmd.split()
command = ''.join(strList[:1])
if command == "COLOR":
num = (len(strList) - 1) / 2
for i in range(1, len(strList) - 1, 2):
self.scene.brushSelection2(strList[i], strList[i + 1],
num)
self.scene.countUndo = self.scene.countUndo + 1
elif command == "SHOWALL":
num_selected_lines = int(''.join(strList[2:]))
for i in range(num_selected_lines):
for j in range(self.scene.axes_number - 1):
self.scene.hideSelected2(''.join(strList[1:2]))
self.scene.countUndo = self.scene.countUndo - 1
cmd = str(statementList[len(statementList)
- self.scene.countUndo])
strList = cmd.split()
elif command == "HIDE":
num_selected_lines = len(strList)
for i in range(1, num_selected_lines, 1):
self.scene.hideSelected2(strList[i])
self.scene.countUndo = self.scene.countUndo + 1
elif command == "ZOOM+":
self.plusZoom2()
self.scene.countUndo = self.scene.countUndo + 1
elif command == "ZOOM-":
self.lessZoom2()
self.scene.countUndo = self.scene.countUndo + 1
elif command == "CHANGE":
listParam = []
num_selected_lines = len(strList)
for i in range(1, num_selected_lines, 3):
listParam.append(strList[i])
listParam.append(strList[i + 1])
listParam.append(strList[i + 2])
self.axisButton.buttonPressed2(listParam)
listParam = []
self.scene.countUndo = self.scene.countUndo + 1
elif command == "WIDTH":
num_selected_lines = len(strList) - 1
for i in range(1, num_selected_lines, 3):
self.scene.changeWidth2(strList[i], strList[i + 1])
self.scene.countUndo = self.scene.countUndo + 1
elif command == "ADDLAYER":
self.scene.addLayer(strList[1], strList[2], strList[3])
self.scene.countUndo = self.scene.countUndo + 1
elif command == "REMOVELAYER":
self.scene.removeLayer2(strList[1])
self.scene.countUndo = self.scene.countUndo + 1
except:
QtGui.QMessageBox.information(
self, self.trUtf8("Redo"),
self.trUtf8("There isn't Statement to Redo!"))
if self.scene.countUndo > (len(statementList) - 1):
self.scene.countUndo = len(statementList) - 1
def undoProcess(self):
try:
if self.scene.countUndo < 0:
QtGui.QMessageBox.information(
self, self.trUtf8("Undo"),
self.trUtf8("There isn't Statement to Undo!"))
self.scene.countUndo = 0
else:
statementList = self.scene.listUndoStatement
cmd = str(statementList[self.scene.countUndo - 1])
strList = cmd.split()
command = ''.join(strList[:1])
if command == "COLOR":
num = (len(strList) - 1) / 2
for i in range(len(strList) - 1, 1, -2):
self.scene.brushSelection2(strList[i - 1],
strList[i], num)
self.scene.countUndo = self.scene.countUndo - 1
elif command == "SHOWALL":
num_selected_lines = int(''.join(strList[2:]))
for i in range(num_selected_lines):
for j in range(self.scene.axes_number - 1):
self.scene.hideSelected2(''.join(strList[1:2]))
self.scene.countUndo = self.scene.countUndo + 1
cmd = str(statementList[len(statementList)
- self.scene.countUndo])
strList = cmd.split()
self.scene.countUndo = self.scene.countUndo + 1
elif command == "HIDE":
num_selected_lines = (len(strList) - 1)
for i in range(num_selected_lines, 0, -1):
self.scene.showAllLines2(strList[i])
self.scene.countUndo = self.scene.countUndo - 1
elif command == "ZOOM+":
self.lessZoom2()
self.scene.countUndo = self.scene.countUndo - 1
elif command == "ZOOM-":
self.plusZoom2()
self.scene.countUndo = self.scene.countUndo - 1
elif command == "CHANGE":
listParam = []
num_selected_lines = len(strList)
for i in range(num_selected_lines - 1, 0, -3):
listParam.append(strList[i - 2])
listParam.append(strList[i - 1])
listParam.append(strList[i])
self.axisButton.buttonPressed2(listParam)
listParam = []
self.scene.countUndo = self.scene.countUndo - 1
elif command == "WIDTH":
num_selected_lines = len(strList) - 1
for i in range(num_selected_lines, 0, -3):
self.scene.changeWidth2(strList[i - 2],
strList[i - 1])
self.scene.countUndo = self.scene.countUndo - 1
elif command == "ADDLAYER":
self.scene.removeLayer2(strList[1])
self.scene.countUndo = self.scene.countUndo - 1
elif command == "REMOVELAYER":
i = 1
while not strList[i] and not strList[i]:
i += 1
for j in range(i):
self.scene.createLayer(
strList[1], strList[2 + j],
strList[2 + (i - 1)])
self.scene.countUndo = self.scene.countUndo - 1
except:
QtGui.QMessageBox.information(
self, self.trUtf8("Undo"),
self.trUtf8("There isn't Statement to Undo!"))
def changeWidthDialog(self):
panel = buildWidthPanel(self)
panel.show()
del panel
def increaseAxisDialog(self):
panel = buildSelectIdPanel(self)
panel.show()
del panel
def plusZoom(self):
self.ui.graphicsView.scale(1.15, 1.15)
self.line.decreaseWidth()
for i in range(len(self.scene.listUndoStatement) - 1,
self.scene.countUndo - 1, -1):
del self.scene.listUndoStatement[i]
self.scene.listUndoStatement.append("ZOOM+")
self.scene.countUndo = len(self.scene.listUndoStatement)
def plusZoom2(self):
self.ui.graphicsView.scale(1.15, 1.15)
self.line.decreaseWidth()
def lessZoom(self):
self.ui.graphicsView.scale(1 / 1.15, 1 / 1.15)
self.line.increaseWidth()
for i in range(len(self.scene.listUndoStatement) - 1,
self.scene.countUndo - 1, -1):
del self.scene.listUndoStatement[i]
self.scene.listUndoStatement.append("ZOOM-")
self.scene.countUndo = len(self.scene.listUndoStatement)
def lessZoom2(self):
self.ui.graphicsView.scale(1 / 1.15, 1 / 1.15)
self.line.increaseWidth()
def empty_ImageView(self):
tableHeader = []
self.ui.tableWidget.setHorizontalHeaderLabels(tableHeader)
self.ui.tableWidget.horizontalHeader().setResizeMode(
QtGui.QListView.Adjust, QtGui.QHeaderView.Interactive)
self.ui.tableWidget.verticalHeader().hide()
self.ui.tableWidget.setShowGrid(True)
self.ui.tableWidget.setSelectionBehavior(
QtGui.QAbstractItemView.SelectRows)
def exportToPGDL(self):
self.exporter.asPGDL(self.image)
def exportToPNG(self):
self.exporter.asPNG(self.scene)
def paint_ImageView(self):
self.scene = myScene(self.ui.graphicsView)
self.scene.setBackgroundBrush(QtCore.Qt.white)
self.scene.getUi(self.ui, self.image)
self.ui.graphicsView.setScene(self.scene)
self.ui.graphicsView.setDragMode(2)
ui = self.ui
ui.hideSelectionButton.clicked.connect(self.scene.hideSelected)
ui.brushButton.clicked.connect(self.scene.brushSelection)
ui.showOnlyButton.clicked.connect(self.scene.hideNotSelected)
ui.showAllButton.clicked.connect(self.scene.showAllLines)
ui.actionHide.triggered.connect(self.scene.hideSelected)
ui.actionBrush.triggered.connect(self.scene.brushSelection)
ui.actionShow_only.triggered.connect(self.scene.hideNotSelected)
ui.actionShow_all.triggered.connect(self.scene.showAllLines)
#Layer Buttons
ui.layersTreeWidget.itemClicked.connect(self.scene.selectLayer)
ui.sortLayerButton.clicked.connect(self.sortLayers)
ui.removeLayerButton.clicked.connect(self.scene.removeLayer)
ui.addLayerButton.clicked.connect(self.scene.addLayer)
ui.selectLayerButton.clicked.connect(self.scene.doSelectLayer)
self.axes_number = len(self.image['axeslist'])
i = 0
tableHeader = []
comboList = []
# Handler of engine/ComboBox axis name translate
axesDict = {}
# Flag for not duplicate lines!
dictFull = False
while i < self.axes_number:
combo = axisgui.AxisName(self.ui, self)
combo.show()
temp_index = 0
for axis in self.image['axeslist']:
#itemlabel = "teste"
itemlabel = combo.setItemName(
self.image['axes'][axis]['label'],
self.image['axes'][axis]['id'])
# set the combo names
if not dictFull:
if (self.image['axes'][axis]['label']):
axesDict[self.image['axes'][axis]['label']] = axis
#Add translate for dict if it have label
else:
# Add translate if it not have label
axesDict['axis%d' % temp_index] = axis
if i == 0:
tableHeader.append(itemlabel)
self.ui.tableWidget.insertColumn(
self.ui.tableWidget.columnCount())
temp_index = temp_index + 1
# Set the flag in first iteration
dictFull = True
combo.setCurrentIndex(i)
comboList.append(combo)
i = i + 1
axisWidget = self.ui.axisWidget
axisWidget.setup(comboList, axesDict, self.scene)
self.scene.getButton(axisWidget)
self.ui.horizontalSlider.setPageStep(1)
self.ui.horizontalSlider.setMinimum(0)
linenb = 0
self.comboList = comboList
for self.line in self.image['lines']:
linenb = linenb + 1
self.ui.horizontalSlider.setMaximum(linenb / (self.axes_number - 1))
self.ui.horizontalSlider.setValue(linenb / (self.axes_number - 1))
axisgui.addAxes(self.image, self.scene, self.line, self.axes_number,
self.ui)
self.ui.tableWidget.setHorizontalHeaderLabels(tableHeader)
self.ui.tableWidget.horizontalHeader().setResizeMode(
QtGui.QListView.Adjust, QtGui.QHeaderView.Interactive)
self.ui.tableWidget.verticalHeader().hide()
self.ui.tableWidget.setShowGrid(True)
self.ui.tableWidget.setSelectionBehavior(
QtGui.QAbstractItemView.SelectRows)
self.line = line_graphics_item.Line(self.scene, self.image,
self.axes_number, self.ui,
self.comboList)
self.line.addLines(linenb)
self.connect(self.ui.horizontalSlider,
QtCore.SIGNAL('valueChanged(int)'),
self.line.update_lines_view)
axisWidget.setLines(self.line, linenb)
axisWidget.setImage(self.image)
axisWidget.setCurrentEngine(pcoords)
axisWidget.setSlider(self.ui.horizontalSlider)
self.buttonChange.append(axisWidget)
def closeEvent(self, event):
self.scene.clearSelection()
event.accept()
| gpl-3.0 | -6,879,806,751,401,898,000 | 36.466527 | 79 | 0.553353 | false | 4.136028 | false | false | false |
tisdall/txZMQ | examples/req_rep.py | 2 | 1994 | #!env/bin/python
"""
Example txzmq client.
examples/req_rep.py --method=connect --endpoint=ipc:///tmp/req_rep_sock --mode=req
examples/req_rep.py --method=bind --endpoint=ipc:///tmp/req_rep_sock --mode=rep
"""
import os
import sys
import time
import zmq
from optparse import OptionParser
from twisted.internet import reactor
rootdir = os.path.realpath(os.path.join(os.path.dirname(sys.argv[0]), '..'))
sys.path.insert(0, rootdir)
os.chdir(rootdir)
from txzmq import ZmqEndpoint, ZmqFactory, ZmqREQConnection, ZmqREPConnection, ZmqRequestTimeoutError
parser = OptionParser("")
parser.add_option("-m", "--method", dest="method", help="0MQ socket connection: bind|connect")
parser.add_option("-e", "--endpoint", dest="endpoint", help="0MQ Endpoint")
parser.add_option("-M", "--mode", dest="mode", help="Mode: req|rep")
parser.set_defaults(method="connect", endpoint="ipc:///tmp/txzmq-pc-demo")
(options, args) = parser.parse_args()
zf = ZmqFactory()
e = ZmqEndpoint(options.method, options.endpoint)
if options.mode == "req":
s = ZmqREQConnection(zf, e)
def produce():
# data = [str(time.time()), socket.gethostname()]
data = str(time.time())
print "Requesting %r" % data
try:
d = s.sendMsg(data, timeout=0.95)
def doPrint(reply):
print("Got reply: %s" % (reply))
def onTimeout(fail):
fail.trap(ZmqRequestTimeoutError)
print "Timeout on request, is reply server running?"
d.addCallback(doPrint).addErrback(onTimeout)
except zmq.error.Again:
print "Skipping, no pull consumers..."
reactor.callLater(1, produce)
reactor.callWhenRunning(reactor.callLater, 1, produce)
else:
s = ZmqREPConnection(zf, e)
def doPrint(messageId, message):
print "Replying to %s, %r" % (messageId, message)
s.reply(messageId, "%s %r " % (messageId, message))
s.gotMessage = doPrint
reactor.run()
| gpl-2.0 | -5,228,876,548,383,675,000 | 27.084507 | 101 | 0.647442 | false | 3.42024 | false | false | false |
adalessandro/hpr_project | neonatologia_analisis_app/migrations/0005_auto__add_determinacionestudioneonatologia__del_field_entradaanalisis_.py | 1 | 9826 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'EntradaAnalisis', fields ['fecha', 'apellido', 'nombre']
db.delete_unique(u'neonatologia_analisis_app_entradaanalisis', ['fecha', 'apellido', 'nombre'])
# Adding model 'DeterminacionEstudioNeonatologia'
db.create_table(u'neonatologia_analisis_app_determinacionestudioneonatologia', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('nombre', self.gf('django.db.models.fields.CharField')(max_length=25)),
('descripcion', self.gf('django.db.models.fields.CharField')(max_length=100, blank=True)),
))
db.send_create_signal(u'neonatologia_analisis_app', ['DeterminacionEstudioNeonatologia'])
# Deleting field 'EntradaAnalisis.determinacion'
db.delete_column(u'neonatologia_analisis_app_entradaanalisis', 'determinacion')
# Adding M2M table for field determinacion on 'EntradaAnalisis'
m2m_table_name = db.shorten_name(u'neonatologia_analisis_app_entradaanalisis_determinacion')
db.create_table(m2m_table_name, (
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),
('entradaanalisis', models.ForeignKey(orm[u'neonatologia_analisis_app.entradaanalisis'], null=False)),
('determinacionestudioneonatologia', models.ForeignKey(orm[u'neonatologia_analisis_app.determinacionestudioneonatologia'], null=False))
))
db.create_unique(m2m_table_name, ['entradaanalisis_id', 'determinacionestudioneonatologia_id'])
def backwards(self, orm):
# Deleting model 'DeterminacionEstudioNeonatologia'
db.delete_table(u'neonatologia_analisis_app_determinacionestudioneonatologia')
# Adding field 'EntradaAnalisis.determinacion'
db.add_column(u'neonatologia_analisis_app_entradaanalisis', 'determinacion',
self.gf('django.db.models.fields.CharField')(default='', max_length=50, blank=True),
keep_default=False)
# Removing M2M table for field determinacion on 'EntradaAnalisis'
db.delete_table(db.shorten_name(u'neonatologia_analisis_app_entradaanalisis_determinacion'))
# Adding unique constraint on 'EntradaAnalisis', fields ['fecha', 'apellido', 'nombre']
db.create_unique(u'neonatologia_analisis_app_entradaanalisis', ['fecha', 'apellido', 'nombre'])
models = {
u'auth.group': {
'Meta': {'object_name': 'Group'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
u'auth.permission': {
'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Group']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "u'user_set'", 'blank': 'True', 'to': u"orm['auth.Permission']"}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
u'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
u'neonatologia_analisis_app.determinacionestudioneonatologia': {
'Meta': {'object_name': 'DeterminacionEstudioNeonatologia'},
'descripcion': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '25'})
},
u'neonatologia_analisis_app.entradaanalisis': {
'Meta': {'object_name': 'EntradaAnalisis'},
'apellido': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'apellido_madre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'created': ('django.db.models.fields.DateTimeField', [], {}),
'created_user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'determinacion': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['neonatologia_analisis_app.DeterminacionEstudioNeonatologia']", 'symmetrical': 'False'}),
'domicilio': ('django.db.models.fields.CharField', [], {'max_length': '100', 'blank': 'True'}),
'estado': ('django.db.models.fields.CharField', [], {'default': "'A'", 'max_length': '1'}),
'etapa': ('django.db.models.fields.CharField', [], {'default': "'INI'", 'max_length': '3'}),
'fecha': ('django.db.models.fields.DateField', [], {'default': 'datetime.date.today'}),
'fecha_nacimiento': ('django.db.models.fields.DateField', [], {}),
'fecha_notif_familia': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'laboratorio_obs': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'muestra_fecha_1': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'muestra_fecha_2': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'muestra_num_1': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'muestra_num_2': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'muestra_texto_2': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'neonatologia_obs': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'}),
'nombre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'nombre_madre': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'notificar_trabsoc': ('django.db.models.fields.CharField', [], {'default': "'SI'", 'max_length': '2'}),
'prioridad': ('django.db.models.fields.CharField', [], {'default': "'N'", 'max_length': '1'}),
'sexo': ('django.db.models.fields.CharField', [], {'max_length': '1', 'blank': 'True'}),
'telefono': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'trabsoc_obs': ('django.db.models.fields.CharField', [], {'max_length': '500', 'blank': 'True'})
},
u'neonatologia_analisis_app.entradaanalisisadjunto': {
'Meta': {'object_name': 'EntradaAnalisisAdjunto'},
'adjunto': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'null': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {}),
'created_user': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['auth.User']"}),
'entrada_analisis': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['neonatologia_analisis_app.EntradaAnalisis']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['neonatologia_analisis_app'] | gpl-2.0 | -3,852,291,647,734,132,000 | 72.887218 | 195 | 0.593934 | false | 3.343314 | false | false | false |
joaormatos/anaconda | Anaconda/standalone/post_build.py | 1 | 1810 | # Copyright (c) Mathias Kaerlev 2012.
# This file is part of Anaconda.
# Anaconda 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.
# Anaconda 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 Anaconda. If not, see <http://www.gnu.org/licenses/>.
import shutil
import zipfile
import sys
import os
def make_zipfile(zip_filename, base_dir):
zip = zipfile.ZipFile(zip_filename, 'w', compression = zipfile.ZIP_DEFLATED)
cwd = os.getcwd()
os.chdir(base_dir)
for dirpath, dirnames, filenames in os.walk('.'):
for name in filenames:
path = os.path.normpath(os.path.join(dirpath, name))
if os.path.isfile(path):
zip.write(path, path)
zip.close()
os.chdir(cwd)
return zip_filename
path = './dist/%s' % sys.platform
if sys.platform == 'darwin':
# lipo files so we only get i386
cwd = os.getcwd()
os.chdir(path)
import subprocess
for dirpath, dirnames, filenames in os.walk('.'):
for name in filenames:
full_path = os.path.normpath(os.path.join(dirpath, name))
if not os.path.isfile(full_path):
continue
subprocess.call(['lipo', full_path, '-thin', 'i386', '-output',
full_path])
os.chdir(cwd)
make_zipfile('./dist/%s.zip' % sys.platform, path)
shutil.rmtree(path) | gpl-3.0 | 8,281,787,660,215,163,000 | 30.224138 | 80 | 0.654696 | false | 3.770833 | false | false | false |
roderickmackenzie/gpvdm | gpvdm_gui/gui/ribbon_cluster.py | 1 | 5252 | # -*- coding: utf-8 -*-
#
# General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall
# model for 1st, 2nd and 3rd generation solar cells.
# Copyright (C) 2012-2017 Roderick C. I. MacKenzie r.c.i.mackenzie at googlemail.com
#
# https://www.gpvdm.com
# Room B86 Coates, University Park, Nottingham, NG7 2RD, UK
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License v2.0, 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 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 Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
#
## @package ribbon_cluster
# A ribbon containing clustering commands.
#
import os
from icon_lib import icon_get
from dump_io import dump_io
from tb_item_sim_mode import tb_item_sim_mode
from tb_item_sun import tb_item_sun
from code_ctrl import enable_betafeatures
from cal_path import get_css_path
#qt
from PyQt5.QtWidgets import QMainWindow, QTextEdit, QAction, QApplication
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QSize, Qt,QFile,QIODevice
from PyQt5.QtWidgets import QWidget,QSizePolicy,QVBoxLayout,QHBoxLayout,QPushButton,QDialog,QFileDialog,QToolBar,QMessageBox, QLineEdit, QToolButton
from PyQt5.QtWidgets import QTabWidget
from info import sim_info
from win_lin import desktop_open
#windows
from scan import scan_class
from help import help_window
from error_dlg import error_dlg
from server import server_get
from fit_window import fit_window
from cmp_class import cmp_class
from global_objects import global_object_run
from util import isfiletype
from util import wrap_text
class ribbon_cluster(QToolBar):
def __init__(self):
QToolBar.__init__(self)
self.myserver=server_get()
self.setToolButtonStyle( Qt.ToolButtonTextUnderIcon)
self.setIconSize(QSize(42, 42))
self.cluster_get_data = QAction(icon_get("server_get_data"), wrap_text(_("Cluster get data"),8), self)
self.cluster_get_data.triggered.connect(self.callback_cluster_get_data)
self.addAction(self.cluster_get_data)
self.cluster_get_data.setEnabled(False)
self.cluster_copy_src = QAction(icon_get("server_copy_src"), wrap_text(_("Copy src to cluster"),8), self)
self.cluster_copy_src.triggered.connect(self.callback_cluster_copy_src)
self.addAction(self.cluster_copy_src)
self.cluster_copy_src.setEnabled(False)
self.cluster_make = QAction(icon_get("server_make"), wrap_text(_("Make on cluster"),6), self)
self.cluster_make.triggered.connect(self.callback_cluster_make)
self.addAction(self.cluster_make)
self.cluster_make.setEnabled(False)
self.cluster_clean = QAction(icon_get("server_clean"), wrap_text(_("Clean cluster"),8), self)
self.cluster_clean.triggered.connect(self.callback_cluster_clean)
self.addAction(self.cluster_clean)
self.cluster_clean.setEnabled(False)
self.cluster_off = QAction(icon_get("off"), wrap_text(_("Kill all cluster code"),8), self)
self.cluster_off.triggered.connect(self.callback_cluster_off)
self.addAction(self.cluster_off)
self.cluster_off.setEnabled(False)
self.cluster_sync = QAction(icon_get("sync"), _("Sync"), self)
self.cluster_sync.triggered.connect(self.callback_cluster_sync)
self.addAction(self.cluster_sync)
self.cluster_sync.setEnabled(False)
spacer = QWidget()
spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.addWidget(spacer)
self.help = QAction(icon_get("internet-web-browser"), _("Help"), self)
self.addAction(self.help)
def callback_cluster_make(self):
self.myserver.cluster_make()
def callback_cluster_clean(self):
self.myserver.cluster_clean()
def callback_cluster_off(self):
self.myserver.cluster_quit()
self.update()
def callback_cluster_sync(self):
self.myserver.copy_src_to_cluster_fast()
def callback_cluster_sleep(self):
self.myserver.sleep()
def callback_cluster_poweroff(self):
self.myserver.poweroff()
def callback_cluster_print_jobs(self):
self.myserver.print_jobs()
def callback_wol(self, widget, data):
self.myserver.wake_nodes()
def update(self):
if self.myserver.cluster==True:
self.cluster_clean.setEnabled(True)
self.cluster_make.setEnabled(True)
self.cluster_copy_src.setEnabled(True)
self.cluster_get_data.setEnabled(True)
self.cluster_off.setEnabled(True)
self.cluster_sync.setEnabled(True)
else:
self.cluster_clean.setEnabled(False)
self.cluster_make.setEnabled(False)
self.cluster_copy_src.setEnabled(False)
self.cluster_get_data.setEnabled(False)
self.cluster_off.setEnabled(False)
self.cluster_sync.setEnabled(False)
def setEnabled(self,val):
print("")
#self.undo.setEnabled(val)
def callback_cluster_get_data(self, widget, data=None):
self.myserver.cluster_get_data()
def callback_cluster_copy_src(self, widget, data=None):
self.myserver.copy_src_to_cluster()
| gpl-2.0 | 8,479,352,780,645,095,000 | 31.220859 | 148 | 0.751904 | false | 3.169584 | false | false | false |
weapp/miner | miner.py | 1 | 1803 | #!/usr/bin/env python
import os
import argparse
from multiprocessing import Process
import yaml
import json
from shared.utils import build_components, build_component, apply_envs
from shared.path import Path
if __name__ == '__main__':
# print "Visit this!"
# print "http://wubytes.com/w/grid/example:cpu,swap,memory,procs,networkout,networkin"
# print
parser = argparse.ArgumentParser()
parser.add_argument("--secrets", help="yml file for your secret data", default=None)
parser.add_argument("--conf", help="publish the string you use here", default=None)
parser.add_argument("--publish", help="publish the string you use here")
parser.add_argument("--publisher", help="publish the string you use here", type=build_component)
args = parser.parse_args()
confpath = args.conf or os.path.join(os.path.dirname(os.path.realpath(__file__)), "conf.yml")
conf = yaml.load(open(confpath))
try:
default_secret = os.path.join(os.path.dirname(os.path.realpath(__file__)), "secrets.yml")
secretspath = args.secrets or default_secret
secrets = yaml.load(open(secretspath)) or {}
except IOError:
if secretspath == default_secret:
secrets = {}
else:
raise
environ = dict(os.environ)
environ.update(secrets)
conf = apply_envs(conf, environ)
if args.publisher:
publishers=[args.publisher]
else:
publishers = build_components(conf, "publishers")
if args.publish:
[p(json.loads(args.publish)) for p in publishers]
else:
extractors = build_components(conf, "extractors")
process = [Process(**extractor(publishers)) for extractor in extractors]
[p.start() for p in process]
[p.join() for p in process]
| mit | 5,180,890,249,039,874,000 | 30.086207 | 100 | 0.655574 | false | 3.83617 | false | false | false |
neo4j/neo4j-python-driver | neo4j/data.py | 1 | 13145 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright (c) "Neo4j"
# Neo4j Sweden AB [http://neo4j.com]
#
# This file is part of Neo4j.
#
# 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 abc import ABCMeta, abstractmethod
from collections.abc import Sequence, Set, Mapping
from datetime import date, time, datetime, timedelta
from functools import reduce
from operator import xor as xor_operator
from neo4j.conf import iter_items
from neo4j.graph import Graph, Node, Relationship, Path
from neo4j.packstream import INT64_MIN, INT64_MAX, Structure
from neo4j.spatial import Point, hydrate_point, dehydrate_point
from neo4j.time import Date, Time, DateTime, Duration
from neo4j.time.hydration import (
hydrate_date, dehydrate_date,
hydrate_time, dehydrate_time,
hydrate_datetime, dehydrate_datetime,
hydrate_duration, dehydrate_duration, dehydrate_timedelta,
)
map_type = type(map(str, range(0)))
class Record(tuple, Mapping):
""" A :class:`.Record` is an immutable ordered collection of key-value
pairs. It is generally closer to a :py:class:`namedtuple` than to a
:py:class:`OrderedDict` inasmuch as iteration of the collection will
yield values rather than keys.
"""
__keys = None
def __new__(cls, iterable=()):
keys = []
values = []
for key, value in iter_items(iterable):
keys.append(key)
values.append(value)
inst = tuple.__new__(cls, values)
inst.__keys = tuple(keys)
return inst
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__,
" ".join("%s=%r" % (field, self[i]) for i, field in enumerate(self.__keys)))
def __eq__(self, other):
""" In order to be flexible regarding comparison, the equality rules
for a record permit comparison with any other Sequence or Mapping.
:param other:
:return:
"""
compare_as_sequence = isinstance(other, Sequence)
compare_as_mapping = isinstance(other, Mapping)
if compare_as_sequence and compare_as_mapping:
return list(self) == list(other) and dict(self) == dict(other)
elif compare_as_sequence:
return list(self) == list(other)
elif compare_as_mapping:
return dict(self) == dict(other)
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return reduce(xor_operator, map(hash, self.items()))
def __getitem__(self, key):
if isinstance(key, slice):
keys = self.__keys[key]
values = super(Record, self).__getitem__(key)
return self.__class__(zip(keys, values))
try:
index = self.index(key)
except IndexError:
return None
else:
return super(Record, self).__getitem__(index)
def __getslice__(self, start, stop):
key = slice(start, stop)
keys = self.__keys[key]
values = tuple(self)[key]
return self.__class__(zip(keys, values))
def get(self, key, default=None):
""" Obtain a value from the record by key, returning a default
value if the key does not exist.
:param key: a key
:param default: default value
:return: a value
"""
try:
index = self.__keys.index(str(key))
except ValueError:
return default
if 0 <= index < len(self):
return super(Record, self).__getitem__(index)
else:
return default
def index(self, key):
""" Return the index of the given item.
:param key: a key
:return: index
:rtype: int
"""
if isinstance(key, int):
if 0 <= key < len(self.__keys):
return key
raise IndexError(key)
elif isinstance(key, str):
try:
return self.__keys.index(key)
except ValueError:
raise KeyError(key)
else:
raise TypeError(key)
def value(self, key=0, default=None):
""" Obtain a single value from the record by index or key. If no
index or key is specified, the first value is returned. If the
specified item does not exist, the default value is returned.
:param key: an index or key
:param default: default value
:return: a single value
"""
try:
index = self.index(key)
except (IndexError, KeyError):
return default
else:
return self[index]
def keys(self):
""" Return the keys of the record.
:return: list of key names
"""
return list(self.__keys)
def values(self, *keys):
""" Return the values of the record, optionally filtering to
include only certain values by index or key.
:param keys: indexes or keys of the items to include; if none
are provided, all values will be included
:return: list of values
:rtype: list
"""
if keys:
d = []
for key in keys:
try:
i = self.index(key)
except KeyError:
d.append(None)
else:
d.append(self[i])
return d
return list(self)
def items(self, *keys):
""" Return the fields of the record as a list of key and value tuples
:return: a list of value tuples
:rtype: list
"""
if keys:
d = []
for key in keys:
try:
i = self.index(key)
except KeyError:
d.append((key, None))
else:
d.append((self.__keys[i], self[i]))
return d
return list((self.__keys[i], super(Record, self).__getitem__(i)) for i in range(len(self)))
def data(self, *keys):
""" Return the keys and values of this record as a dictionary,
optionally including only certain values by index or key. Keys
provided in the items that are not in the record will be
inserted with a value of :const:`None`; indexes provided
that are out of bounds will trigger an :exc:`IndexError`.
:param keys: indexes or keys of the items to include; if none
are provided, all values will be included
:return: dictionary of values, keyed by field name
:raises: :exc:`IndexError` if an out-of-bounds index is specified
"""
return RecordExporter().transform(dict(self.items(*keys)))
class DataTransformer(metaclass=ABCMeta):
""" Abstract base class for transforming data from one form into
another.
"""
@abstractmethod
def transform(self, x):
""" Transform a value, or collection of values.
:param x: input value
:return: output value
"""
class RecordExporter(DataTransformer):
""" Transformer class used by the :meth:`.Record.data` method.
"""
def transform(self, x):
if isinstance(x, Node):
return self.transform(dict(x))
elif isinstance(x, Relationship):
return (self.transform(dict(x.start_node)),
x.__class__.__name__,
self.transform(dict(x.end_node)))
elif isinstance(x, Path):
path = [self.transform(x.start_node)]
for i, relationship in enumerate(x.relationships):
path.append(self.transform(relationship.__class__.__name__))
path.append(self.transform(x.nodes[i + 1]))
return path
elif isinstance(x, str):
return x
elif isinstance(x, Sequence):
t = type(x)
return t(map(self.transform, x))
elif isinstance(x, Set):
t = type(x)
return t(map(self.transform, x))
elif isinstance(x, Mapping):
t = type(x)
return t((k, self.transform(v)) for k, v in x.items())
else:
return x
class DataHydrator:
# TODO: extend DataTransformer
def __init__(self):
super(DataHydrator, self).__init__()
self.graph = Graph()
self.graph_hydrator = Graph.Hydrator(self.graph)
self.hydration_functions = {
b"N": self.graph_hydrator.hydrate_node,
b"R": self.graph_hydrator.hydrate_relationship,
b"r": self.graph_hydrator.hydrate_unbound_relationship,
b"P": self.graph_hydrator.hydrate_path,
b"X": hydrate_point,
b"Y": hydrate_point,
b"D": hydrate_date,
b"T": hydrate_time, # time zone offset
b"t": hydrate_time, # no time zone
b"F": hydrate_datetime, # time zone offset
b"f": hydrate_datetime, # time zone name
b"d": hydrate_datetime, # no time zone
b"E": hydrate_duration,
}
def hydrate(self, values):
""" Convert PackStream values into native values.
"""
def hydrate_(obj):
if isinstance(obj, Structure):
try:
f = self.hydration_functions[obj.tag]
except KeyError:
# If we don't recognise the structure
# type, just return it as-is
return obj
else:
return f(*map(hydrate_, obj.fields))
elif isinstance(obj, list):
return list(map(hydrate_, obj))
elif isinstance(obj, dict):
return {key: hydrate_(value) for key, value in obj.items()}
else:
return obj
return tuple(map(hydrate_, values))
def hydrate_records(self, keys, record_values):
for values in record_values:
yield Record(zip(keys, self.hydrate(values)))
class DataDehydrator:
# TODO: extend DataTransformer
@classmethod
def fix_parameters(cls, parameters):
if not parameters:
return {}
dehydrator = cls()
try:
dehydrated, = dehydrator.dehydrate([parameters])
except TypeError as error:
value = error.args[0]
raise TypeError("Parameters of type {} are not supported".format(type(value).__name__))
else:
return dehydrated
def __init__(self):
self.dehydration_functions = {}
self.dehydration_functions.update({
Point: dehydrate_point,
Date: dehydrate_date,
date: dehydrate_date,
Time: dehydrate_time,
time: dehydrate_time,
DateTime: dehydrate_datetime,
datetime: dehydrate_datetime,
Duration: dehydrate_duration,
timedelta: dehydrate_timedelta,
})
# Allow dehydration from any direct Point subclass
self.dehydration_functions.update({cls: dehydrate_point for cls in Point.__subclasses__()})
def dehydrate(self, values):
""" Convert native values into PackStream values.
"""
def dehydrate_(obj):
try:
f = self.dehydration_functions[type(obj)]
except KeyError:
pass
else:
return f(obj)
if obj is None:
return None
elif isinstance(obj, bool):
return obj
elif isinstance(obj, int):
if INT64_MIN <= obj <= INT64_MAX:
return obj
raise ValueError("Integer out of bounds (64-bit signed "
"integer values only)")
elif isinstance(obj, float):
return obj
elif isinstance(obj, str):
return obj
elif isinstance(obj, (bytes, bytearray)):
# order is important here - bytes must be checked after str
return obj
elif isinstance(obj, (list, map_type)):
return list(map(dehydrate_, obj))
elif isinstance(obj, dict):
if any(not isinstance(key, str) for key in obj.keys()):
raise TypeError("Non-string dictionary keys are "
"not supported")
return {key: dehydrate_(value) for key, value in obj.items()}
else:
raise TypeError(obj)
return tuple(map(dehydrate_, values))
| apache-2.0 | 1,572,899,761,663,884,300 | 32.878866 | 104 | 0.556333 | false | 4.24443 | false | false | false |
kurtraschke/camelot | camelot/view/wizard/pages/progress_page.py | 1 | 4527 | # ============================================================================
#
# Copyright (C) 2007-2010 Conceptive Engineering bvba. All rights reserved.
# www.conceptive.be / [email protected]
#
# This file is part of the Camelot Library.
#
# This file may be used under the terms of the GNU General Public
# License version 2.0 as published by the Free Software Foundation
# and appearing in the file license.txt included in the packaging of
# this file. Please review this information to ensure GNU
# General Public Licensing requirements will be met.
#
# If you are unsure which license is appropriate for your use, please
# visit www.python-camelot.com or contact [email protected]
#
# This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
# WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
#
# For use of this library in commercial applications, please contact
# [email protected]
#
# ============================================================================
'''
Created on Jan 7, 2010
@author: tw55413
'''
from PyQt4 import QtCore, QtGui
from camelot.core.utils import ugettext_lazy as _
class ProgressPage(QtGui.QWizardPage):
"""Generic progress page for a wizard.
Subclass and reimplement the run method. And within this run method,
regulary emit the update_progress_signal and the update_maximum_signal.
the update_maximum_signal should have as its single argument an integer
value indicating the maximum of the progress bar.
the update_progress_signal should two arguments, the first is an integer
indicating the current position of the progress bar, and the second is
a string telling the user what is going on.
If required, set the title and sub_title class attribute to change the
text displayed to the user.
"""
update_progress_signal = QtCore.pyqtSignal(int, str)
update_maximum_signal = QtCore.pyqtSignal(int)
title = _('Action in progress')
sub_title = _('Please wait for completion')
def __init__(self, parent=None):
super(ProgressPage, self).__init__( parent )
self.update_progress_signal.connect( self.update_progress )
self.update_maximum_signal.connect( self.update_maximum )
self._complete = False
self.setTitle(unicode(self.title))
self.setSubTitle(unicode(self.sub_title))
layout = QtGui.QVBoxLayout()
progress = QtGui.QProgressBar(self)
progress.setObjectName('progress')
progress.setMinimum(0)
progress.setMaximum(1)
label = QtGui.QTextEdit(self)
label.setObjectName('label')
label.setSizePolicy( QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding )
label.setReadOnly(True)
layout.addWidget(progress)
layout.addWidget(label)
self.setLayout(layout)
def isComplete(self):
return self._complete
@QtCore.pyqtSlot(int)
def update_maximum(self, maximum):
progress = self.findChild(QtGui.QWidget, 'progress' )
if progress:
progress.setMaximum(maximum)
@QtCore.pyqtSlot(int, str)
def update_progress(self, value, label):
progress_widget = self.findChild(QtGui.QWidget, 'progress' )
if progress_widget:
progress_widget.setValue(value)
label_widget = self.findChild(QtGui.QWidget, 'label' )
if label_widget:
label_widget.setHtml(unicode(label))
def exception(self, args):
self.finished()
from camelot.view.controls.exception import model_thread_exception_message_box
model_thread_exception_message_box(args)
def finished(self):
self._complete = True
progress_widget = self.findChild(QtGui.QWidget, 'progress' )
if progress_widget:
progress_widget.setMaximum(1)
progress_widget.setValue(1)
self.completeChanged.emit()
def run(self):
"""
This method contains the actual action, that will be run in the model thread.
Reimplement this method, while regulary emiting update_progress_signal and
update_maximum_signal to keep the progress bar moving.
"""
pass
def initializePage(self):
from camelot.view.model_thread import post
post(self.run, self.finished, self.exception)
| gpl-2.0 | -2,214,981,055,944,820,000 | 36.413223 | 86 | 0.648111 | false | 4.299145 | false | false | false |
machinedesign/grammaropt | grammaropt/terminal_types.py | 1 | 1819 | """
This module contain types, which are special kinds of
grammar terminals that represent pre-defined types like int, float, etc.
The main goal of theses classes is not to provide functionality (they
are basically a Regex) but rather to be identified as Type so that
some special treatment is reserved to them, because for inst. the RNN
based walker needs to know that there are types so that it predicts a value.
"""
import re
from scipy.stats import poisson
from scipy.stats import norm
from parsimonious.expressions import Regex
class Type(Regex):
pass
class Int(Type):
"""
Integer `Type`, defined in an interval [low, high]
(low and high are included).
"""
def __init__(self, low, high):
assert type(low) == int and type(high) == int
assert low <= high
super()
self.name = ""
self.low = low
self.high = high
self.re = re.compile("[0-9]+") # TODO do the actual regex
self.identity_tuple = (low, high)
def uniform_sample(self, rng):
# assumes rng is `np.random.Random` rather than `random.Random`
return rng.randint(self.low, self.high + 1)
@staticmethod
def from_str(s):
return int(s)
class Float(Type):
"""
Float `Type`, defined in an interval [low, high]
(low and high are included)
"""
def __init__(self, low, high):
assert type(low) == float and type(high) == float
assert low <= high
super()
self.name = ""
self.low = low
self.high = high
self.re = re.compile("[0-9]+\.[0-9]+") # TODO do the actual regex
self.identity_tuple = (low, high)
def uniform_sample(self, rng):
return rng.uniform(self.low, self.high)
@staticmethod
def from_str(s):
return float(s)
| mit | 2,067,762,234,421,951,200 | 26.149254 | 76 | 0.62122 | false | 3.781705 | false | false | false |
clarete/curdling | curdling/web/__main__.py | 1 | 1050 | from __future__ import absolute_import, print_function, unicode_literals
from curdling.web import Server
import argparse
def parse_args():
parser = argparse.ArgumentParser(
description='Share your cheese binaries with your folks')
parser.add_argument(
'curddir', metavar='DIRECTORY',
help='Path for your cache directory')
parser.add_argument(
'-d', '--debug', action='store_true', default=False,
help='Runs without gevent and enables debug')
parser.add_argument(
'-H', '--host', default='0.0.0.0',
help='Host name to bind')
parser.add_argument(
'-p', '--port', type=int, default=8000,
help='Port to bind')
parser.add_argument(
'-u', '--user-db',
help='An htpasswd-compatible file saying who can access your curd server')
return parser.parse_args()
def main():
args = parse_args()
server = Server(args.curddir, args.user_db)
server.start(args.host, args.port, args.debug)
if __name__ == '__main__':
main()
| gpl-3.0 | -335,939,266,285,223,600 | 24.609756 | 82 | 0.622857 | false | 3.736655 | false | false | false |
zachdj/ultimate-tic-tac-toe | models/game/LocalBoard.py | 1 | 1811 | import numpy
from .Board import Board
class LocalBoard(Board):
""" Represents a traditional 3x3 tic tac toe board
"""
def __init__(self):
Board.__init__(self)
self.board = numpy.ones((3, 3)) * Board.EMPTY
self.cats_game = False
def check_cell(self, row, col):
""" Overrides Board.check_cell
"""
if row < 0 or row > 2 or col < 0 or col > 2:
raise Exception("Requested cell is out of bounds")
return self.board[row][col]
def make_move(self, move):
""" Overrides Board.make_move
"""
if self.board[move.row][move.col] != Board.EMPTY:
raise Exception("You cannot make a move in an occupied slot")
self.board[move.row][move.col] = move.player
self.total_moves += 1
self.check_board_completed(move.row, move.col)
if self.total_moves == 9 and self.winner != Board.X and self.winner != Board.O:
self.cats_game = True
def clone(self):
new_local_board = LocalBoard()
new_local_board.board = numpy.copy(self.board)
new_local_board.cats_game = self.cats_game
new_local_board.board_completed = self.board_completed
new_local_board.total_moves = self.total_moves
new_local_board.winner = self.winner
return new_local_board
def __str__(self):
representation = ""
for row in [0, 1, 2]:
for col in [0, 1, 2]:
if self.board[row][col] == Board.O:
representation += "O"
elif self.board[row][col] == Board.X:
representation += "x"
else:
representation += "_"
if row != 2:
representation += "\n"
return representation
| mit | -5,562,757,951,391,829,000 | 31.927273 | 87 | 0.545555 | false | 3.780793 | false | false | false |
scionrep/scioncc | setup.py | 1 | 5141 | #!/usr/bin/env python
from setuptools import setup, find_packages
import os
import sys
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def get_data_dirs(path, patterns):
data_dirs = [(rt+"/"+dn+"/") for rt, ds, fs in os.walk(path) for dn in ds]
data_dir_patterns = []
for pat in patterns:
data_dir_patterns += [(dn+pat)[len(path)+1:] for dn in data_dirs]
return data_dir_patterns
# Add /usr/local/include to the path for macs, fixes easy_install for several packages (like gevent and pyyaml)
if sys.platform == 'darwin':
os.environ['C_INCLUDE_PATH'] = '/usr/local/include'
VERSION = read("VERSION").strip()
# See http://pythonhosted.org/setuptools/setuptools.html
# noinspection PyPackageRequirements
setup( name='scioncc',
version=VERSION,
description='Scientific Observatory Network Capability Container',
long_description=read('README'),
url='https://www.github.com/scionrep/scioncc/wiki',
download_url='https://github.com/scionrep/scioncc/releases',
license='BSD',
author='SciON Contributors',
author_email='[email protected]',
keywords=['scion', 'pyon', 'ion'],
classifiers=['Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Environment :: Web Environment',
'Topic :: Internet',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Scientific/Engineering',
'Topic :: Software Development',
'Topic :: Software Development :: Libraries :: Application Frameworks'],
packages=find_packages('src') + find_packages('.'),
package_dir={'': 'src',
'interface': 'interface',
'defs': 'defs'},
include_package_data=True,
package_data={
'': ['*.yml', '*.txt'] + get_data_dirs("defs", ["*.yml", "*.sql", "*.xml"]) + get_data_dirs("src/ion/process/ui", ["*.css", "*.js"]),
},
entry_points={
'nose.plugins.0.10': [
'timer_plugin=pyon.util.testing.timer_plugin:TestTimer',
'greenletleak=pyon.util.testing.greenlet_plugin:GreenletLeak',
'gevent_profiler=pyon.util.testing.nose_gevent_profiler:TestGeventProfiler',
],
'console_scripts': [
'pycc=scripts.pycc:entry',
'control_cc=scripts.control_cc:main',
'generate_interfaces=scripts.generate_interfaces:main',
'store_interfaces=scripts.store_interfaces:main',
'clear_db=pyon.datastore.clear_db_util:main',
'coverage=scripts.coverage:main',
]
},
dependency_links=[],
install_requires=[
# NOTE: Install order is bottom to top! Lower level dependencies need to be down
'setuptools',
# Advanced packages
'pyproj==1.9.4', # For geospatial calculations
'numpy==1.9.2',
# HTTP related packages
'flask-socketio==0.4.1',
'flask-oauthlib==0.9.1',
'Flask==0.10.1',
'requests==2.5.3',
# Basic container packages
'graypy==0.2.11', # For production logging (used by standard logger config)
'ipython==3.2.3',
'readline==6.2.4.1', # For IPython shell
'ndg-xacml==0.5.1', # For policy rule engine
'psutil==2.1.3', # For host and process stats
'python-dateutil==2.4.2',
'bcrypt==1.0.1', # For password authentication
'python-daemon==2.0.5',
'simplejson==3.6.5',
'msgpack-python==0.4.7',
'pyyaml==3.10',
'pika==0.9.5', # NEED THIS VERSION. Messaging stack tweaked to this version
'zope.interface==4.1.1',
'psycopg2==2.5.4', # PostgreSQL driver
'gevent==1.0.2',
'greenlet==0.4.9',
# Pin dependent libraries (better in buildout/versions?)
'httplib2==0.9.2',
'pyzmq==15.4.0', # For IPython manhole
'cffi==0.9.2',
'oauthlib==0.7.2',
'six==1.9.0',
# Test support
'nose==1.1.2',
'mock==0.8',
'coverage==4.0', # Code coverage
],
extras_require={
'utils': [
'xlrd==0.9.3', # For Excel file read (dev tools)
'xlwt==0.7.5', # For Excel file write (dev tools)
],
'data': [
'h5py==2.5.0',
'Cython==0.23.4',
],
}
)
| bsd-2-clause | -8,226,793,217,231,396,000 | 40.128 | 145 | 0.511963 | false | 3.918445 | true | false | false |
jonnybazookatone/flask-watchman | tests/test_watchman.py | 1 | 4269 | import mock
import unittest
from flask import Flask
from flask.ext.testing import TestCase
from flask_watchman import Watchman, Environment
class TestWatchman(TestCase):
"""
Test flask apps that are using class based views
"""
def create_app(self):
app = Flask(__name__, static_folder=None)
Watchman(app, environment={})
app.config.setdefault('APP_LOGGING', 'MY LOGGING')
return app
def test_watchman_routes_exist(self):
"""
Test that the routes added exist
"""
r = self.client.options('/version')
self.assertStatus(r, 200)
r = self.client.options('/environment')
self.assertStatus(r, 200)
@mock.patch('flask_watchman.subprocess')
def test_version_route_works(self, mocked_subprocess):
"""
Tests that the version route works
"""
process = mock.Mock()
process.communicate.side_effect = [
['latest-release', 'error'],
['latest-commit', 'error']
]
mocked_subprocess.Popen.return_value = process
r = self.client.get('/version')
self.assertStatus(r, 200)
self.assertTrue(mocked_subprocess.Popen.called)
self.assertEqual(
r.json['commit'],
'latest-commit'
)
self.assertEqual(
r.json['release'],
'latest-release'
)
@mock.patch('flask_watchman.os.environ')
def test_environment_route_works(self, mocked_environ):
"""
Tests that the environment route works
"""
mocked_environ.keys.return_value = ['OS_SHELL']
mocked_environ.get.return_value = '/bin/favourite-shell'
r = self.client.get('/environment')
self.assertStatus(r, 200)
self.assertEqual(
r.json['os']['OS_SHELL'],
'/bin/favourite-shell'
)
self.assertEqual(
r.json['app']['APP_LOGGING'],
'MY LOGGING'
)
class TestWatchmanScopes(unittest.TestCase):
def tearDown(self):
"""
Hack to cleanup class attributes set in the tests
"""
for key in ['scopes', 'decorators', 'rate_limit']:
try:
delattr(Environment, key)
except AttributeError:
pass
def test_adding_scopes_to_routes(self):
"""
Check the behaviour when scopes are specified
"""
app = Flask(__name__, static_folder=None)
environment = {
'scopes': ['adsws:internal'],
}
with self.assertRaises(AttributeError):
getattr(Environment, 'scopes')
getattr(Environment, 'rate_limit')
getattr(Environment, 'decorators')
Watchman(app, environment=environment)
self.assertEqual(Environment.scopes, ['adsws:internal'])
self.assertIsInstance(Environment.decorators, list)
self.assertIsInstance(Environment.rate_limit, list)
def test_empty_scopes(self):
"""
Check the behaviour when empty scopes are requested
"""
app = Flask(__name__, static_folder=None)
environment = {
'scopes': [],
}
with self.assertRaises(AttributeError):
getattr(Environment, 'scopes')
getattr(Environment, 'rate_limit')
print getattr(Environment, 'decorators')
Watchman(app, environment=environment)
self.assertEqual(Environment.scopes, [])
self.assertIsInstance(Environment.decorators, list)
self.assertIsInstance(Environment.rate_limit, list)
def test_no_scopes(self):
"""
Check the behaviour when no scopes are requested at all
"""
app = Flask(__name__, static_folder=None)
with self.assertRaises(AttributeError):
getattr(Environment, 'scopes')
getattr(Environment, 'rate_limit')
getattr(Environment, 'decorators')
Watchman(app)
with self.assertRaises(AttributeError):
getattr(Environment, 'scopes')
getattr(Environment, 'decorators')
getattr(Environment, 'rate_limit')
if __name__ == '__main__':
unittest.main(verbosity=2)
| mit | 3,942,468,869,551,875,600 | 26.018987 | 64 | 0.580932 | false | 4.51746 | true | false | false |
netblue30/firetools | src/profile_editor/profileEditUI.py | 1 | 23223 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'fj1.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.formLayoutWidget = QtWidgets.QWidget(self.centralwidget)
self.formLayoutWidget.setGeometry(QtCore.QRect(270, 30, 181, 509))
self.formLayoutWidget.setObjectName("formLayoutWidget")
self.formLayout = QtWidgets.QFormLayout(self.formLayoutWidget)
self.formLayout.setContentsMargins(0, 0, 0, 0)
self.formLayout.setObjectName("formLayout")
self.capsDropLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.capsDropLabel.setObjectName("capsDropLabel")
self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.capsDropLabel)
self.capsDropSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.capsDropSlider.setFocusPolicy(QtCore.Qt.NoFocus)
self.capsDropSlider.setMaximum(1)
self.capsDropSlider.setPageStep(1)
self.capsDropSlider.setTracking(False)
self.capsDropSlider.setOrientation(QtCore.Qt.Horizontal)
self.capsDropSlider.setTickPosition(QtWidgets.QSlider.NoTicks)
self.capsDropSlider.setObjectName("capsDropSlider")
self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.capsDropSlider)
self.ipcLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.ipcLabel.setObjectName("ipcLabel")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.ipcLabel)
self.ipcSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.ipcSlider.setMaximum(1)
self.ipcSlider.setOrientation(QtCore.Qt.Horizontal)
self.ipcSlider.setObjectName("ipcSlider")
self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.ipcSlider)
self.netfilterLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.netfilterLabel.setObjectName("netfilterLabel")
self.formLayout.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.netfilterLabel)
self.netfilterSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.netfilterSlider.setMaximum(1)
self.netfilterSlider.setOrientation(QtCore.Qt.Horizontal)
self.netfilterSlider.setObjectName("netfilterSlider")
self.formLayout.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.netfilterSlider)
self.machineIDLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.machineIDLabel.setObjectName("machineIDLabel")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.machineIDLabel)
self.machineIDSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.machineIDSlider.setMaximum(1)
self.machineIDSlider.setOrientation(QtCore.Qt.Horizontal)
self.machineIDSlider.setObjectName("machineIDSlider")
self.formLayout.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.machineIDSlider)
self.nodvdLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.nodvdLabel.setObjectName("nodvdLabel")
self.formLayout.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.nodvdLabel)
self.nodvdSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.nodvdSlider.setMaximum(1)
self.nodvdSlider.setOrientation(QtCore.Qt.Horizontal)
self.nodvdSlider.setObjectName("nodvdSlider")
self.formLayout.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.nodvdSlider)
self.nomountLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.nomountLabel.setObjectName("nomountLabel")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.nomountLabel)
self.nomountSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.nomountSlider.setMaximum(1)
self.nomountSlider.setOrientation(QtCore.Qt.Horizontal)
self.nomountSlider.setObjectName("nomountSlider")
self.formLayout.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.nomountSlider)
self.notvLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.notvLabel.setObjectName("notvLabel")
self.formLayout.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.notvLabel)
self.notvSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.notvSlider.setMaximum(1)
self.notvSlider.setOrientation(QtCore.Qt.Horizontal)
self.notvSlider.setObjectName("notvSlider")
self.formLayout.setWidget(6, QtWidgets.QFormLayout.FieldRole, self.notvSlider)
self.nosoundLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.nosoundLabel.setObjectName("nosoundLabel")
self.formLayout.setWidget(7, QtWidgets.QFormLayout.LabelRole, self.nosoundLabel)
self.nosoundSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.nosoundSlider.setMaximum(1)
self.nosoundSlider.setOrientation(QtCore.Qt.Horizontal)
self.nosoundSlider.setObjectName("nosoundSlider")
self.formLayout.setWidget(7, QtWidgets.QFormLayout.FieldRole, self.nosoundSlider)
self.novideoLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.novideoLabel.setObjectName("novideoLabel")
self.formLayout.setWidget(8, QtWidgets.QFormLayout.LabelRole, self.novideoLabel)
self.novideoSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.novideoSlider.setMaximum(1)
self.novideoSlider.setOrientation(QtCore.Qt.Horizontal)
self.novideoSlider.setObjectName("novideoSlider")
self.formLayout.setWidget(8, QtWidgets.QFormLayout.FieldRole, self.novideoSlider)
self.nogroupsLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.nogroupsLabel.setObjectName("nogroupsLabel")
self.formLayout.setWidget(9, QtWidgets.QFormLayout.LabelRole, self.nogroupsLabel)
self.nogroupsSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.nogroupsSlider.setMaximum(1)
self.nogroupsSlider.setOrientation(QtCore.Qt.Horizontal)
self.nogroupsSlider.setObjectName("nogroupsSlider")
self.formLayout.setWidget(9, QtWidgets.QFormLayout.FieldRole, self.nogroupsSlider)
self.nonewprivsLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.nonewprivsLabel.setObjectName("nonewprivsLabel")
self.formLayout.setWidget(10, QtWidgets.QFormLayout.LabelRole, self.nonewprivsLabel)
self.nonewprivsSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.nonewprivsSlider.setMaximum(1)
self.nonewprivsSlider.setOrientation(QtCore.Qt.Horizontal)
self.nonewprivsSlider.setObjectName("nonewprivsSlider")
self.formLayout.setWidget(10, QtWidgets.QFormLayout.FieldRole, self.nonewprivsSlider)
self.norootLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.norootLabel.setObjectName("norootLabel")
self.formLayout.setWidget(11, QtWidgets.QFormLayout.LabelRole, self.norootLabel)
self.norootSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.norootSlider.setMaximum(1)
self.norootSlider.setOrientation(QtCore.Qt.Horizontal)
self.norootSlider.setObjectName("norootSlider")
self.formLayout.setWidget(11, QtWidgets.QFormLayout.FieldRole, self.norootSlider)
self.noshellLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.noshellLabel.setObjectName("noshellLabel")
self.formLayout.setWidget(12, QtWidgets.QFormLayout.LabelRole, self.noshellLabel)
self.noshellSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.noshellSlider.setMaximum(1)
self.noshellSlider.setOrientation(QtCore.Qt.Horizontal)
self.noshellSlider.setObjectName("noshellSlider")
self.formLayout.setWidget(12, QtWidgets.QFormLayout.FieldRole, self.noshellSlider)
self.seccompLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.seccompLabel.setObjectName("seccompLabel")
self.formLayout.setWidget(13, QtWidgets.QFormLayout.LabelRole, self.seccompLabel)
self.seccompSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.seccompSlider.setMaximum(1)
self.seccompSlider.setOrientation(QtCore.Qt.Horizontal)
self.seccompSlider.setObjectName("seccompSlider")
self.formLayout.setWidget(13, QtWidgets.QFormLayout.FieldRole, self.seccompSlider)
self.mdweLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.mdweLabel.setObjectName("mdweLabel")
self.formLayout.setWidget(14, QtWidgets.QFormLayout.LabelRole, self.mdweLabel)
self.mdweSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.mdweSlider.setMaximum(1)
self.mdweSlider.setOrientation(QtCore.Qt.Horizontal)
self.mdweSlider.setObjectName("mdweSlider")
self.formLayout.setWidget(14, QtWidgets.QFormLayout.FieldRole, self.mdweSlider)
self.tracelogLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.tracelogLabel.setObjectName("tracelogLabel")
self.formLayout.setWidget(15, QtWidgets.QFormLayout.LabelRole, self.tracelogLabel)
self.tracelogSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.tracelogSlider.setMaximum(1)
self.tracelogSlider.setOrientation(QtCore.Qt.Horizontal)
self.tracelogSlider.setObjectName("tracelogSlider")
self.formLayout.setWidget(15, QtWidgets.QFormLayout.FieldRole, self.tracelogSlider)
self.noexecHomeLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.noexecHomeLabel.setObjectName("noexecHomeLabel")
self.formLayout.setWidget(16, QtWidgets.QFormLayout.LabelRole, self.noexecHomeLabel)
self.noexecHomeSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.noexecHomeSlider.setMaximum(1)
self.noexecHomeSlider.setOrientation(QtCore.Qt.Horizontal)
self.noexecHomeSlider.setObjectName("noexecHomeSlider")
self.formLayout.setWidget(16, QtWidgets.QFormLayout.FieldRole, self.noexecHomeSlider)
self.noexecTmpLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.noexecTmpLabel.setObjectName("noexecTmpLabel")
self.formLayout.setWidget(17, QtWidgets.QFormLayout.LabelRole, self.noexecTmpLabel)
self.noexecTmpSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.noexecTmpSlider.setMaximum(1)
self.noexecTmpSlider.setOrientation(QtCore.Qt.Horizontal)
self.noexecTmpSlider.setObjectName("noexecTmpSlider")
self.formLayout.setWidget(17, QtWidgets.QFormLayout.FieldRole, self.noexecTmpSlider)
self.quietLabel = QtWidgets.QLabel(self.formLayoutWidget)
self.quietLabel.setObjectName("quietLabel")
self.formLayout.setWidget(18, QtWidgets.QFormLayout.LabelRole, self.quietLabel)
self.quietSlider = QtWidgets.QSlider(self.formLayoutWidget)
self.quietSlider.setMaximum(1)
self.quietSlider.setOrientation(QtCore.Qt.Horizontal)
self.quietSlider.setObjectName("quietSlider")
self.formLayout.setWidget(18, QtWidgets.QFormLayout.FieldRole, self.quietSlider)
self.genOptionsLabel = QtWidgets.QLabel(self.centralwidget)
self.genOptionsLabel.setGeometry(QtCore.QRect(300, 10, 111, 17))
self.genOptionsLabel.setObjectName("genOptionsLabel")
self.formLayoutWidget_2 = QtWidgets.QWidget(self.centralwidget)
self.formLayoutWidget_2.setGeometry(QtCore.QRect(630, 40, 161, 482))
self.formLayoutWidget_2.setObjectName("formLayoutWidget_2")
self.formLayout_2 = QtWidgets.QFormLayout(self.formLayoutWidget_2)
self.formLayout_2.setContentsMargins(0, 0, 0, 0)
self.formLayout_2.setObjectName("formLayout_2")
self.homeLabel = QtWidgets.QLabel(self.formLayoutWidget_2)
self.homeLabel.setObjectName("homeLabel")
self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.homeLabel)
self.horizontalSlider_24 = QtWidgets.QSlider(self.formLayoutWidget_2)
self.horizontalSlider_24.setMaximum(1)
self.horizontalSlider_24.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider_24.setObjectName("horizontalSlider_24")
self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.horizontalSlider_24)
self.devLabel = QtWidgets.QLabel(self.formLayoutWidget_2)
self.devLabel.setObjectName("devLabel")
self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.devLabel)
self.horizontalSlider_19 = QtWidgets.QSlider(self.formLayoutWidget_2)
self.horizontalSlider_19.setMaximum(1)
self.horizontalSlider_19.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider_19.setObjectName("horizontalSlider_19")
self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.horizontalSlider_19)
self.tmpLabel = QtWidgets.QLabel(self.formLayoutWidget_2)
self.tmpLabel.setObjectName("tmpLabel")
self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.tmpLabel)
self.horizontalSlider_20 = QtWidgets.QSlider(self.formLayoutWidget_2)
self.horizontalSlider_20.setMaximum(1)
self.horizontalSlider_20.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider_20.setObjectName("horizontalSlider_20")
self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.horizontalSlider_20)
self.etcLabel = QtWidgets.QLabel(self.formLayoutWidget_2)
self.etcLabel.setObjectName("etcLabel")
self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.etcLabel)
self.horizontalSlider_21 = QtWidgets.QSlider(self.formLayoutWidget_2)
self.horizontalSlider_21.setMaximum(1)
self.horizontalSlider_21.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider_21.setObjectName("horizontalSlider_21")
self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.horizontalSlider_21)
self.etcBrowser = QtWidgets.QTextBrowser(self.formLayoutWidget_2)
self.etcBrowser.setObjectName("etcBrowser")
self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.SpanningRole, self.etcBrowser)
self.binLabel = QtWidgets.QLabel(self.formLayoutWidget_2)
self.binLabel.setObjectName("binLabel")
self.formLayout_2.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.binLabel)
self.horizontalSlider_23 = QtWidgets.QSlider(self.formLayoutWidget_2)
self.horizontalSlider_23.setMaximum(1)
self.horizontalSlider_23.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider_23.setObjectName("horizontalSlider_23")
self.formLayout_2.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.horizontalSlider_23)
self.binBrowser = QtWidgets.QTextBrowser(self.formLayoutWidget_2)
self.binBrowser.setObjectName("binBrowser")
self.formLayout_2.setWidget(6, QtWidgets.QFormLayout.SpanningRole, self.binBrowser)
self.libLabel = QtWidgets.QLabel(self.formLayoutWidget_2)
self.libLabel.setObjectName("libLabel")
self.formLayout_2.setWidget(7, QtWidgets.QFormLayout.LabelRole, self.libLabel)
self.horizontalSlider_22 = QtWidgets.QSlider(self.formLayoutWidget_2)
self.horizontalSlider_22.setMaximum(1)
self.horizontalSlider_22.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider_22.setObjectName("horizontalSlider_22")
self.formLayout_2.setWidget(7, QtWidgets.QFormLayout.FieldRole, self.horizontalSlider_22)
self.libBrowser = QtWidgets.QTextBrowser(self.formLayoutWidget_2)
self.libBrowser.setObjectName("libBrowser")
self.formLayout_2.setWidget(8, QtWidgets.QFormLayout.SpanningRole, self.libBrowser)
self.optLabel = QtWidgets.QLabel(self.formLayoutWidget_2)
self.optLabel.setObjectName("optLabel")
self.formLayout_2.setWidget(9, QtWidgets.QFormLayout.LabelRole, self.optLabel)
self.horizontalSlider_25 = QtWidgets.QSlider(self.formLayoutWidget_2)
self.horizontalSlider_25.setMaximum(1)
self.horizontalSlider_25.setOrientation(QtCore.Qt.Horizontal)
self.horizontalSlider_25.setObjectName("horizontalSlider_25")
self.formLayout_2.setWidget(9, QtWidgets.QFormLayout.FieldRole, self.horizontalSlider_25)
self.optBrowser = QtWidgets.QTextBrowser(self.formLayoutWidget_2)
self.optBrowser.setObjectName("optBrowser")
self.formLayout_2.setWidget(10, QtWidgets.QFormLayout.SpanningRole, self.optBrowser)
self.privateLabel = QtWidgets.QLabel(self.centralwidget)
self.privateLabel.setGeometry(QtCore.QRect(660, 20, 121, 20))
self.privateLabel.setObjectName("privateLabel")
self.formLayoutWidget_3 = QtWidgets.QWidget(self.centralwidget)
self.formLayoutWidget_3.setGeometry(QtCore.QRect(460, 260, 160, 80))
self.formLayoutWidget_3.setObjectName("formLayoutWidget_3")
self.formLayout_3 = QtWidgets.QFormLayout(self.formLayoutWidget_3)
self.formLayout_3.setContentsMargins(0, 0, 0, 0)
self.formLayout_3.setObjectName("formLayout_3")
self.x11Slider = QtWidgets.QSlider(self.formLayoutWidget_3)
self.x11Slider.setMaximum(1)
self.x11Slider.setPageStep(1)
self.x11Slider.setOrientation(QtCore.Qt.Horizontal)
self.x11Slider.setObjectName("x11Slider")
self.formLayout_3.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.x11Slider)
self.xephyrButton = QtWidgets.QRadioButton(self.formLayoutWidget_3)
self.xephyrButton.setObjectName("xephyrButton")
self.formLayout_3.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.xephyrButton)
self.xorgButton = QtWidgets.QRadioButton(self.formLayoutWidget_3)
self.xorgButton.setObjectName("xorgButton")
self.formLayout_3.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.xorgButton)
self.xpraButton = QtWidgets.QRadioButton(self.formLayoutWidget_3)
self.xpraButton.setObjectName("xpraButton")
self.formLayout_3.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.xpraButton)
self.xvfbButton = QtWidgets.QRadioButton(self.formLayoutWidget_3)
self.xvfbButton.setObjectName("xvfbButton")
self.formLayout_3.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.xvfbButton)
self.x11Label = QtWidgets.QLabel(self.formLayoutWidget_3)
self.x11Label.setObjectName("x11Label")
self.formLayout_3.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.x11Label)
self.graphicsLabel = QtWidgets.QLabel(self.centralwidget)
self.graphicsLabel.setGeometry(QtCore.QRect(480, 240, 121, 20))
self.graphicsLabel.setObjectName("graphicsLabel")
self.auditProgressBar = QtWidgets.QProgressBar(self.centralwidget)
self.auditProgressBar.setGeometry(QtCore.QRect(460, 490, 118, 23))
self.auditProgressBar.setProperty("value", 24)
self.auditProgressBar.setObjectName("auditProgressBar")
self.auditPushButton = QtWidgets.QPushButton(self.centralwidget)
self.auditPushButton.setGeometry(QtCore.QRect(470, 520, 101, 25))
self.auditPushButton.setObjectName("auditPushButton")
self.programListWidget = QtWidgets.QListWidget(self.centralwidget)
self.programListWidget.setGeometry(QtCore.QRect(10, 30, 211, 501))
self.programListWidget.setObjectName("programListWidget")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.capsDropLabel.setText(_translate("MainWindow", "Drop all capabilities"))
self.ipcLabel.setText(_translate("MainWindow", "IPC restriction"))
self.netfilterLabel.setText(_translate("MainWindow", "Network filter"))
self.machineIDLabel.setText(_translate("MainWindow", "Random machine ID"))
self.nodvdLabel.setText(_translate("MainWindow", "Hide DVDs"))
self.nomountLabel.setText(_translate("MainWindow", "Hide external drives"))
self.notvLabel.setText(_translate("MainWindow", "Hide TV devices"))
self.nosoundLabel.setText(_translate("MainWindow", "No audio/microphone"))
self.novideoLabel.setText(_translate("MainWindow", "No webcam"))
self.nogroupsLabel.setText(_translate("MainWindow", "No groups"))
self.nonewprivsLabel.setText(_translate("MainWindow", "No new privileges"))
self.norootLabel.setText(_translate("MainWindow", "No root"))
self.noshellLabel.setText(_translate("MainWindow", "No shell"))
self.seccompLabel.setText(_translate("MainWindow", "Use seccomp filter"))
self.mdweLabel.setText(_translate("MainWindow", "Hardened seccomp"))
self.tracelogLabel.setText(_translate("MainWindow", "Log violation attempts"))
self.noexecHomeLabel.setText(_translate("MainWindow", "Noexec home folder"))
self.noexecTmpLabel.setText(_translate("MainWindow", "Noexec /tmp"))
self.quietLabel.setText(_translate("MainWindow", "Disable output"))
self.genOptionsLabel.setText(_translate("MainWindow", "General Options"))
self.homeLabel.setText(_translate("MainWindow", "Private /home"))
self.devLabel.setText(_translate("MainWindow", "Private /dev"))
self.tmpLabel.setText(_translate("MainWindow", "Private /tmp"))
self.etcLabel.setText(_translate("MainWindow", "Private /etc"))
self.binLabel.setText(_translate("MainWindow", "Private /bin"))
self.libLabel.setText(_translate("MainWindow", "Private /lib"))
self.optLabel.setText(_translate("MainWindow", "Private /opt"))
self.privateLabel.setText(_translate("MainWindow", "Private Filesystem"))
self.xephyrButton.setText(_translate("MainWindow", "xephyr"))
self.xorgButton.setText(_translate("MainWindow", "xorg"))
self.xpraButton.setText(_translate("MainWindow", "xpra"))
self.xvfbButton.setText(_translate("MainWindow", "xvfb"))
self.x11Label.setText(_translate("MainWindow", "X11 Isolation"))
self.graphicsLabel.setText(_translate("MainWindow", "Graphics Sandbox"))
self.auditPushButton.setText(_translate("MainWindow", "Audit Profile"))
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
| gpl-2.0 | 594,753,417,943,092,900 | 63.688022 | 97 | 0.739052 | false | 3.805178 | false | false | false |
JohnVinyard/zounds | zounds/spectral/frequencyscale.py | 1 | 20309 |
import numpy as np
import bisect
class Hertz(float):
def __init__(self, hz):
try:
self.hz = hz.hz
except AttributeError:
self.hz = hz
def __neg__(self):
return Hertz(-self.hz)
def __add__(self, other):
try:
other = other.hz
except AttributeError:
pass
return Hertz(self.hz + other)
def __float__(self):
return self.hz
Hz = Hertz
# TODO: What commonalities can be factored out of this class and TimeSlice?
class FrequencyBand(object):
"""
Represents an interval, or band of frequencies in hertz (cycles per second)
Args:
start_hz (float): The lower bound of the frequency band in hertz
stop_hz (float): The upper bound of the frequency band in hertz
Examples::
>>> import zounds
>>> band = zounds.FrequencyBand(500, 1000)
>>> band.center_frequency
750.0
>>> band.bandwidth
500
"""
def __init__(self, start_hz, stop_hz):
super(FrequencyBand, self).__init__()
if stop_hz <= start_hz:
raise ValueError('stop_hz must be greater than start_hz')
self.stop_hz = stop_hz
self.start_hz = start_hz
def __eq__(self, other):
try:
return \
self.start_hz == other.start_hz \
and self.stop_hz == other.stop_hz
except AttributeError:
return super(FrequencyBand, self).__eq__(other)
def __hash__(self):
return (self.__class__.__name__, self.start_hz, self.stop_hz).__hash__()
def intersect(self, other):
"""
Return the intersection between this frequency band and another.
Args:
other (FrequencyBand): the instance to intersect with
Examples::
>>> import zounds
>>> b1 = zounds.FrequencyBand(500, 1000)
>>> b2 = zounds.FrequencyBand(900, 2000)
>>> intersection = b1.intersect(b2)
>>> intersection.start_hz, intersection.stop_hz
(900, 1000)
"""
lowest_stop = min(self.stop_hz, other.stop_hz)
highest_start = max(self.start_hz, other.start_hz)
return FrequencyBand(highest_start, lowest_stop)
@classmethod
def audible_range(cls, samplerate):
return FrequencyBand(Hz(20), Hz(samplerate.nyquist))
def bandwidth_ratio(self, other):
return other.bandwidth / self.bandwidth
def intersection_ratio(self, other):
intersection = self.intersect(other)
return self.bandwidth_ratio(intersection)
@staticmethod
def from_start(start_hz, bandwidth_hz):
"""
Produce a :class:`FrequencyBand` instance from a lower bound and
bandwidth
Args:
start_hz (float): the lower bound of the desired FrequencyBand
bandwidth_hz (float): the bandwidth of the desired FrequencyBand
"""
return FrequencyBand(start_hz, start_hz + bandwidth_hz)
@staticmethod
def from_center(center_hz, bandwidth_hz):
half_bandwidth = bandwidth_hz / 2
return FrequencyBand(
center_hz - half_bandwidth, center_hz + half_bandwidth)
@property
def bandwidth(self):
"""
The span of this frequency band, in hertz
"""
return self.stop_hz - self.start_hz
@property
def center_frequency(self):
return self.start_hz + (self.bandwidth / 2)
def __repr__(self):
return '''FrequencyBand(
start_hz={start_hz},
stop_hz={stop_hz},
center={center},
bandwidth={bandwidth})'''.format(
start_hz=self.start_hz,
stop_hz=self.stop_hz,
center=self.center_frequency,
bandwidth=self.bandwidth)
class FrequencyScale(object):
"""
Represents a set of frequency bands with monotonically increasing start
frequencies
Args:
frequency_band (FrequencyBand): A band representing the entire span of
this scale. E.g., one might want to generate a scale spanning the
entire range of human hearing by starting with
:code:`FrequencyBand(20, 20000)`
n_bands (int): The number of bands in this scale
always_even (bool): when converting frequency slices to integer indices
that numpy can understand, should the slice size always be even?
See Also:
:class:`~zounds.spectral.LinearScale`
:class:`~zounds.spectral.GeometricScale`
"""
def __init__(self, frequency_band, n_bands, always_even=False):
super(FrequencyScale, self).__init__()
self.always_even = always_even
self.n_bands = n_bands
self.frequency_band = frequency_band
self._bands = None
self._starts = None
self._stops = None
@property
def bands(self):
"""
An iterable of all bands in this scale
"""
if self._bands is None:
self._bands = self._compute_bands()
return self._bands
@property
def band_starts(self):
if self._starts is None:
self._starts = [b.start_hz for b in self.bands]
return self._starts
@property
def band_stops(self):
if self._stops is None:
self._stops = [b.stop_hz for b in self.bands]
return self._stops
def _compute_bands(self):
raise NotImplementedError()
def __len__(self):
return self.n_bands
@property
def center_frequencies(self):
"""
An iterable of the center frequencies of each band in this scale
"""
return (band.center_frequency for band in self)
@property
def bandwidths(self):
"""
An iterable of the bandwidths of each band in this scale
"""
return (band.bandwidth for band in self)
def ensure_overlap_ratio(self, required_ratio=0.5):
"""
Ensure that every adjacent pair of frequency bands meets the overlap
ratio criteria. This can be helpful in scenarios where a scale is
being used in an invertible transform, and something like the `constant
overlap add constraint
<https://ccrma.stanford.edu/~jos/sasp/Constant_Overlap_Add_COLA_Cases.html>`_
must be met in order to not introduce artifacts in the reconstruction.
Args:
required_ratio (float): The required overlap ratio between all
adjacent frequency band pairs
Raises:
AssertionError: when the overlap ratio for one or more adjacent
frequency band pairs is not met
"""
msg = \
'band {i}: ratio must be at least {required_ratio} but was {ratio}'
for i in range(0, len(self) - 1):
b1 = self[i]
b2 = self[i + 1]
try:
ratio = b1.intersection_ratio(b2)
except ValueError:
ratio = 0
if ratio < required_ratio:
raise AssertionError(msg.format(**locals()))
@property
def Q(self):
"""
The quality factor of the scale, or, the ratio of center frequencies
to bandwidths
"""
return np.array(list(self.center_frequencies)) \
/ np.array(list(self.bandwidths))
@property
def start_hz(self):
"""
The lower bound of this frequency scale
"""
return self.frequency_band.start_hz
@property
def stop_hz(self):
"""
The upper bound of this frequency scale
"""
return self.frequency_band.stop_hz
def _basis(self, other_scale, window):
weights = np.zeros((len(self), len(other_scale)))
for i, band in enumerate(self):
band_slice = other_scale.get_slice(band)
slce = weights[i, band_slice]
slce[:] = window * np.ones(len(slce))
return weights
def apply(self, time_frequency_repr, window):
basis = self._basis(time_frequency_repr.dimensions[-1].scale, window)
transformed = np.dot(basis, time_frequency_repr.T).T
return transformed
def __eq__(self, other):
return \
self.__class__ == other.__class__ \
and self.frequency_band == other.frequency_band \
and self.n_bands == other.n_bands
def __iter__(self):
return iter(self.bands)
def _construct_scale_from_slice(self, bands):
freq_band = FrequencyBand(bands[0].start_hz, bands[-1].stop_hz)
return self.__class__(freq_band, len(bands))
def get_slice(self, frequency_band):
"""
Given a frequency band, and a frequency dimension comprised of
n_samples, return a slice using integer indices that may be used to
extract only the frequency samples that intersect with the frequency
band
"""
index = frequency_band
if isinstance(index, slice):
types = {
index.start.__class__,
index.stop.__class__,
index.step.__class__
}
if Hertz not in types:
return index
try:
start = Hertz(0) if index.start is None else index.start
if start < Hertz(0):
start = self.stop_hz + start
stop = self.stop_hz if index.stop is None else index.stop
if stop < Hertz(0):
stop = self.stop_hz + stop
frequency_band = FrequencyBand(start, stop)
except (ValueError, TypeError):
pass
start_index = bisect.bisect_left(
self.band_stops, frequency_band.start_hz)
stop_index = bisect.bisect_left(
self.band_starts, frequency_band.stop_hz)
if self.always_even and (stop_index - start_index) % 2:
# KLUDGE: This is simple, but it may make sense to choose move the
# upper *or* lower bound, based on which one introduces a lower
# error
stop_index += 1
return slice(start_index, stop_index)
def __getitem__(self, index):
try:
# index is an integer or slice
bands = self.bands[index]
except TypeError:
# index is a frequency band
bands = self.bands[self.get_slice(index)]
if isinstance(bands, FrequencyBand):
return bands
return self._construct_scale_from_slice(bands)
def __str__(self):
cls = self.__class__.__name__
return '{cls}(band={self.frequency_band}, n_bands={self.n_bands})' \
.format(**locals())
def __repr__(self):
return self.__str__()
class LinearScale(FrequencyScale):
"""
A linear frequency scale with constant bandwidth. Appropriate for use
with transforms whose coefficients also lie on a linear frequency scale,
e.g. the FFT or DCT transforms.
Args:
frequency_band (FrequencyBand): A band representing the entire span of
this scale. E.g., one might want to generate a scale spanning the
entire range of human hearing by starting with
:code:`FrequencyBand(20, 20000)`
n_bands (int): The number of bands in this scale
always_even (bool): when converting frequency slices to integer indices
that numpy can understand, should the slice size always be even?
Examples:
>>> from zounds import FrequencyBand, LinearScale
>>> scale = LinearScale(FrequencyBand(20, 20000), 10)
>>> scale
LinearScale(band=FrequencyBand(
start_hz=20,
stop_hz=20000,
center=10010.0,
bandwidth=19980), n_bands=10)
>>> scale.Q
array([ 0.51001001, 1.51001001, 2.51001001, 3.51001001, 4.51001001,
5.51001001, 6.51001001, 7.51001001, 8.51001001, 9.51001001])
"""
def __init__(self, frequency_band, n_bands, always_even=False):
super(LinearScale, self).__init__(frequency_band, n_bands, always_even)
@staticmethod
def from_sample_rate(sample_rate, n_bands, always_even=False):
"""
Return a :class:`~zounds.spectral.LinearScale` instance whose upper
frequency bound is informed by the nyquist frequency of the sample rate.
Args:
sample_rate (SamplingRate): the sample rate whose nyquist frequency
will serve as the upper frequency bound of this scale
n_bands (int): the number of evenly-spaced frequency bands
"""
fb = FrequencyBand(0, sample_rate.nyquist)
return LinearScale(fb, n_bands, always_even=always_even)
def _compute_bands(self):
freqs = np.linspace(
self.start_hz, self.stop_hz, self.n_bands, endpoint=False)
# constant, non-overlapping bandwidth
bandwidth = freqs[1] - freqs[0]
return tuple(FrequencyBand(f, f + bandwidth) for f in freqs)
# class LogScale(FrequencyScale):
# def __init__(self, frequency_band, n_bands, always_even=False):
# super(LogScale, self).__init__(
# frequency_band, n_bands, always_even=always_even)
#
# def _compute_bands(self):
# center_freqs = np.logspace(
# np.log10(self.start_hz),
# np.log10(self.stop_hz),
# self.n_bands + 1)
# # variable bandwidth
# bandwidths = np.diff(center_freqs)
# return tuple(FrequencyBand.from_center(cf, bw)
# for (cf, bw) in zip(center_freqs[:-1], bandwidths))
class GeometricScale(FrequencyScale):
"""
A constant-Q scale whose center frequencies progress geometrically rather
than linearly
Args:
start_center_hz (int): the center frequency of the first band in the
scale
stop_center_hz (int): the center frequency of the last band in the scale
bandwidth_ratio (float): the center frequency to bandwidth ratio
n_bands (int): the total number of bands
Examples:
>>> from zounds import GeometricScale
>>> scale = GeometricScale(20, 20000, 0.05, 10)
>>> scale
GeometricScale(band=FrequencyBand(
start_hz=19.5,
stop_hz=20500.0,
center=10259.75,
bandwidth=20480.5), n_bands=10)
>>> scale.Q
array([ 20., 20., 20., 20., 20., 20., 20., 20., 20., 20.])
>>> list(scale.center_frequencies)
[20.000000000000004, 43.088693800637671, 92.831776672255558,
200.00000000000003, 430.88693800637651, 928.31776672255558,
2000.0000000000005, 4308.8693800637648, 9283.1776672255564,
20000.000000000004]
"""
def __init__(
self,
start_center_hz,
stop_center_hz,
bandwidth_ratio,
n_bands,
always_even=False):
self.__bands = [
FrequencyBand.from_center(cf, cf * bandwidth_ratio)
for cf in np.geomspace(start_center_hz, stop_center_hz, num=n_bands)
]
band = FrequencyBand(self.__bands[0].start_hz, self.__bands[-1].stop_hz)
super(GeometricScale, self).__init__(
band, n_bands, always_even=always_even)
self.start_center_hz = start_center_hz
self.stop_center_hz = stop_center_hz
self.bandwidth_ratio = bandwidth_ratio
def _construct_scale_from_slice(self, bands):
return ExplicitScale(bands)
def __eq__(self, other):
return \
super(GeometricScale, self).__eq__(other) \
and self.start_center_hz == other.start_center_hz \
and self.stop_center_hz == other.stop_center_hz \
and self.bandwidth_ratio == other.bandwidth_ratio
def _compute_bands(self):
return self.__bands
class ExplicitScale(FrequencyScale):
"""
A scale where the frequency bands are provided explicitly, rather than
computed
Args:
bands (list of FrequencyBand): The explicit bands used by this scale
See Also:
:class:`~zounds.spectral.FrequencyAdaptive`
"""
def __init__(self, bands):
bands = list(bands)
frequency_band = FrequencyBand(bands[0].start_hz, bands[-1].stop_hz)
super(ExplicitScale, self).__init__(
frequency_band, len(bands), always_even=False)
self._bands = bands
def _construct_scale_from_slice(self, bands):
return ExplicitScale(bands)
def _compute_bands(self):
return self._bands
def __eq__(self, other):
return all([a == b for (a, b) in zip(self, other)])
class Bark(Hertz):
def __init__(self, bark):
self.bark = bark
super(Bark, self).__init__(Bark.to_hz(bark))
@staticmethod
def to_hz(bark):
return 300. * ((np.e ** (bark / 6.0)) - (np.e ** (-bark / 6.)))
@staticmethod
def to_bark(hz):
return 6. * np.log((hz / 600.) + np.sqrt((hz / 600.) ** 2 + 1))
def equivalent_rectangular_bandwidth(hz):
return (0.108 * hz) + 24.7
class BarkScale(FrequencyScale):
def __init__(self, frequency_band, n_bands):
super(BarkScale, self).__init__(frequency_band, n_bands)
def _compute_bands(self):
start = Bark.to_bark(self.frequency_band.start_hz)
stop = Bark.to_bark(self.frequency_band.stop_hz)
barks = np.linspace(start, stop, self.n_bands)
center_frequencies_hz = Bark.to_hz(barks)
bandwidths = equivalent_rectangular_bandwidth(center_frequencies_hz)
return [
FrequencyBand.from_center(c, b)
for c, b in zip(center_frequencies_hz, bandwidths)]
class Mel(Hertz):
def __init__(self, mel):
self.mel = mel
super(Mel, self).__init__(Mel.to_hz(mel))
@staticmethod
def to_hz(mel):
return 700 * ((np.e ** (mel / 1127)) - 1)
@staticmethod
def to_mel(hz):
return 1127 * np.log(1 + (hz / 700))
class MelScale(FrequencyScale):
def __init__(self, frequency_band, n_bands):
super(MelScale, self).__init__(frequency_band, n_bands)
def _compute_bands(self):
start = Mel.to_mel(self.frequency_band.start_hz)
stop = Mel.to_mel(self.frequency_band.stop_hz)
mels = np.linspace(start, stop, self.n_bands)
center_frequencies_hz = Mel.to_hz(mels)
bandwidths = equivalent_rectangular_bandwidth(center_frequencies_hz)
return [
FrequencyBand.from_center(c, b)
for c, b in zip(center_frequencies_hz, bandwidths)]
class ChromaScale(FrequencyScale):
def __init__(self, frequency_band):
self._a440 = 440.
self._a = 2 ** (1 / 12.)
super(ChromaScale, self).__init__(frequency_band, n_bands=12)
def _compute_bands(self):
raise NotImplementedError()
def get_slice(self, frequency_band):
raise NotImplementedError()
def _semitones_to_hz(self, semitone):
return self._a440 * (self._a ** semitone)
def _hz_to_semitones(self, hz):
"""
Convert hertz into a number of semitones above or below some reference
value, in this case, A440
"""
return np.log(hz / self._a440) / np.log(self._a)
def _basis(self, other_scale, window):
basis = np.zeros((self.n_bands, len(other_scale)))
# for each tone in the twelve-tone scale, generate narrow frequency
# bands for every octave of that note that falls within the frequency
# band.
start_semitones = \
int(np.round(self._hz_to_semitones(self.frequency_band.start_hz)))
stop_semitones = \
int(np.round(self._hz_to_semitones(self.frequency_band.stop_hz)))
semitones = np.arange(start_semitones - 1, stop_semitones)
hz = self._semitones_to_hz(semitones)
bands = []
for i in range(0, len(semitones) - 2):
fh, mh, lh = hz[i: i + 3]
bands.append(FrequencyBand(fh, lh))
for semitone, band in zip(semitones, bands):
slce = other_scale.get_slice(band)
chroma_index = semitone % self.n_bands
slce = basis[chroma_index, slce]
slce[:] += np.ones(len(slce)) * window
return basis
| mit | -9,029,838,508,317,869,000 | 31.546474 | 85 | 0.587129 | false | 3.859559 | false | false | false |
JohnVinyard/zounds | zounds/spectral/spectral.py | 1 | 11596 |
import numpy as np
from featureflow import Node
from scipy.fftpack import dct
from scipy.stats.mstats import gmean
from .functional import fft, mdct
from .frequencyscale import LinearScale, ChromaScale, BarkScale
from .weighting import AWeighting
from .tfrepresentation import FrequencyDimension
from .frequencyadaptive import FrequencyAdaptive
from zounds.core import ArrayWithUnits, IdentityDimension
from zounds.nputil import safe_log
from zounds.timeseries import audio_sample_rate
from .sliding_window import HanningWindowingFunc
class FrequencyWeighting(Node):
"""
`FrequencyWeighting` is a processing node that expects to be passed an
:class:`~zounds.core.ArrayWithUnits` instance whose last dimension is a
:class:`~zounds.spectral.FrequencyDimension`
Args:
weighting (FrequencyWeighting): the frequency weighting to apply
needs (Node): a processing node on which this node depends whose last
dimension is a :class:`~zounds.spectral.FrequencyDimension`
"""
def __init__(self, weighting=None, needs=None):
super(FrequencyWeighting, self).__init__(needs=needs)
self.weighting = weighting
def _process(self, data):
yield data * self.weighting
class FFT(Node):
"""
A processing node that performs an FFT of a real-valued signal
Args:
axis (int): The axis over which the FFT should be computed
padding_samples (int): number of zero samples to pad each window with
before applying the FFT
needs (Node): a processing node on which this one depends
See Also:
:class:`~zounds.synthesize.FFTSynthesizer`
"""
def __init__(self, needs=None, axis=-1, padding_samples=0):
super(FFT, self).__init__(needs=needs)
self._axis = axis
self._padding_samples = padding_samples
def _process(self, data):
yield fft(data, axis=self._axis, padding_samples=self._padding_samples)
class DCT(Node):
"""
A processing node that performs a Type II Discrete Cosine Transform
(https://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-II) of the
input
Args:
axis (int): The axis over which to perform the DCT transform
needs (Node): a processing node on which this one depends
See Also:
:class:`~zounds.synthesize.DctSynthesizer`
"""
def __init__(self, axis=-1, scale_always_even=False, needs=None):
super(DCT, self).__init__(needs=needs)
self.scale_always_even = scale_always_even
self._axis = axis
def _process(self, data):
transformed = dct(data, norm='ortho', axis=self._axis)
sr = audio_sample_rate(
int(data.shape[1] / data.dimensions[0].duration_in_seconds))
scale = LinearScale.from_sample_rate(
sr, transformed.shape[-1], always_even=self.scale_always_even)
yield ArrayWithUnits(
transformed, [data.dimensions[0], FrequencyDimension(scale)])
class DCTIV(Node):
"""
A processing node that performs a Type IV Discrete Cosine Transform
(https://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-IV) of the
input
Args:
needs (Node): a processing node on which this one depends
See Also:
:class:`~zounds.synthesize.DCTIVSynthesizer`
"""
def __init__(self, scale_always_even=False, needs=None):
super(DCTIV, self).__init__(needs=needs)
self.scale_always_even = scale_always_even
def _process_raw(self, data):
l = data.shape[1]
tf = np.arange(0, l)
z = np.zeros((len(data), l * 2))
z[:, :l] = (data * np.exp(-1j * np.pi * tf / 2 / l)).real
z = np.fft.fft(z)[:, :l]
raw = np.sqrt(2 / l) * \
(z * np.exp(-1j * np.pi * (tf + 0.5) / 2 / l)).real
return raw
def _process(self, data):
raw = self._process_raw(data)
sr = audio_sample_rate(
int(data.shape[1] / data.dimensions[0].duration_in_seconds))
scale = LinearScale.from_sample_rate(
sr, data.shape[1], always_even=self.scale_always_even)
yield ArrayWithUnits(
raw, [data.dimensions[0], FrequencyDimension(scale)])
class MDCT(Node):
"""
A processing node that performs a modified discrete cosine transform
(https://en.wikipedia.org/wiki/Modified_discrete_cosine_transform) of the
input.
This is really just a lapped version of the DCT-IV transform
Args:
needs (Node): a processing node on which this one depends
See Also:
:class:`~zounds.synthesize.MDCTSynthesizer`
"""
def __init__(self, needs=None):
super(MDCT, self).__init__(needs=needs)
def _process(self, data):
transformed = mdct(data)
sr = audio_sample_rate(data.dimensions[1].samples_per_second)
scale = LinearScale.from_sample_rate(sr, transformed.shape[1])
yield ArrayWithUnits(
transformed, [data.dimensions[0], FrequencyDimension(scale)])
class FrequencyAdaptiveTransform(Node):
"""
A processing node that expects to receive the input from a frequency domain
transformation (e.g. :class:`~zounds.spectral.FFT`), and produces a
:class:`~zounds.spectral.FrequencyAdaptive` instance where time resolution
can vary by frequency. This is similar to, but not precisely the same as
ideas introduced in:
* `A quasi-orthogonal, invertible, and perceptually relevant time-frequency transform for audio coding <https://hal-amu.archives-ouvertes.fr/hal-01194806/document>`_
* `A FRAMEWORK FOR INVERTIBLE, REAL-TIME CONSTANT-Q TRANSFORMS <http://www.univie.ac.at/nonstatgab/pdf_files/dogrhove12_amsart.pdf>`_
Args:
transform (function): the transform to be applied to each frequency band
scale (FrequencyScale): the scale used to take frequency band slices
window_func (numpy.ndarray): the windowing function to apply each band
before the transform is applied
check_scale_overlap_ratio (bool): If this feature is to be used for
resynthesis later, ensure that each frequency band overlaps with
the previous one by at least half, to ensure artifact-free synthesis
See Also:
:class:`~zounds.spectral.FrequencyAdaptive`
:class:`~zounds.synthesize.FrequencyAdaptiveDCTSynthesizer`
:class:`~zounds.synthesize.FrequencyAdaptiveFFTSynthesizer`
"""
def __init__(
self,
transform=None,
scale=None,
window_func=None,
check_scale_overlap_ratio=False,
needs=None):
super(FrequencyAdaptiveTransform, self).__init__(needs=needs)
if check_scale_overlap_ratio:
try:
scale.ensure_overlap_ratio(0.5)
except AssertionError as e:
raise ValueError(*e.args)
self._window_func = window_func or np.ones
self._scale = scale
self._transform = transform
def _process_band(self, data, band):
try:
raw_coeffs = data[:, band]
except IndexError:
raise ValueError(
'data must have FrequencyDimension as its last dimension, '
'but it was {dim}'.format(dim=data.dimensions[-1]))
window = self._window_func(raw_coeffs.shape[1])
return self._transform(raw_coeffs * window[None, :], norm='ortho')
def _process(self, data):
yield FrequencyAdaptive(
[self._process_band(data, band) for band in self._scale],
data.dimensions[0],
self._scale)
class BaseScaleApplication(Node):
def __init__(self, scale, window, needs=None):
super(BaseScaleApplication, self).__init__(needs=needs)
self.window = window
self.scale = scale
def _new_dim(self):
return FrequencyDimension(self.scale)
def _preprocess(self, data):
return data
def _process(self, data):
x = self._preprocess(data)
x = self.scale.apply(x, self.window)
yield ArrayWithUnits(
x, data.dimensions[:-1] + (self._new_dim(),))
class Chroma(BaseScaleApplication):
def __init__(
self, frequency_band, window=HanningWindowingFunc(), needs=None):
super(Chroma, self).__init__(
ChromaScale(frequency_band), window, needs=needs)
def _new_dim(self):
return IdentityDimension()
def _preprocess(self, data):
return np.abs(data) * AWeighting()
class BarkBands(BaseScaleApplication):
def __init__(
self,
frequency_band,
n_bands=100,
window=HanningWindowingFunc(),
needs=None):
super(BarkBands, self).__init__(
BarkScale(frequency_band, n_bands), window, needs=needs)
def _preprocess(self, data):
return np.abs(data)
class SpectralCentroid(Node):
"""
Indicates where the "center of mass" of the spectrum is. Perceptually,
it has a robust connection with the impression of "brightness" of a
sound. It is calculated as the weighted mean of the frequencies
present in the signal, determined using a Fourier transform, with
their magnitudes as the weights...
-- http://en.wikipedia.org/wiki/Spectral_centroid
"""
def __init__(self, needs=None):
super(SpectralCentroid, self).__init__(needs=needs)
def _first_chunk(self, data):
self._bins = np.arange(1, data.shape[-1] + 1)
self._bins_sum = np.sum(self._bins)
return data
def _process(self, data):
data = np.abs(data)
yield (data * self._bins).sum(axis=1) / self._bins_sum
class SpectralFlatness(Node):
"""
Spectral flatness or tonality coefficient, also known as Wiener
entropy, is a measure used in digital signal processing to characterize an
audio spectrum. Spectral flatness is typically measured in decibels, and
provides a way to quantify how tone-like a sound is, as opposed to being
noise-like. The meaning of tonal in this context is in the sense of the
amount of peaks or resonant structure in a power spectrum, as opposed to
flat spectrum of a white noise. A high spectral flatness indicates that
the spectrum has a similar amount of power in all spectral bands - this
would sound similar to white noise, and the graph of the spectrum would
appear relatively flat and smooth. A low spectral flatness indicates that
the spectral power is concentrated in a relatively small number of
bands - this would typically sound like a mixture of sine waves, and the
spectrum would appear "spiky"...
-- http://en.wikipedia.org/wiki/Spectral_flatness
"""
def __init__(self, needs=None):
super(SpectralFlatness, self).__init__(needs=needs)
def _process(self, data):
data = np.abs(data)
mean = data.mean(axis=1)
mean[mean == 0] = -1e5
flatness = gmean(data, axis=1) / mean
yield ArrayWithUnits(flatness, data.dimensions[:1])
class BFCC(Node):
"""
Bark frequency cepstral coefficients
"""
def __init__(self, needs=None, n_coeffs=13, exclude=1):
super(BFCC, self).__init__(needs=needs)
self._n_coeffs = n_coeffs
self._exclude = exclude
def _process(self, data):
data = np.abs(data)
bfcc = dct(safe_log(data), axis=1) \
[:, self._exclude: self._exclude + self._n_coeffs]
yield ArrayWithUnits(
bfcc.copy(), [data.dimensions[0], IdentityDimension()])
| mit | -8,911,567,143,534,565,000 | 33.614925 | 169 | 0.644964 | false | 3.843553 | false | false | false |
flychen50/thinkstat | chi.py | 2 | 3747 | """This file contains code for use with "Think Stats",
by Allen B. Downey, available from greenteapress.com
Copyright 2010 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
import descriptive
import itertools
import Pmf
import random
import risk
import thinkstats
def ComputeRow(n, probs):
"""Multiplies out a row of a table.
Args:
n: sum of the elements in the row
prob: sequence of float probabilities
"""
row = [n * prob for prob in probs]
return row
def SimulateRow(n, probs):
"""Generates a random row of a table.
Chooses all but the last element at random, then chooses the
last element to make the sums work.
Args:
n: sum of the elements in the row
prob: sequence of float probabilities
"""
row = [Binomial(n, prob) for prob in probs]
row[-1] += n - sum(row)
return row
def Binomial(n, prob):
"""Returns a random sample from a binomial distribution.
Args:
n: int number of trials
prob: float probability
Returns:
int: number of successes
"""
t = [1 for _ in range(n) if random.random() < prob]
return sum(t)
def ComputeRows(firsts, others, funcs, probs=None, row_func=ComputeRow):
"""Computes a table suitable for use with chi-squared stats.
There are three uses of this function:
1) To compute observed values, use probs=None and row_func=ComputeRow
2) To compute expected values, provide probs from the pooled data,
and row_func=ComputeRow
3) To generate random values, provide pooled probs,
and row_func=SimulateRow
Returns:
row of rows of float values
"""
rows = []
for table in [firsts, others]:
n = len(table)
row_probs = probs or [func(table.pmf) for func in funcs]
row = row_func(n, row_probs)
rows.append(row)
return rows
def ChiSquared(expected, observed):
"""Compute the Chi-squared statistic for two tables.
Args:
expected: row of rows of values
observed: row of rows of values
Returns:
float chi-squared statistic
"""
it = zip(itertools.chain(*expected),
itertools.chain(*observed))
t = [(obs - exp)**2 / exp for exp, obs in it]
return sum(t)
def Test(pool, firsts, others, num_trials=1000):
# collect the functions from risk.py that take Pmfs and compute
# various probabilities
funcs = [risk.ProbEarly, risk.ProbOnTime, risk.ProbLate]
# get the observed frequency in each bin
print 'observed'
observed = ComputeRows(firsts, others, funcs, probs=None)
print observed
# compute the expected frequency in each bin
tables = [firsts, others]
probs = [func(pool.pmf) for func in funcs]
print 'expected'
expected = ComputeRows(firsts, others, funcs, probs=probs)
print expected
# compute the chi-squared stat
print 'chi-squared'
threshold = ChiSquared(expected, observed)
print threshold
print 'simulated %d trials' % num_trials
chi2s = []
count = 0
for _ in range(num_trials):
simulated = ComputeRows(firsts, others, funcs, probs=probs,
row_func=SimulateRow)
chi2 = ChiSquared(expected, simulated)
chi2s.append(chi2)
if chi2 >= threshold:
count += 1
print 'max chi2'
print max(chi2s)
pvalue = 1.0 * count / num_trials
print 'p-value'
print pvalue
return pvalue
def main():
# get the data
pool, firsts, others = descriptive.MakeTables()
Test(pool, firsts, others, num_trials=1000)
if __name__ == "__main__":
main()
| mit | -3,031,374,080,909,250,600 | 24.317568 | 73 | 0.628503 | false | 3.83521 | false | false | false |
go1dshtein/pgv | pgv/loader.py | 1 | 1947 | import os
import re
import logging
logger = logging.getLogger(__name__)
class Loader:
def __init__(self, basedir):
self.basedir = basedir
self.ipattern = re.compile(r'^\\i\s+(.+?)\s*$', re.U | re.M)
self.irpattern = re.compile(r'^\\ir\s+(.+?)\s*$', re.U | re.M)
def load(self, path):
filename = os.path.join(self.basedir, path)
script = self._read(filename)
script = self._preproceed(filename, script)
return script
def _read(self, path):
with open(path) as h:
return h.read()
def _preproceed(self, path, script):
imatch = self.ipattern.search(script)
irmatch = self.irpattern.search(script)
while imatch or irmatch:
if imatch:
script = self._preproceed_i(path, script, imatch)
elif irmatch:
script = self._preproceed_ir(path, script, irmatch)
imatch = self.ipattern.search(script)
irmatch = self.irpattern.search(script)
return script
def _preproceed_i(self, path, script, match):
filename = match.group(1)
if filename != os.path.abspath(filename):
filename = os.path.join(self.basedir, match.group(1))
return self._include(path, script, match, filename)
def _preproceed_ir(self, path, script, match):
filename = match.group(1)
if filename != os.path.abspath(filename):
dirname = os.path.dirname(path)
filename = os.path.join(dirname, match.group(1))
return self._include(path, script, match, filename)
def _include(self, path, script, match, filename):
if not os.path.isfile(filename):
raise IOError("Script: %s: line: %s: file %s not found" %
(path, match.group(0), filename))
return script[:match.start()] + \
self._read(filename) + \
script[match.end():]
| gpl-2.0 | 1,194,491,291,310,016,800 | 34.4 | 70 | 0.576271 | false | 3.6875 | false | false | false |
DJO3/regex_grounds | exercise_1/add_to_mongo.py | 1 | 1605 | import os
import re
import sys
import pymongo
# Looks for local baby names directory and outputs a dictionary in the format year: "name,sex,num_occurrence".
def get_data():
data = {}
names = os.getcwd() + '/names'
if os.path.exists(names):
names_dir = os.listdir(names)
for yob in names_dir:
if yob[-4:] == '.txt':
year = re.search(r'\d\d\d\d', yob)
with open(names + '/' + yob) as txt:
data[year.group()] = re.findall(r'\S+', txt.read())
return data
return "names directory not found!"
# Cleans up data for friendly JSON output
def fix_data(data):
fixed_data = {}
temp = {}
for year in data:
id = 0
for value in data[year]:
name = re.search(r'\w+', value).group()
sex = re.search(r'(,)(\w+)', value).group()[1]
num_occurrence = re.search(r'\d+', value).group()
temp[id] = {"name": name, "sex": sex, "num_occurrence": num_occurrence}
id += 1
fixed_data[year] = temp.values()
return fixed_data
# Outputs fixed_data to MongoDB
def sendto_mongo(fixed_data):
connection = pymongo.Connection("mongodb://localhost", safe=True)
db = connection.social_security_data
baby_names = db.baby_names
for year in fixed_data:
try:
baby_names.insert({"_id": year, "info": fixed_data[year]})
except:
print "Unexpected error:", sys.exc_info()[0]
if __name__ == '__main__':
data = get_data()
fixed_data = fix_data(data)
sendto_mongo(fixed_data)
| mit | 4,289,941,324,790,862,000 | 28.722222 | 110 | 0.561371 | false | 3.451613 | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.