code
stringlengths
3
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.05M
#---------------------------------------------------------------------------- # Use Python's bool constants if available, make some if not try: True except NameError: __builtins__.True = 1==1 __builtins__.False = 1==0 def bool(value): return not not value __builtins__.bool = bool # workarounds for bad wxRTTI names __wxPyPtrTypeMap['wxGauge95'] = 'wxGauge' __wxPyPtrTypeMap['wxSlider95'] = 'wxSlider' __wxPyPtrTypeMap['wxStatusBar95'] = 'wxStatusBar' #---------------------------------------------------------------------------- # Load version numbers from __version__... Ensure that major and minor # versions are the same for both wxPython and wxWidgets. from __version__ import * __version__ = VERSION_STRING assert MAJOR_VERSION == _core_.MAJOR_VERSION, "wxPython/wxWidgets version mismatch" assert MINOR_VERSION == _core_.MINOR_VERSION, "wxPython/wxWidgets version mismatch" if RELEASE_VERSION != _core_.RELEASE_VERSION: import warnings warnings.warn("wxPython/wxWidgets release number mismatch") def version(): """Returns a string containing version and port info""" ctype = wx.USE_UNICODE and 'unicode' or 'ansi' if wx.Platform == '__WXMSW__': port = 'msw' elif wx.Platform == '__WXMAC__': port = 'mac' elif wx.Platform == '__WXGTK__': port = 'gtk' if 'gtk2' in wx.PlatformInfo: port = 'gtk2' else: port = '?' return "%s (%s-%s)" % (wx.VERSION_STRING, port, ctype) #---------------------------------------------------------------------------- # Set wxPython's default string<-->unicode conversion encoding from # the locale, but only if Python's default hasn't been changed. (We # assume that if the user has customized it already then that is the # encoding we need to use as well.) # # The encoding selected here is used when string or unicode objects # need to be converted in order to pass them to wxWidgets. Please be # aware that the default encoding within the same locale may be # slightly different on different platforms. For example, please see # http://www.alanwood.net/demos/charsetdiffs.html for differences # between the common latin/roman encodings. default = _sys.getdefaultencoding() if default == 'ascii': import locale import codecs try: if hasattr(locale, 'getpreferredencoding'): default = locale.getpreferredencoding() else: default = locale.getdefaultlocale()[1] codecs.lookup(default) except (ValueError, LookupError, TypeError): default = _sys.getdefaultencoding() del locale del codecs if default: wx.SetDefaultPyEncoding(default) del default #---------------------------------------------------------------------------- class PyDeadObjectError(AttributeError): pass class _wxPyDeadObject(object): """ Instances of wx objects that are OOR capable will have their __class__ changed to this class when the C++ object is deleted. This should help prevent crashes due to referencing a bogus C++ pointer. """ reprStr = "wxPython wrapper for DELETED %s object! (The C++ object no longer exists.)" attrStr = "The C++ part of the %s object has been deleted, attribute access no longer allowed." def __repr__(self): if not hasattr(self, "_name"): self._name = "[unknown]" return self.reprStr % self._name def __getattr__(self, *args): if not hasattr(self, "_name"): self._name = "[unknown]" raise PyDeadObjectError(self.attrStr % self._name) def __nonzero__(self): return 0 class PyUnbornObjectError(AttributeError): pass class _wxPyUnbornObject(object): """ Some stock objects are created when the wx._core module is imported, but their C++ instance is not created until the wx.App object is created and initialized. These object instances will temporarily have their __class__ changed to this class so an exception will be raised if they are used before the C++ instance is ready. """ reprStr = "wxPython wrapper for UNBORN object! (The C++ object is not initialized yet.)" attrStr = "The C++ part of this object has not been initialized, attribute access not allowed." def __repr__(self): return self.reprStr def __getattr__(self, *args): raise PyUnbornObjectError(self.attrStr) def __nonzero__(self): return 0 #---------------------------------------------------------------------------- def CallAfter(callable, *args, **kw): """ Call the specified function after the current and pending event handlers have been completed. This is also good for making GUI method calls from non-GUI threads. Any extra positional or keyword args are passed on to the callable when it is called. :see: `wx.CallLater` """ app = wx.GetApp() assert app is not None, 'No wx.App created yet' if not hasattr(app, "_CallAfterId"): app._CallAfterId = wx.NewEventType() app.Connect(-1, -1, app._CallAfterId, lambda event: event.callable(*event.args, **event.kw) ) evt = wx.PyEvent() evt.SetEventType(app._CallAfterId) evt.callable = callable evt.args = args evt.kw = kw wx.PostEvent(app, evt) #---------------------------------------------------------------------------- class CallLater: """ A convenience class for `wx.Timer`, that calls the given callable object once after the given amount of milliseconds, passing any positional or keyword args. The return value of the callable is availbale after it has been run with the `GetResult` method. If you don't need to get the return value or restart the timer then there is no need to hold a reference to this object. It will hold a reference to itself while the timer is running (the timer has a reference to self.Notify) but the cycle will be broken when the timer completes, automatically cleaning up the wx.CallLater object. :see: `wx.CallAfter` """ def __init__(self, millis, callable, *args, **kwargs): self.millis = millis self.callable = callable self.SetArgs(*args, **kwargs) self.runCount = 0 self.running = False self.hasRun = False self.result = None self.timer = None self.Start() def __del__(self): self.Stop() def Start(self, millis=None, *args, **kwargs): """ (Re)start the timer """ self.hasRun = False if millis is not None: self.millis = millis if args or kwargs: self.SetArgs(*args, **kwargs) self.Stop() self.timer = wx.PyTimer(self.Notify) self.timer.Start(self.millis, wx.TIMER_ONE_SHOT) self.running = True Restart = Start def Stop(self): """ Stop and destroy the timer. """ if self.timer is not None: self.timer.Stop() self.timer = None def GetInterval(self): if self.timer is not None: return self.timer.GetInterval() else: return 0 def IsRunning(self): return self.timer is not None and self.timer.IsRunning() def SetArgs(self, *args, **kwargs): """ (Re)set the args passed to the callable object. This is useful in conjunction with Restart if you want to schedule a new call to the same callable object but with different parameters. """ self.args = args self.kwargs = kwargs def HasRun(self): return self.hasRun def GetResult(self): return self.result def Notify(self): """ The timer has expired so call the callable. """ if self.callable and getattr(self.callable, 'im_self', True): self.runCount += 1 self.running = False self.result = self.callable(*self.args, **self.kwargs) self.hasRun = True if not self.running: # if it wasn't restarted, then cleanup wx.CallAfter(self.Stop) Interval = property(GetInterval) Result = property(GetResult) class FutureCall(CallLater): """A compatibility alias for `CallLater`.""" #---------------------------------------------------------------------------- # Control which items in this module should be documented by epydoc. # We allow only classes and functions, which will help reduce the size # of the docs by filtering out the zillions of constants, EVT objects, # and etc that don't make much sense by themselves, but are instead # documented (or will be) as part of the classes/functions/methods # where they should be used. class __DocFilter: """ A filter for epydoc that only allows non-Ptr classes and functions, in order to reduce the clutter in the API docs. """ def __init__(self, globals): self._globals = globals def __call__(self, name): import types obj = self._globals.get(name, None) # only document classes and function if type(obj) not in [type, types.ClassType, types.FunctionType, types.BuiltinFunctionType]: return False # skip other things that are private or will be documented as part of somethign else if name.startswith('_') or name.startswith('EVT') or name.endswith('_swigregister') or name.endswith('Ptr') : return False # skip functions that are duplicates of static functions in a class if name.find('_') != -1: cls = self._globals.get(name.split('_')[0], None) methname = name.split('_')[1] if hasattr(cls, methname) and type(getattr(cls, methname)) is types.FunctionType: return False return True #---------------------------------------------------------------------------- #---------------------------------------------------------------------------- # Import other modules in this package that should show up in the # "core" wx namespace from _gdi import * from _windows import * from _controls import * from _misc import * #---------------------------------------------------------------------------- #----------------------------------------------------------------------------
sschiesser/ASK_server
MacOSX10.6/usr/include/wx-2.8/wx/wxPython/i_files/_core_ex.py
Python
gpl-2.0
10,418
from django import forms from django.utils.safestring import mark_safe from django.utils.safestring import SafeUnicode from santaclara_base.models import Tag,Icon class SantaClaraWidget(forms.Textarea): class Media: js = ('js/jquery.js', 'localjs/santa-clara-widget.js') def render(self, name, value, attrs=None): html = super(SantaClaraWidget, self).render(name, value, attrs=attrs) S=u'<div class="editor"><div class="toolbar">' for (tag,i) in [ ("left","align-left"), ("center","align-center"), ("right","align-right"), ("justify","align-justify"), ("b","bold"), ("i","italic"), ("s","strikethrough"), ("u","underline") ]: S+=u'<a href="" name="'+tag+'"><i class="editor-button icon-'+i+'"></i></a>' S+=u'<a href="" name="code"><span class="editor-button"><b><tt>TT</tt></b></span></a>' S+=u'<a href="" name="term"><i class="editor-button icon-desktop"></i></a>' S+=u"</div>" return mark_safe(S+html+"</div>") class TagWidget(forms.TextInput): class Media: js = ('js/jquery.js', 'santaclara_base/tag-widget.js') def render(self, name, value, attrs=None): def render_tag(tag): T=unicode(tag) T='<a class="taglabel" data-widget-name='+name+'>'+T+'</a>' return T html = super(TagWidget, self).render(name, value, attrs=attrs) S="" S+=u'<a class="taglistopen" data-widget-name="'+name+'"><i class="icon-chevron-sign-left"></i><span class="tooltip">view tag list</span></a>' S+=u'<div class="taglist" id="taglist_'+name+'">' S+=u"<br/>".join(map(render_tag,Tag.objects.all())) S+=u'</div>' S+=u'<a class="taglistclose" data-widget-name="'+name+'"><i class="icon-chevron-sign-up"></i><span class="tooltip">close tag list</span></a>' S='<div class="taginput">'+S+html+'</div>' return mark_safe(S) #class IconSelect(forms.Select): class IconSelect(forms.HiddenInput): class Media: css = { 'all': ( 'santaclara_base/iconselect.css', ) } js = ('js/jquery.js', 'santaclara_base/iconselect.js') def render(self, name, value, attrs=None): field_id=attrs["id"] if value == None: selected=u'none selected' else: k=int(value) icon=Icon.objects.get(id=k) selected=SafeUnicode(icon.html) k_selected=unicode(value) optionsarea=u'<ul id="'+field_id+'_optionsarea" class="santaclaraiconselectul"' optionsarea+=u' data-filled="no"' optionsarea+=u' data-target_view="'+field_id+'_view"' optionsarea+=u' data-target_input="'+field_id+'">\n' optionsarea+="</ul>" hidden=u'<input id="'+field_id+'" name="'+name+'" type="hidden" value="'+k_selected+'" />' U=u'<a href="" id="'+field_id+'_view" class="santaclaraiconselectview"' U+=u' data-input_id="'+field_id+'" data-optionsarea_id="'+field_id+'_optionsarea">' U+=selected+' <i class="fa fa-caret-down"></i></a>' U+="\n&nbsp;" U+=optionsarea U+=hidden return U
chiara-paci/santaclara-base
santaclara_base/widgets.py
Python
gpl-3.0
3,276
VERSION = (0, 0, 3, 'alpha') if VERSION[-1] != "final": # pragma: no cover __version__ = '.'.join(map(str, VERSION)) else: # pragma: no cover __version__ = '.'.join(map(str, VERSION[:-1])) __author__ = u'Anton Yevzhakov' __maintainer__ = u'Anton Yevzhakov' __email__ = 'anber@anber.ru' from api import * from django.contrib.messages.constants import *
Anber/django-extended-messages
extended_messages/__init__.py
Python
bsd-3-clause
362
#!/usr/bin/env python #Copyright 2008 Sebastian Hagen # This file is part of gonium. # # gonium 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. # # gonium 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 collections import logging import os from ._io import IORequest, IOManager, IO_CMD_PREAD, IO_CMD_PWRITE from ..service_aggregation import ServiceAggregate _logger = logging.getLogger() _log = _logger.log class LinuxAIORequest(IORequest): """Linux AIO Request.""" def __new__(cls, *args, callback): return IORequest.__new__(cls, *args) def __init__(self, mode, buf, *args, callback): IORequest.__init__(self) self.buf = buf self.callback = callback class LinuxAIOManager(IOManager): """Linux AIOManager with eventing support""" REQ_CLS = LinuxAIORequest MODE_READ = IO_CMD_PREAD MODE_WRITE = IO_CMD_PWRITE def __new__(cls, sa:ServiceAggregate, size=12800): return IOManager.__new__(cls, size) def __init__(self, sa, *args, **kwargs): self._fdwrap = sa.ed.fd_wrap(self.fd) self._fdwrap.process_readability = self._process_readability self._fdwrap.read_r() def _process_readability(self): req_s = self.getevents(0,0) try: os.read(self.fd, 1024) except OSError: pass for req in req_s: try: req.callback(req) except Exception: if (req.callback is None): continue _log(40, 'Exception in AIO handler {0} on Request {1}:'.format(req.callback, req), exc_info=True) def io(self, req_s:collections.Sequence): """Request IO action req_s: Sequence of LinuxAIORequest objects """ self.submit(req_s) def _selftest(): from ..posix.aio import _test_aiom _test_aiom(LinuxAIOManager) if (__name__ == '__main__'): _selftest()
sh01/gonium
src/linux/io.py
Python
gpl-2.0
2,385
"""RT-DC dataset core classes and methods""" import warnings import numpy as np from dclab import definitions as dfn from .. import downsampling from ..polygon_filter import PolygonFilter class NanWarning(UserWarning): pass class Filter(object): def __init__(self, rtdc_ds): """Boolean filter arrays for RT-DC measurements Parameters ---------- rtdc_ds: instance of RTDCBase The RT-DC dataset the filter applies to """ # dictionary of boolean array for box filters self._box_filters = {} # dictionary of (hash, boolean array) for polygon filters self._poly_filters = {} # initialize important parameters self._init_rtdc_ds(rtdc_ds) # initialize properties self.reset() def __getitem__(self, key): """Return the filter for a feature in `self.features`""" if key in self.features and dfn.scalar_feature_exists(key): if key not in self._box_filters: # Generate filters on-the-fly self._box_filters[key] = np.ones(self.size, dtype=bool) else: raise KeyError("Feature not available: '{}'".format(key)) return self._box_filters[key] def _init_rtdc_ds(self, rtdc_ds): #: Available feature names self.features = rtdc_ds.features_scalar if hasattr(self, "size") and self.size != len(rtdc_ds): raise ValueError("Change of RTDCBase size not supported!") self.size = len(rtdc_ds) # determine box filters that have been removed for key in list(self._box_filters.keys()): if key not in self.features: self._box_filters.pop(key) # determine polygon filters that have been removed for pf_id in list(self._poly_filters.keys()): pf = PolygonFilter.get_instance_from_id(pf_id) if (pf_id in rtdc_ds.config["filtering"]["polygon filters"] and pf.axes[0] in self.features and pf.axes[1] in self.features): pass else: # filter has been removed self._poly_filters.pop(pf_id) def reset(self): """Reset all filters""" self._box_filters = {} self._poly_filters = {} #: All filters combined (see :func:`Filter.update`); #: Use this property to filter the features of #: :class:`dclab.rtdc_dataset.RTDCBase` instances self.all = np.ones(self.size, dtype=bool) #: All box filters self.box = np.ones(self.size, dtype=bool) #: Invalid (nan/inf) events self.invalid = np.ones(self.size, dtype=bool) #: 1D boolean array for manually excluding events; `False` values #: are excluded. self.manual = np.ones(self.size, dtype=bool) #: Polygon filters self.polygon = np.ones(self.size, dtype=bool) # old filter configuration of `rtdc_ds` self._old_config = {} def update(self, rtdc_ds, force=[]): """Update the filters according to `rtdc_ds.config["filtering"]` Parameters ---------- rtdc_ds: dclab.rtdc_dataset.core.RTDCBase The measurement to which the filter is applied force : list A list of feature names that must be refiltered with min/max values. Notes ----- This function is called when :func:`ds.apply_filter <dclab.rtdc_dataset.RTDCBase.apply_filter>` is called. """ # re-initialize important parameters self._init_rtdc_ds(rtdc_ds) # These lists may help us become very fast in the future newkeys = [] oldvals = [] newvals = [] cfg_cur = rtdc_ds.config["filtering"] cfg_old = self._old_config # Determine which data was updated for skey in list(cfg_cur.keys()): if cfg_cur[skey] != cfg_old.get(skey, None): newkeys.append(skey) oldvals.append(cfg_old.get(skey, None)) newvals.append(cfg_cur[skey]) # 1. Invalid filters self.invalid[:] = True if cfg_cur["remove invalid events"]: for feat in self.features: data = rtdc_ds[feat] invalid = np.isinf(data) | np.isnan(data) self.invalid &= ~invalid # 2. Filter all feature min/max values. feat2filter = [] for k in newkeys: # k[:-4] because we want to crop " min" and " max" if (dfn.scalar_feature_exists(k[:-4]) and (k.endswith(" min") or k.endswith(" max"))): feat2filter.append(k[:-4]) for f in force: # add forced features if dfn.scalar_feature_exists(f): feat2filter.append(f) else: # Make sure the feature name is valid. raise ValueError("Unknown scalar feature name '{}'!".format(f)) feat2filter = np.unique(feat2filter) for feat in feat2filter: fstart = feat + " min" fend = feat + " max" must_be_filtered = (fstart in cfg_cur and fend in cfg_cur and cfg_cur[fstart] != cfg_cur[fend]) if ((fstart in cfg_cur and fend not in cfg_cur) or (fstart not in cfg_cur and fend in cfg_cur)): # User is responsible for setting min and max values! raise ValueError("Box filter: Please make sure that both " "'{}' and '{}' are set!".format(fstart, fend)) if feat in self.features: # Get the current feature filter feat_filt = self[feat] feat_filt[:] = True # If min and max exist and if they are not identical: if must_be_filtered: ivalstart = cfg_cur[fstart] ivalend = cfg_cur[fend] if ivalstart > ivalend: msg = "inverting filter: {} > {}".format(fstart, fend) warnings.warn(msg) ivalstart, ivalend = ivalend, ivalstart data = rtdc_ds[feat] # treat nan-values in a special way disnan = np.isnan(data) if np.sum(disnan): # this avoids RuntimeWarnings (invalid value # encountered due to nan-values) feat_filt[disnan] = False idx = ~disnan if not cfg_cur["remove invalid events"]: msg = "Feature '{}' contains ".format(feat) \ + "nan-values! Box filters remove those." warnings.warn(msg, NanWarning) else: idx = slice(0, len(self.all)) # place-holder for [:] feat_filt[idx] &= ivalstart <= data[idx] feat_filt[idx] &= data[idx] <= ivalend elif must_be_filtered: warnings.warn("Dataset '{}' does ".format(rtdc_ds.identifier) + "not contain the feature '{}'! ".format(feat) + "A box filter has been ignored.") # store box filters self.box[:] = True for feat in self._box_filters: self.box &= self._box_filters[feat] # 3. Filter with polygon filters # check if something has changed # perform polygon filtering for pf_id in cfg_cur["polygon filters"]: pf = PolygonFilter.get_instance_from_id(pf_id) if (pf_id not in self._poly_filters or pf.hash != self._poly_filters[pf_id][0]): datax = rtdc_ds[pf.axes[0]] datay = rtdc_ds[pf.axes[1]] self._poly_filters[pf_id] = (pf.hash, pf.filter(datax, datay)) # store polygon filters self.polygon[:] = True for pf_id in self._poly_filters: self.polygon &= self._poly_filters[pf_id][1] # 4. Finally combine all filters and apply "limit events" # get a list of all filters if cfg_cur["enable filters"]: self.all[:] = self.invalid & self.manual & self.polygon & self.box # Filter with configuration keyword argument "limit events". # This additional step limits the total number of events in # self.all. if cfg_cur["limit events"] > 0: limit = cfg_cur["limit events"] sub = self.all[self.all] _f, idx = downsampling.downsample_rand(sub, samples=limit, ret_idx=True) sub[~idx] = False self.all[self.all] = sub else: self.all[:] = True # Actual filtering is then done during plotting self._old_config = rtdc_ds.config.copy()["filtering"]
ZellMechanik-Dresden/dclab
dclab/rtdc_dataset/filter.py
Python
gpl-2.0
9,234
from django import forms from bootcamp.results.models import Result class ResultForm(forms.ModelForm): status = forms.CharField(widget=forms.HiddenInput()) name = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255) variable = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255) description = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255) MULTIPLECHOICES=[('EMC','EMC'), ('MTN','MTN'),('Both','Both')] network = forms.ChoiceField(choices=MULTIPLECHOICES, widget=forms.RadioSelect(), help_text='Mention the network in which task is expected to run') tags = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control'}), max_length=255, required=False, help_text='Use spaces to separate the tags, such as "interfaces emc automation"') class Meta: model = Result fields = ['name', 'description', 'tags', 'status', 'network', 'variable']
davismathew/netbot-django
bootcamp/results/forms.py
Python
mit
1,137
# Prints a statement print "I will now count my chickens:" # Prints the number of hens print "Hens", 25.0 + 30.0 / 6.0 # Prints the number of roosters print "Roosters", 100.0 - 25.0 * 3.0 % 4.0 # Prints a question print "Is it true that 3 + 2 < 5 - 7?" # Prints the answer to the question above print 3 + 2 < 5 - 7 # Prints the result of the addition b/w 3 and 2 print "What is 3 + 2?", 3 + 2 # Prints the result to the question print "What is 5 - 7?", 5 - 7 # Prints a statement print "Oh, that's why it's False." # Prints a statement print "How about some more." # Prints a question and the answer print "Is it greater?", 5 > -2 # Prints a question and the answer print "Is it greater or equal?", 5 >= -2 # Prints a question and the answer print "Is it less or equal?", 5 <= -2
udoyen/pythonlearning
1-35/ex3.py
Python
mit
788
from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.conf import settings from django.views.generic import TemplateView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^', include('mydashboard.urls', namespace='mydashboard')), url(r'^admin/', include(admin.site.urls)), ) # Uncomment the next line to serve media files in dev. # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: import debug_toolbar urlpatterns += patterns('', url(r'^__debug__/', include(debug_toolbar.urls)), url(r'^', include('mydashboard.urls', namespace='mydashboard')), )
anduslim/codex
codex_project/codex_project/urls.py
Python
mit
840
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations def update_site_forward(apps, schema_editor): """Set site domain and name.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "gvl.org.au", "name": "gvldash" } ) def update_site_backward(apps, schema_editor): """Revert site domain and name to default.""" Site = apps.get_model("sites", "Site") Site.objects.update_or_create( id=settings.SITE_ID, defaults={ "domain": "example.com", "name": "example.com" } ) class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), ] operations = [ migrations.RunPython(update_site_forward, update_site_backward), ]
gvlproject/gvldash
gvldash/contrib/sites/migrations/0002_set_site_domain_and_name.py
Python
bsd-3-clause
945
def get_sponsor(self, key): with dbapi2.connect(self.dsn) as connection: cursor = connection.cursor() query = "SELECT SPONSORID, SWIMMERNAME, BIRTHYEAR FROM SPONSORS WHERE (LISTNO = %s)" cursor.execute(query, (key,)) Sponsorid,Swimmername,Birthyear = cursor.fetchone() return Sponsor(Sponsorid,Swimmername,Birthyear) def get_sponsors(self): with dbapi2.connect(self.dsn) as connection: cursor = connection.cursor() query = "SELECT LISTNO, SPONSORID, SWIMMERNAME, BIRTHYEAR FROM SPONSORS ORDER BY LISTNO" cursor.execute(query) Sponsors = [(key, Sponsor(Sponsorid,Swimmername,Birthyear)) for key, Sponsorid,Swimmername,Birthyear in cursor] return Sponsors def add_sponsor(self, Olymp): with dbapi2.connect(self.dsn) as connection: cursor = connection.cursor() query = "INSERT INTO SPONSORS (SPONSORID, SWIMMERNAME, BIRTHYEAR ) VALUES ( %s, %s, %s)" cursor.execute(query, (Olymp.Fullname, Olymp.SwimmerId,Olymp.Year, Olymp.Poolid)) connection.commit() self.last_key = cursor.lastrowid def delete_sponsor(self, key): with dbapi2.connect(self.dsn) as connection: cursor = connection.cursor() query = "DELETE FROM SPONSORS WHERE (LISTNO = %s)" cursor.execute(query, (key,)) connection.commit() def update_sponsor(self, key,Sponsorid,Swimmername,Birthyear): with dbapi2.connect(self.dsn) as connection: cursor = connection.cursor() query = "UPDATE SPONSORS SET SPONSORID = %s, SWIMMERNAME = %s, BIRTHYEAR = %s WHERE (LISTNO = %s)" cursor.execute(query, (Sponsorid,Swimmername,Birthyear, key)) connection.commit() def sponsors_search(self, word): with dbapi2.connect(self.dsn) as connection: cursor = connection.cursor() query = "SELECT SPONSORID, SWIMMERNAME, BIRTHYEAR FROM SPONSORS WHERE (FULLNAME LIKE %s)" cursor.execute(query,(word,)) Sponsors = [(key, Sponsor(Sponsorid,Swimmername,Birthyear)) for key,Sponsorid,Swimmername,Birthyear in cursor] return Sponsors
itucsdb1506/itucsdb1506
Pools.py
Python
gpl-3.0
2,390
# test sys.getsizeof() function import sys try: sys.getsizeof except AttributeError: print("SKIP") raise SystemExit print(sys.getsizeof(1.0) >= 2)
pfalcon/micropython
tests/float/sys_getsizeof_float.py
Python
mit
162
# # # This source file is part of ELINA (ETH LIbrary for Numerical Analysis). # ELINA is Copyright © 2019 Department of Computer Science, ETH Zurich # This software is distributed under GNU Lesser General Public License Version 3.0. # For more information, see the ELINA project website at: # http://elina.ethz.ch # # THE SOFTWARE IS PROVIDED "AS-IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER # EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO ANY WARRANTY # THAT THE SOFTWARE WILL CONFORM TO SPECIFICATIONS OR BE ERROR-FREE AND ANY # IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, # TITLE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ETH ZURICH BE LIABLE FOR ANY # DAMAGES, INCLUDING BUT NOT LIMITED TO DIRECT, INDIRECT, # SPECIAL OR CONSEQUENTIAL DAMAGES, ARISING OUT OF, RESULTING FROM, OR IN # ANY WAY CONNECTED WITH THIS SOFTWARE (WHETHER OR NOT BASED UPON WARRANTY, # CONTRACT, TORT OR OTHERWISE). # # from elina_auxiliary_imports import * # ********************************************************************** # # I. Datatypes # ********************************************************************** # class ElinaScalarDiscr(CtypesEnum): """ Enum compatible with discr field in elina_scalar_t from elina_scalar.h """ ELINA_SCALAR_DOUBLE = 0 ELINA_SCALAR_MPQ = 1 ELINA_SCALAR_MPFR = 2 class ElinaScalarUnion(Union): """ Ctype representing the union field in elina_scalar_t from elina_scalar.h """ _fields_ = [('dbl', c_double), ('mpq_ptr', POINTER(Mpq)), ('mpfr_ptr', POINTER(Mpfr))] class ElinaScalar(Structure): """ ElinaScalar ctype compatible with elina_scalar_t from elina_scalar.h """ _fields_ = [('discr', c_uint), ('val', ElinaScalarUnion)] ElinaScalarPtr = POINTER(ElinaScalar) elina_scalar_print_prec = c_int(20)
eth-srl/OptOctagon
python_interface/elina_scalar_h.py
Python
apache-2.0
1,831
"""Expression module """ # The core class from .ExpressionSet import ExpressionSet # I/O tools from ..io.ExpressionSetIO import RData2ExpressionSet from ..io.ExpressionSetIO import HDF52ExpressionSet from ..io.ExpressionSetIO import ExpressionSet2RData from ..io.ExpressionSetIO import ExpressionSet2HDF5
choyichen/omics
omics/expression/__init__.py
Python
mit
306
# Standard imports import unittest import json import logging from datetime import datetime, timedelta # Our imports from emission.clients.gamified import gamified from emission.core.get_database import get_db, get_mode_db, get_section_db from emission.core.wrapper.user import User from emission.core.wrapper.client import Client import emission.tests.common logging.basicConfig(level=logging.DEBUG) class TestGamified(unittest.TestCase): def setUp(self): import emission.tests.common from copy import copy self.testUsers = ["test@example.com", "best@example.com", "fest@example.com", "rest@example.com", "nest@example.com"] self.serverName = 'localhost' # Sometimes, we may have entries left behind in the database if one of the tests failed # or threw an exception, so let us start by cleaning up all entries emission.tests.common.dropAllCollections(get_db()) self.ModesColl = get_mode_db() self.assertEquals(self.ModesColl.find().count(), 0) self.setupUserAndClient() emission.tests.common.loadTable(self.serverName, "Stage_Modes", "emission/tests/data/modes.json") emission.tests.common.loadTable(self.serverName, "Stage_Sections", "emission/tests/data/testCarbonFile") self.SectionsColl = get_section_db() self.walkExpect = 1057.2524056424411 self.busExpect = 2162.668467546699 self.busCarbon = 267.0/1609 self.airCarbon = 217.0/1609 self.driveCarbon = 278.0/1609 self.busOptimalCarbon = 92.0/1609 self.allDriveExpect = (self.busExpect * self.driveCarbon + self.walkExpect * self.driveCarbon)/1000 self.myFootprintExpect = float(self.busExpect * self.busCarbon)/1000 self.sb375GoalExpect = 40.142892/7 self.mineMinusOptimalExpect = 0 self.allDriveMinusMineExpect = float(self.allDriveExpect - self.myFootprintExpect)/self.allDriveExpect self.sb375DailyGoalMinusMineExpect = float(self.sb375GoalExpect - self.myFootprintExpect)/self.sb375GoalExpect self.now = datetime.now() self.twodaysago = self.now - timedelta(days=2) self.weekago = self.now - timedelta(weeks = 1) for section in self.SectionsColl.find(): section['section_start_datetime'] = self.twodaysago section['section_end_datetime'] = self.twodaysago + timedelta(hours = 1) section['predicted_mode'] = {'walking': 1.0} if section['user_id'] == 'fest@example.com': logging.debug("Setting user_id for section %s, %s = %s" % (section['trip_id'], section['section_id'], self.user.uuid)) section['user_id'] = self.user.uuid if section['confirmed_mode'] == 5: airSection = copy(section) airSection['confirmed_mode'] = 9 airSection['_id'] = section['_id'] + "_air" self.SectionsColl.insert(airSection) airSection['confirmed_mode'] = '' airSection['_id'] = section['_id'] + "_unconf" self.SectionsColl.insert(airSection) # print("Section start = %s, section end = %s" % # (section['section_start_datetime'], section['section_end_datetime'])) self.SectionsColl.save(section) def setupUserAndClient(self): # At this point, the more important test is to execute the query and see # how well it works fakeEmail = "fest@example.com" client = Client("gamified") client.update(createKey = False) emission.tests.common.makeValid(client) (resultPre, resultReg) = client.preRegister("this_is_the_super_secret_id", fakeEmail) studyList = Client.getPendingClientRegs(fakeEmail) self.assertEqual(studyList, ["gamified"]) user = User.register("fest@example.com") self.assertEqual(user.getFirstStudy(), 'gamified') self.user = user def testGetScoreComponents(self): components = gamified.getScoreComponents(self.user.uuid, self.weekago, self.now) self.assertEqual(components[0], 0.75) # bus_short disappears in optimal, air_short disappears as long motorized, so optimal = 0 # self.assertEqual(components[1], (self.busExpect * self.busCarbon) / 1000) # TODO: Figure out what we should do when optimal == 0. Currently, we # return 0, which seems sub-optimal (pun intended) self.assertEqual(components[1], 0.0) # air_short disappears as long motorized, but we need to consider walking self.assertAlmostEqual(components[2], self.allDriveMinusMineExpect, places=4) # air_short disappears as long motorized, so only bus_short is left self.assertAlmostEqual(components[3], self.sb375DailyGoalMinusMineExpect, places = 4) # Checks both calcScore and updateScore, since we calculate the score before we update it def testUpdateScore(self): self.assertEqual(gamified.getStoredScore(self.user), (0, 0)) components = gamified.updateScore(self.user.uuid) print "self.allDriveMinusMineExpect = %s, self.sb375DailyGoalMinusMineExpect = %s" % \ (self.allDriveMinusMineExpect, self.sb375DailyGoalMinusMineExpect) expectedScore = 0.75 * 50 + 30 * self.allDriveMinusMineExpect + 20 * 0.0 + \ 10 * self.sb375DailyGoalMinusMineExpect storedScore = gamified.getStoredScore(self.user) self.assertEqual(storedScore[0], 0) self.assertAlmostEqual(storedScore[1], expectedScore, 6) def testGetLevel(self): self.assertEqual(gamified.getLevel(0), (1, 1)) self.assertEqual(gamified.getLevel(11.0), (1, 1)) self.assertEqual(gamified.getLevel(21.0), (1, 2)) self.assertEqual(gamified.getLevel(100), (2, 1)) self.assertEqual(gamified.getLevel(199.0), (2, 1)) self.assertEqual(gamified.getLevel(200), (2, 2)) self.assertEqual(gamified.getLevel(201.0), (2, 2)) self.assertEqual(gamified.getLevel(999), (2, 5)) self.assertEqual(gamified.getLevel(1000), (3, 1)) self.assertEqual(gamified.getLevel(9999.0), (3, 5)) self.assertEqual(gamified.getLevel(10000), (3, 5)) self.assertEqual(gamified.getLevel(100000), (3, 5)) def testGetFileName(self): self.assertEqual(gamified.getFileName(1, 1), "level_1_1.png") self.assertEqual(gamified.getFileName(1.0, 2.0), "level_1_2.png") self.assertEqual(gamified.getFileName(1.055, 2), "level_1_2.png") def testRunBackgroundTasksForDay(self): self.assertEqual(gamified.getStoredScore(self.user), (0, 0)) components = gamified.runBackgroundTasks(self.user.uuid) expectedScore = 0.75 * 50 + 30 * self.allDriveMinusMineExpect + 20 * 0.0 + \ 10 * self.sb375DailyGoalMinusMineExpect storedScore = gamified.getStoredScore(self.user) self.assertEqual(storedScore[0], 0) self.assertAlmostEqual(storedScore[1], expectedScore, 6) if __name__ == '__main__': unittest.main()
joshzarrabi/e-mission-server
emission/tests/client_tests/TestGamified.py
Python
bsd-3-clause
7,135
# vim: ai ts=4 sts=4 et sw=4 # -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function, unicode_literals from django.db import models from django.apps import apps from django.utils.translation import ugettext_lazy as _ from clubhouse.core.models import BlockContext, BlockBase from clubhouse.utils.enum import Enum, Option __all__ = ['ContentBlock','AsideBlock','SizeMixin','BlockLibrary'] class BlockLibrary(BlockContext): """ Abstract model to be used as an All block admin page, i.e. Block Library You can extend this and use as a BlockContext if you want all blocks in a certain place. """ class Meta: abstract = True verbose_name = _('Block Library') verbose_name_plural = _('Block Library') @classmethod def get_block_models(cls): for model in apps.get_models(): if issubclass(model, BlockBase): yield model @property def block_template(self): raise ImproperlyConfigured('Subclass of clubhouse_contrib.BlockLibrary requires a block_template property') class BlockSizes(Enum): SMALL = Option('s',description=_('Small')) MEDIUM = Option('m', description=_('Medium')) LARGE = Option('l', description=_('Large')) SPAN = Option('f', description=_('Span')) class SizeMixin(models.Model): size = models.CharField(max_length=1, default=BlockSizes.MEDIUM, null=True, blank=True, choices=BlockSizes.get_choices()) class Meta: abstract = True @property def col_class(self): if self.size == BlockSizes.SMALL: return 'col-md-3' elif self.size == BlockSizes.MEDIUM: return 'col-md-6' elif self.size == BlockSizes.LARGE: return 'col-md-9' elif self.size == BlockSizes.SPAN: return 'col-md-12' class ContentBlock(BlockContext, SizeMixin): class Meta: verbose_name = _('Content Block') verbose_name_plural = _('Content Blocks') @property def block_template(self): return 'content-blocks/%s.html' % self.block_object._meta.model_name @property def classes(self): return '%s %s' % (super(ContentBlock,self).classes, self.col_class) class AsideBlock(BlockContext): class Meta: verbose_name = _('Aside Block') verbose_name_plural = _('Aside Blocks') ordering = ('order',) @property def block_template(self): return 'aside-blocks/%s.html' % self.block_object._meta.model_name
chazmead/django-clubhouse
clubhouse/contrib/models/types.py
Python
bsd-2-clause
2,536
import torch import torch.nn as nn import torchvision.datasets as dsets import torchvision.transforms as transforms from torch.autograd import Variable # Hyper Parameters sequence_length = 28 input_size = 28 hidden_size = 128 num_layers = 2 num_classes = 10 batch_size = 100 num_epochs = 2 learning_rate = 0.003 # MNIST Dataset train_dataset = dsets.MNIST(root='./data/', train=True, transform=transforms.ToTensor(), download=True) test_dataset = dsets.MNIST(root='./data/', train=False, transform=transforms.ToTensor()) # Data Loader (Input Pipeline) train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False) # BiRNN Model (Many-to-One) class BiRNN(nn.Module): def __init__(self, input_size, hidden_size, num_layers, num_classes): super(BiRNN, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True, bidirectional=True) self.fc = nn.Linear(hidden_size*2, num_classes) # 2 for bidirection def forward(self, x): # Set initial states h0 = Variable(torch.zeros(self.num_layers*2, x.size(0), self.hidden_size)) # 2 for bidirection c0 = Variable(torch.zeros(self.num_layers*2, x.size(0), self.hidden_size)) # Forward propagate RNN out, _ = self.lstm(x, (h0, c0)) # Decode hidden state of last time step out = self.fc(out[:, -1, :]) return out rnn = BiRNN(input_size, hidden_size, num_layers, num_classes) # Loss and Optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(rnn.parameters(), lr=learning_rate) # Train the Model for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): images = Variable(images.view(-1, sequence_length, input_size)) labels = Variable(labels) # Forward + Backward + Optimize optimizer.zero_grad() outputs = rnn(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() if (i+1) % 100 == 0: print ('Epoch [%d/%d], Step [%d/%d], Loss: %.4f' %(epoch+1, num_epochs, i+1, len(train_dataset)//batch_size, loss.data[0])) # Test the Model correct = 0 total = 0 for images, labels in test_loader: images = Variable(images.view(-1, sequence_length, input_size)) outputs = rnn(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum() print('Test Accuracy of the model on the 10000 test images: %d %%' % (100 * correct / total)) # Save the Model torch.save(rnn.state_dict(), 'rnn.pkl')
jastarex/DeepLearningCourseCodes
08_RNN_and_Seq2Seq/bidirection_rnn_pytorch.py
Python
apache-2.0
3,204
from .node import Node class Scope(Node): def __init__(self, file, position, access, comments, children): super(Scope, self).__init__(file, position, access, comments, children)
gfelbing/cppstyle
cppstyle/model/scope.py
Python
gpl-3.0
192
from django.conf import settings from django.core.management.base import BaseCommand from kombu import (Connection, Exchange) from treeherder.etl.pulse_consumer import ResultsetConsumer class Command(BaseCommand): """ Management command to read resultsets from a set of pulse exchanges This adds the resultsets to a celery queue called ``store_pulse_resultsets`` which does the actual storing of the resultsets in the database. """ help = "Read resultsets from a set of pulse exchanges and queue for ingestion" def handle(self, *args, **options): config = settings.PULSE_DATA_INGESTION_CONFIG assert config, "PULSE_DATA_INGESTION_CONFIG must be set" sources = settings.PULSE_RESULTSET_SOURCES assert sources, "PULSE_RESULTSET_SOURCES must be set" new_bindings = [] with Connection(config.geturl()) as connection: consumer = ResultsetConsumer(connection, "resultsets") for source in sources: # When creating this exchange object, it is important that it # be set to ``passive=True``. This will prevent any attempt by # Kombu to actually create the exchange. exchange = Exchange(source["exchange"], type="topic", passive=True) # ensure the exchange exists. Throw an error if it doesn't exchange(connection).declare() for routing_key in source["routing_keys"]: consumer.bind_to(exchange, routing_key) new_binding_str = consumer.get_binding_str( exchange.name, routing_key) new_bindings.append(new_binding_str) self.stdout.write( "Pulse queue {} bound to: {}".format( consumer.queue_name, new_binding_str )) consumer.prune_bindings(new_bindings) try: consumer.run() except KeyboardInterrupt: self.stdout.write("Pulse Resultset listening stopped...")
akhileshpillai/treeherder
treeherder/etl/management/commands/read_pulse_resultsets.py
Python
mpl-2.0
2,229
# -*- coding: utf-8 -*- # # This file is part of EventGhost. # Copyright © 2005-2020 EventGhost Project <http://www.eventghost.net/> # # EventGhost 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. # # EventGhost 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 EventGhost. If not, see <http://www.gnu.org/licenses/>. import base64 import pickle import wx # Local imports import eg from ActionItem import ActionItem from TreeItem import TreeItem class PluginItem(ActionItem): xmlTag = "Plugin" icon = eg.Icons.PLUGIN_ICON isRenameable = False info = None @eg.AssertInActionThread def __init__(self, parent, node): TreeItem.__init__(self, parent, node) if node.text: try: args = pickle.loads(base64.b64decode(node.text)) except AttributeError: args = () else: args = () evalName = node.attrib.get('identifier', None) self.pluginName = node.attrib.get('file', None) guid = node.attrib.get('guid', self.pluginName) self.info = info = eg.pluginManager.OpenPlugin( guid, evalName, args, self, ) self.name = eg.text.General.pluginLabel % info.label if info.icon != self.icon: self.icon = eg.Icons.PluginSubIcon(info.icon) #self.icon = info.icon self.url = info.url self.executable = info.instance def AskCut(self): return self.AskDelete() def AskDelete(self): actionItemCls = self.document.ActionItem def SearchFunc(obj): if obj.__class__ == actionItemCls: if obj.executable and obj.executable.plugin == self.executable: return True return None if self.root.Traverse(SearchFunc) is not None: eg.MessageBox( eg.text.General.deletePlugin, eg.APP_NAME, wx.NO_DEFAULT | wx.OK | wx.ICON_EXCLAMATION ) return False if not TreeItem.AskDelete(self): return False return True @eg.AssertInActionThread def Delete(self): info = self.info def DoIt(): info.Close() info.instance.OnDelete() info.RemovePluginInstance() eg.actionThread.Call(DoIt) ActionItem.Delete(self) self.executable = None self.info = None @eg.AssertInActionThread def Execute(self): if not self.isEnabled: return None, None if eg.config.logActions: self.Print(self.name) if self.shouldSelectOnExecute: wx.CallAfter(self.Select) eg.indent += 1 self.info.Start() eg.indent -= 1 eg.result = self.executable return None, None # The Find function calls this from MainThread, so we can't restrict this # to the ActionThread #@eg.AssertInActionThread def GetArguments(self): return self.info.args def GetBasePath(self): """ Returns the filesystem path, where additional files (like pictures) should be found. Overrides ActionItem.GetBasePath() """ return self.info.path def GetData(self): attr, text = TreeItem.GetData(self) del attr[0] attr.append(('Identifier', self.executable.info.evalName)) guid = self.executable.info.guid if guid: attr.append(('Guid', guid)) attr.append(('File', self.pluginName)) text = base64.b64encode(pickle.dumps(self.info.args, 2)) return attr, text def GetLabel(self): return self.name def GetTypeName(self): return self.executable.info.name def NeedsStartupConfiguration(self): """ Returns True if the item wants to be configured after creation. Overrides ActionItem.NeedsStartupConfiguration() """ # if the Configure method of the executable is overriden, we assume # the item wants to be configured after creation return ( self.executable.Configure.im_func != eg.PluginBase.Configure.im_func ) def RefreshAllVisibleActions(self): """ Calls Refresh() for all currently visible actions of this plugin. """ actionItemCls = self.document.ActionItem plugin = self.info.instance def Traverse(item): if item.__class__ == actionItemCls: if item.executable.plugin == plugin: pass #eg.Notify("NodeChanged", item) else: if item.childs and item in item.document.expandedNodes: for child in item.childs: Traverse(child) Traverse(self.root) @eg.LogIt def RestoreState(self): if self.isEnabled: eg.actionThread.Call(self.info.Start) @eg.LogIt @eg.AssertInActionThread def SetArguments(self, args): info = self.info if not info.lastException and args == self.info.args: return self.info.args = args label = info.instance.GetLabel(*args) if label != info.label: info.label = label self.name = eg.text.General.pluginLabel % label #eg.Notify("NodeChanged", self) self.RefreshAllVisibleActions() if self.isEnabled: eg.actionThread.Call(self.info.Stop) eg.actionThread.Call(self.info.Start) def SetAttributes(self, tree, itemId): if ( self.info is None or self.info.lastException or self.info.initFailed ): tree.SetItemTextColour(itemId, eg.colour.pluginError) @eg.AssertInActionThread def SetEnable(self, flag=True): ActionItem.SetEnable(self, flag) if flag: self.info.Start() else: self.info.Stop()
tfroehlich82/EventGhost
eg/Classes/PluginItem.py
Python
gpl-2.0
6,460
# Copyright (C) 2014-2016 New York University # This file is part of ReproZip which is released under the Revised BSD License # See file LICENSE for full license details. """VisTrails package for reprounzip. This package is the component loaded by VisTrails that provide the reprounzip modules. A separate component, reprounzip-vistrails, is a plugin for reprounzip that creates VisTrails pipelines that use this package. """ from __future__ import division from vistrails.core.configuration import ConfigurationObject identifier = 'io.github.vida-nyu.reprozip.reprounzip' name = 'reprounzip' version = '0.1' configuration = ConfigurationObject(reprounzip_python='python')
VisTrails/VisTrails
vistrails/packages/reprounzip/__init__.py
Python
bsd-3-clause
681
#/usr/bin/python # The following module(s) are required for listing the files in a directory. from os import listdir from os.path import isfile, join # The following module(s) are rquired for regular expressions. import re class ParseGTF: # Function that initializes the ParseGTF class. def __init__(self, pathToGTF): # Verbose information for the programmer. print("Initializing ParseGTF...\n") # Specified path to all annotated gene files. self.path = pathToGTF print("Specified path:\n{}\n".format(self.path)) # Empty paramater for the file stream, having a global access to the file. self.transcriptExpressionCSV = "" # Counts the amount of processed files. self.gtf_index_count = 0 # Saves the indexed content for each annotated gene file. #self.gtf_index = { file_name : [self.gtf.file.index[ element ], ... } self.gtf_index = {} # The indexed content for an annotated gene file. #self.gtf.file.index = { transcript_id : [ gene_id, raw_count ], ... } self.gtf_file_index = {} # A list with all the 'human readable' sample names. self.gtf_names = [] self.alternate = {} # Function that reads in GTF Files one by one, and closes the file stream afterward. def GTFReader(self): # Verbose information for the programmer. print("Reading GTF File...\n") # Store all files in the specified path. files = [f for f in listdir(self.path) if isfile(join(self.path, f))] #files = ['out.batch4_TCC-18-2_t10_150622_SN163_0652_AC7EUNACXX_L6_TGACCA.gtf', 'out.batch5_TCC-20-1_t10_160408_SN163_0708_BHMJTMBCXX_L2_TAGCTT_1.gtf'] # Filters file by Origin based on the file name information. gtf_files = self.filterByFileOrigin(files) # For file in filtered gtf_files. for file in gtf_files: # Add the file to self.gtf_file_index self.gtf_index[file] = self.gtf_file_index # Add the sub-dir to the file. file = "FluxCapacitor/"+file # Open file handle on variable gtf. gtf = open(file, "r") # Call GTFParser and start parsing the file. self.GTFParser(gtf) # Close the file handle, ending the stream for this partiuclar file in the loop. gtf.close() # Function that filters the files in the directory by file name. def filterByFileOrigin(self, files): # Verbose information for the programmer. print("Filtering by File Origin...") # Create an empty list to append all the 'correct' files. gtf_files = [] # Compose a pattern to filter by file name, since the sample is in the file name we can easily pick out the samples we won't need. pattern = re.compile(r'(out.(batch\d{1}_TCC-\d{2}-\d{1}_t\d+).*)') # For every file in the listed list of files. for file in files: # Match each file against the pattern. m = re.match(pattern, file) # If regex finds a match between the pattern and the file name, thus filtering the files on file name. if m: # Increase the gtf_index_count with 1, telling us later that we have a total of n files. self.gtf_index_count += 1 # Append the found files to the gtf_files list. gtf_files.append(m.group(1)) # Append the found files to the gtf_names list. self.gtf_names.append(m.group(2)) # return the filtered gtf files. return gtf_files # Function that parses the gtf file handle. def GTFParser(self, fileHandle): # Verbose information for the programmer. #print("Parsing GTF File...\n") # Read in the file handle. gtf_content = fileHandle.readlines() # For each line in the gtf file. for line in gtf_content: # If the line validates. if self.validateLineConsistency(line): # Split the line into bits, containing elements of lenght 9. bits = line.split("\t") # Split the 9th element (8) on the ";". bits = bits[8].split(";") # Save transcript id, gene id and reads. transcript_id = bits[0] gene_id = bits[2] reads = bits[3] # Store the transcript id as key in the gtf_file_index variable and assign gene_id and their reads as values. self.gtf_file_index[transcript_id] = [gene_id, reads] id = transcript_id + " " + gene_id if id not in self.alternate.keys(): self.alternate[id] = [reads] else: self.alternate[id].append(reads) def validateLineConsistency(self, line): # Set a flag for the boolean. validity = False # Splits each line, generating exactly 9 elements. line_elements = line.split("\t") # Change this according to the TODO below. if len(line_elements) != 9: print("something went wrong with:\n") print(line_elements) sys.exit(1) else: validity = True # Returns a True or False according to the validity check. return validity def assembleTranscriptExpressionMatrix(self): print("Assembling Transcript Expression Matrix...\n\n") # Opens a file handle for the new Transcript Expression Matrix. self.createTranscriptExpressionCSV() # Store all the keys for the files. gtf_keys = self.gtf_index.keys() # Create an empty list that will contain row's. rows = [] # For each key in the stored keys. for key in gtf_keys: # Save the values from the files' keys. This is another dictionary with the content of the file. content = self.gtf_index[key] #self.writeToTranscriptExpressionCSV(content) # Store the keys (Transcript id's) for each file. content_keys = content.keys() # For every key in the content of the file. for c_key in content_keys: # Save the value pair from the keys (Gene ID and read count). values = content[c_key] # Splitting the key results in the "ENSTXXXXX". c_k = c_key.split(" ") tr_id = c_k[1] # Splitting the first element of the values results in a gene id literal and the gene id. We save the third element, which is the gene_id. gene_id = values[0].split(" ") gene_id = gene_id[2] # Splitting the 2nd element of the values results in a reads literal and the read count. We save the third element, which is the read count. reads = values[1].split(" ") reads = reads[2] # Assemble row. row = tr_id + "\t" + gene_id + "\t" + reads + "\n" # Add row to rows. rows.append(row) #self.writeToTranscriptExpressionCSV(rows) self.writeToTranscriptExpressionCSV() def createTranscriptExpressionCSV(self): print("Creating Transcript Expression CSV...") # Creates a class wide filehandle with name gsTcell_TranscriptExpression.csv self.transcriptExpressionCSV = open("gsTcell_TranscriptExpression.csv","w") # Create a string with sample names. sample_row = "trId\tgeneId\t" for i in self.gtf_names: sample_row += i + "\t" sample_row = sample_row + "\n" # Write sample_row to transcript expression file. This happens only once! self.transcriptExpressionCSV.write(sample_row) def writeToTranscriptExpressionCSV(self): #print("Writing to Transcript Expression CSV...") # Store all the keys from the content of the gtf file. keys = self.alternate.keys() # Write row to file. #self.transcriptExpressionCSV.write() # For each key in the keys list. row = "" for key in keys: # Get the value pairs from the keys. #values = content[key] counts = self.alternate[key] #print(self.alternate) # Split the key, so that the transcript id string is separated from the transcript id. #k = key.split(" ") id = key.split(" ") id = id[1] + "\t" + id[4] row += id + "\t" # Split the gene id value, to separate the literal from the id. #gene_id = values[0].split(" ") #gene_id = gene_id[2] # Split the reads value, to separate the literal from the reads. #reads = values[1].split(" ") #reads = reads[2] reads = "" for i in counts: i = i.split(" ") i = i[2] reads += i + "\t" row += reads + "\n" #if self.gtf_index_count < 2: # Create row string. #row = k[1] + "\t" + gene_id + "\t" + count + "\t" # Write to the CSV file. self.transcriptExpressionCSV.write(row) def main(): p = ParseGTF("/groups/umcg-wijmenga/tmp04/umcg-eschutte/projects/gluten_specific_Tcells/output/FluxCapacitor/") p.GTFReader() p.assembleTranscriptExpressionMatrix() if "__main__" == __name__: main()
ErikSchutte/QTL-mapping
data_file_conversion/parse_flux_gtf_to_transcrip_matrix.py
Python
apache-2.0
8,209
from django.conf.urls import patterns, include, url urlpatterns = patterns('jumpserver.views', # Examples: url(r'^$', 'index', name='index'), # url(r'^api/user/$', 'api_user'), url(r'^skin_config/$', 'skin_config', name='skin_config'), url(r'^login/$', 'Login', name='login'), url(r'^logout/$', 'Logout', name='logout'), url(r'^exec_cmd/$', 'exec_cmd', name='exec_cmd'), url(r'^file/upload/$', 'upload', name='file_upload'), url(r'^file/download/$', 'download', name='file_download'), url(r'^setting', 'setting', name='setting'), url(r'^terminal/$', 'web_terminal', name='terminal'), url(r'^mylog/$', 'mylog', name='mylog'), url(r'^juser/', include('juser.urls')), url(r'^jasset/', include('jasset.urls')), url(r'^jlog/', include('jlog.urls')), url(r'^jperm/', include('jperm.urls')), url(r'^dbtool/', include('dbtool.urls')), url(r'^cachemanage/', include('cachemanage.urls')), )
xskh2007/zjump
jumpserver/urls.py
Python
gpl-2.0
955
#!/usr/bin/python import sys import random if len(sys.argv) < 2: print ('Usage:<filename> <k> [nfold = 5]') exit(0) random.seed( 10 ) k = int( sys.argv[2] ) if len(sys.argv) > 3: nfold = int( sys.argv[3] ) else: nfold = 5 fi = open( sys.argv[1], 'r' ) ftr = open( sys.argv[1]+'.train', 'w' ) fte = open( sys.argv[1]+'.test', 'w' ) for l in fi: if random.randint( 1 , nfold ) == k: fte.write( l ) else: ftr.write( l ) fi.close() ftr.close() fte.close()
RPGOne/Skynet
xgboost-master/demo/regression/mknfold.py
Python
bsd-3-clause
498
from __future__ import absolute_import, division, print_function, with_statement import contextlib import functools import sys import textwrap import time import platform import weakref from tornado.concurrent import return_future from tornado.escape import url_escape from tornado.httpclient import AsyncHTTPClient from tornado.ioloop import IOLoop from tornado.log import app_log from tornado import stack_context from tornado.testing import AsyncHTTPTestCase, AsyncTestCase, ExpectLog, gen_test from tornado.test.util import unittest, skipOnTravis from tornado.web import Application, RequestHandler, asynchronous, HTTPError from tornado import gen skipBefore33 = unittest.skipIf(sys.version_info < (3, 3), 'PEP 380 not available') skipNotCPython = unittest.skipIf(platform.python_implementation() != 'CPython', 'Not CPython implementation') class GenEngineTest(AsyncTestCase): def setUp(self): super(GenEngineTest, self).setUp() self.named_contexts = [] def named_context(self, name): @contextlib.contextmanager def context(): self.named_contexts.append(name) try: yield finally: self.assertEqual(self.named_contexts.pop(), name) return context def run_gen(self, f): f() return self.wait() def delay_callback(self, iterations, callback, arg): """Runs callback(arg) after a number of IOLoop iterations.""" if iterations == 0: callback(arg) else: self.io_loop.add_callback(functools.partial( self.delay_callback, iterations - 1, callback, arg)) @return_future def async_future(self, result, callback): self.io_loop.add_callback(callback, result) def test_no_yield(self): @gen.engine def f(): self.stop() self.run_gen(f) def test_inline_cb(self): @gen.engine def f(): (yield gen.Callback("k1"))() res = yield gen.Wait("k1") self.assertTrue(res is None) self.stop() self.run_gen(f) def test_ioloop_cb(self): @gen.engine def f(): self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.stop() self.run_gen(f) def test_exception_phase1(self): @gen.engine def f(): 1 / 0 self.assertRaises(ZeroDivisionError, self.run_gen, f) def test_exception_phase2(self): @gen.engine def f(): self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") 1 / 0 self.assertRaises(ZeroDivisionError, self.run_gen, f) def test_exception_in_task_phase1(self): def fail_task(callback): 1 / 0 @gen.engine def f(): try: yield gen.Task(fail_task) raise Exception("did not get expected exception") except ZeroDivisionError: self.stop() self.run_gen(f) def test_exception_in_task_phase2(self): # This is the case that requires the use of stack_context in gen.engine def fail_task(callback): self.io_loop.add_callback(lambda: 1 / 0) @gen.engine def f(): try: yield gen.Task(fail_task) raise Exception("did not get expected exception") except ZeroDivisionError: self.stop() self.run_gen(f) def test_with_arg(self): @gen.engine def f(): (yield gen.Callback("k1"))(42) res = yield gen.Wait("k1") self.assertEqual(42, res) self.stop() self.run_gen(f) def test_with_arg_tuple(self): @gen.engine def f(): (yield gen.Callback((1, 2)))((3, 4)) res = yield gen.Wait((1, 2)) self.assertEqual((3, 4), res) self.stop() self.run_gen(f) def test_key_reuse(self): @gen.engine def f(): yield gen.Callback("k1") yield gen.Callback("k1") self.stop() self.assertRaises(gen.KeyReuseError, self.run_gen, f) def test_key_reuse_tuple(self): @gen.engine def f(): yield gen.Callback((1, 2)) yield gen.Callback((1, 2)) self.stop() self.assertRaises(gen.KeyReuseError, self.run_gen, f) def test_key_mismatch(self): @gen.engine def f(): yield gen.Callback("k1") yield gen.Wait("k2") self.stop() self.assertRaises(gen.UnknownKeyError, self.run_gen, f) def test_key_mismatch_tuple(self): @gen.engine def f(): yield gen.Callback((1, 2)) yield gen.Wait((2, 3)) self.stop() self.assertRaises(gen.UnknownKeyError, self.run_gen, f) def test_leaked_callback(self): @gen.engine def f(): yield gen.Callback("k1") self.stop() self.assertRaises(gen.LeakedCallbackError, self.run_gen, f) def test_leaked_callback_tuple(self): @gen.engine def f(): yield gen.Callback((1, 2)) self.stop() self.assertRaises(gen.LeakedCallbackError, self.run_gen, f) def test_parallel_callback(self): @gen.engine def f(): for k in range(3): self.io_loop.add_callback((yield gen.Callback(k))) yield gen.Wait(1) self.io_loop.add_callback((yield gen.Callback(3))) yield gen.Wait(0) yield gen.Wait(3) yield gen.Wait(2) self.stop() self.run_gen(f) def test_bogus_yield(self): @gen.engine def f(): yield 42 self.assertRaises(gen.BadYieldError, self.run_gen, f) def test_bogus_yield_tuple(self): @gen.engine def f(): yield (1, 2) self.assertRaises(gen.BadYieldError, self.run_gen, f) def test_reuse(self): @gen.engine def f(): self.io_loop.add_callback((yield gen.Callback(0))) yield gen.Wait(0) self.stop() self.run_gen(f) self.run_gen(f) def test_task(self): @gen.engine def f(): yield gen.Task(self.io_loop.add_callback) self.stop() self.run_gen(f) def test_wait_all(self): @gen.engine def f(): (yield gen.Callback("k1"))("v1") (yield gen.Callback("k2"))("v2") results = yield gen.WaitAll(["k1", "k2"]) self.assertEqual(results, ["v1", "v2"]) self.stop() self.run_gen(f) def test_exception_in_yield(self): @gen.engine def f(): try: yield gen.Wait("k1") raise Exception("did not get expected exception") except gen.UnknownKeyError: pass self.stop() self.run_gen(f) def test_resume_after_exception_in_yield(self): @gen.engine def f(): try: yield gen.Wait("k1") raise Exception("did not get expected exception") except gen.UnknownKeyError: pass (yield gen.Callback("k2"))("v2") self.assertEqual((yield gen.Wait("k2")), "v2") self.stop() self.run_gen(f) def test_orphaned_callback(self): @gen.engine def f(): self.orphaned_callback = yield gen.Callback(1) try: self.run_gen(f) raise Exception("did not get expected exception") except gen.LeakedCallbackError: pass self.orphaned_callback() def test_multi(self): @gen.engine def f(): (yield gen.Callback("k1"))("v1") (yield gen.Callback("k2"))("v2") results = yield [gen.Wait("k1"), gen.Wait("k2")] self.assertEqual(results, ["v1", "v2"]) self.stop() self.run_gen(f) def test_multi_dict(self): @gen.engine def f(): (yield gen.Callback("k1"))("v1") (yield gen.Callback("k2"))("v2") results = yield dict(foo=gen.Wait("k1"), bar=gen.Wait("k2")) self.assertEqual(results, dict(foo="v1", bar="v2")) self.stop() self.run_gen(f) def test_multi_delayed(self): @gen.engine def f(): # callbacks run at different times responses = yield [ gen.Task(self.delay_callback, 3, arg="v1"), gen.Task(self.delay_callback, 1, arg="v2"), ] self.assertEqual(responses, ["v1", "v2"]) self.stop() self.run_gen(f) def test_multi_dict_delayed(self): @gen.engine def f(): # callbacks run at different times responses = yield dict( foo=gen.Task(self.delay_callback, 3, arg="v1"), bar=gen.Task(self.delay_callback, 1, arg="v2"), ) self.assertEqual(responses, dict(foo="v1", bar="v2")) self.stop() self.run_gen(f) @skipOnTravis @gen_test def test_multi_performance(self): # Yielding a list used to have quadratic performance; make # sure a large list stays reasonable. On my laptop a list of # 2000 used to take 1.8s, now it takes 0.12. start = time.time() yield [gen.Task(self.io_loop.add_callback) for i in range(2000)] end = time.time() self.assertLess(end - start, 1.0) @gen_test def test_multi_empty(self): # Empty lists or dicts should return the same type. x = yield [] self.assertTrue(isinstance(x, list)) y = yield {} self.assertTrue(isinstance(y, dict)) @gen_test def test_future(self): result = yield self.async_future(1) self.assertEqual(result, 1) @gen_test def test_multi_future(self): results = yield [self.async_future(1), self.async_future(2)] self.assertEqual(results, [1, 2]) @gen_test def test_multi_dict_future(self): results = yield dict(foo=self.async_future(1), bar=self.async_future(2)) self.assertEqual(results, dict(foo=1, bar=2)) def test_arguments(self): @gen.engine def f(): (yield gen.Callback("noargs"))() self.assertEqual((yield gen.Wait("noargs")), None) (yield gen.Callback("1arg"))(42) self.assertEqual((yield gen.Wait("1arg")), 42) (yield gen.Callback("kwargs"))(value=42) result = yield gen.Wait("kwargs") self.assertTrue(isinstance(result, gen.Arguments)) self.assertEqual(((), dict(value=42)), result) self.assertEqual(dict(value=42), result.kwargs) (yield gen.Callback("2args"))(42, 43) result = yield gen.Wait("2args") self.assertTrue(isinstance(result, gen.Arguments)) self.assertEqual(((42, 43), {}), result) self.assertEqual((42, 43), result.args) def task_func(callback): callback(None, error="foo") result = yield gen.Task(task_func) self.assertTrue(isinstance(result, gen.Arguments)) self.assertEqual(((None,), dict(error="foo")), result) self.stop() self.run_gen(f) def test_stack_context_leak(self): # regression test: repeated invocations of a gen-based # function should not result in accumulated stack_contexts def _stack_depth(): head = stack_context._state.contexts[1] length = 0 while head is not None: length += 1 head = head.old_contexts[1] return length @gen.engine def inner(callback): yield gen.Task(self.io_loop.add_callback) callback() @gen.engine def outer(): for i in range(10): yield gen.Task(inner) stack_increase = _stack_depth() - initial_stack_depth self.assertTrue(stack_increase <= 2) self.stop() initial_stack_depth = _stack_depth() self.run_gen(outer) def test_stack_context_leak_exception(self): # same as previous, but with a function that exits with an exception @gen.engine def inner(callback): yield gen.Task(self.io_loop.add_callback) 1 / 0 @gen.engine def outer(): for i in range(10): try: yield gen.Task(inner) except ZeroDivisionError: pass stack_increase = len(stack_context._state.contexts) - initial_stack_depth self.assertTrue(stack_increase <= 2) self.stop() initial_stack_depth = len(stack_context._state.contexts) self.run_gen(outer) def function_with_stack_context(self, callback): # Technically this function should stack_context.wrap its callback # upon entry. However, it is very common for this step to be # omitted. def step2(): self.assertEqual(self.named_contexts, ['a']) self.io_loop.add_callback(callback) with stack_context.StackContext(self.named_context('a')): self.io_loop.add_callback(step2) @gen_test def test_wait_transfer_stack_context(self): # Wait should not pick up contexts from where callback was invoked, # even if that function improperly fails to wrap its callback. cb = yield gen.Callback('k1') self.function_with_stack_context(cb) self.assertEqual(self.named_contexts, []) yield gen.Wait('k1') self.assertEqual(self.named_contexts, []) @gen_test def test_task_transfer_stack_context(self): yield gen.Task(self.function_with_stack_context) self.assertEqual(self.named_contexts, []) def test_raise_after_stop(self): # This pattern will be used in the following tests so make sure # the exception propagates as expected. @gen.engine def f(): self.stop() 1 / 0 with self.assertRaises(ZeroDivisionError): self.run_gen(f) def test_sync_raise_return(self): # gen.Return is allowed in @gen.engine, but it may not be used # to return a value. @gen.engine def f(): self.stop(42) raise gen.Return() result = self.run_gen(f) self.assertEqual(result, 42) def test_async_raise_return(self): @gen.engine def f(): yield gen.Task(self.io_loop.add_callback) self.stop(42) raise gen.Return() result = self.run_gen(f) self.assertEqual(result, 42) def test_sync_raise_return_value(self): @gen.engine def f(): raise gen.Return(42) with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) def test_sync_raise_return_value_tuple(self): @gen.engine def f(): raise gen.Return((1, 2)) with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) def test_async_raise_return_value(self): @gen.engine def f(): yield gen.Task(self.io_loop.add_callback) raise gen.Return(42) with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) def test_async_raise_return_value_tuple(self): @gen.engine def f(): yield gen.Task(self.io_loop.add_callback) raise gen.Return((1, 2)) with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) def test_return_value(self): # It is an error to apply @gen.engine to a function that returns # a value. @gen.engine def f(): return 42 with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) def test_return_value_tuple(self): # It is an error to apply @gen.engine to a function that returns # a value. @gen.engine def f(): return (1, 2) with self.assertRaises(gen.ReturnValueIgnoredError): self.run_gen(f) @skipNotCPython def test_task_refcounting(self): # On CPython, tasks and their arguments should be released immediately # without waiting for garbage collection. @gen.engine def f(): class Foo(object): pass arg = Foo() self.arg_ref = weakref.ref(arg) task = gen.Task(self.io_loop.add_callback, arg=arg) self.task_ref = weakref.ref(task) yield task self.stop() self.run_gen(f) self.assertIs(self.arg_ref(), None) self.assertIs(self.task_ref(), None) class GenCoroutineTest(AsyncTestCase): def setUp(self): # Stray StopIteration exceptions can lead to tests exiting prematurely, # so we need explicit checks here to make sure the tests run all # the way through. self.finished = False super(GenCoroutineTest, self).setUp() def tearDown(self): super(GenCoroutineTest, self).tearDown() assert self.finished @gen_test def test_sync_gen_return(self): @gen.coroutine def f(): raise gen.Return(42) result = yield f() self.assertEqual(result, 42) self.finished = True @gen_test def test_async_gen_return(self): @gen.coroutine def f(): yield gen.Task(self.io_loop.add_callback) raise gen.Return(42) result = yield f() self.assertEqual(result, 42) self.finished = True @gen_test def test_sync_return(self): @gen.coroutine def f(): return 42 result = yield f() self.assertEqual(result, 42) self.finished = True @skipBefore33 @gen_test def test_async_return(self): # It is a compile-time error to return a value in a generator # before Python 3.3, so we must test this with exec. # Flatten the real global and local namespace into our fake globals: # it's all global from the perspective of f(). global_namespace = dict(globals(), **locals()) local_namespace = {} exec(textwrap.dedent(""" @gen.coroutine def f(): yield gen.Task(self.io_loop.add_callback) return 42 """), global_namespace, local_namespace) result = yield local_namespace['f']() self.assertEqual(result, 42) self.finished = True @skipBefore33 @gen_test def test_async_early_return(self): # A yield statement exists but is not executed, which means # this function "returns" via an exception. This exception # doesn't happen before the exception handling is set up. global_namespace = dict(globals(), **locals()) local_namespace = {} exec(textwrap.dedent(""" @gen.coroutine def f(): if True: return 42 yield gen.Task(self.io_loop.add_callback) """), global_namespace, local_namespace) result = yield local_namespace['f']() self.assertEqual(result, 42) self.finished = True @gen_test def test_sync_return_no_value(self): @gen.coroutine def f(): return result = yield f() self.assertEqual(result, None) self.finished = True @gen_test def test_async_return_no_value(self): # Without a return value we don't need python 3.3. @gen.coroutine def f(): yield gen.Task(self.io_loop.add_callback) return result = yield f() self.assertEqual(result, None) self.finished = True @gen_test def test_sync_raise(self): @gen.coroutine def f(): 1 / 0 # The exception is raised when the future is yielded # (or equivalently when its result method is called), # not when the function itself is called). future = f() with self.assertRaises(ZeroDivisionError): yield future self.finished = True @gen_test def test_async_raise(self): @gen.coroutine def f(): yield gen.Task(self.io_loop.add_callback) 1 / 0 future = f() with self.assertRaises(ZeroDivisionError): yield future self.finished = True @gen_test def test_pass_callback(self): @gen.coroutine def f(): raise gen.Return(42) result = yield gen.Task(f) self.assertEqual(result, 42) self.finished = True @gen_test def test_replace_yieldpoint_exception(self): # Test exception handling: a coroutine can catch one exception # raised by a yield point and raise a different one. @gen.coroutine def f1(): 1 / 0 @gen.coroutine def f2(): try: yield f1() except ZeroDivisionError: raise KeyError() future = f2() with self.assertRaises(KeyError): yield future self.finished = True @gen_test def test_swallow_yieldpoint_exception(self): # Test exception handling: a coroutine can catch an exception # raised by a yield point and not raise a different one. @gen.coroutine def f1(): 1 / 0 @gen.coroutine def f2(): try: yield f1() except ZeroDivisionError: raise gen.Return(42) result = yield f2() self.assertEqual(result, 42) self.finished = True @gen_test def test_replace_context_exception(self): # Test exception handling: exceptions thrown into the stack context # can be caught and replaced. @gen.coroutine def f2(): self.io_loop.add_callback(lambda: 1 / 0) try: yield gen.Task(self.io_loop.add_timeout, self.io_loop.time() + 10) except ZeroDivisionError: raise KeyError() future = f2() with self.assertRaises(KeyError): yield future self.finished = True @gen_test def test_swallow_context_exception(self): # Test exception handling: exceptions thrown into the stack context # can be caught and ignored. @gen.coroutine def f2(): self.io_loop.add_callback(lambda: 1 / 0) try: yield gen.Task(self.io_loop.add_timeout, self.io_loop.time() + 10) except ZeroDivisionError: raise gen.Return(42) result = yield f2() self.assertEqual(result, 42) self.finished = True class GenSequenceHandler(RequestHandler): @asynchronous @gen.engine def get(self): self.io_loop = self.request.connection.stream.io_loop self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.write("1") self.io_loop.add_callback((yield gen.Callback("k2"))) yield gen.Wait("k2") self.write("2") # reuse an old key self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.finish("3") class GenCoroutineSequenceHandler(RequestHandler): @gen.coroutine def get(self): self.io_loop = self.request.connection.stream.io_loop self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.write("1") self.io_loop.add_callback((yield gen.Callback("k2"))) yield gen.Wait("k2") self.write("2") # reuse an old key self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.finish("3") class GenCoroutineUnfinishedSequenceHandler(RequestHandler): @asynchronous @gen.coroutine def get(self): self.io_loop = self.request.connection.stream.io_loop self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") self.write("1") self.io_loop.add_callback((yield gen.Callback("k2"))) yield gen.Wait("k2") self.write("2") # reuse an old key self.io_loop.add_callback((yield gen.Callback("k1"))) yield gen.Wait("k1") # just write, don't finish self.write("3") class GenTaskHandler(RequestHandler): @asynchronous @gen.engine def get(self): io_loop = self.request.connection.stream.io_loop client = AsyncHTTPClient(io_loop=io_loop) response = yield gen.Task(client.fetch, self.get_argument('url')) response.rethrow() self.finish(b"got response: " + response.body) class GenExceptionHandler(RequestHandler): @asynchronous @gen.engine def get(self): # This test depends on the order of the two decorators. io_loop = self.request.connection.stream.io_loop yield gen.Task(io_loop.add_callback) raise Exception("oops") class GenCoroutineExceptionHandler(RequestHandler): @gen.coroutine def get(self): # This test depends on the order of the two decorators. io_loop = self.request.connection.stream.io_loop yield gen.Task(io_loop.add_callback) raise Exception("oops") class GenYieldExceptionHandler(RequestHandler): @asynchronous @gen.engine def get(self): io_loop = self.request.connection.stream.io_loop # Test the interaction of the two stack_contexts. def fail_task(callback): io_loop.add_callback(lambda: 1 / 0) try: yield gen.Task(fail_task) raise Exception("did not get expected exception") except ZeroDivisionError: self.finish('ok') class UndecoratedCoroutinesHandler(RequestHandler): @gen.coroutine def prepare(self): self.chunks = [] yield gen.Task(IOLoop.current().add_callback) self.chunks.append('1') @gen.coroutine def get(self): self.chunks.append('2') yield gen.Task(IOLoop.current().add_callback) self.chunks.append('3') yield gen.Task(IOLoop.current().add_callback) self.write(''.join(self.chunks)) class AsyncPrepareErrorHandler(RequestHandler): @gen.coroutine def prepare(self): yield gen.Task(IOLoop.current().add_callback) raise HTTPError(403) def get(self): self.finish('ok') class GenWebTest(AsyncHTTPTestCase): def get_app(self): return Application([ ('/sequence', GenSequenceHandler), ('/coroutine_sequence', GenCoroutineSequenceHandler), ('/coroutine_unfinished_sequence', GenCoroutineUnfinishedSequenceHandler), ('/task', GenTaskHandler), ('/exception', GenExceptionHandler), ('/coroutine_exception', GenCoroutineExceptionHandler), ('/yield_exception', GenYieldExceptionHandler), ('/undecorated_coroutine', UndecoratedCoroutinesHandler), ('/async_prepare_error', AsyncPrepareErrorHandler), ]) def test_sequence_handler(self): response = self.fetch('/sequence') self.assertEqual(response.body, b"123") def test_coroutine_sequence_handler(self): response = self.fetch('/coroutine_sequence') self.assertEqual(response.body, b"123") def test_coroutine_unfinished_sequence_handler(self): response = self.fetch('/coroutine_unfinished_sequence') self.assertEqual(response.body, b"123") def test_task_handler(self): response = self.fetch('/task?url=%s' % url_escape(self.get_url('/sequence'))) self.assertEqual(response.body, b"got response: 123") def test_exception_handler(self): # Make sure we get an error and not a timeout with ExpectLog(app_log, "Uncaught exception GET /exception"): response = self.fetch('/exception') self.assertEqual(500, response.code) def test_coroutine_exception_handler(self): # Make sure we get an error and not a timeout with ExpectLog(app_log, "Uncaught exception GET /coroutine_exception"): response = self.fetch('/coroutine_exception') self.assertEqual(500, response.code) def test_yield_exception_handler(self): response = self.fetch('/yield_exception') self.assertEqual(response.body, b'ok') def test_undecorated_coroutines(self): response = self.fetch('/undecorated_coroutine') self.assertEqual(response.body, b'123') def test_async_prepare_error_handler(self): response = self.fetch('/async_prepare_error') self.assertEqual(response.code, 403) if __name__ == '__main__': unittest.main()
nephics/tornado
tornado/test/gen_test.py
Python
apache-2.0
29,521
# sqlalchemy/pool/dbapi_proxy.py # Copyright (C) 2005-2019 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """DBAPI proxy utility. Provides transparent connection pooling on top of a Python DBAPI. This is legacy SQLAlchemy functionality that is not typically used today. """ from .impl import QueuePool from .. import util from ..util import threading proxies = {} @util.deprecated( "1.3", "The :func:`.pool.manage` function is deprecated, and will be " "removed in a future release.", ) def manage(module, **params): r"""Return a proxy for a DB-API module that automatically pools connections. Given a DB-API 2.0 module and pool management parameters, returns a proxy for the module that will automatically pool connections, creating new connection pools for each distinct set of connection arguments sent to the decorated module's connect() function. :param module: a DB-API 2.0 database module :param poolclass: the class used by the pool module to provide pooling. Defaults to :class:`.QueuePool`. :param \**params: will be passed through to *poolclass* """ try: return proxies[module] except KeyError: return proxies.setdefault(module, _DBProxy(module, **params)) def clear_managers(): """Remove all current DB-API 2.0 managers. All pools and connections are disposed. """ for manager in proxies.values(): manager.close() proxies.clear() class _DBProxy(object): """Layers connection pooling behavior on top of a standard DB-API module. Proxies a DB-API 2.0 connect() call to a connection pool keyed to the specific connect parameters. Other functions and attributes are delegated to the underlying DB-API module. """ def __init__(self, module, poolclass=QueuePool, **kw): """Initializes a new proxy. module a DB-API 2.0 module poolclass a Pool class, defaulting to QueuePool Other parameters are sent to the Pool object's constructor. """ self.module = module self.kw = kw self.poolclass = poolclass self.pools = {} self._create_pool_mutex = threading.Lock() def close(self): for key in list(self.pools): del self.pools[key] def __del__(self): self.close() def __getattr__(self, key): return getattr(self.module, key) def get_pool(self, *args, **kw): key = self._serialize(*args, **kw) try: return self.pools[key] except KeyError: self._create_pool_mutex.acquire() try: if key not in self.pools: kw.pop("sa_pool_key", None) pool = self.poolclass( lambda: self.module.connect(*args, **kw), **self.kw ) self.pools[key] = pool return pool else: return self.pools[key] finally: self._create_pool_mutex.release() def connect(self, *args, **kw): """Activate a connection to the database. Connect to the database using this DBProxy's module and the given connect arguments. If the arguments match an existing pool, the connection will be returned from the pool's current thread-local connection instance, or if there is no thread-local connection instance it will be checked out from the set of pooled connections. If the pool has no available connections and allows new connections to be created, a new database connection will be made. """ return self.get_pool(*args, **kw).connect() def dispose(self, *args, **kw): """Dispose the pool referenced by the given connect arguments.""" key = self._serialize(*args, **kw) try: del self.pools[key] except KeyError: pass def _serialize(self, *args, **kw): if "sa_pool_key" in kw: return kw["sa_pool_key"] return tuple(list(args) + [(k, kw[k]) for k in sorted(kw)])
skarra/PRS
libs/sqlalchemy/pool/dbapi_proxy.py
Python
agpl-3.0
4,320
from boilerpipe.extract import Extractor extractor = Extractor(extractor='ArticleExtractor', url='http://www.christiantoday.com/article/iphone.6.problems.bendgate.still.continues.apple.mocked.videos.memes/41216.htm') print extractor.getText()
lasoren/hivemind
python/summary.py
Python
mit
243
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Tue Nov 14 11:46:48 2017 @author: p """ from epics import caget,caput import time import numpy as np import tensorflow as tf import matplotlib.pyplot as plt plt.close('all') filenRec='log_'+time.asctime().replace(' __','_').replace(' ','_')[4:] fid=open(filenRec,'a+') psUseStart=4 psUseEnd=7 bpmUseStart=2 bpmUseEnd=5 """ psSetListLib=['MEBT_PS:DCH_01:ISet','MEBT_PS:DCV_01:ISet', \ # 1 'MEBT_PS:DCH_02:ISet','MEBT_PS:DCV_02:ISet', \ # 2 'MEBT_PS:DCH_03:ISet','MEBT_PS:DCV_03:ISet', \ # 3 'MEBT_PS:DCH_04:ISet','MEBT_PS:DCV_04:ISet', \ # 4 'MEBT_PS:DCH_05:ISet','MEBT_PS:DCV_05:ISet', \ # 5 'MEBT_PS:DCH_06:ISet','MEBT_PS:DCV_06:ISet', \ # 6 'MEBT_PS:DCH_07:ISet','MEBT_PS:DCV_07:ISet', \ # 7 'HCM1_PS:DCH_01:ISet','HCM1_PS:DCV_01:ISet', \ # 8 'HCM1_PS:DCH_02:ISet','HCM1_PS:DCV_02:ISet', \ # 9 'HCM1_PS:DCH_03:ISet','HCM1_PS:DCV_03:ISet', \ # 10 'HCM1_PS:DCH_04:ISet','HCM1_PS:DCV_04:ISet', \ # 11 'HCM1_PS:DCH_05:ISet','HCM1_PS:DCV_05:ISet', \ # 12 'HCM1_PS:DCH_06:ISet','HCM1_PS:DCV_06:ISet', \ # 13 ] psMonListLib=[] for iSet in psSetList: psMonList.append(iSet.replace('Set','Mon')) bpmListLib=['BPM:1-X11','BPM:1-Y11',\ # 1 'BPM:2-X11', 'BPM:2-Y11',\ # 2 'BPM:3-X11','BPM:3-Y11',\ # 3 'BPM:4-X11','BPM:4-Y11',\ # 4 'BPM:5-X11','BPM:5-Y11',\ # 5 'BPM:6-X11', 'BPM:6-Y11',\ # 6 'BPM:7-X11','BPM:7-Y11',\ # 7 'BPM:8-X11','BPM:8-Y11',\ # 8 'BPM:9-X11','BPM:9-Y11',\ # 9 'BPM:10-X11','BPM:10-Y11',\ # 10 'BPM:11-X11','BPM:11-Y11',\ # 11 ] psSetMaxLib=[15,15,\ # MEBT 1 15 ,15,\ # MEBT 2 15 ,15,\ # MEBT 3 15 ,15,\ # MEBT 4 15 ,15,\ # MEBT 5 15 ,15,\ # MEBT 6 15 ,15,\ # MEBT 7 65,65,\ # HCM1# 1 65,65,\ # HCM1# 2 65,65,\ # HCM1# 3 65,65,\ # HCM1# 4 65,65,\ # HCM1# 5 65,65,\ # HCM1# 6 ] psSetMinLib=[-15,-15,\ # MEBT 1 -15 ,-15,\ # MEBT 2 -15 ,-15,\ # MEBT 3 -15 ,-15,\ # MEBT 4 -15 ,-15,\ # MEBT 5 -15 ,-15,\ # MEBT 6 -15 ,-15,\ # MEBT 7 -65,-65,\ # HCM1# 1 -65,-65,\ # HCM1# 2 -65,-65,\ # HCM1# 3 -65,-65,\ # HCM1# 4 -65,-65,\ # HCM1# 5 -65,-65,\ # HCM1# 6 ] psSetAmpLib=[5,5,\ # MEBT 1 5 ,5,\ # MEBT 2 5 ,5,\ # MEBT 3 5 ,5,\ # MEBT 4 5 ,5,\ # MEBT 5 5 ,5,\ # MEBT 6 5 ,5,\ # MEBT 7 5,5,\ # HCM1# 1 5,5,\ # HCM1# 2 5,5,\ # HCM1# 3 5,5,\ # HCM1# 4 5,5,\ # HCM1# 5 5,5,\ # HCM1# 6 ] """ psSetListLib=['MEBT_PS:DCH_01:ISet','MEBT_PS:DCV_01:ISet', \ 'MEBT_PS:DCH_02:ISet','MEBT_PS:DCV_02:ISet', \ 'MEBT_PS:DCH_03:ISet','MEBT_PS:DCV_03:ISet', \ 'MEBT_PS:DCH_04:ISet','MEBT_PS:DCV_04:ISet', \ 'MEBT_PS:DCH_05:ISet','MEBT_PS:DCV_05:ISet', \ 'MEBT_PS:DCH_06:ISet','MEBT_PS:DCV_06:ISet', \ 'MEBT_PS:DCH_07:ISet','MEBT_PS:DCV_07:ISet', \ 'HCM1_PS:DCH_01:ISet','HCM1_PS:DCV_01:ISet', \ 'HCM1_PS:DCH_02:ISet','HCM1_PS:DCV_02:ISet', \ 'HCM1_PS:DCH_03:ISet','HCM1_PS:DCV_03:ISet', \ 'HCM1_PS:DCH_04:ISet','HCM1_PS:DCV_04:ISet', \ 'HCM1_PS:DCH_05:ISet','HCM1_PS:DCV_05:ISet', \ 'HCM1_PS:DCH_06:ISet','HCM1_PS:DCV_06:ISet', \ ] psMonListLib=[] for iSet in psSetListLib: psMonListLib.append(iSet.replace('Set','Mon')) bpmListLib=['BPM:1-X11','BPM:1-Y11',\ 'BPM:2-X11', 'BPM:2-Y11',\ 'BPM:3-X11','BPM:3-Y11',\ 'BPM:4-X11','BPM:4-Y11',\ 'BPM:5-X11','BPM:5-Y11',\ 'BPM:6-X11', 'BPM:6-Y11',\ 'BPM:7-X11','BPM:7-Y11',\ 'BPM:8-X11','BPM:8-Y11',\ 'BPM:9-X11','BPM:9-Y11',\ 'BPM:10-X11','BPM:10-Y11',\ 'BPM:11-X11','BPM:11-Y11',\ ] psSetMaxLib=[15,15,\ 15 ,15,\ 15 ,15,\ 15 ,15,\ 15 ,15,\ 15 ,15,\ 15 ,15,\ 65,65,\ 65,65,\ 65,65,\ 65,65,\ 65,65,\ 65,65,\ ] psSetMinLib=[-15,-15,\ -15 ,-15,\ -15 ,-15,\ -15 ,-15,\ -15 ,-15,\ -15 ,-15,\ -15 ,-15,\ -65,-65,\ -65,-65,\ -65,-65,\ -65,-65,\ -65,-65,\ -65,-65,\ ] psSetAmpLib=[8,8,\ 8 ,8,\ 8 ,8,\ 8 ,8,\ 8 ,8,\ 8 ,8,\ 8 ,8,\ 5,5,\ 5,5,\ 5,5,\ 5,5,\ 5,5,\ 5,5,\ ] # -------------------- psSetList=psSetListLib[(psUseStart-1)*2:(psUseEnd)*2] psMonList=psMonListLib[(psUseStart-1)*2:(psUseEnd)*2] psSetMax=psSetMaxLib[(psUseStart-1)*2:(psUseEnd)*2] psSetMin=psSetMinLib[(psUseStart-1)*2:(psUseEnd)*2] psSetAmp=psSetAmpLib[(psUseStart-1)*2:(psUseEnd)*2] bpmList=bpmListLib[(bpmUseStart-1)*2:(bpmUseEnd)*2] ### ----------------- PICK ------------------------------- eroorList=['MEBT_PS:DCH_05:ISet'] for iError in eroorList: indexError=psSetList.index(eroorList[0]) psSetList.pop(indexError) psMonList.pop(indexError) psSetMax.pop(indexError) psSetMin.pop(indexError) psSetAmp.pop(indexError) ##-------------- def LogWrite(fid,X_,Y_): X1=X_[0,0::2] Y1=Y_[0,0::2] X2=X_[0,1::2] Y2=Y_[0,1::2] timeNow='# BPM : X>>Y | PS : X>>Y | '+time.asctime() fid.writelines(timeNow) fid.writelines('\n') for iX in X1: fid.writelines('%.2f ' %iX) fid.writelines('\n') for iX in X2: fid.writelines('%.2f ' %iX) fid.writelines('\n') for iX in Y1: fid.writelines('%.2f ' %iX) fid.writelines('\n') for iX in Y2: fid.writelines('%.2f ' %iX) fid.writelines('\n') def Plot(hPlot,bpmRec,psSetRec,psMonList,numRec): numItem=np.shape(bpmRec)[0] if numItem<numRec: X1=bpmRec[:,0::2] X2=bpmRec[:,1::2] Y1=psSetRec[:,0::2] Y2=psSetRec[:,1::2] else: X1=bpmRec[-numRec::,0::2] X2=bpmRec[-numRec::,1::2] Y1=psSetRec[-numRec::,0::2] Y2=psSetRec[-numRec::,1::2] psMon=GetPS(psMonList) xPSMon=psMon[0,0::2] yPSMon=psMon[0,1::2] plt.figure(hPlot) plt.clf() plt.subplot(1,2,1) plt.plot(X1.T,'-*') plt.grid('on') plt.axis([-0.5,len(X1.T)-0.5,-10,10]) plt.subplot(1,2,2) plt.plot(X2.T,'-*') plt.grid('on') plt.axis([-0.5,len(X2.T)-0.5,-10,10]) plt.pause(0.01) plt.figure(hPlot+1) plt.clf() plt.hold plt.subplot(1,2,1) plt.plot(Y1.T,'-*') plt.plot(xPSMon,'ro') plt.grid('on') plt.axis([-0.5,len(Y1.T)-0.5,-15.5,15.5]) plt.subplot(1,2,2) plt.plot(Y2.T,'-*') plt.plot(yPSMon,'ro') plt.grid('on') plt.axis([-0.5,len(Y1.T)-0.5,-15.5,15.5]) plt.pause(0.01) ## ---------------- def GetBPM(bpmList): bpmNow=[] for iBPM in bpmList: bpmNow.append(caget(iBPM)) bpmNow=np.array(bpmNow)[np.newaxis,:] return bpmNow def GetPS(psSetList): psNow=[] for iPS in psSetList: psNow.append(caget(iPS)) psNow=np.array(psNow)[np.newaxis,:] return psNow ## ------------------- INIT 4 ALL ---------- bpmNow=GetBPM(bpmList) psSetNow=GetPS(psSetList) bpmAim=-bpmNow bpmAim[0,0:2]=0 bpmAimOri=np.zeros(np.shape(bpmAim)) bpmAimOri[0,0:2]=bpmNow[0,0:2] bpmAim=np.hstack((bpmAimOri,bpmAim)) LogWrite(fid,bpmNow,psSetNow) bpmRec=bpmNow psSetRec=psSetNow ## ---------------- INIT 4 DATA ------------ def PutPS(psSetList,psSetNow): for i in range(len(psSetList)): iStr,iVal=psSetList[i],psSetNow[i] caput(iStr,iVal) def Sleep(psSetNow_,psMonList): iPrint=0 while True: iPrint+=1 psMonNow_= GetPS(psMonList) psSetNow=psSetNow_[0,:] psMonNow=psMonNow_[0,:] d_PS=np.abs(psSetNow-psMonNow) #print psMonList #print d_PS flag_PS=d_PS<1.2 flag_PS_All=np.prod(flag_PS) time.sleep(1) if flag_PS_All==0: idFalse=np.array(np.where( flag_PS==False))[0,:]+1 numQ=np.int32(idFalse/2) if idFalse[0] % 2 ==1: nameCV='H' else: nameCV='V' if iPrint>3: print 'Please check '+str(numQ)+' '+nameCV+' '+str(np.round(100*psSetNow[idFalse])/100)+' '+str(np.round(100*psMonNow[idFalse])/100) if flag_PS_All==1: break def CheckPSSet(psSetNow,psSetMax,psSetMin,flagPSSet): psSetMaxArray=np.array(psSetMax) psSetMinArray=np.array(psSetMin) flagPSSet[psSetNow<psSetMinArray]=1 flagPSSet[psSetNow>psSetMaxArray]=-1 psSetNow[psSetNow<psSetMinArray]=2*psSetMinArray[psSetNow<psSetMinArray]-psSetNow[psSetNow<psSetMinArray] psSetNow[psSetNow>psSetMaxArray]=2*psSetMaxArray[psSetNow>psSetMaxArray]-psSetNow[psSetNow>psSetMaxArray] return psSetNow,flagPSSet def CheckPSSetSim(psSetNow,psSetMax,psSetMin): psSetMaxArray=np.array(psSetMax) psSetMinArray=np.array(psSetMin) psSetNow[psSetNow<psSetMinArray]=2*psSetMinArray[psSetNow<psSetMinArray]-psSetNow[psSetNow<psSetMinArray] psSetNow[psSetNow>psSetMaxArray]=2*psSetMaxArray[psSetNow>psSetMaxArray]-psSetNow[psSetNow>psSetMaxArray] return psSetNow def CheckPSSetChange(psSetChange_,psSetAmp): psSetChange=psSetChange_[0,:] psSetMax=np.array(psSetAmp) psSetMin=-np.array(psSetAmp) psSetMaxArray=np.array(psSetMax) psSetMinArray=np.array(psSetMin) psSetChange[psSetChange<psSetMinArray]=psSetMinArray[psSetChange<psSetMinArray] psSetChange[psSetChange>psSetMaxArray]=psSetMaxArray[psSetChange>psSetMaxArray] return psSetChange #####---------------------------- numBPM=len(bpmList) numPS=len(psSetList) numInitData=5 ###################################################### for i in xrange(numInitData): print "Init Data" print i psSetLast=psSetRec[-1,:] if i==0: flagPSSet=np.sign(np.random.random(np.shape(psSetLast))-0.5) psSetChange=(np.random.random((np.shape(psSetLast)))*1)*np.array(psSetAmp) psSetChange=psSetChange*flagPSSet psSetNow=psSetLast+psSetChange psSetNow,flagPSSet=CheckPSSet(psSetNow,psSetMax,psSetMin,flagPSSet) PutPS(psSetList,psSetNow) psSetNow=psSetNow[np.newaxis,:] psSetRec=np.vstack((psSetRec,psSetNow)) Sleep(psSetNow,psMonList) bpmNow=GetBPM(bpmList) bpmRec=np.vstack((bpmRec,bpmNow)) Plot(1001,bpmRec,psSetRec,psMonList,3) LogWrite(fid,bpmNow,psSetNow) #### ------- CONFIG ------------------------------- def GenWeight(shape): initial = tf.truncated_normal(shape, stddev=1.) return tf.Variable(initial) def GenBias(shape): initial=GenWeight((1,shape(0))) return initial[0,:] def PreTrain(psSetRec,bpmRec,batchSize): numItem=np.shape(bpmRec)[0] idChoose_0=np.random.randint(0,high=numItem,size=(batchSize)) idChoose_1=np.random.randint(1,high=numItem,size=(batchSize)) #idChoose_0=idChoose_1-1 d_psChoose=psSetRec[idChoose_1,:]-psSetRec[idChoose_0,:] d_BPMChoose=bpmRec[idChoose_1,:]-bpmRec[idChoose_0,:] x0=bpmRec[idChoose_0,:] dx=d_BPMChoose X=np.hstack((x0,dx)) Y=d_psChoose return X,Y def RunTrain(se,opt,loss,numEpoch,batchSize,psSetRec,bpmRec): lossRecRec=[] for _ in range(numEpoch): X,Y=PreTrain(psSetRec,bpmRec,batchSize) se.run(opt,feed_dict={xIn:X,yIn:Y}) if _% 50==0: lossRecTmp=se.run(loss,feed_dict={xIn:X,yIn:Y}) lossRecRec.append(lossRecTmp) return lossRecRec learningRate=0.001 #-------------------------------------------- numEpoch=5000 batchSize=50 numInput=numBPM*2 numOutput=numPS xIn=tf.placeholder(tf.float32,shape=(None,numInput)) yIn=tf.placeholder(tf.float32,shape=(None,numOutput)) ''' num1=8 w1=GenWeight((numInput,num1)) b1= GenWeight((1,num1))[0,:] x1=tf.nn.relu(tf.nn.xw_plus_b(xIn,w1,b1)) # num2=numOutput w2=GenWeight((num1,num2)) b2= GenWeight((1,num2))[0,:] x2=tf.nn.xw_plus_b(x1,w2,b2) ''' w0=GenWeight((numInput,numOutput)) x0=tf.matmul(xIn,w0) xOut=x0 yOut=yIn lossRegularPre=tf.contrib.layers.l2_regularizer(0.5) lossRegular=tf.contrib.layers.apply_regularization(lossRegularPre,weights_list=[w0]) loss=tf.losses.mean_squared_error(xOut,yOut)+lossRegular+tf.reduce_mean(tf.square(xOut))*2 train=tf.train.AdamOptimizer(learningRate) opt=train.minimize(loss) se=tf.Session() se.run(tf.global_variables_initializer()) ######## --------- Train Initial------------------ lossRecRec=RunTrain(se,opt,loss,numEpoch,batchSize,psSetRec,bpmRec) ######## --------- Train ------------------ numTrain=200 for iTrain in range(numTrain): print "Train" print iTrain psSetLast=psSetRec[-1,:] psSetChange=se.run(xOut,feed_dict={xIn:bpmAim}) #psSetChange=CheckPSSetChange(psSetChange,psSetAmp) psSetChange=psSetChange[0,:] #-------??????????? psSetChange*=0.1 print psSetChange psSetNow=psSetLast+psSetChange psSetNow=CheckPSSetSim(psSetNow,psSetMax,psSetMin) ''' ##------- bpmNow=GetBPM(bpmList) if np.std(bpmNow)>1.2: flagMin=psSetNow>(np.array(psSetMax)*0.75) flagMax=psSetNow<(np.array(psSetMin)*0.75) flagM=flagMin * flagMax psSetNow[flagM]=psSetNow[flagM==1]*(np.random.random((np.shape(psSetNow[flagM==1])))*0.5+0.5) ## ------- ''' PutPS(psSetList,psSetNow) psSetNow=psSetNow[np.newaxis,:] psSetRec=np.vstack((psSetRec,psSetNow)) lossRecRec=RunTrain(se,opt,loss,numEpoch,batchSize,psSetRec,bpmRec) Sleep(psSetNow,psMonList) #time.sleep(7) bpmNow=GetBPM(bpmList) bpmRec=np.vstack((bpmRec,bpmNow)) Plot(1001,bpmRec,psSetRec,psMonList,1) LogWrite(fid,bpmNow,psSetNow) plt.figure(999) plt.clf() plt.plot(lossRecRec) plt.pause(0.01) ##-------- Final ------------------------ se.close() fid.close()
iABC2XYZ/abc
CM/cmCooorect_5.py
Python
gpl-3.0
14,829
# coding: utf-8 # # Antibody Response Pulse # https://github.com/blab/antibody-response-pulse # # ### B-cells evolution --- cross-reactive antibody response after influenza virus infection or vaccination # ### Adaptive immune response for repeated infection # In[1]: ''' author: Alvason Zhenhua Li date: 04/09/2015 ''' get_ipython().magic(u'matplotlib inline') import numpy as np import matplotlib.pyplot as plt import os from matplotlib.ticker import FuncFormatter import alva_machinery_event_OAS_new as alva AlvaFontSize = 23 AlvaFigSize = (15, 5) numberingFig = 0 # plotting dir_path = '/Users/al/Desktop/GitHub/antibody-response-pulse/bcell-array/figure' file_name = 'Virus-Bcell-IgM-IgG' figure_name = '-equation' file_suffix = '.png' save_figure = os.path.join(dir_path, file_name + figure_name + file_suffix) numberingFig = numberingFig + 1 plt.figure(numberingFig, figsize=(12, 5)) plt.axis('off') plt.title(r'$ Virus-Bcell-IgM-IgG \ equations \ (antibody-response \ for \ repeated-infection) $' , fontsize = AlvaFontSize) plt.text(0, 7.0/9, r'$ \frac{\partial V_n(t)}{\partial t} = +\mu_{v}V_{n}(t)(1 - \frac{V_n(t)}{V_{max}}) - \phi_{m} M_{n}(t) V_{n}(t) - \phi_{g} G_{n}(t) V_{n}(t) $' , fontsize = 1.2*AlvaFontSize) plt.text(0, 5.0/9, r'$ \frac{\partial B_n(t)}{\partial t} = +\mu_{b}V_{n}(t)(1 - \frac{V_n(t)}{V_{max}}) + (\beta_{m} + \beta_{g}) V_{n}(t) B_{n}(t) - \mu_{b} B_{n}(t) + m_b V_{n}(t)\frac{B_{i-1}(t) - 2B_i(t) + B_{i+1}(t)}{(\Delta i)^2} $' , fontsize = 1.2*AlvaFontSize) plt.text(0, 3.0/9,r'$ \frac{\partial M_n(t)}{\partial t} = +\xi_{m} B_{n}(t) - \phi_{m} M_{n}(t) V_{n}(t) - \mu_{m} M_{n}(t) $' , fontsize = 1.2*AlvaFontSize) plt.text(0, 1.0/9,r'$ \frac{\partial G_n(t)}{\partial t} = +\xi_{g} B_{n}(t) - \phi_{g} G_{n}(t) V_{n}(t) - \mu_{g} G_{n}(t) + m_a V_{n}(t)\frac{G_{i-1}(t) - 2G_i(t) + G_{i+1}(t)}{(\Delta i)^2} $' , fontsize = 1.2*AlvaFontSize) plt.savefig(save_figure, dpi = 100) plt.show() # define the V-M-G partial differential equations def dVdt_array(VBMGxt = [], *args): # naming V = VBMGxt[0] B = VBMGxt[1] M = VBMGxt[2] G = VBMGxt[3] x_totalPoint = VBMGxt.shape[1] # there are n dSdt dV_dt_array = np.zeros(x_totalPoint) # each dSdt with the same equation form dV_dt_array[:] = +inRateV*V[:]*(1 - V[:]/maxV) - killRateVm*M[:]*V[:] - killRateVg*G[:]*V[:] return(dV_dt_array) def dBdt_array(VBMGxt = [], *args): # naming V = VBMGxt[0] B = VBMGxt[1] M = VBMGxt[2] G = VBMGxt[3] x_totalPoint = VBMGxt.shape[1] # there are n dSdt dB_dt_array = np.zeros(x_totalPoint) # each dSdt with the same equation form Bcopy = np.copy(B) centerX = Bcopy[:] leftX = np.roll(Bcopy[:], 1) rightX = np.roll(Bcopy[:], -1) leftX[0] = centerX[0] rightX[-1] = centerX[-1] dB_dt_array[:] = +inRateB*V[:]*(1 - V[:]/maxV) + (actRateBm + alva.event_active + alva.event_OAS_B)*V[:]*B[:] - outRateB*B[:] + mutatRateB*V[:]*(leftX[:] - 2*centerX[:] + rightX[:])/(dx**2) return(dB_dt_array) def dMdt_array(VBMGxt = [], *args): # naming V = VBMGxt[0] B = VBMGxt[1] M = VBMGxt[2] G = VBMGxt[3] x_totalPoint = VBMGxt.shape[1] # there are n dSdt dM_dt_array = np.zeros(x_totalPoint) # each dSdt with the same equation form dM_dt_array[:] = +inRateM*B[:] - consumeRateM*M[:]*V[:] - outRateM*M[:] return(dM_dt_array) def dGdt_array(VBMGxt = [], *args): # naming V = VBMGxt[0] B = VBMGxt[1] M = VBMGxt[2] G = VBMGxt[3] x_totalPoint = VBMGxt.shape[1] # there are n dSdt dG_dt_array = np.zeros(x_totalPoint) # each dSdt with the same equation form Gcopy = np.copy(G) centerX = Gcopy[:] leftX = np.roll(Gcopy[:], 1) rightX = np.roll(Gcopy[:], -1) leftX[0] = centerX[0] rightX[-1] = centerX[-1] dG_dt_array[:] = +(inRateG + alva.event_OAS)*B[:] - consumeRateG*G[:]*V[:] - outRateG*G[:] + mutatRateA*(leftX[:] - 2*centerX[:] + rightX[:])/(dx**2) return(dG_dt_array) # In[2]: # setting parameter timeUnit = 'day' if timeUnit == 'hour': hour = float(1) day = float(24) elif timeUnit == 'day': day = float(1) hour = float(1)/24 elif timeUnit == 'year': year = float(1) day = float(1)/365 hour = float(1)/24/365 maxV = float(50) # max virus/micro-liter inRateV = 0.2/hour # in-rate of virus killRateVm = 0.0003/hour # kill-rate of virus by antibody-IgM killRateVg = killRateVm # kill-rate of virus by antibody-IgG inRateB = 0.06/hour # in-rate of B-cell outRateB = inRateB/8 # out-rate of B-cell actRateBm = killRateVm # activation rate of naive B-cell inRateM = 0.16/hour # in-rate of antibody-IgM from naive B-cell outRateM = inRateM/1 # out-rate of antibody-IgM from naive B-cell consumeRateM = killRateVm # consume-rate of antibody-IgM by cleaning virus inRateG = inRateM/10 # in-rate of antibody-IgG from memory B-cell outRateG = outRateM/250 # out-rate of antibody-IgG from memory B-cell consumeRateG = killRateVg # consume-rate of antibody-IgG by cleaning virus mutatRateB = 0.00003/hour # B-cell mutation rate mutatRateA = 0.0001/hour # antibody mutation rate # time boundary and griding condition minT = float(0) maxT = float(6*28*day) totalPoint_T = int(1*10**3 + 1) gT = np.linspace(minT, maxT, totalPoint_T) spacingT = np.linspace(minT, maxT, num = totalPoint_T, retstep = True) gT = spacingT[0] dt = spacingT[1] # space boundary and griding condition minX = float(0) maxX = float(3) totalPoint_X = int(maxX - minX + 1) gX = np.linspace(minX, maxX, totalPoint_X) gridingX = np.linspace(minX, maxX, num = totalPoint_X, retstep = True) gX = gridingX[0] dx = gridingX[1] gV_array = np.zeros([totalPoint_X, totalPoint_T]) gB_array = np.zeros([totalPoint_X, totalPoint_T]) gM_array = np.zeros([totalPoint_X, totalPoint_T]) gG_array = np.zeros([totalPoint_X, totalPoint_T]) # initial output condition #gV_array[1, 0] = float(2) #[pre-parameter, post-parameter, recovered-day, OAS+, OSA-] actRateBg_1st = 0.0002/hour # activation rate of memory B-cell at 1st time (pre-) actRateBg_2nd = actRateBg_1st*10 # activation rate of memory B-cell at 2nd time (post-) origin_virus = int(1) event_parameter = np.array([[actRateBg_1st, actRateBg_2nd, 14*day, +5/hour, -actRateBm - actRateBg_1st + (actRateBm + actRateBg_1st)/3, origin_virus]]) # [viral population, starting time, first] # [viral population, starting time] ---first infection_period = 1*28*day viral_population = np.zeros(int(maxX + 1)) viral_population[origin_virus:-1] = 3 infection_starting_time = np.arange(int(maxX + 1))*infection_period event_1st = np.zeros([int(maxX + 1), 2]) event_1st[:, 0] = viral_population event_1st[:, 1] = infection_starting_time print ('event_1st = {:}'.format(event_1st)) # [viral population, starting time] ---2nd] viral_population = np.zeros(int(maxX + 1)) viral_population[origin_virus:-1] = 0 infection_starting_time = np.arange(int(maxX + 1))*0 event_2nd = np.zeros([int(maxX + 1), 2]) event_2nd[:, 0] = viral_population event_2nd[:, 1] = infection_starting_time print ('event_2nd = {:}'.format(event_2nd)) event_table = np.array([event_parameter, event_1st, event_2nd]) # Runge Kutta numerical solution pde_array = np.array([dVdt_array, dBdt_array, dMdt_array, dGdt_array]) initial_Out = np.array([gV_array, gB_array, gM_array, gG_array]) gOut_array = alva.AlvaRungeKutta4XT(pde_array, initial_Out, minX, maxX, totalPoint_X, minT, maxT, totalPoint_T, event_table) # plotting gV = gOut_array[0] gB = gOut_array[1] gM = gOut_array[2] gG = gOut_array[3] numberingFig = numberingFig + 1 for i in range(totalPoint_X): figure_name = '-response-%i'%(i) figure_suffix = '.png' save_figure = os.path.join(dir_path, file_name + figure_name + file_suffix) plt.figure(numberingFig, figsize = AlvaFigSize) plt.plot(gT, gV[i], color = 'red', label = r'$ V_{%i}(t) $'%(i), linewidth = 3.0, alpha = 0.5) plt.plot(gT, gM[i], color = 'blue', label = r'$ IgM_{%i}(t) $'%(i), linewidth = 3.0, alpha = 0.5) plt.plot(gT, gG[i], color = 'green', label = r'$ IgG_{%i}(t) $'%(i), linewidth = 3.0, alpha = 0.5) plt.plot(gT, gM[i] + gG[i], color = 'gray', linewidth = 5.0, alpha = 0.5, linestyle = 'dashed' , label = r'$ IgM_{%i}(t) + IgG_{%i}(t) $'%(i, i)) plt.grid(True, which = 'both') plt.title(r'$ Antibody \ from \ Virus-{%i} $'%(i), fontsize = AlvaFontSize) plt.xlabel(r'$time \ (%s)$'%(timeUnit), fontsize = AlvaFontSize) plt.ylabel(r'$ Neutralization \ \ titer $', fontsize = AlvaFontSize) plt.xlim([minT, maxT]) plt.xticks(fontsize = AlvaFontSize*0.6) plt.yticks(fontsize = AlvaFontSize*0.6) plt.ylim([2**0, 2**14]) plt.yscale('log', basey = 2) plt.legend(loc = (1,0), fontsize = AlvaFontSize) plt.savefig(save_figure, dpi = 100) plt.show() # In[3]: # Experimental lab data from OAS paper gT_lab = np.array([28, 28 + 7, 28 + 14, 28 + 28]) + 28 gPR8_lab = np.array([2**(9 + 1.0/10), 2**(13 - 1.0/5), 2**(13 + 1.0/3), 2**(13 - 1.0/4)]) standard_PR8 = gPR8_lab**(3.0/4) gFM1_lab = np.array([0, 2**(6 - 1.0/5), 2**(7 - 1.0/4), 2**(8 + 1.0/4)]) standard_FM1 = gFM1_lab**(3.0/4) bar_width = 2.0 # Sequential immunization graph numberingFig = numberingFig + 1 plt.figure(numberingFig, figsize = (12, 6)) plt.subplot(111) plt.plot(gT, (gM[origin_virus] + gG[origin_virus]), linewidth = 5.0, alpha = 0.5, color = 'gray' , label = r'$ Origin-virus $') plt.plot(gT, (gM[origin_virus + 1] + gG[origin_virus + 1]), linewidth = 5.0, alpha = 0.5, color = 'red' , label = r'$ Subsequence-virus $') plt.bar(gT_lab - bar_width/2, gPR8_lab, bar_width, alpha = 0.6, color = 'gray', yerr = standard_PR8 , error_kw = dict(elinewidth = 1, ecolor = 'black'), label = r'$ PR8-virus $') plt.bar(gT_lab + bar_width/2, gFM1_lab, bar_width, alpha = 0.6, color = 'red', yerr = standard_FM1 , error_kw = dict(elinewidth = 1, ecolor = 'black'), label = r'$ FM1-virus $') plt.grid(True, which = 'both') plt.title(r'$ Original \ Antigenic \ Sin \ (sequential-infection)$', fontsize = AlvaFontSize) plt.xlabel(r'$time \ (%s)$'%(timeUnit), fontsize = AlvaFontSize) plt.ylabel(r'$ Neutralization \ \ titer $', fontsize = AlvaFontSize) plt.xticks(fontsize = AlvaFontSize*0.6) plt.yticks(fontsize = AlvaFontSize*0.6) plt.xlim([minT, 6*30*day]) plt.ylim([2**5, 2**14]) plt.yscale('log', basey = 2) # gca()---GetCurrentAxis and Format the ticklabel to be 2**x plt.gca().yaxis.set_major_formatter(FuncFormatter(lambda x, pos: int(2**(np.log(x)/np.log(2))))) #plt.gca().xaxis.set_major_locator(plt.MultipleLocator(7)) plt.legend(loc = (1, 0), fontsize = AlvaFontSize) plt.show() # In[4]: # Experimental lab data from OAS paper gT_lab = np.array([28, 28 + 7, 28 + 14, 28 + 28]) + 28 gPR8_lab = np.array([2**(9 + 1.0/10), 2**(13 - 1.0/5), 2**(13 + 1.0/3), 2**(13 - 1.0/4)]) standard_PR8 = gPR8_lab**(3.0/4) gFM1_lab = np.array([0, 2**(6 - 1.0/5), 2**(7 - 1.0/4), 2**(8 + 1.0/4)]) standard_FM1 = gFM1_lab**(3.0/4) bar_width = 1.0 # Sequential immunization graph figure_name = '-Original-Antigenic-Sin-infection' figure_suffix = '.png' save_figure = os.path.join(dir_path, file_name + figure_name + file_suffix) numberingFig = numberingFig + 1 plt.figure(numberingFig, figsize = (12, 6)) plt.subplot(111) plt.plot(gT, (gM[origin_virus] + gG[origin_virus]), linewidth = 5.0, alpha = 0.5, color = 'gray' , label = r'$ Origin-virus $') plt.plot(gT, (gM[origin_virus + 1] + gG[origin_virus + 1]), linewidth = 5.0, alpha = 0.5, color = 'red' , label = r'$ Subsequence-virus $') plt.bar(gT_lab - bar_width/2, gPR8_lab, bar_width, alpha = 0.6, color = 'gray', yerr = standard_PR8 , error_kw = dict(elinewidth = 1, ecolor = 'black'), label = r'$ PR8-virus $') plt.bar(gT_lab + bar_width/2, gFM1_lab, bar_width, alpha = 0.6, color = 'red', yerr = standard_FM1 , error_kw = dict(elinewidth = 1, ecolor = 'black'), label = r'$ FM1-virus $') plt.grid(True, which = 'both') plt.title(r'$ Original \ Antigenic \ Sin \ (sequential-infection)$', fontsize = AlvaFontSize) plt.xlabel(r'$time \ (%s)$'%(timeUnit), fontsize = AlvaFontSize) plt.ylabel(r'$ Neutralization \ \ titer $', fontsize = AlvaFontSize) plt.xticks(fontsize = AlvaFontSize*0.6) plt.yticks(fontsize = AlvaFontSize*0.6) plt.xlim([minT, 3*30*day]) plt.ylim([2**5, 2**14]) plt.yscale('log', basey = 2) # gca()---GetCurrentAxis and Format the ticklabel to be 2**x plt.gca().yaxis.set_major_formatter(FuncFormatter(lambda x, pos: int(2**(np.log(x)/np.log(2))))) plt.gca().xaxis.set_major_locator(plt.MultipleLocator(7)) plt.legend(loc = (1, 0), fontsize = AlvaFontSize) plt.savefig(save_figure, dpi = 100, bbox_inches='tight') plt.show() # In[ ]:
blab/antibody-response-pulse
bcell-array/code/Virus_Bcell_IgM_IgG_Infection_OAS_new-Copy2.py
Python
gpl-2.0
13,001
#!/usr/bin/env python # Copyright 2014-2018 The PySCF Developers. 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. # # Author: Qiming Sun <osirpt.sun@gmail.com> # from pyscf.pbc.tdscf import rks from pyscf.pbc.tdscf import rhf
gkc1000/pyscf
pyscf/pbc/tddft/__init__.py
Python
apache-2.0
746
import matplotlib.pyplot as plt from datos import data import pandas colors = ['lightcoral', 'lightskyblue','yellowgreen'] d=data('mtcars') ps = pandas.Series([i for i in d.cyl]) c = ps.value_counts() plt.pie(c, labels=c.index, colors=colors, autopct='%1.1f%%', shadow=True, startangle=0) plt.axis('equal') plt.title('Car Distribution by Cylindres', size=18) plt.show()
cimat/data-visualization-patterns
display-patterns/Proportions/Pruebas/A41Simple_Pie_Chart_Matplotlib.py
Python
cc0-1.0
371
#python3.4 generate-testresult-docker.py output_dir=/home/geryxyz/major/testresults/ original_path=/home/geryxyz/major/joda-time patch_root=/home/geryxyz/major/joda-time-mutants merge_root=/home/geryxyz/major/joda-time-merge2 relative_path_to_patch=src/main/java from soda import * Phase( 'generate test results', SetVariable(aString('external_timeout'), 60 ** 2), SetVariable(aString('maven'), 'mvn'), Need(aString('output_dir')), Need(aString('original_path')), Need(aString('patch_root')), Need(aString('merge_root')), Need(aString('relative_path_to_patch')), ParalellGenerateTestResultForMutants( 'execute tests', '${output_dir}', MutantsPatchLoader( '${original_path}', '${patch_root}', '${merge_root}', '${relative_path_to_patch}'), valar) ).do()
sed-szeged/soda-coverage-tools
java/script/sample/try/generate-testresult-docker.py
Python
lgpl-3.0
890
from operator import attrgetter import logging import blocks import sys logger = logging.getLogger(__name__) class HashChainTask(object): """ - get hashes chain until we see a known block hash """ NUM_HASHES_PER_REQUEST = 2000 def __init__(self, chain_manager, peer, block_hash): self.chain_manager = chain_manager self.peer = peer self.hash_chain = [] # [youngest, ..., oldest] self.request(block_hash) def request(self, block_hash): logger.debug('%r requesting block_hashes starting from %r', self.peer, block_hash.encode('hex')) self.peer.send_GetBlockHashes(block_hash, self.NUM_HASHES_PER_REQUEST) def received_block_hashes(self, block_hashes): logger.debug('HashChainTask.received_block_hashes %d', len(block_hashes)) if block_hashes and self.chain_manager.genesis.hash == block_hashes[-1]: logger.debug('%r has different chain starting from genesis', self.peer) for bh in block_hashes: if bh in self.chain_manager or bh == self.chain_manager.genesis.hash: logger.debug('%r matching block hash found %r, %d blocks to fetch', self.peer, bh.encode('hex'), len(self.hash_chain)) return list(reversed(self.hash_chain)) self.hash_chain.append(bh) if len(block_hashes) == 0: return list(reversed(self.hash_chain)) # logger.debug('hash_chain.append(%r) %d', bh.encode('hex'), len(self.hash_chain)) self.request(bh) class SynchronizationTask(object): """ Created if we receive a unknown block w/o known parent. Possibly from a different branch. - get hashes chain until we see a known block hash - request missing blocks - once synced - rerequest blocks that lacked a reference before syncing """ NUM_BLOCKS_PER_REQUEST = 200 def __init__(self, chain_manager, peer, block_hash): self.chain_manager = chain_manager self.peer = peer self.hash_chain = [] # [oldest to youngest] logger.debug('%r syncing %r', self.peer, block_hash.encode('hex')) self.hash_chain_task = HashChainTask(self.chain_manager, self.peer, block_hash) def received_block_hashes(self, block_hashes): res = self.hash_chain_task.received_block_hashes(block_hashes) if res: self.hash_chain = res logger.debug('%r hash chain with %d hashes for missing blocks', self.peer, len(self.hash_chain)) self.request_blocks() def received_blocks(self, transient_blocks): logger.debug('%r received %d blocks. %d missing', self.peer, len(transient_blocks), len(self.hash_chain)) for tb in transient_blocks: if len(self.hash_chain) and self.hash_chain[0] == tb.hash: self.hash_chain.pop(0) else: logger.debug('%r received unexpected block %r', self.peer, tb) return False if self.hash_chain: # still blocks to fetch logger.debug('%r still missing %d blocks', self.peer, len(self.hash_chain)) self.request_blocks() else: # done return True def request_blocks(self): logger.debug('%r requesting %d of %d missing blocks', self.peer, self.NUM_BLOCKS_PER_REQUEST, len(self.hash_chain)) self.peer.send_GetBlocks(self.hash_chain[:self.NUM_BLOCKS_PER_REQUEST]) class Synchronizer(object): """" Cases: on "recv_Status": received unknown head_hash w/ sufficient difficulty on "recv_Blocks": received block w/o parent (new block mined, competing chain discovered) Naive Strategy: assert we see a block for which we have no parent assume that the sending peer knows the parent if we have not yet syncer for this unknown block: create new syncer sync direction genesis until we see known block_hash sync also (re)requests the block we missed, so it can be added on top of the synced chain else do nothing syncing (if finished) will be started with the next broadcasted block w/ missing parent """ def __init__(self, chain_manager): self.chain_manager = chain_manager self.synchronization_tasks = {} # peer > syncer # syncer.unknown_hash as marker for task def stop_synchronization(self, peer): logger.debug('%r sync stopped', peer) if peer in self.synchronization_tasks: del self.synchronization_tasks[peer] def synchronize_unknown_block(self, peer, block_hash, force=False): "Case: block with unknown parent. Fetches unknown ancestors and this block" logger.debug('%r sync %r', peer, block_hash.encode('hex')) if block_hash == self.chain_manager.genesis.hash or block_hash in self.chain_manager: logger.debug('%r known_hash %r, skipping', peer, block_hash.encode('hex')) return if peer and (not peer in self.synchronization_tasks) or force: logger.debug('%r new sync task', peer) self.synchronization_tasks[peer] = SynchronizationTask(self.chain_manager, peer, block_hash) else: logger.debug('%r already has a synctask, sorry', peer) def synchronize_status(self, peer, block_hash, total_difficulty): "Case: unknown head with sufficient difficulty" logger.debug('%r status with %r %d', peer, block_hash.encode('hex'), total_difficulty) # guesstimate the max difficulty difference possible for a sucessfully competing chain # worst case if skip it: we are on a stale chain until the other catched up # assume difficulty is constant num_blocks_behind = 7 avg_uncles_per_block = 4 max_diff = self.chain_manager.head.difficulty * num_blocks_behind * (1 + avg_uncles_per_block) if total_difficulty + max_diff > self.chain_manager.head.difficulty: logger.debug('%r sufficient difficulty, syncing', peer) self.synchronize_unknown_block(peer, block_hash) else: logger.debug('%r insufficient difficulty, not syncing', peer) def received_block_hashes(self, peer, block_hashes): if peer in self.synchronization_tasks: logger.debug("Synchronizer.received_block_hashes %d for: %r", len(block_hashes), peer) self.synchronization_tasks[peer].received_block_hashes(block_hashes) def received_blocks(self, peer, transient_blocks): if peer in self.synchronization_tasks: res = self.synchronization_tasks[peer].received_blocks(transient_blocks) if res is True: logger.debug("Synchronizer.received_blocks: chain w %r synced", peer) del self.synchronization_tasks[peer]
jnnk/pyethereum
pyethereum/synchronizer.py
Python
mit
6,870
# -*- coding: utf-8 -*- from datetime import datetime from flask import (Blueprint, request, current_app, session, url_for, redirect, render_template, g, flash, abort) from flask_babel import gettext from sqlalchemy.sql.expression import false import crypto_util import store from db import db_session, Source, SourceStar, Submission, Reply from journalist_app.decorators import login_required from journalist_app.forms import ReplyForm from journalist_app.utils import (validate_user, bulk_delete, download, confirm_bulk_delete, get_source) def make_blueprint(config): view = Blueprint('main', __name__) @view.route('/login', methods=('GET', 'POST')) def login(): if request.method == 'POST': user = validate_user(request.form['username'], request.form['password'], request.form['token']) if user: current_app.logger.info("'{}' logged in with the token {}" .format(request.form['username'], request.form['token'])) # Update access metadata user.last_access = datetime.utcnow() db_session.add(user) db_session.commit() session['uid'] = user.id return redirect(url_for('main.index')) return render_template("login.html") @view.route('/logout') def logout(): session.pop('uid', None) session.pop('expires', None) return redirect(url_for('main.index')) @view.route('/') @login_required def index(): unstarred = [] starred = [] # Long SQLAlchemy statements look best when formatted according to # the Pocoo style guide, IMHO: # http://www.pocoo.org/internal/styleguide/ sources = Source.query.filter_by(pending=False) \ .order_by(Source.last_updated.desc()) \ .all() for source in sources: star = SourceStar.query.filter_by(source_id=source.id).first() if star and star.starred: starred.append(source) else: unstarred.append(source) source.num_unread = len( Submission.query.filter_by(source_id=source.id, downloaded=False).all()) return render_template('index.html', unstarred=unstarred, starred=starred) @view.route('/reply', methods=('POST',)) @login_required def reply(): """Attempt to send a Reply from a Journalist to a Source. Empty messages are rejected, and an informative error message is flashed on the client. In the case of unexpected errors involving database transactions (potentially caused by racing request threads that modify the same the database object) logging is done in such a way so as not to write potentially sensitive information to disk, and a generic error message is flashed on the client. Returns: flask.Response: The user is redirected to the same Source collection view, regardless if the Reply is created successfully. """ form = ReplyForm() if not form.validate_on_submit(): for error in form.message.errors: flash(error, "error") return redirect(url_for('col.col', filesystem_id=g.filesystem_id)) g.source.interaction_count += 1 filename = "{0}-{1}-reply.gpg".format(g.source.interaction_count, g.source.journalist_filename) crypto_util.encrypt(form.message.data, [crypto_util.getkey(g.filesystem_id), config.JOURNALIST_KEY], output=store.path(g.filesystem_id, filename)) reply = Reply(g.user, g.source, filename) try: db_session.add(reply) db_session.commit() except Exception as exc: flash(gettext( "An unexpected error occurred! Please " "inform your administrator."), "error") # We take a cautious approach to logging here because we're dealing # with responses to sources. It's possible the exception message # could contain information we don't want to write to disk. current_app.logger.error( "Reply from '{}' (ID {}) failed: {}!".format(g.user.username, g.user.id, exc.__class__)) else: flash(gettext("Thanks. Your reply has been stored."), "notification") finally: return redirect(url_for('col.col', filesystem_id=g.filesystem_id)) @view.route('/flag', methods=('POST',)) @login_required def flag(): g.source.flagged = True db_session.commit() return render_template('flag.html', filesystem_id=g.filesystem_id, codename=g.source.journalist_designation) @view.route('/bulk', methods=('POST',)) @login_required def bulk(): action = request.form['action'] doc_names_selected = request.form.getlist('doc_names_selected') selected_docs = [doc for doc in g.source.collection if doc.filename in doc_names_selected] if selected_docs == []: if action == 'download': flash(gettext("No collections selected for download."), "error") elif action in ('delete', 'confirm_delete'): flash(gettext("No collections selected for deletion."), "error") return redirect(url_for('col.col', filesystem_id=g.filesystem_id)) if action == 'download': source = get_source(g.filesystem_id) return download(source.journalist_filename, selected_docs) elif action == 'delete': return bulk_delete(g.filesystem_id, selected_docs) elif action == 'confirm_delete': return confirm_bulk_delete(g.filesystem_id, selected_docs) else: abort(400) @view.route('/regenerate-code', methods=('POST',)) @login_required def regenerate_code(): original_journalist_designation = g.source.journalist_designation g.source.journalist_designation = crypto_util.display_id() for item in g.source.collection: item.filename = store.rename_submission( g.filesystem_id, item.filename, g.source.journalist_filename) db_session.commit() flash(gettext( "The source '{original_name}' has been renamed to '{new_name}'") .format(original_name=original_journalist_designation, new_name=g.source.journalist_designation), "notification") return redirect(url_for('col.col', filesystem_id=g.filesystem_id)) @view.route('/download_unread/<filesystem_id>') @login_required def download_unread_filesystem_id(filesystem_id): id = Source.query.filter(Source.filesystem_id == filesystem_id) \ .one().id submissions = Submission.query.filter( Submission.source_id == id, Submission.downloaded == false()).all() if submissions == []: flash(gettext("No unread submissions for this source.")) return redirect(url_for('col.col', filesystem_id=filesystem_id)) source = get_source(filesystem_id) return download(source.journalist_filename, submissions) return view
micahflee/securedrop
securedrop/journalist_app/main.py
Python
agpl-3.0
8,000
#!/usr/bin/env python # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import TestSCons import sys import string import re import time _python_ = TestSCons._python_ test = TestSCons.TestSCons() test.write('sleep_cat.py', """\ import sys import time time.sleep(int(sys.argv[1])) fp = open(sys.argv[2], 'wb') for arg in sys.argv[3:]: fp.write(open(arg, 'rb').read()) fp.close() sys.exit(0) """) test.write('SConstruct', """ env = Environment(PYTHON = r'%(_python_)s', SLEEP_CAT = r'sleep_cat.py', CATCOM = '$PYTHON $SLEEP_CAT $SECONDS $TARGET $SOURCES', SECONDS = ARGUMENTS.get('SLEEP', '0')) f1 = env.Command('f1.out', 'f1.in', '$CATCOM') f2 = env.Command('f2.out', 'f2.in', '$CATCOM') f3 = env.Command('f3.out', 'f3.in', '$CATCOM') f4 = env.Command('f4.out', 'f4.in', '$CATCOM') env.Command('output', [f1, f2, f3, f4], '$CATCOM') """ % locals()) test.write('f1.in', "f1.in\n") test.write('f2.in', "f2.in\n") test.write('f3.in', "f3.in\n") test.write('f4.in', "f4.in\n") def num(s, match): return float(re.search(match, s).group(1)) def within_tolerance(expected, actual, tolerance): return abs((expected-actual)/actual) <= tolerance # Try to make our results a little more accurate and repeatable by # measuring Python overhead executing a minimal file, and reading the # scons.py script itself from disk so that it's already been cached. test.write('pass.py', "pass\n") test.read(test.program) start_time = time.time() test.run(program=TestSCons.python, arguments=test.workpath('pass.py')) overhead = time.time() - start_time start_time = time.time() test.run(arguments = "-j1 --debug=time . SLEEP=0") complete_time = time.time() - start_time expected_total_time = complete_time - overhead pattern = r'Command execution time: (\d+\.\d+) seconds' times = map(float, re.findall(pattern, test.stdout())) expected_command_time = reduce(lambda x, y: x + y, times, 0.0) stdout = test.stdout() total_time = num(stdout, r'Total build time: (\d+\.\d+) seconds') sconscript_time = num(stdout, r'Total SConscript file execution time: (\d+\.\d+) seconds') scons_time = num(stdout, r'Total SCons execution time: (\d+\.\d+) seconds') command_time = num(stdout, r'Total command execution time: (\d+\.\d+) seconds') failures = [] if not within_tolerance(expected_command_time, command_time, 0.01): failures.append("""\ SCons -j1 reported a total command execution time of %(command_time)s, but command execution times really totalled %(expected_command_time)s, outside of the 1%% tolerance. """ % locals()) added_times = sconscript_time+scons_time+command_time if not within_tolerance(total_time, added_times, 0.01): failures.append("""\ SCons -j1 reported a total build time of %(total_time)s, but the various execution times actually totalled %(added_times)s, outside of the 1%% tolerance. """ % locals()) if not within_tolerance(total_time, expected_total_time, 0.15): failures.append("""\ SCons -j1 reported total build time of %(total_time)s, but the actual measured build time was %(expected_total_time)s (end-to-end time of %(complete_time)s less Python overhead of %(overhead)s), outside of the 15%% tolerance. """ % locals()) if failures: print string.join([test.stdout()] + failures, '\n') test.fail_test(1) test.run(arguments = "-c") test.run(arguments = "-j4 --debug=time . SLEEP=1") stdout = test.stdout() total_time = num(stdout, r'Total build time: (\d+\.\d+) seconds') sconscript_time = num(stdout, r'Total SConscript file execution time: (\d+\.\d+) seconds') scons_time = num(stdout, r'Total SCons execution time: (\d+\.\d+) seconds') command_time = num(stdout, r'Total command execution time: (\d+\.\d+) seconds') failures = [] added_times = sconscript_time+scons_time+command_time if not within_tolerance(total_time, added_times, 0.01): failures.append("""\ SCons -j4 reported a total build time of %(total_time)s, but the various execution times actually totalled %(added_times)s, outside of the 1%% tolerance. """ % locals()) if failures: print string.join([test.stdout()] + failures, '\n') test.fail_test(1) test.pass_test()
datalogics/scons
test/option/debug-time.py
Python
mit
5,292
import _plotly_utils.basevalidators class ShowlegendValidator(_plotly_utils.basevalidators.BooleanValidator): def __init__(self, plotly_name="showlegend", parent_name="volume", **kwargs): super(ShowlegendValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), role=kwargs.pop("role", "info"), **kwargs )
plotly/python-api
packages/python/plotly/plotly/validators/volume/_showlegend.py
Python
mit
450
# a waf tool to add autoconf-like macros to the configure section # and for SAMBA_ macros for building libraries, binaries etc import Build, os, sys, Options, Task, Utils, cc, TaskGen, fnmatch, re, shutil, Logs, Constants from Configure import conf from Logs import debug from samba_utils import SUBST_VARS_RECURSIVE TaskGen.task_gen.apply_verif = Utils.nada # bring in the other samba modules from samba_optimisation import * from samba_utils import * from samba_version import * from samba_autoconf import * from samba_patterns import * from samba_pidl import * from samba_autoproto import * from samba_python import * from samba_perl import * from samba_deps import * from samba_bundled import * from samba_third_party import * import samba_cross import samba_install import samba_conftests import samba_abi import samba_headers import tru64cc import irixcc import hpuxcc import generic_cc import samba_dist import samba_wildcard import stale_files import symbols import pkgconfig import configure_file # some systems have broken threading in python if os.environ.get('WAF_NOTHREADS') == '1': import nothreads LIB_PATH="shared" os.environ['PYTHONUNBUFFERED'] = '1' if Constants.HEXVERSION < 0x105019: Logs.error(''' Please use the version of waf that comes with Samba, not a system installed version. See http://wiki.samba.org/index.php/Waf for details. Alternatively, please run ./configure and make as usual. That will call the right version of waf.''') sys.exit(1) @conf def SAMBA_BUILD_ENV(conf): '''create the samba build environment''' conf.env.BUILD_DIRECTORY = conf.blddir mkdir_p(os.path.join(conf.blddir, LIB_PATH)) mkdir_p(os.path.join(conf.blddir, LIB_PATH, "private")) mkdir_p(os.path.join(conf.blddir, "modules")) mkdir_p(os.path.join(conf.blddir, 'python/samba/dcerpc')) # this allows all of the bin/shared and bin/python targets # to be expressed in terms of build directory paths mkdir_p(os.path.join(conf.blddir, 'default')) for (source, target) in [('shared', 'shared'), ('modules', 'modules'), ('python', 'python_modules')]: link_target = os.path.join(conf.blddir, 'default/' + target) if not os.path.lexists(link_target): os.symlink('../' + source, link_target) # get perl to put the blib files in the build directory blib_bld = os.path.join(conf.blddir, 'default/pidl/blib') blib_src = os.path.join(conf.srcdir, 'pidl/blib') mkdir_p(blib_bld + '/man1') mkdir_p(blib_bld + '/man3') if os.path.islink(blib_src): os.unlink(blib_src) elif os.path.exists(blib_src): shutil.rmtree(blib_src) def ADD_INIT_FUNCTION(bld, subsystem, target, init_function): '''add an init_function to the list for a subsystem''' if init_function is None: return bld.ASSERT(subsystem is not None, "You must specify a subsystem for init_function '%s'" % init_function) cache = LOCAL_CACHE(bld, 'INIT_FUNCTIONS') if not subsystem in cache: cache[subsystem] = [] cache[subsystem].append( { 'TARGET':target, 'INIT_FUNCTION':init_function } ) Build.BuildContext.ADD_INIT_FUNCTION = ADD_INIT_FUNCTION def generate_empty_file(task): task.outputs[0].write('') return 0 ################################################################# def SAMBA_LIBRARY(bld, libname, source, deps='', public_deps='', includes='', public_headers=None, public_headers_install=True, private_headers=None, header_path=None, pc_files=None, vnum=None, soname=None, cflags='', ldflags='', external_library=False, realname=None, keep_underscore=False, autoproto=None, autoproto_extra_source='', group='main', depends_on='', local_include=True, global_include=True, vars=None, subdir=None, install_path=None, install=True, pyembed=False, pyext=False, target_type='LIBRARY', bundled_extension=False, bundled_name=None, link_name=None, abi_directory=None, abi_match=None, hide_symbols=False, manpages=None, private_library=False, grouping_library=False, allow_undefined_symbols=False, allow_warnings=False, enabled=True): '''define a Samba library''' if pyembed and bld.env['IS_EXTRA_PYTHON']: public_headers = None if private_library and public_headers: raise Utils.WafError("private library '%s' must not have public header files" % libname) if LIB_MUST_BE_PRIVATE(bld, libname): private_library = True if not enabled: SET_TARGET_TYPE(bld, libname, 'DISABLED') return source = bld.EXPAND_VARIABLES(source, vars=vars) if subdir: source = bld.SUBDIR(subdir, source) # remember empty libraries, so we can strip the dependencies if ((source == '') or (source == [])): if deps == '' and public_deps == '': SET_TARGET_TYPE(bld, libname, 'EMPTY') return empty_c = libname + '.empty.c' bld.SAMBA_GENERATOR('%s_empty_c' % libname, rule=generate_empty_file, target=empty_c) source=empty_c if BUILTIN_LIBRARY(bld, libname): obj_target = libname else: obj_target = libname + '.objlist' if group == 'libraries': subsystem_group = 'main' else: subsystem_group = group # first create a target for building the object files for this library # by separating in this way, we avoid recompiling the C files # separately for the install library and the build library bld.SAMBA_SUBSYSTEM(obj_target, source = source, deps = deps, public_deps = public_deps, includes = includes, public_headers = public_headers, public_headers_install = public_headers_install, private_headers= private_headers, header_path = header_path, cflags = cflags, group = subsystem_group, autoproto = autoproto, autoproto_extra_source=autoproto_extra_source, depends_on = depends_on, hide_symbols = hide_symbols, allow_warnings = allow_warnings, pyembed = pyembed, pyext = pyext, local_include = local_include, global_include = global_include) if BUILTIN_LIBRARY(bld, libname): return if not SET_TARGET_TYPE(bld, libname, target_type): return # the library itself will depend on that object target deps += ' ' + public_deps deps = TO_LIST(deps) deps.append(obj_target) realname = bld.map_shlib_extension(realname, python=(target_type=='PYTHON')) link_name = bld.map_shlib_extension(link_name, python=(target_type=='PYTHON')) # we don't want any public libraries without version numbers if (not private_library and target_type != 'PYTHON' and not realname): if vnum is None and soname is None: raise Utils.WafError("public library '%s' must have a vnum" % libname) if pc_files is None: raise Utils.WafError("public library '%s' must have pkg-config file" % libname) if public_headers is None and not bld.env['IS_EXTRA_PYTHON']: raise Utils.WafError("public library '%s' must have header files" % libname) if bundled_name is not None: pass elif target_type == 'PYTHON' or realname or not private_library: if keep_underscore: bundled_name = libname else: bundled_name = libname.replace('_', '-') else: assert (private_library == True and realname is None) if abi_directory or vnum or soname: bundled_extension=True bundled_name = PRIVATE_NAME(bld, libname.replace('_', '-'), bundled_extension, private_library) ldflags = TO_LIST(ldflags) if bld.env['ENABLE_RELRO'] is True: ldflags.extend(TO_LIST('-Wl,-z,relro,-z,now')) features = 'c cshlib symlink_lib install_lib' if pyext: features += ' pyext' if pyembed: features += ' pyembed' if abi_directory: features += ' abi_check' if pyembed and bld.env['PYTHON_SO_ABI_FLAG']: # For ABI checking, we don't care about the exact Python version. # Replace the Python ABI tag (e.g. ".cpython-35m") by a generic ".py3" abi_flag = bld.env['PYTHON_SO_ABI_FLAG'] replacement = '.py%s' % bld.env['PYTHON_VERSION'].split('.')[0] version_libname = libname.replace(abi_flag, replacement) else: version_libname = libname vscript = None if bld.env.HAVE_LD_VERSION_SCRIPT: if private_library: version = "%s_%s" % (Utils.g_module.APPNAME, Utils.g_module.VERSION) elif vnum: version = "%s_%s" % (libname, vnum) else: version = None if version: vscript = "%s.vscript" % libname bld.ABI_VSCRIPT(version_libname, abi_directory, version, vscript, abi_match) fullname = apply_pattern(bundled_name, bld.env.shlib_PATTERN) fullpath = bld.path.find_or_declare(fullname) vscriptpath = bld.path.find_or_declare(vscript) if not fullpath: raise Utils.WafError("unable to find fullpath for %s" % fullname) if not vscriptpath: raise Utils.WafError("unable to find vscript path for %s" % vscript) bld.add_manual_dependency(fullpath, vscriptpath) if bld.is_install: # also make the .inst file depend on the vscript instname = apply_pattern(bundled_name + '.inst', bld.env.shlib_PATTERN) bld.add_manual_dependency(bld.path.find_or_declare(instname), bld.path.find_or_declare(vscript)) vscript = os.path.join(bld.path.abspath(bld.env), vscript) bld.SET_BUILD_GROUP(group) t = bld( features = features, source = [], target = bundled_name, depends_on = depends_on, samba_ldflags = ldflags, samba_deps = deps, samba_includes = includes, version_script = vscript, version_libname = version_libname, local_include = local_include, global_include = global_include, vnum = vnum, soname = soname, install_path = None, samba_inst_path = install_path, name = libname, samba_realname = realname, samba_install = install, abi_directory = "%s/%s" % (bld.path.abspath(), abi_directory), abi_match = abi_match, private_library = private_library, grouping_library=grouping_library, allow_undefined_symbols=allow_undefined_symbols ) if realname and not link_name: link_name = 'shared/%s' % realname if link_name: t.link_name = link_name if pc_files is not None and not private_library: if pyembed and bld.env['IS_EXTRA_PYTHON']: bld.PKG_CONFIG_FILES(pc_files, vnum=vnum, extra_name=bld.env['PYTHON_SO_ABI_FLAG']) else: bld.PKG_CONFIG_FILES(pc_files, vnum=vnum) if (manpages is not None and 'XSLTPROC_MANPAGES' in bld.env and bld.env['XSLTPROC_MANPAGES']): bld.MANPAGES(manpages, install) Build.BuildContext.SAMBA_LIBRARY = SAMBA_LIBRARY ################################################################# def SAMBA_BINARY(bld, binname, source, deps='', includes='', public_headers=None, private_headers=None, header_path=None, modules=None, ldflags=None, cflags='', autoproto=None, use_hostcc=False, use_global_deps=True, compiler=None, group='main', manpages=None, local_include=True, global_include=True, subsystem_name=None, pyembed=False, vars=None, subdir=None, install=True, install_path=None, enabled=True): '''define a Samba binary''' if not enabled: SET_TARGET_TYPE(bld, binname, 'DISABLED') return if not SET_TARGET_TYPE(bld, binname, 'BINARY'): return features = 'c cprogram symlink_bin install_bin' if pyembed: features += ' pyembed' obj_target = binname + '.objlist' source = bld.EXPAND_VARIABLES(source, vars=vars) if subdir: source = bld.SUBDIR(subdir, source) source = unique_list(TO_LIST(source)) if group == 'binaries': subsystem_group = 'main' else: subsystem_group = group # only specify PIE flags for binaries pie_cflags = cflags pie_ldflags = TO_LIST(ldflags) if bld.env['ENABLE_PIE'] is True: pie_cflags += ' -fPIE' pie_ldflags.extend(TO_LIST('-pie')) if bld.env['ENABLE_RELRO'] is True: pie_ldflags.extend(TO_LIST('-Wl,-z,relro,-z,now')) # first create a target for building the object files for this binary # by separating in this way, we avoid recompiling the C files # separately for the install binary and the build binary bld.SAMBA_SUBSYSTEM(obj_target, source = source, deps = deps, includes = includes, cflags = pie_cflags, group = subsystem_group, autoproto = autoproto, subsystem_name = subsystem_name, local_include = local_include, global_include = global_include, use_hostcc = use_hostcc, pyext = pyembed, use_global_deps= use_global_deps) bld.SET_BUILD_GROUP(group) # the binary itself will depend on that object target deps = TO_LIST(deps) deps.append(obj_target) t = bld( features = features, source = [], target = binname, samba_deps = deps, samba_includes = includes, local_include = local_include, global_include = global_include, samba_modules = modules, top = True, samba_subsystem= subsystem_name, install_path = None, samba_inst_path= install_path, samba_install = install, samba_ldflags = pie_ldflags ) if manpages is not None and 'XSLTPROC_MANPAGES' in bld.env and bld.env['XSLTPROC_MANPAGES']: bld.MANPAGES(manpages, install) Build.BuildContext.SAMBA_BINARY = SAMBA_BINARY ################################################################# def SAMBA_MODULE(bld, modname, source, deps='', includes='', subsystem=None, init_function=None, module_init_name='samba_init_module', autoproto=None, autoproto_extra_source='', cflags='', internal_module=True, local_include=True, global_include=True, vars=None, subdir=None, enabled=True, pyembed=False, manpages=None, allow_undefined_symbols=False, allow_warnings=False, install=True ): '''define a Samba module.''' bld.ASSERT(subsystem, "You must specify a subsystem for SAMBA_MODULE(%s)" % modname) source = bld.EXPAND_VARIABLES(source, vars=vars) if subdir: source = bld.SUBDIR(subdir, source) if internal_module or BUILTIN_LIBRARY(bld, modname): # Do not create modules for disabled subsystems if GET_TARGET_TYPE(bld, subsystem) == 'DISABLED': return bld.SAMBA_SUBSYSTEM(modname, source, deps=deps, includes=includes, autoproto=autoproto, autoproto_extra_source=autoproto_extra_source, cflags=cflags, local_include=local_include, global_include=global_include, allow_warnings=allow_warnings, enabled=enabled) bld.ADD_INIT_FUNCTION(subsystem, modname, init_function) return if not enabled: SET_TARGET_TYPE(bld, modname, 'DISABLED') return # Do not create modules for disabled subsystems if GET_TARGET_TYPE(bld, subsystem) == 'DISABLED': return realname = modname deps += ' ' + subsystem while realname.startswith("lib"+subsystem+"_"): realname = realname[len("lib"+subsystem+"_"):] while realname.startswith(subsystem+"_"): realname = realname[len(subsystem+"_"):] build_name = "%s_module_%s" % (subsystem, realname) realname = bld.make_libname(realname) while realname.startswith("lib"): realname = realname[len("lib"):] build_link_name = "modules/%s/%s" % (subsystem, realname) if init_function: cflags += " -D%s=%s" % (init_function, module_init_name) bld.SAMBA_LIBRARY(modname, source, deps=deps, includes=includes, cflags=cflags, realname = realname, autoproto = autoproto, local_include=local_include, global_include=global_include, vars=vars, bundled_name=build_name, link_name=build_link_name, install_path="${MODULESDIR}/%s" % subsystem, pyembed=pyembed, manpages=manpages, allow_undefined_symbols=allow_undefined_symbols, allow_warnings=allow_warnings, install=install ) Build.BuildContext.SAMBA_MODULE = SAMBA_MODULE ################################################################# def SAMBA_SUBSYSTEM(bld, modname, source, deps='', public_deps='', includes='', public_headers=None, public_headers_install=True, private_headers=None, header_path=None, cflags='', cflags_end=None, group='main', init_function_sentinel=None, autoproto=None, autoproto_extra_source='', depends_on='', local_include=True, local_include_first=True, global_include=True, subsystem_name=None, enabled=True, use_hostcc=False, use_global_deps=True, vars=None, subdir=None, hide_symbols=False, allow_warnings=False, pyext=False, pyembed=False): '''define a Samba subsystem''' if not enabled: SET_TARGET_TYPE(bld, modname, 'DISABLED') return # remember empty subsystems, so we can strip the dependencies if ((source == '') or (source == [])): if deps == '' and public_deps == '': SET_TARGET_TYPE(bld, modname, 'EMPTY') return empty_c = modname + '.empty.c' bld.SAMBA_GENERATOR('%s_empty_c' % modname, rule=generate_empty_file, target=empty_c) source=empty_c if not SET_TARGET_TYPE(bld, modname, 'SUBSYSTEM'): return source = bld.EXPAND_VARIABLES(source, vars=vars) if subdir: source = bld.SUBDIR(subdir, source) source = unique_list(TO_LIST(source)) deps += ' ' + public_deps bld.SET_BUILD_GROUP(group) features = 'c' if pyext: features += ' pyext' if pyembed: features += ' pyembed' t = bld( features = features, source = source, target = modname, samba_cflags = CURRENT_CFLAGS(bld, modname, cflags, allow_warnings=allow_warnings, hide_symbols=hide_symbols), depends_on = depends_on, samba_deps = TO_LIST(deps), samba_includes = includes, local_include = local_include, local_include_first = local_include_first, global_include = global_include, samba_subsystem= subsystem_name, samba_use_hostcc = use_hostcc, samba_use_global_deps = use_global_deps, ) if cflags_end is not None: t.samba_cflags.extend(TO_LIST(cflags_end)) if autoproto is not None: bld.SAMBA_AUTOPROTO(autoproto, source + TO_LIST(autoproto_extra_source)) if public_headers is not None: bld.PUBLIC_HEADERS(public_headers, header_path=header_path, public_headers_install=public_headers_install) return t Build.BuildContext.SAMBA_SUBSYSTEM = SAMBA_SUBSYSTEM def SAMBA_GENERATOR(bld, name, rule, source='', target='', group='generators', enabled=True, public_headers=None, public_headers_install=True, private_headers=None, header_path=None, vars=None, dep_vars=[], always=False): '''A generic source generator target''' if not SET_TARGET_TYPE(bld, name, 'GENERATOR'): return if not enabled: return dep_vars.append('ruledeps') dep_vars.append('SAMBA_GENERATOR_VARS') bld.SET_BUILD_GROUP(group) t = bld( rule=rule, source=bld.EXPAND_VARIABLES(source, vars=vars), target=target, shell=isinstance(rule, str), update_outputs=True, before='cc', ext_out='.c', samba_type='GENERATOR', dep_vars = dep_vars, name=name) if vars is None: vars = {} t.env.SAMBA_GENERATOR_VARS = vars if always: t.always = True if public_headers is not None: bld.PUBLIC_HEADERS(public_headers, header_path=header_path, public_headers_install=public_headers_install) return t Build.BuildContext.SAMBA_GENERATOR = SAMBA_GENERATOR @Utils.run_once def SETUP_BUILD_GROUPS(bld): '''setup build groups used to ensure that the different build phases happen consecutively''' bld.p_ln = bld.srcnode # we do want to see all targets! bld.env['USING_BUILD_GROUPS'] = True bld.add_group('setup') bld.add_group('build_compiler_source') bld.add_group('vscripts') bld.add_group('base_libraries') bld.add_group('generators') bld.add_group('compiler_prototypes') bld.add_group('compiler_libraries') bld.add_group('build_compilers') bld.add_group('build_source') bld.add_group('prototypes') bld.add_group('headers') bld.add_group('main') bld.add_group('symbolcheck') bld.add_group('syslibcheck') bld.add_group('final') Build.BuildContext.SETUP_BUILD_GROUPS = SETUP_BUILD_GROUPS def SET_BUILD_GROUP(bld, group): '''set the current build group''' if not 'USING_BUILD_GROUPS' in bld.env: return bld.set_group(group) Build.BuildContext.SET_BUILD_GROUP = SET_BUILD_GROUP @conf def ENABLE_TIMESTAMP_DEPENDENCIES(conf): """use timestamps instead of file contents for deps this currently doesn't work""" def h_file(filename): import stat st = os.stat(filename) if stat.S_ISDIR(st[stat.ST_MODE]): raise IOError('not a file') m = Utils.md5() m.update(str(st.st_mtime)) m.update(str(st.st_size)) m.update(filename) return m.digest() Utils.h_file = h_file def SAMBA_SCRIPT(bld, name, pattern, installdir, installname=None): '''used to copy scripts from the source tree into the build directory for use by selftest''' source = bld.path.ant_glob(pattern, flat=True) bld.SET_BUILD_GROUP('build_source') for s in TO_LIST(source): iname = s if installname is not None: iname = installname target = os.path.join(installdir, iname) tgtdir = os.path.dirname(os.path.join(bld.srcnode.abspath(bld.env), '..', target)) mkdir_p(tgtdir) link_src = os.path.normpath(os.path.join(bld.curdir, s)) link_dst = os.path.join(tgtdir, os.path.basename(iname)) if os.path.islink(link_dst) and os.readlink(link_dst) == link_src: continue if os.path.exists(link_dst): os.unlink(link_dst) Logs.info("symlink: %s -> %s/%s" % (s, installdir, iname)) os.symlink(link_src, link_dst) Build.BuildContext.SAMBA_SCRIPT = SAMBA_SCRIPT def copy_and_fix_python_path(task): pattern='sys.path.insert(0, "bin/python")' if task.env["PYTHONARCHDIR"] in sys.path and task.env["PYTHONDIR"] in sys.path: replacement = "" elif task.env["PYTHONARCHDIR"] == task.env["PYTHONDIR"]: replacement="""sys.path.insert(0, "%s")""" % task.env["PYTHONDIR"] else: replacement="""sys.path.insert(0, "%s") sys.path.insert(1, "%s")""" % (task.env["PYTHONARCHDIR"], task.env["PYTHONDIR"]) if task.env["PYTHON"][0] == "/": replacement_shebang = "#!%s\n" % task.env["PYTHON"] else: replacement_shebang = "#!/usr/bin/env %s\n" % task.env["PYTHON"] installed_location=task.outputs[0].bldpath(task.env) source_file = open(task.inputs[0].srcpath(task.env)) installed_file = open(installed_location, 'w') lineno = 0 for line in source_file: newline = line if (lineno == 0 and task.env["PYTHON_SPECIFIED"] is True and line[:2] == "#!"): newline = replacement_shebang elif pattern in line: newline = line.replace(pattern, replacement) installed_file.write(newline) lineno = lineno + 1 installed_file.close() os.chmod(installed_location, 0755) return 0 def copy_and_fix_perl_path(task): pattern='use lib "$RealBin/lib";' replacement = "" if not task.env["PERL_LIB_INSTALL_DIR"] in task.env["PERL_INC"]: replacement = 'use lib "%s";' % task.env["PERL_LIB_INSTALL_DIR"] if task.env["PERL"][0] == "/": replacement_shebang = "#!%s\n" % task.env["PERL"] else: replacement_shebang = "#!/usr/bin/env %s\n" % task.env["PERL"] installed_location=task.outputs[0].bldpath(task.env) source_file = open(task.inputs[0].srcpath(task.env)) installed_file = open(installed_location, 'w') lineno = 0 for line in source_file: newline = line if lineno == 0 and task.env["PERL_SPECIFIED"] == True and line[:2] == "#!": newline = replacement_shebang elif pattern in line: newline = line.replace(pattern, replacement) installed_file.write(newline) lineno = lineno + 1 installed_file.close() os.chmod(installed_location, 0755) return 0 def install_file(bld, destdir, file, chmod=MODE_644, flat=False, python_fixup=False, perl_fixup=False, destname=None, base_name=None): '''install a file''' destdir = bld.EXPAND_VARIABLES(destdir) if not destname: destname = file if flat: destname = os.path.basename(destname) dest = os.path.join(destdir, destname) if python_fixup: # fix the path python will use to find Samba modules inst_file = file + '.inst' bld.SAMBA_GENERATOR('python_%s' % destname, rule=copy_and_fix_python_path, dep_vars=["PYTHON","PYTHON_SPECIFIED","PYTHONDIR","PYTHONARCHDIR"], source=file, target=inst_file) file = inst_file if perl_fixup: # fix the path perl will use to find Samba modules inst_file = file + '.inst' bld.SAMBA_GENERATOR('perl_%s' % destname, rule=copy_and_fix_perl_path, dep_vars=["PERL","PERL_SPECIFIED","PERL_LIB_INSTALL_DIR"], source=file, target=inst_file) file = inst_file if base_name: file = os.path.join(base_name, file) bld.install_as(dest, file, chmod=chmod) def INSTALL_FILES(bld, destdir, files, chmod=MODE_644, flat=False, python_fixup=False, perl_fixup=False, destname=None, base_name=None): '''install a set of files''' for f in TO_LIST(files): install_file(bld, destdir, f, chmod=chmod, flat=flat, python_fixup=python_fixup, perl_fixup=perl_fixup, destname=destname, base_name=base_name) Build.BuildContext.INSTALL_FILES = INSTALL_FILES def INSTALL_WILDCARD(bld, destdir, pattern, chmod=MODE_644, flat=False, python_fixup=False, exclude=None, trim_path=None): '''install a set of files matching a wildcard pattern''' files=TO_LIST(bld.path.ant_glob(pattern, flat=True)) if trim_path: files2 = [] for f in files: files2.append(os_path_relpath(f, trim_path)) files = files2 if exclude: for f in files[:]: if fnmatch.fnmatch(f, exclude): files.remove(f) INSTALL_FILES(bld, destdir, files, chmod=chmod, flat=flat, python_fixup=python_fixup, base_name=trim_path) Build.BuildContext.INSTALL_WILDCARD = INSTALL_WILDCARD def INSTALL_DIRS(bld, destdir, dirs): '''install a set of directories''' destdir = bld.EXPAND_VARIABLES(destdir) dirs = bld.EXPAND_VARIABLES(dirs) for d in TO_LIST(dirs): bld.install_dir(os.path.join(destdir, d)) Build.BuildContext.INSTALL_DIRS = INSTALL_DIRS def MANPAGES(bld, manpages, install): '''build and install manual pages''' bld.env.MAN_XSL = 'http://docbook.sourceforge.net/release/xsl/current/manpages/docbook.xsl' for m in manpages.split(): source = m + '.xml' bld.SAMBA_GENERATOR(m, source=source, target=m, group='final', rule='${XSLTPROC} --xinclude -o ${TGT} --nonet ${MAN_XSL} ${SRC}' ) if install: bld.INSTALL_FILES('${MANDIR}/man%s' % m[-1], m, flat=True) Build.BuildContext.MANPAGES = MANPAGES def SAMBAMANPAGES(bld, manpages, extra_source=None): '''build and install manual pages''' bld.env.SAMBA_EXPAND_XSL = bld.srcnode.abspath() + '/docs-xml/xslt/expand-sambadoc.xsl' bld.env.SAMBA_MAN_XSL = bld.srcnode.abspath() + '/docs-xml/xslt/man.xsl' bld.env.SAMBA_CATALOG = bld.srcnode.abspath() + '/bin/default/docs-xml/build/catalog.xml' bld.env.SAMBA_CATALOGS = 'file:///usr/local/share/xml/catalog file://' + bld.srcnode.abspath() + '/bin/default/docs-xml/build/catalog.xml' for m in manpages.split(): source = m + '.xml' if extra_source is not None: source = [source, extra_source] bld.SAMBA_GENERATOR(m, source=source, target=m, group='final', dep_vars=['SAMBA_MAN_XSL', 'SAMBA_EXPAND_XSL', 'SAMBA_CATALOG'], rule='''XML_CATALOG_FILES="${SAMBA_CATALOGS}" export XML_CATALOG_FILES ${XSLTPROC} --xinclude --stringparam noreference 0 -o ${TGT}.xml --nonet ${SAMBA_EXPAND_XSL} ${SRC[0].abspath(env)} ${XSLTPROC} --nonet -o ${TGT} ${SAMBA_MAN_XSL} ${TGT}.xml''' ) bld.INSTALL_FILES('${MANDIR}/man%s' % m[-1], m, flat=True) Build.BuildContext.SAMBAMANPAGES = SAMBAMANPAGES ############################################################# # give a nicer display when building different types of files def progress_display(self, msg, fname): col1 = Logs.colors(self.color) col2 = Logs.colors.NORMAL total = self.position[1] n = len(str(total)) fs = '[%%%dd/%%%dd] %s %%s%%s%%s\n' % (n, n, msg) return fs % (self.position[0], self.position[1], col1, fname, col2) def link_display(self): if Options.options.progress_bar != 0: return Task.Task.old_display(self) fname = self.outputs[0].bldpath(self.env) return progress_display(self, 'Linking', fname) Task.TaskBase.classes['cc_link'].display = link_display def samba_display(self): if Options.options.progress_bar != 0: return Task.Task.old_display(self) targets = LOCAL_CACHE(self, 'TARGET_TYPE') if self.name in targets: target_type = targets[self.name] type_map = { 'GENERATOR' : 'Generating', 'PROTOTYPE' : 'Generating' } if target_type in type_map: return progress_display(self, type_map[target_type], self.name) if len(self.inputs) == 0: return Task.Task.old_display(self) fname = self.inputs[0].bldpath(self.env) if fname[0:3] == '../': fname = fname[3:] ext_loc = fname.rfind('.') if ext_loc == -1: return Task.Task.old_display(self) ext = fname[ext_loc:] ext_map = { '.idl' : 'Compiling IDL', '.et' : 'Compiling ERRTABLE', '.asn1': 'Compiling ASN1', '.c' : 'Compiling' } if ext in ext_map: return progress_display(self, ext_map[ext], fname) return Task.Task.old_display(self) Task.TaskBase.classes['Task'].old_display = Task.TaskBase.classes['Task'].display Task.TaskBase.classes['Task'].display = samba_display @after('apply_link') @feature('cshlib') def apply_bundle_remove_dynamiclib_patch(self): if self.env['MACBUNDLE'] or getattr(self,'mac_bundle',False): if not getattr(self,'vnum',None): try: self.env['LINKFLAGS'].remove('-dynamiclib') self.env['LINKFLAGS'].remove('-single_module') except ValueError: pass
freenas/samba
buildtools/wafsamba/wafsamba.py
Python
gpl-3.0
35,849
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'add_body_dialog.ui', # licensing of 'add_body_dialog.ui' applies. # # Created: Tue Aug 7 17:47:07 2018 # by: pyside2-uic running on PySide2 5.11.0 # # WARNING! All changes made in this file will be lost! from PySide2 import QtCore, QtGui, QtWidgets class Ui_AddBodyDialog(object): def setupUi(self, AddBodyDialog): AddBodyDialog.setObjectName("AddBodyDialog") AddBodyDialog.resize(465, 467) self.verticalLayout = QtWidgets.QVBoxLayout(AddBodyDialog) self.verticalLayout.setObjectName("verticalLayout") self.unitsLabel = QtWidgets.QLabel(AddBodyDialog) self.unitsLabel.setObjectName("unitsLabel") self.verticalLayout.addWidget(self.unitsLabel) self.bodyInfoBox = QtWidgets.QGroupBox(AddBodyDialog) self.bodyInfoBox.setObjectName("bodyInfoBox") self.formLayout = QtWidgets.QFormLayout(self.bodyInfoBox) self.formLayout.setObjectName("formLayout") self.nameEdit = QtWidgets.QLineEdit(self.bodyInfoBox) self.nameEdit.setObjectName("nameEdit") self.formLayout.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.nameEdit) self.nameLabel = QtWidgets.QLabel(self.bodyInfoBox) self.nameLabel.setObjectName("nameLabel") self.formLayout.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.nameLabel) self.massLabel = QtWidgets.QLabel(self.bodyInfoBox) self.massLabel.setObjectName("massLabel") self.formLayout.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.massLabel) self.massEdit = QtWidgets.QLineEdit(self.bodyInfoBox) self.massEdit.setObjectName("massEdit") self.formLayout.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.massEdit) self.verticalLayout.addWidget(self.bodyInfoBox) self.orbitInfoBox = QtWidgets.QGroupBox(AddBodyDialog) self.orbitInfoBox.setEnabled(False) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(1) sizePolicy.setHeightForWidth(self.orbitInfoBox.sizePolicy().hasHeightForWidth()) self.orbitInfoBox.setSizePolicy(sizePolicy) self.orbitInfoBox.setObjectName("orbitInfoBox") self.formLayout_2 = QtWidgets.QFormLayout(self.orbitInfoBox) self.formLayout_2.setObjectName("formLayout_2") self.parentNameLabel = QtWidgets.QLabel(self.orbitInfoBox) self.parentNameLabel.setObjectName("parentNameLabel") self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.parentNameLabel) self.parentBodySelectorBox = QtWidgets.QComboBox(self.orbitInfoBox) self.parentBodySelectorBox.setObjectName("parentBodySelectorBox") self.formLayout_2.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.parentBodySelectorBox) self.semiMajorAxisLabel = QtWidgets.QLabel(self.orbitInfoBox) self.semiMajorAxisLabel.setObjectName("semiMajorAxisLabel") self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.semiMajorAxisLabel) self.semiMajorAxisEdit = QtWidgets.QLineEdit(self.orbitInfoBox) self.semiMajorAxisEdit.setObjectName("semiMajorAxisEdit") self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.semiMajorAxisEdit) self.eccentricityLabel = QtWidgets.QLabel(self.orbitInfoBox) self.eccentricityLabel.setObjectName("eccentricityLabel") self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.eccentricityLabel) self.eccentricitySpinBox = QtWidgets.QDoubleSpinBox(self.orbitInfoBox) self.eccentricitySpinBox.setMaximum(10000.0) self.eccentricitySpinBox.setObjectName("eccentricitySpinBox") self.formLayout_2.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.eccentricitySpinBox) self.inclinationLabel = QtWidgets.QLabel(self.orbitInfoBox) self.inclinationLabel.setObjectName("inclinationLabel") self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.inclinationLabel) self.inclinationSpinBox = QtWidgets.QDoubleSpinBox(self.orbitInfoBox) self.inclinationSpinBox.setMinimum(-180.0) self.inclinationSpinBox.setMaximum(180.0) self.inclinationSpinBox.setObjectName("inclinationSpinBox") self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.inclinationSpinBox) self.longitudeAscNodeLabel = QtWidgets.QLabel(self.orbitInfoBox) self.longitudeAscNodeLabel.setObjectName("longitudeAscNodeLabel") self.formLayout_2.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.longitudeAscNodeLabel) self.longitudeAscNodeSpinBox = QtWidgets.QDoubleSpinBox(self.orbitInfoBox) self.longitudeAscNodeSpinBox.setMinimum(-180.0) self.longitudeAscNodeSpinBox.setMaximum(180.0) self.longitudeAscNodeSpinBox.setObjectName("longitudeAscNodeSpinBox") self.formLayout_2.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.longitudeAscNodeSpinBox) self.argOfPeriapsisLabel = QtWidgets.QLabel(self.orbitInfoBox) self.argOfPeriapsisLabel.setObjectName("argOfPeriapsisLabel") self.formLayout_2.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.argOfPeriapsisLabel) self.argOfPeriapsisSpinBox = QtWidgets.QDoubleSpinBox(self.orbitInfoBox) self.argOfPeriapsisSpinBox.setMinimum(-180.0) self.argOfPeriapsisSpinBox.setMaximum(180.0) self.argOfPeriapsisSpinBox.setObjectName("argOfPeriapsisSpinBox") self.formLayout_2.setWidget(6, QtWidgets.QFormLayout.FieldRole, self.argOfPeriapsisSpinBox) self.meanAnomalyLabel = QtWidgets.QLabel(self.orbitInfoBox) self.meanAnomalyLabel.setObjectName("meanAnomalyLabel") self.formLayout_2.setWidget(7, QtWidgets.QFormLayout.LabelRole, self.meanAnomalyLabel) self.meanAnomalySpinBox = QtWidgets.QDoubleSpinBox(self.orbitInfoBox) self.meanAnomalySpinBox.setMinimum(-180.0) self.meanAnomalySpinBox.setMaximum(180.0) self.meanAnomalySpinBox.setObjectName("meanAnomalySpinBox") self.formLayout_2.setWidget(7, QtWidgets.QFormLayout.FieldRole, self.meanAnomalySpinBox) self.celestialBodyBox = QtWidgets.QCheckBox(self.orbitInfoBox) self.celestialBodyBox.setChecked(True) self.celestialBodyBox.setObjectName("celestialBodyBox") self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.celestialBodyBox) self.verticalLayout.addWidget(self.orbitInfoBox) self.buttonBox = QtWidgets.QDialogButtonBox(AddBodyDialog) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok) self.buttonBox.setObjectName("buttonBox") self.verticalLayout.addWidget(self.buttonBox) self.retranslateUi(AddBodyDialog) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), AddBodyDialog.accept) QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), AddBodyDialog.reject) QtCore.QMetaObject.connectSlotsByName(AddBodyDialog) def retranslateUi(self, AddBodyDialog): AddBodyDialog.setWindowTitle(QtWidgets.QApplication.translate("AddBodyDialog", "Dialog", None, -1)) self.unitsLabel.setText(QtWidgets.QApplication.translate("AddBodyDialog", "All Units are MKS (Meters, Kilograms, Seconds); Angles are degrees (-180 .. 180) ", None, -1)) self.bodyInfoBox.setTitle(QtWidgets.QApplication.translate("AddBodyDialog", "Body Info", None, -1)) self.nameLabel.setText(QtWidgets.QApplication.translate("AddBodyDialog", "Name", None, -1)) self.massLabel.setText(QtWidgets.QApplication.translate("AddBodyDialog", "Mass", None, -1)) self.massEdit.setPlaceholderText(QtWidgets.QApplication.translate("AddBodyDialog", "kg", None, -1)) self.orbitInfoBox.setTitle(QtWidgets.QApplication.translate("AddBodyDialog", "Orbit Info", None, -1)) self.parentNameLabel.setText(QtWidgets.QApplication.translate("AddBodyDialog", "Parent Name", None, -1)) self.semiMajorAxisLabel.setText(QtWidgets.QApplication.translate("AddBodyDialog", "Semi Major Axis", None, -1)) self.eccentricityLabel.setText(QtWidgets.QApplication.translate("AddBodyDialog", "Eccentricity", None, -1)) self.inclinationLabel.setText(QtWidgets.QApplication.translate("AddBodyDialog", "Inclination", None, -1)) self.longitudeAscNodeLabel.setText(QtWidgets.QApplication.translate("AddBodyDialog", "Longitude of Asc. Node", None, -1)) self.argOfPeriapsisLabel.setText(QtWidgets.QApplication.translate("AddBodyDialog", "Argument of Periapsis", None, -1)) self.meanAnomalyLabel.setText(QtWidgets.QApplication.translate("AddBodyDialog", "Mean Anomaly at Epoch", None, -1)) self.celestialBodyBox.setText(QtWidgets.QApplication.translate("AddBodyDialog", "Celestial Body", None, -1))
shavera/Davidian
Astrolabe/system_ui/ui_add_body_dialog.py
Python
gpl-2.0
9,113
#!/usr/bin/python # -*- coding: utf-8 -*- from gui.dwidgets import DMenu class SettingsMenu(DMenu): """docstring for SettingsMenu""" def __init__(self, parent=None): super(SettingsMenu, self).__init__(parent) self.parent = parent self.menuItems = [ { 'name': self.tr('Login'), 'icon': u'', 'shortcut': u'', 'trigger': 'Login', }, { 'name': self.tr('Show suspension window'), 'icon': u'', 'shortcut': u'', 'trigger': 'Suspension', }, { 'name': self.tr('Show float window'), 'icon': u'', 'shortcut': u'', 'trigger': 'Float', }, { 'name': self.tr('Show Dock window'), 'icon': u'', 'shortcut': u'', 'trigger': 'Dock', }, { 'name': self.tr('Language'), 'trigger': 'Language', 'type': 'submenu', 'actions': [ { 'name': 'English', 'icon': u'', 'shortcut': u'', 'trigger': 'English', "checkable": True }, { 'name': 'Chinese', 'icon': u'', 'shortcut': u'', 'trigger': 'Chinese', "checkable": True }, ] }, { 'name': self.tr('Document'), 'trigger': 'Document', 'type': 'submenu', 'actions': [ { 'name': 'Android developer guide', 'icon': u'', 'shortcut': u'', 'trigger': 'AndroidDeveloper', "checkable": False }, { 'name': 'iOS developer guide', 'icon': u'', 'shortcut': u'', 'trigger': 'IOSDeveloper', "checkable": False }, { 'name': 'Ford developer center', 'icon': u'', 'shortcut': u'', 'trigger': 'FordDeveloper', "checkable": False }, ] }, { 'name': self.tr('ObjectView'), 'icon': u'', 'shortcut': u'', 'trigger': 'ObjectView', }, { 'name': self.tr('About'), 'icon': u'', 'shortcut': u'Qt.Key_F12', 'trigger': 'About', }, { 'name': self.tr('Exit'), 'icon': u'', 'shortcut': u'', 'trigger': 'Exit', }, ] self.creatMenus(self.menuItems) self.initConnect() getattr(self, '%sAction' % 'English').setChecked(True) def initConnect(self): for item in ['English', 'Chinese']: getattr(self, '%sAction' % item).triggered.connect(self.updateChecked) def updateChecked(self): for item in ['English', 'Chinese']: action = getattr(self, '%sAction' % item) if self.sender() is action: action.setChecked(True) else: action.setChecked(False)
dragondjf/musicplayer
gui/menus/settingsmenu.py
Python
gpl-2.0
3,819
"""CherryPy tools. A "tool" is any helper, adapted to CP. Tools are usually designed to be used in a variety of ways (although some may only offer one if they choose): Library calls: All tools are callables that can be used wherever needed. The arguments are straightforward and should be detailed within the docstring. Function decorators: All tools, when called, may be used as decorators which configure individual CherryPy page handlers (methods on the CherryPy tree). That is, "@tools.anytool()" should "turn on" the tool via the decorated function's _cp_config attribute. CherryPy config: If a tool exposes a "_setup" callable, it will be called once per Request (if the feature is "turned on" via config). Tools may be implemented as any object with a namespace. The builtins are generally either modules or instances of the tools.Tool class. """ import cherrypy import warnings def _getargs(func): """Return the names of all static arguments to the given function.""" # Use this instead of importing inspect for less mem overhead. import types if isinstance(func, types.MethodType): func = func.im_func co = func.func_code return co.co_varnames[:co.co_argcount] _attr_error = ("CherryPy Tools cannot be turned on directly. Instead, turn them " "on via config, or use them as decorators on your page handlers.") class Tool(object): """A registered function for use with CherryPy request-processing hooks. help(tool.callable) should give you more information about this Tool. """ namespace = "tools" def __init__(self, point, callable, name=None, priority=50): self._point = point self.callable = callable self._name = name self._priority = priority self.__doc__ = self.callable.__doc__ self._setargs() def _get_on(self): raise AttributeError(_attr_error) def _set_on(self, value): raise AttributeError(_attr_error) on = property(_get_on, _set_on) def _setargs(self): """Copy func parameter names to obj attributes.""" try: for arg in _getargs(self.callable): setattr(self, arg, None) except (TypeError, AttributeError): if hasattr(self.callable, "__call__"): for arg in _getargs(self.callable.__call__): setattr(self, arg, None) # IronPython 1.0 raises NotImplementedError because # inspect.getargspec tries to access Python bytecode # in co_code attribute. except NotImplementedError: pass # IronPython 1B1 may raise IndexError in some cases, # but if we trap it here it doesn't prevent CP from working. except IndexError: pass def _merged_args(self, d=None): """Return a dict of configuration entries for this Tool.""" if d: conf = d.copy() else: conf = {} tm = cherrypy.serving.request.toolmaps[self.namespace] if self._name in tm: conf.update(tm[self._name]) if "on" in conf: del conf["on"] return conf def __call__(self, *args, **kwargs): """Compile-time decorator (turn on the tool in config). For example: @tools.proxy() def whats_my_base(self): return cherrypy.request.base whats_my_base.exposed = True """ if args: raise TypeError("The %r Tool does not accept positional " "arguments; you must use keyword arguments." % self._name) def tool_decorator(f): if not hasattr(f, "_cp_config"): f._cp_config = {} subspace = self.namespace + "." + self._name + "." f._cp_config[subspace + "on"] = True for k, v in kwargs.items(): f._cp_config[subspace + k] = v return f return tool_decorator def _setup(self): """Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config. """ conf = self._merged_args() p = conf.pop("priority", None) if p is None: p = getattr(self.callable, "priority", self._priority) cherrypy.serving.request.hooks.attach(self._point, self.callable, priority=p, **conf) class HandlerTool(Tool): """Tool which is called 'before main', that may skip normal handlers. If the tool successfully handles the request (by setting response.body), if should return True. This will cause CherryPy to skip any 'normal' page handler. If the tool did not handle the request, it should return False to tell CherryPy to continue on and call the normal page handler. If the tool is declared AS a page handler (see the 'handler' method), returning False will raise NotFound. """ def __init__(self, callable, name=None): Tool.__init__(self, 'before_handler', callable, name) def handler(self, *args, **kwargs): """Use this tool as a CherryPy page handler. For example: class Root: nav = tools.staticdir.handler(section="/nav", dir="nav", root=absDir) """ def handle_func(*a, **kw): handled = self.callable(*args, **self._merged_args(kwargs)) if not handled: raise cherrypy.NotFound() return cherrypy.serving.response.body handle_func.exposed = True return handle_func def _wrapper(self, **kwargs): if self.callable(**kwargs): cherrypy.serving.request.handler = None def _setup(self): """Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config. """ conf = self._merged_args() p = conf.pop("priority", None) if p is None: p = getattr(self.callable, "priority", self._priority) cherrypy.serving.request.hooks.attach(self._point, self._wrapper, priority=p, **conf) class HandlerWrapperTool(Tool): """Tool which wraps request.handler in a provided wrapper function. The 'newhandler' arg must be a handler wrapper function that takes a 'next_handler' argument, plus *args and **kwargs. Like all page handler functions, it must return an iterable for use as cherrypy.response.body. For example, to allow your 'inner' page handlers to return dicts which then get interpolated into a template: def interpolator(next_handler, *args, **kwargs): filename = cherrypy.request.config.get('template') cherrypy.response.template = env.get_template(filename) response_dict = next_handler(*args, **kwargs) return cherrypy.response.template.render(**response_dict) cherrypy.tools.jinja = HandlerWrapperTool(interpolator) """ def __init__(self, newhandler, point='before_handler', name=None, priority=50): self.newhandler = newhandler self._point = point self._name = name self._priority = priority def callable(self, debug=False): innerfunc = cherrypy.serving.request.handler def wrap(*args, **kwargs): return self.newhandler(innerfunc, *args, **kwargs) cherrypy.serving.request.handler = wrap class ErrorTool(Tool): """Tool which is used to replace the default request.error_response.""" def __init__(self, callable, name=None): Tool.__init__(self, None, callable, name) def _wrapper(self): self.callable(**self._merged_args()) def _setup(self): """Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config. """ cherrypy.serving.request.error_response = self._wrapper # Builtin tools # from cherrypy.lib import cptools, encoding, auth, static, jsontools from cherrypy.lib import sessions as _sessions, xmlrpc as _xmlrpc from cherrypy.lib import caching as _caching from cherrypy.lib import auth_basic, auth_digest class SessionTool(Tool): """Session Tool for CherryPy. sessions.locking: When 'implicit' (the default), the session will be locked for you, just before running the page handler. When 'early', the session will be locked before reading the request body. This is off by default for safety reasons; for example, a large upload would block the session, denying an AJAX progress meter (see http://www.cherrypy.org/ticket/630). When 'explicit' (or any other value), you need to call cherrypy.session.acquire_lock() yourself before using session data. """ def __init__(self): # _sessions.init must be bound after headers are read Tool.__init__(self, 'before_request_body', _sessions.init) def _lock_session(self): cherrypy.serving.session.acquire_lock() def _setup(self): """Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config. """ hooks = cherrypy.serving.request.hooks conf = self._merged_args() p = conf.pop("priority", None) if p is None: p = getattr(self.callable, "priority", self._priority) hooks.attach(self._point, self.callable, priority=p, **conf) locking = conf.pop('locking', 'implicit') if locking == 'implicit': hooks.attach('before_handler', self._lock_session) elif locking == 'early': # Lock before the request body (but after _sessions.init runs!) hooks.attach('before_request_body', self._lock_session, priority=60) else: # Don't lock pass hooks.attach('before_finalize', _sessions.save) hooks.attach('on_end_request', _sessions.close) def regenerate(self): """Drop the current session and make a new one (with a new id).""" sess = cherrypy.serving.session sess.regenerate() # Grab cookie-relevant tool args conf = dict([(k, v) for k, v in self._merged_args().items() if k in ('path', 'path_header', 'name', 'timeout', 'domain', 'secure')]) _sessions.set_response_cookie(**conf) class XMLRPCController(object): """A Controller (page handler collection) for XML-RPC. To use it, have your controllers subclass this base class (it will turn on the tool for you). You can also supply the following optional config entries: tools.xmlrpc.encoding: 'utf-8' tools.xmlrpc.allow_none: 0 XML-RPC is a rather discontinuous layer over HTTP; dispatching to the appropriate handler must first be performed according to the URL, and then a second dispatch step must take place according to the RPC method specified in the request body. It also allows a superfluous "/RPC2" prefix in the URL, supplies its own handler args in the body, and requires a 200 OK "Fault" response instead of 404 when the desired method is not found. Therefore, XML-RPC cannot be implemented for CherryPy via a Tool alone. This Controller acts as the dispatch target for the first half (based on the URL); it then reads the RPC method from the request body and does its own second dispatch step based on that method. It also reads body params, and returns a Fault on error. The XMLRPCDispatcher strips any /RPC2 prefix; if you aren't using /RPC2 in your URL's, you can safely skip turning on the XMLRPCDispatcher. Otherwise, you need to use declare it in config: request.dispatch: cherrypy.dispatch.XMLRPCDispatcher() """ # Note we're hard-coding this into the 'tools' namespace. We could do # a huge amount of work to make it relocatable, but the only reason why # would be if someone actually disabled the default_toolbox. Meh. _cp_config = {'tools.xmlrpc.on': True} def default(self, *vpath, **params): rpcparams, rpcmethod = _xmlrpc.process_body() subhandler = self for attr in str(rpcmethod).split('.'): subhandler = getattr(subhandler, attr, None) if subhandler and getattr(subhandler, "exposed", False): body = subhandler(*(vpath + rpcparams), **params) else: # http://www.cherrypy.org/ticket/533 # if a method is not found, an xmlrpclib.Fault should be returned # raising an exception here will do that; see # cherrypy.lib.xmlrpc.on_error raise Exception('method "%s" is not supported' % attr) conf = cherrypy.serving.request.toolmaps['tools'].get("xmlrpc", {}) _xmlrpc.respond(body, conf.get('encoding', 'utf-8'), conf.get('allow_none', 0)) return cherrypy.serving.response.body default.exposed = True class SessionAuthTool(HandlerTool): def _setargs(self): for name in dir(cptools.SessionAuth): if not name.startswith("__"): setattr(self, name, None) class CachingTool(Tool): """Caching Tool for CherryPy.""" def _wrapper(self, **kwargs): request = cherrypy.serving.request if _caching.get(**kwargs): request.handler = None else: if request.cacheable: # Note the devious technique here of adding hooks on the fly request.hooks.attach('before_finalize', _caching.tee_output, priority=90) _wrapper.priority = 20 def _setup(self): """Hook caching into cherrypy.request.""" conf = self._merged_args() p = conf.pop("priority", None) cherrypy.serving.request.hooks.attach('before_handler', self._wrapper, priority=p, **conf) class Toolbox(object): """A collection of Tools. This object also functions as a config namespace handler for itself. Custom toolboxes should be added to each Application's toolboxes dict. """ def __init__(self, namespace): self.namespace = namespace def __setattr__(self, name, value): # If the Tool._name is None, supply it from the attribute name. if isinstance(value, Tool): if value._name is None: value._name = name value.namespace = self.namespace object.__setattr__(self, name, value) def __enter__(self): """Populate request.toolmaps from tools specified in config.""" cherrypy.serving.request.toolmaps[self.namespace] = map = {} def populate(k, v): toolname, arg = k.split(".", 1) bucket = map.setdefault(toolname, {}) bucket[arg] = v return populate def __exit__(self, exc_type, exc_val, exc_tb): """Run tool._setup() for each tool in our toolmap.""" map = cherrypy.serving.request.toolmaps.get(self.namespace) if map: for name, settings in map.items(): if settings.get("on", False): tool = getattr(self, name) tool._setup() class DeprecatedTool(Tool): _name = None warnmsg = "This Tool is deprecated." def __init__(self, point, warnmsg=None): self.point = point if warnmsg is not None: self.warnmsg = warnmsg def __call__(self, *args, **kwargs): warnings.warn(self.warnmsg) def tool_decorator(f): return f return tool_decorator def _setup(self): warnings.warn(self.warnmsg) default_toolbox = _d = Toolbox("tools") _d.session_auth = SessionAuthTool(cptools.session_auth) _d.proxy = Tool('before_request_body', cptools.proxy, priority=30) _d.response_headers = Tool('on_start_resource', cptools.response_headers) _d.log_tracebacks = Tool('before_error_response', cptools.log_traceback) _d.log_headers = Tool('before_error_response', cptools.log_request_headers) _d.log_hooks = Tool('on_end_request', cptools.log_hooks, priority=100) _d.err_redirect = ErrorTool(cptools.redirect) _d.etags = Tool('before_finalize', cptools.validate_etags, priority=75) _d.decode = Tool('before_request_body', encoding.decode) # the order of encoding, gzip, caching is important _d.encode = Tool('before_handler', encoding.ResponseEncoder, priority=70) _d.gzip = Tool('before_finalize', encoding.gzip, priority=80) _d.staticdir = HandlerTool(static.staticdir) _d.staticfile = HandlerTool(static.staticfile) _d.sessions = SessionTool() _d.xmlrpc = ErrorTool(_xmlrpc.on_error) _d.caching = CachingTool('before_handler', _caching.get, 'caching') _d.expires = Tool('before_finalize', _caching.expires) _d.tidy = DeprecatedTool('before_finalize', "The tidy tool has been removed from the standard distribution of CherryPy. " "The most recent version can be found at http://tools.cherrypy.org/browser.") _d.nsgmls = DeprecatedTool('before_finalize', "The nsgmls tool has been removed from the standard distribution of CherryPy. " "The most recent version can be found at http://tools.cherrypy.org/browser.") _d.ignore_headers = Tool('before_request_body', cptools.ignore_headers) _d.referer = Tool('before_request_body', cptools.referer) _d.basic_auth = Tool('on_start_resource', auth.basic_auth) _d.digest_auth = Tool('on_start_resource', auth.digest_auth) _d.trailing_slash = Tool('before_handler', cptools.trailing_slash, priority=60) _d.flatten = Tool('before_finalize', cptools.flatten) _d.accept = Tool('on_start_resource', cptools.accept) _d.redirect = Tool('on_start_resource', cptools.redirect) _d.autovary = Tool('on_start_resource', cptools.autovary, priority=0) _d.json_in = Tool('before_request_body', jsontools.json_in, priority=30) _d.json_out = Tool('before_handler', jsontools.json_out, priority=30) _d.auth_basic = Tool('before_handler', auth_basic.basic_auth, priority=1) _d.auth_digest = Tool('before_handler', auth_digest.digest_auth, priority=1) del _d, cptools, encoding, auth, static
imajes/Sick-Beard
cherrypy/_cptools.py
Python
gpl-3.0
19,648
# This file is released under the GNU GPL, version 3 or a later revision. # For further details see the COPYING file from collections.abc import Set # for backward compatibility with Python <3.7 from collections import OrderedDict class OrderedSet(Set): """ Ordered collection of distinct hashable objects. Taken from https://stackoverflow.com/a/10006674 """ def __init__(self, iterable=()): self.d = OrderedDict.fromkeys(iterable) def __len__(self): return len(self.d) def __contains__(self, element): return element in self.d def __iter__(self): return iter(self.d) def __repr__(self): return str(list(self))
GuillaumeSeren/alot
alot/utils/collections.py
Python
gpl-3.0
696
import unittest import transaction from pyramid import testing from .models import DBSession class TestMyViewSuccessCondition(unittest.TestCase): def setUp(self): self.config = testing.setUp() from sqlalchemy import create_engine engine = create_engine('sqlite://') from .models import ( Base, MyModel, ) DBSession.configure(bind=engine) Base.metadata.create_all(engine) with transaction.manager: model = MyModel(name='one', value=55) DBSession.add(model) def tearDown(self): DBSession.remove() testing.tearDown() def test_passing_view(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info['one'].name, 'one') self.assertEqual(info['project'], 'artcrm') class TestMyViewFailureCondition(unittest.TestCase): def setUp(self): self.config = testing.setUp() from sqlalchemy import create_engine engine = create_engine('sqlite://') from .models import ( Base, MyModel, ) DBSession.configure(bind=engine) def tearDown(self): DBSession.remove() testing.tearDown() def test_failing_view(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info.status_int, 500)
gahayashi/artcrm
src/artcrm/tests.py
Python
gpl-3.0
1,497
#!/usr/bin/env python3 import datetime import os import subprocess import sys import time if len(sys.argv) != 5: sys.exit("Usage:\n\t%s <binary> <testcase> <checker> <report-builder>" % (sys.argv[0],)) binary = sys.argv[1] testcase = sys.argv[2] checker = sys.argv[3] reportbuilder = sys.argv[4] for i in [testcase, checker, reportbuilder]: if not os.path.exists(i): sys.exit("File not found: %s" % (i,)) exec(open(testcase).read()) for i in ['input', 'output']: if i not in locals(): sys.exit("Testcase %s does not provide variable '%s'" % (testcase, i)) if 'flags' not in locals(): flags = "" if 'timeout' not in locals(): timeout = 100 exec(open(checker).read()) for i in ['checker']: if i not in locals(): sys.exit("Checker %s does not provide variable '%s'" % (checker, i)) exec(open(reportbuilder).read()) for i in ['reportStartTest', 'reportStreams', 'reportTimeout', 'reportFailure', 'reportSuccess', 'reportEndTest']: if i not in locals(): sys.exit("Report-builder %s does not provide variable '%s'" % (reportbuilder, i)) args = binary.split() args.extend(flags.split()) reportStartTest(args, testcase) first = 0 out = input.strip().encode() err = "" def run(args): global input global out global err global timeout try: if timeout < 0: return begin = time.time() process = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = process.communicate(out, timeout=timeout) timeout = timeout - time.time() + begin except subprocess.TimeoutExpired: timeout = -1 process.kill() for i in range(0, len(args)): if args[i] == "|": run(args[first:i]) first = i+1 if first < len(args): run(args[first:]) if timeout < 0: reportTimeout(out, err) else: out = out.decode() err = err.decode() reportStreams(out, err) checker(out, err) reportEndTest(args, testcase)
dbaeck/aspino
tests/pyregtest.py
Python
apache-2.0
2,046
# MIT License # # Copyright (c) 2019 Looker Data Sciences, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # 275 API models: 202 Spec, 0 Request, 55 Write, 18 Enum # NOTE: Do not edit this file generated by Looker SDK Codegen for Looker 7.18 API 4.0 import datetime import enum from typing import Any, MutableMapping, Optional, Sequence try: from typing import ForwardRef # type: ignore except ImportError: from typing import _ForwardRef as ForwardRef # type: ignore import attr from looker_sdk.rtl import model from looker_sdk.rtl import serialize as sr EXPLICIT_NULL = model.EXPLICIT_NULL # type: ignore DelimSequence = model.DelimSequence @attr.s(auto_attribs=True, init=False) class AccessToken(model.Model): """ Attributes: access_token: Access Token used for API calls token_type: Type of Token expires_in: Number of seconds before the token expires refresh_token: Refresh token which can be used to obtain a new access token """ access_token: Optional[str] = None token_type: Optional[str] = None expires_in: Optional[int] = None refresh_token: Optional[str] = None def __init__( self, *, access_token: Optional[str] = None, token_type: Optional[str] = None, expires_in: Optional[int] = None, refresh_token: Optional[str] = None ): self.access_token = access_token self.token_type = token_type self.expires_in = expires_in self.refresh_token = refresh_token class Align(enum.Enum): """ The appropriate horizontal text alignment the values of this field should be displayed in. Valid values are: "left", "right". """ left = "left" right = "right" invalid_api_enum_value = "invalid_api_enum_value" Align.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class ApiSession(model.Model): """ Attributes: can: Operations the current user is able to perform on this object workspace_id: The id of active workspace for this session sudo_user_id: The id of the actual user in the case when this session represents one user sudo'ing as another """ can: Optional[MutableMapping[str, bool]] = None workspace_id: Optional[str] = None sudo_user_id: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, workspace_id: Optional[str] = None, sudo_user_id: Optional[int] = None ): self.can = can self.workspace_id = workspace_id self.sudo_user_id = sudo_user_id @attr.s(auto_attribs=True, init=False) class ApiVersion(model.Model): """ Attributes: looker_release_version: Current Looker release version number current_version: supported_versions: Array of versions supported by this Looker instance """ looker_release_version: Optional[str] = None current_version: Optional["ApiVersionElement"] = None supported_versions: Optional[Sequence["ApiVersionElement"]] = None def __init__( self, *, looker_release_version: Optional[str] = None, current_version: Optional["ApiVersionElement"] = None, supported_versions: Optional[Sequence["ApiVersionElement"]] = None ): self.looker_release_version = looker_release_version self.current_version = current_version self.supported_versions = supported_versions @attr.s(auto_attribs=True, init=False) class ApiVersionElement(model.Model): """ Attributes: version: Version number as it appears in '/api/xxx/' urls full_version: Full version number including minor version status: Status of this version swagger_url: Url for swagger.json for this version """ version: Optional[str] = None full_version: Optional[str] = None status: Optional[str] = None swagger_url: Optional[str] = None def __init__( self, *, version: Optional[str] = None, full_version: Optional[str] = None, status: Optional[str] = None, swagger_url: Optional[str] = None ): self.version = version self.full_version = full_version self.status = status self.swagger_url = swagger_url @attr.s(auto_attribs=True, init=False) class BackupConfiguration(model.Model): """ Attributes: can: Operations the current user is able to perform on this object type: Type of backup: looker-s3 or custom-s3 custom_s3_bucket: Name of bucket for custom-s3 backups custom_s3_bucket_region: Name of region where the bucket is located custom_s3_key: (Write-Only) AWS S3 key used for custom-s3 backups custom_s3_secret: (Write-Only) AWS S3 secret used for custom-s3 backups url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None type: Optional[str] = None custom_s3_bucket: Optional[str] = None custom_s3_bucket_region: Optional[str] = None custom_s3_key: Optional[str] = None custom_s3_secret: Optional[str] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, type: Optional[str] = None, custom_s3_bucket: Optional[str] = None, custom_s3_bucket_region: Optional[str] = None, custom_s3_key: Optional[str] = None, custom_s3_secret: Optional[str] = None, url: Optional[str] = None ): self.can = can self.type = type self.custom_s3_bucket = custom_s3_bucket self.custom_s3_bucket_region = custom_s3_bucket_region self.custom_s3_key = custom_s3_key self.custom_s3_secret = custom_s3_secret self.url = url @attr.s(auto_attribs=True, init=False) class Board(model.Model): """ Attributes: can: Operations the current user is able to perform on this object content_metadata_id: Id of associated content_metadata record created_at: Date of board creation deleted_at: Date of board deletion description: Description of the board board_sections: Sections of the board id: Unique Id section_order: ids of the board sections in the order they should be displayed title: Title of the board updated_at: Date of last board update user_id: User id of board creator primary_homepage: Whether the board is the primary homepage or not """ can: Optional[MutableMapping[str, bool]] = None content_metadata_id: Optional[int] = None created_at: Optional[datetime.datetime] = None deleted_at: Optional[datetime.datetime] = None description: Optional[str] = None board_sections: Optional[Sequence["BoardSection"]] = None id: Optional[int] = None section_order: Optional[Sequence[int]] = None title: Optional[str] = None updated_at: Optional[datetime.datetime] = None user_id: Optional[int] = None primary_homepage: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, content_metadata_id: Optional[int] = None, created_at: Optional[datetime.datetime] = None, deleted_at: Optional[datetime.datetime] = None, description: Optional[str] = None, board_sections: Optional[Sequence["BoardSection"]] = None, id: Optional[int] = None, section_order: Optional[Sequence[int]] = None, title: Optional[str] = None, updated_at: Optional[datetime.datetime] = None, user_id: Optional[int] = None, primary_homepage: Optional[bool] = None ): self.can = can self.content_metadata_id = content_metadata_id self.created_at = created_at self.deleted_at = deleted_at self.description = description self.board_sections = board_sections self.id = id self.section_order = section_order self.title = title self.updated_at = updated_at self.user_id = user_id self.primary_homepage = primary_homepage @attr.s(auto_attribs=True, init=False) class BoardItem(model.Model): """ Attributes: can: Operations the current user is able to perform on this object content_created_by: Name of user who created the content this item is based on content_favorite_id: Content favorite id associated with the item this content is based on content_metadata_id: Content metadata id associated with the item this content is based on content_updated_at: Last time the content that this item is based on was updated dashboard_id: Dashboard to base this item on description: The actual description for display favorite_count: Number of times content has been favorited, if present board_section_id: Associated Board Section id: Unique Id location: The container folder name of the content look_id: Look to base this item on lookml_dashboard_id: LookML Dashboard to base this item on order: An arbitrary integer representing the sort order within the section title: The actual title for display url: Relative url for the associated content view_count: Number of times content has been viewed, if present """ can: Optional[MutableMapping[str, bool]] = None content_created_by: Optional[str] = None content_favorite_id: Optional[int] = None content_metadata_id: Optional[int] = None content_updated_at: Optional[str] = None dashboard_id: Optional[int] = None description: Optional[str] = None favorite_count: Optional[int] = None board_section_id: Optional[int] = None id: Optional[int] = None location: Optional[str] = None look_id: Optional[int] = None lookml_dashboard_id: Optional[str] = None order: Optional[int] = None title: Optional[str] = None url: Optional[str] = None view_count: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, content_created_by: Optional[str] = None, content_favorite_id: Optional[int] = None, content_metadata_id: Optional[int] = None, content_updated_at: Optional[str] = None, dashboard_id: Optional[int] = None, description: Optional[str] = None, favorite_count: Optional[int] = None, board_section_id: Optional[int] = None, id: Optional[int] = None, location: Optional[str] = None, look_id: Optional[int] = None, lookml_dashboard_id: Optional[str] = None, order: Optional[int] = None, title: Optional[str] = None, url: Optional[str] = None, view_count: Optional[int] = None ): self.can = can self.content_created_by = content_created_by self.content_favorite_id = content_favorite_id self.content_metadata_id = content_metadata_id self.content_updated_at = content_updated_at self.dashboard_id = dashboard_id self.description = description self.favorite_count = favorite_count self.board_section_id = board_section_id self.id = id self.location = location self.look_id = look_id self.lookml_dashboard_id = lookml_dashboard_id self.order = order self.title = title self.url = url self.view_count = view_count @attr.s(auto_attribs=True, init=False) class BoardSection(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Time at which this section was created. deleted_at: Time at which this section was deleted. description: Description of the content found in this section. board_id: Id reference to parent board board_items: Items in the board section id: Unique Id item_order: ids of the board items in the order they should be displayed title: Name of row updated_at: Time at which this section was last updated. """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[datetime.datetime] = None deleted_at: Optional[datetime.datetime] = None description: Optional[str] = None board_id: Optional[int] = None board_items: Optional[Sequence["BoardItem"]] = None id: Optional[int] = None item_order: Optional[Sequence[int]] = None title: Optional[str] = None updated_at: Optional[datetime.datetime] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[datetime.datetime] = None, deleted_at: Optional[datetime.datetime] = None, description: Optional[str] = None, board_id: Optional[int] = None, board_items: Optional[Sequence["BoardItem"]] = None, id: Optional[int] = None, item_order: Optional[Sequence[int]] = None, title: Optional[str] = None, updated_at: Optional[datetime.datetime] = None ): self.can = can self.created_at = created_at self.deleted_at = deleted_at self.description = description self.board_id = board_id self.board_items = board_items self.id = id self.item_order = item_order self.title = title self.updated_at = updated_at class Category(enum.Enum): """ Field category Valid values are: "parameter", "filter", "measure", "dimension". """ parameter = "parameter" filter = "filter" measure = "measure" dimension = "dimension" invalid_api_enum_value = "invalid_api_enum_value" Category.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class ColorCollection(model.Model): """ Attributes: id: Unique Id label: Label of color collection categoricalPalettes: Array of categorical palette definitions sequentialPalettes: Array of discrete palette definitions divergingPalettes: Array of diverging palette definitions """ id: Optional[str] = None label: Optional[str] = None categoricalPalettes: Optional[Sequence["DiscretePalette"]] = None sequentialPalettes: Optional[Sequence["ContinuousPalette"]] = None divergingPalettes: Optional[Sequence["ContinuousPalette"]] = None def __init__( self, *, id: Optional[str] = None, label: Optional[str] = None, categoricalPalettes: Optional[Sequence["DiscretePalette"]] = None, sequentialPalettes: Optional[Sequence["ContinuousPalette"]] = None, divergingPalettes: Optional[Sequence["ContinuousPalette"]] = None ): self.id = id self.label = label self.categoricalPalettes = categoricalPalettes self.sequentialPalettes = sequentialPalettes self.divergingPalettes = divergingPalettes @attr.s(auto_attribs=True, init=False) class ColorStop(model.Model): """ Attributes: color: CSS color string offset: Offset in continuous palette (0 to 100) """ color: Optional[str] = None offset: Optional[int] = None def __init__(self, *, color: Optional[str] = None, offset: Optional[int] = None): self.color = color self.offset = offset @attr.s(auto_attribs=True, init=False) class ColumnSearch(model.Model): """ Attributes: schema_name: Name of schema containing the table table_name: Name of table containing the column column_name: Name of column data_type: Column data type """ schema_name: Optional[str] = None table_name: Optional[str] = None column_name: Optional[str] = None data_type: Optional[str] = None def __init__( self, *, schema_name: Optional[str] = None, table_name: Optional[str] = None, column_name: Optional[str] = None, data_type: Optional[str] = None ): self.schema_name = schema_name self.table_name = table_name self.column_name = column_name self.data_type = data_type @attr.s(auto_attribs=True, init=False) class Command(model.Model): """ Attributes: id: Id of the command record author_id: Id of the command author name: Name of the command description: Description of the command linked_content_id: Id of the content associated with the command linked_content_type: Name of the command Valid values are: "dashboard", "lookml_dashboard". """ id: Optional[int] = None author_id: Optional[int] = None name: Optional[str] = None description: Optional[str] = None linked_content_id: Optional[str] = None linked_content_type: Optional["LinkedContentType"] = None def __init__( self, *, id: Optional[int] = None, author_id: Optional[int] = None, name: Optional[str] = None, description: Optional[str] = None, linked_content_id: Optional[str] = None, linked_content_type: Optional["LinkedContentType"] = None ): self.id = id self.author_id = author_id self.name = name self.description = description self.linked_content_id = linked_content_id self.linked_content_type = linked_content_type @attr.s(auto_attribs=True, init=False) class ConnectionFeatures(model.Model): """ Attributes: dialect_name: Name of the dialect for this connection cost_estimate: True for cost estimating support multiple_databases: True for multiple database support column_search: True for cost estimating support persistent_table_indexes: True for secondary index support persistent_derived_tables: True for persistent derived table support turtles: True for turtles support percentile: True for percentile support distinct_percentile: True for distinct percentile support stable_views: True for stable views support milliseconds: True for millisecond support microseconds: True for microsecond support subtotals: True for subtotal support location: True for geographic location support timezone: True for timezone conversion in query support connection_pooling: True for connection pooling support """ dialect_name: Optional[str] = None cost_estimate: Optional[bool] = None multiple_databases: Optional[bool] = None column_search: Optional[bool] = None persistent_table_indexes: Optional[bool] = None persistent_derived_tables: Optional[bool] = None turtles: Optional[bool] = None percentile: Optional[bool] = None distinct_percentile: Optional[bool] = None stable_views: Optional[bool] = None milliseconds: Optional[bool] = None microseconds: Optional[bool] = None subtotals: Optional[bool] = None location: Optional[bool] = None timezone: Optional[bool] = None connection_pooling: Optional[bool] = None def __init__( self, *, dialect_name: Optional[str] = None, cost_estimate: Optional[bool] = None, multiple_databases: Optional[bool] = None, column_search: Optional[bool] = None, persistent_table_indexes: Optional[bool] = None, persistent_derived_tables: Optional[bool] = None, turtles: Optional[bool] = None, percentile: Optional[bool] = None, distinct_percentile: Optional[bool] = None, stable_views: Optional[bool] = None, milliseconds: Optional[bool] = None, microseconds: Optional[bool] = None, subtotals: Optional[bool] = None, location: Optional[bool] = None, timezone: Optional[bool] = None, connection_pooling: Optional[bool] = None ): self.dialect_name = dialect_name self.cost_estimate = cost_estimate self.multiple_databases = multiple_databases self.column_search = column_search self.persistent_table_indexes = persistent_table_indexes self.persistent_derived_tables = persistent_derived_tables self.turtles = turtles self.percentile = percentile self.distinct_percentile = distinct_percentile self.stable_views = stable_views self.milliseconds = milliseconds self.microseconds = microseconds self.subtotals = subtotals self.location = location self.timezone = timezone self.connection_pooling = connection_pooling @attr.s(auto_attribs=True, init=False) class ContentFavorite(model.Model): """ Attributes: id: Unique Id user_id: User Id which owns this ContentFavorite content_metadata_id: Content Metadata Id associated with this ContentFavorite look_id: Id of a look dashboard_id: Id of a dashboard look: dashboard: board_id: Id of a board """ id: Optional[int] = None user_id: Optional[int] = None content_metadata_id: Optional[int] = None look_id: Optional[int] = None dashboard_id: Optional[int] = None look: Optional["LookBasic"] = None dashboard: Optional["DashboardBase"] = None board_id: Optional[int] = None def __init__( self, *, id: Optional[int] = None, user_id: Optional[int] = None, content_metadata_id: Optional[int] = None, look_id: Optional[int] = None, dashboard_id: Optional[int] = None, look: Optional["LookBasic"] = None, dashboard: Optional["DashboardBase"] = None, board_id: Optional[int] = None ): self.id = id self.user_id = user_id self.content_metadata_id = content_metadata_id self.look_id = look_id self.dashboard_id = dashboard_id self.look = look self.dashboard = dashboard self.board_id = board_id @attr.s(auto_attribs=True, init=False) class ContentMeta(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id name: Name or title of underlying content parent_id: Id of Parent Content dashboard_id: Id of associated dashboard when content_type is "dashboard" look_id: Id of associated look when content_type is "look" folder_id: Id of associated folder when content_type is "space" content_type: Content Type ("dashboard", "look", or "folder") inherits: Whether content inherits its access levels from parent inheriting_id: Id of Inherited Content slug: Content Slug """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None name: Optional[str] = None parent_id: Optional[int] = None dashboard_id: Optional[str] = None look_id: Optional[int] = None folder_id: Optional[str] = None content_type: Optional[str] = None inherits: Optional[bool] = None inheriting_id: Optional[int] = None slug: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, name: Optional[str] = None, parent_id: Optional[int] = None, dashboard_id: Optional[str] = None, look_id: Optional[int] = None, folder_id: Optional[str] = None, content_type: Optional[str] = None, inherits: Optional[bool] = None, inheriting_id: Optional[int] = None, slug: Optional[str] = None ): self.can = can self.id = id self.name = name self.parent_id = parent_id self.dashboard_id = dashboard_id self.look_id = look_id self.folder_id = folder_id self.content_type = content_type self.inherits = inherits self.inheriting_id = inheriting_id self.slug = slug @attr.s(auto_attribs=True, init=False) class ContentMetaGroupUser(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id content_metadata_id: Id of associated Content Metadata permission_type: Type of permission: "view" or "edit" Valid values are: "view", "edit". group_id: ID of associated group user_id: ID of associated user """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None content_metadata_id: Optional[str] = None permission_type: Optional["PermissionType"] = None group_id: Optional[int] = None user_id: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, content_metadata_id: Optional[str] = None, permission_type: Optional["PermissionType"] = None, group_id: Optional[int] = None, user_id: Optional[int] = None ): self.can = can self.id = id self.content_metadata_id = content_metadata_id self.permission_type = permission_type self.group_id = group_id self.user_id = user_id @attr.s(auto_attribs=True, init=False) class ContentValidation(model.Model): """ Attributes: content_with_errors: A list of content errors computation_time: Duration of content validation in seconds total_looks_validated: The number of looks validated total_dashboard_elements_validated: The number of dashboard elements validated total_dashboard_filters_validated: The number of dashboard filters validated total_scheduled_plans_validated: The number of scheduled plans validated total_alerts_validated: The number of alerts validated total_explores_validated: The number of explores used across all content validated """ content_with_errors: Optional[Sequence["ContentValidatorError"]] = None computation_time: Optional[float] = None total_looks_validated: Optional[int] = None total_dashboard_elements_validated: Optional[int] = None total_dashboard_filters_validated: Optional[int] = None total_scheduled_plans_validated: Optional[int] = None total_alerts_validated: Optional[int] = None total_explores_validated: Optional[int] = None def __init__( self, *, content_with_errors: Optional[Sequence["ContentValidatorError"]] = None, computation_time: Optional[float] = None, total_looks_validated: Optional[int] = None, total_dashboard_elements_validated: Optional[int] = None, total_dashboard_filters_validated: Optional[int] = None, total_scheduled_plans_validated: Optional[int] = None, total_alerts_validated: Optional[int] = None, total_explores_validated: Optional[int] = None ): self.content_with_errors = content_with_errors self.computation_time = computation_time self.total_looks_validated = total_looks_validated self.total_dashboard_elements_validated = total_dashboard_elements_validated self.total_dashboard_filters_validated = total_dashboard_filters_validated self.total_scheduled_plans_validated = total_scheduled_plans_validated self.total_alerts_validated = total_alerts_validated self.total_explores_validated = total_explores_validated @attr.s(auto_attribs=True, init=False) class ContentValidationAlert(model.Model): """ Attributes: id: ID of the alert lookml_dashboard_id: ID of the LookML dashboard associated with the alert lookml_link_id: ID of the LookML dashboard element associated with the alert custom_title: An optional, user-defined title for the alert """ id: Optional[int] = None lookml_dashboard_id: Optional[str] = None lookml_link_id: Optional[str] = None custom_title: Optional[str] = None def __init__( self, *, id: Optional[int] = None, lookml_dashboard_id: Optional[str] = None, lookml_link_id: Optional[str] = None, custom_title: Optional[str] = None ): self.id = id self.lookml_dashboard_id = lookml_dashboard_id self.lookml_link_id = lookml_link_id self.custom_title = custom_title @attr.s(auto_attribs=True, init=False) class ContentValidationDashboard(model.Model): """ Attributes: description: Description id: Unique Id folder: title: Dashboard Title """ description: Optional[str] = None id: Optional[str] = None folder: Optional["ContentValidationFolder"] = None title: Optional[str] = None def __init__( self, *, description: Optional[str] = None, id: Optional[str] = None, folder: Optional["ContentValidationFolder"] = None, title: Optional[str] = None ): self.description = description self.id = id self.folder = folder self.title = title @attr.s(auto_attribs=True, init=False) class ContentValidationDashboardElement(model.Model): """ Attributes: body_text: Text tile body text dashboard_id: Id of Dashboard id: Unique Id look_id: Id Of Look note_display: Note Display note_state: Note State note_text: Note Text note_text_as_html: Note Text as Html query_id: Id Of Query subtitle_text: Text tile subtitle text title: Title of dashboard element title_hidden: Whether title is hidden title_text: Text tile title type: Type """ body_text: Optional[str] = None dashboard_id: Optional[str] = None id: Optional[str] = None look_id: Optional[str] = None note_display: Optional[str] = None note_state: Optional[str] = None note_text: Optional[str] = None note_text_as_html: Optional[str] = None query_id: Optional[int] = None subtitle_text: Optional[str] = None title: Optional[str] = None title_hidden: Optional[bool] = None title_text: Optional[str] = None type: Optional[str] = None def __init__( self, *, body_text: Optional[str] = None, dashboard_id: Optional[str] = None, id: Optional[str] = None, look_id: Optional[str] = None, note_display: Optional[str] = None, note_state: Optional[str] = None, note_text: Optional[str] = None, note_text_as_html: Optional[str] = None, query_id: Optional[int] = None, subtitle_text: Optional[str] = None, title: Optional[str] = None, title_hidden: Optional[bool] = None, title_text: Optional[str] = None, type: Optional[str] = None ): self.body_text = body_text self.dashboard_id = dashboard_id self.id = id self.look_id = look_id self.note_display = note_display self.note_state = note_state self.note_text = note_text self.note_text_as_html = note_text_as_html self.query_id = query_id self.subtitle_text = subtitle_text self.title = title self.title_hidden = title_hidden self.title_text = title_text self.type = type @attr.s(auto_attribs=True, init=False) class ContentValidationDashboardFilter(model.Model): """ Attributes: id: Unique Id dashboard_id: Id of Dashboard name: Name of filter title: Title of filter type: Type of filter: one of date, number, string, or field default_value: Default value of filter model: Model of filter (required if type = field) explore: Explore of filter (required if type = field) dimension: Dimension of filter (required if type = field) """ id: Optional[str] = None dashboard_id: Optional[str] = None name: Optional[str] = None title: Optional[str] = None type: Optional[str] = None default_value: Optional[str] = None model: Optional[str] = None explore: Optional[str] = None dimension: Optional[str] = None def __init__( self, *, id: Optional[str] = None, dashboard_id: Optional[str] = None, name: Optional[str] = None, title: Optional[str] = None, type: Optional[str] = None, default_value: Optional[str] = None, model: Optional[str] = None, explore: Optional[str] = None, dimension: Optional[str] = None ): self.id = id self.dashboard_id = dashboard_id self.name = name self.title = title self.type = type self.default_value = default_value self.model = model self.explore = explore self.dimension = dimension @attr.s(auto_attribs=True, init=False) class ContentValidationError(model.Model): """ Attributes: message: Error message field_name: Name of the field involved in the error model_name: Name of the model involved in the error explore_name: Name of the explore involved in the error removable: Whether this validation error is removable """ message: Optional[str] = None field_name: Optional[str] = None model_name: Optional[str] = None explore_name: Optional[str] = None removable: Optional[bool] = None def __init__( self, *, message: Optional[str] = None, field_name: Optional[str] = None, model_name: Optional[str] = None, explore_name: Optional[str] = None, removable: Optional[bool] = None ): self.message = message self.field_name = field_name self.model_name = model_name self.explore_name = explore_name self.removable = removable @attr.s(auto_attribs=True, init=False) class ContentValidationFolder(model.Model): """ Attributes: name: Unique Name id: Unique Id """ name: str id: Optional[str] = None def __init__(self, *, name: str, id: Optional[str] = None): self.name = name self.id = id @attr.s(auto_attribs=True, init=False) class ContentValidationLook(model.Model): """ Attributes: id: Unique Id title: Look Title folder: """ id: Optional[int] = None title: Optional[str] = None folder: Optional["ContentValidationFolder"] = None def __init__( self, *, id: Optional[int] = None, title: Optional[str] = None, folder: Optional["ContentValidationFolder"] = None ): self.id = id self.title = title self.folder = folder @attr.s(auto_attribs=True, init=False) class ContentValidationLookMLDashboard(model.Model): """ Attributes: id: ID of the LookML Dashboard title: Title of the LookML Dashboard space_id: ID of Space """ id: Optional[str] = None title: Optional[str] = None space_id: Optional[str] = None def __init__( self, *, id: Optional[str] = None, title: Optional[str] = None, space_id: Optional[str] = None ): self.id = id self.title = title self.space_id = space_id @attr.s(auto_attribs=True, init=False) class ContentValidationLookMLDashboardElement(model.Model): """ Attributes: lookml_link_id: Link ID of the LookML Dashboard Element title: Title of the LookML Dashboard Element """ lookml_link_id: Optional[str] = None title: Optional[str] = None def __init__( self, *, lookml_link_id: Optional[str] = None, title: Optional[str] = None ): self.lookml_link_id = lookml_link_id self.title = title @attr.s(auto_attribs=True, init=False) class ContentValidationScheduledPlan(model.Model): """ Attributes: name: Name of this scheduled plan look_id: Id of a look id: Unique Id """ name: Optional[str] = None look_id: Optional[int] = None id: Optional[int] = None def __init__( self, *, name: Optional[str] = None, look_id: Optional[int] = None, id: Optional[int] = None ): self.name = name self.look_id = look_id self.id = id @attr.s(auto_attribs=True, init=False) class ContentValidatorError(model.Model): """ Attributes: look: dashboard: dashboard_element: dashboard_filter: scheduled_plan: alert: lookml_dashboard: lookml_dashboard_element: errors: A list of errors found for this piece of content id: An id unique to this piece of content for this validation run """ look: Optional["ContentValidationLook"] = None dashboard: Optional["ContentValidationDashboard"] = None dashboard_element: Optional["ContentValidationDashboardElement"] = None dashboard_filter: Optional["ContentValidationDashboardFilter"] = None scheduled_plan: Optional["ContentValidationScheduledPlan"] = None alert: Optional["ContentValidationAlert"] = None lookml_dashboard: Optional["ContentValidationLookMLDashboard"] = None lookml_dashboard_element: Optional["ContentValidationLookMLDashboardElement"] = None errors: Optional[Sequence["ContentValidationError"]] = None id: Optional[str] = None def __init__( self, *, look: Optional["ContentValidationLook"] = None, dashboard: Optional["ContentValidationDashboard"] = None, dashboard_element: Optional["ContentValidationDashboardElement"] = None, dashboard_filter: Optional["ContentValidationDashboardFilter"] = None, scheduled_plan: Optional["ContentValidationScheduledPlan"] = None, alert: Optional["ContentValidationAlert"] = None, lookml_dashboard: Optional["ContentValidationLookMLDashboard"] = None, lookml_dashboard_element: Optional[ "ContentValidationLookMLDashboardElement" ] = None, errors: Optional[Sequence["ContentValidationError"]] = None, id: Optional[str] = None ): self.look = look self.dashboard = dashboard self.dashboard_element = dashboard_element self.dashboard_filter = dashboard_filter self.scheduled_plan = scheduled_plan self.alert = alert self.lookml_dashboard = lookml_dashboard self.lookml_dashboard_element = lookml_dashboard_element self.errors = errors self.id = id @attr.s(auto_attribs=True, init=False) class ContentView(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id look_id: Id of viewed Look dashboard_id: Id of the viewed Dashboard content_metadata_id: Content metadata id of the Look or Dashboard user_id: Id of user content was viewed by group_id: Id of group content was viewed by view_count: Number of times piece of content was viewed favorite_count: Number of times piece of content was favorited last_viewed_at: Date the piece of content was last viewed start_of_week_date: Week start date for the view and favorite count during that given week """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None look_id: Optional[int] = None dashboard_id: Optional[int] = None content_metadata_id: Optional[int] = None user_id: Optional[int] = None group_id: Optional[int] = None view_count: Optional[int] = None favorite_count: Optional[int] = None last_viewed_at: Optional[str] = None start_of_week_date: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, look_id: Optional[int] = None, dashboard_id: Optional[int] = None, content_metadata_id: Optional[int] = None, user_id: Optional[int] = None, group_id: Optional[int] = None, view_count: Optional[int] = None, favorite_count: Optional[int] = None, last_viewed_at: Optional[str] = None, start_of_week_date: Optional[str] = None ): self.can = can self.id = id self.look_id = look_id self.dashboard_id = dashboard_id self.content_metadata_id = content_metadata_id self.user_id = user_id self.group_id = group_id self.view_count = view_count self.favorite_count = favorite_count self.last_viewed_at = last_viewed_at self.start_of_week_date = start_of_week_date @attr.s(auto_attribs=True, init=False) class ContinuousPalette(model.Model): """ Attributes: id: Unique identity string label: Label for palette type: Type of palette stops: Array of ColorStops in the palette """ id: Optional[str] = None label: Optional[str] = None type: Optional[str] = None stops: Optional[Sequence["ColorStop"]] = None def __init__( self, *, id: Optional[str] = None, label: Optional[str] = None, type: Optional[str] = None, stops: Optional[Sequence["ColorStop"]] = None ): self.id = id self.label = label self.type = type self.stops = stops @attr.s(auto_attribs=True, init=False) class CostEstimate(model.Model): """ Attributes: cost: Cost of SQL statement cache_hit: Does the result come from the cache? cost_unit: Cost measurement size message: Human-friendly message """ cost: Optional[int] = None cache_hit: Optional[bool] = None cost_unit: Optional[str] = None message: Optional[str] = None def __init__( self, *, cost: Optional[int] = None, cache_hit: Optional[bool] = None, cost_unit: Optional[str] = None, message: Optional[str] = None ): self.cost = cost self.cache_hit = cache_hit self.cost_unit = cost_unit self.message = message @attr.s(auto_attribs=True, init=False) class CreateCostEstimate(model.Model): """ Attributes: sql: SQL statement to estimate """ sql: Optional[str] = None def __init__(self, *, sql: Optional[str] = None): self.sql = sql @attr.s(auto_attribs=True, init=False) class CreateDashboardFilter(model.Model): """ Attributes: dashboard_id: Id of Dashboard name: Name of filter title: Title of filter type: Type of filter: one of date, number, string, or field id: Unique Id default_value: Default value of filter model: Model of filter (required if type = field) explore: Explore of filter (required if type = field) dimension: Dimension of filter (required if type = field) field: Field information row: Display order of this filter relative to other filters listens_to_filters: Array of listeners for faceted filters allow_multiple_values: Whether the filter allows multiple filter values required: Whether the filter requires a value to run the dashboard ui_config: The visual configuration for this filter. Used to set up how the UI for this filter should appear. """ dashboard_id: str name: str title: str type: str id: Optional[str] = None default_value: Optional[str] = None model: Optional[str] = None explore: Optional[str] = None dimension: Optional[str] = None field: Optional[MutableMapping[str, Any]] = None row: Optional[int] = None listens_to_filters: Optional[Sequence[str]] = None allow_multiple_values: Optional[bool] = None required: Optional[bool] = None ui_config: Optional[MutableMapping[str, Any]] = None def __init__( self, *, dashboard_id: str, name: str, title: str, type: str, id: Optional[str] = None, default_value: Optional[str] = None, model: Optional[str] = None, explore: Optional[str] = None, dimension: Optional[str] = None, field: Optional[MutableMapping[str, Any]] = None, row: Optional[int] = None, listens_to_filters: Optional[Sequence[str]] = None, allow_multiple_values: Optional[bool] = None, required: Optional[bool] = None, ui_config: Optional[MutableMapping[str, Any]] = None ): self.dashboard_id = dashboard_id self.name = name self.title = title self.type = type self.id = id self.default_value = default_value self.model = model self.explore = explore self.dimension = dimension self.field = field self.row = row self.listens_to_filters = listens_to_filters self.allow_multiple_values = allow_multiple_values self.required = required self.ui_config = ui_config @attr.s(auto_attribs=True, init=False) class CreateDashboardRenderTask(model.Model): """ Attributes: dashboard_filters: Filter values to apply to the dashboard queries, in URL query format dashboard_style: Dashboard layout style: single_column or tiled """ dashboard_filters: Optional[str] = None dashboard_style: Optional[str] = None def __init__( self, *, dashboard_filters: Optional[str] = None, dashboard_style: Optional[str] = None ): self.dashboard_filters = dashboard_filters self.dashboard_style = dashboard_style @attr.s(auto_attribs=True, init=False) class CreateFolder(model.Model): """ Attributes: name: Unique Name parent_id: Id of Parent. If the parent id is null, this is a root-level entry """ name: str parent_id: str def __init__(self, *, name: str, parent_id: str): self.name = name self.parent_id = parent_id @attr.s(auto_attribs=True, init=False) class CreateQueryTask(model.Model): """ Attributes: query_id: Id of query to run result_format: Desired async query result format. Valid values are: "inline_json", "json", "json_detail", "json_fe", "csv", "html", "md", "txt", "xlsx", "gsxml". can: Operations the current user is able to perform on this object source: Source of query task deferred: Create the task but defer execution look_id: Id of look associated with query. dashboard_id: Id of dashboard associated with query. """ query_id: int result_format: "ResultFormat" can: Optional[MutableMapping[str, bool]] = None source: Optional[str] = None deferred: Optional[bool] = None look_id: Optional[int] = None dashboard_id: Optional[str] = None __annotations__ = { "query_id": int, "result_format": ForwardRef("ResultFormat"), "can": Optional[MutableMapping[str, bool]], "source": Optional[str], "deferred": Optional[bool], "look_id": Optional[int], "dashboard_id": Optional[str], } def __init__( self, *, query_id: int, result_format: "ResultFormat", can: Optional[MutableMapping[str, bool]] = None, source: Optional[str] = None, deferred: Optional[bool] = None, look_id: Optional[int] = None, dashboard_id: Optional[str] = None ): self.query_id = query_id self.result_format = result_format self.can = can self.source = source self.deferred = deferred self.look_id = look_id self.dashboard_id = dashboard_id @attr.s(auto_attribs=True, init=False) class CredentialsApi3(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id client_id: API key client_id created_at: Timestamp for the creation of this credential is_disabled: Has this credential been disabled? type: Short name for the type of this kind of credential url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None client_id: Optional[str] = None created_at: Optional[str] = None is_disabled: Optional[bool] = None type: Optional[str] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, client_id: Optional[str] = None, created_at: Optional[str] = None, is_disabled: Optional[bool] = None, type: Optional[str] = None, url: Optional[str] = None ): self.can = can self.id = id self.client_id = client_id self.created_at = created_at self.is_disabled = is_disabled self.type = type self.url = url @attr.s(auto_attribs=True, init=False) class CredentialsEmail(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Timestamp for the creation of this credential email: EMail address used for user login forced_password_reset_at_next_login: Force the user to change their password upon their next login is_disabled: Has this credential been disabled? logged_in_at: Timestamp for most recent login using credential password_reset_url: Url with one-time use secret token that the user can use to reset password type: Short name for the type of this kind of credential url: Link to get this item user_url: Link to get this user """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[str] = None email: Optional[str] = None forced_password_reset_at_next_login: Optional[bool] = None is_disabled: Optional[bool] = None logged_in_at: Optional[str] = None password_reset_url: Optional[str] = None type: Optional[str] = None url: Optional[str] = None user_url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[str] = None, email: Optional[str] = None, forced_password_reset_at_next_login: Optional[bool] = None, is_disabled: Optional[bool] = None, logged_in_at: Optional[str] = None, password_reset_url: Optional[str] = None, type: Optional[str] = None, url: Optional[str] = None, user_url: Optional[str] = None ): self.can = can self.created_at = created_at self.email = email self.forced_password_reset_at_next_login = forced_password_reset_at_next_login self.is_disabled = is_disabled self.logged_in_at = logged_in_at self.password_reset_url = password_reset_url self.type = type self.url = url self.user_url = user_url @attr.s(auto_attribs=True, init=False) class CredentialsEmbed(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Timestamp for the creation of this credential external_group_id: Embedder's id for a group to which this user was added during the most recent login external_user_id: Embedder's unique id for the user id: Unique Id is_disabled: Has this credential been disabled? logged_in_at: Timestamp for most recent login using credential type: Short name for the type of this kind of credential url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[str] = None external_group_id: Optional[str] = None external_user_id: Optional[str] = None id: Optional[int] = None is_disabled: Optional[bool] = None logged_in_at: Optional[str] = None type: Optional[str] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[str] = None, external_group_id: Optional[str] = None, external_user_id: Optional[str] = None, id: Optional[int] = None, is_disabled: Optional[bool] = None, logged_in_at: Optional[str] = None, type: Optional[str] = None, url: Optional[str] = None ): self.can = can self.created_at = created_at self.external_group_id = external_group_id self.external_user_id = external_user_id self.id = id self.is_disabled = is_disabled self.logged_in_at = logged_in_at self.type = type self.url = url @attr.s(auto_attribs=True, init=False) class CredentialsGoogle(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Timestamp for the creation of this credential domain: Google domain email: EMail address google_user_id: Google's Unique ID for this user is_disabled: Has this credential been disabled? logged_in_at: Timestamp for most recent login using credential type: Short name for the type of this kind of credential url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[str] = None domain: Optional[str] = None email: Optional[str] = None google_user_id: Optional[str] = None is_disabled: Optional[bool] = None logged_in_at: Optional[str] = None type: Optional[str] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[str] = None, domain: Optional[str] = None, email: Optional[str] = None, google_user_id: Optional[str] = None, is_disabled: Optional[bool] = None, logged_in_at: Optional[str] = None, type: Optional[str] = None, url: Optional[str] = None ): self.can = can self.created_at = created_at self.domain = domain self.email = email self.google_user_id = google_user_id self.is_disabled = is_disabled self.logged_in_at = logged_in_at self.type = type self.url = url @attr.s(auto_attribs=True, init=False) class CredentialsLDAP(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Timestamp for the creation of this credential email: EMail address is_disabled: Has this credential been disabled? ldap_dn: LDAP Distinguished name for this user (as-of the last login) ldap_id: LDAP Unique ID for this user logged_in_at: Timestamp for most recent login using credential type: Short name for the type of this kind of credential url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[str] = None email: Optional[str] = None is_disabled: Optional[bool] = None ldap_dn: Optional[str] = None ldap_id: Optional[str] = None logged_in_at: Optional[str] = None type: Optional[str] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[str] = None, email: Optional[str] = None, is_disabled: Optional[bool] = None, ldap_dn: Optional[str] = None, ldap_id: Optional[str] = None, logged_in_at: Optional[str] = None, type: Optional[str] = None, url: Optional[str] = None ): self.can = can self.created_at = created_at self.email = email self.is_disabled = is_disabled self.ldap_dn = ldap_dn self.ldap_id = ldap_id self.logged_in_at = logged_in_at self.type = type self.url = url @attr.s(auto_attribs=True, init=False) class CredentialsLookerOpenid(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Timestamp for the creation of this credential email: EMail address used for user login is_disabled: Has this credential been disabled? logged_in_at: Timestamp for most recent login using credential logged_in_ip: IP address of client for most recent login using credential type: Short name for the type of this kind of credential url: Link to get this item user_url: Link to get this user """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[str] = None email: Optional[str] = None is_disabled: Optional[bool] = None logged_in_at: Optional[str] = None logged_in_ip: Optional[str] = None type: Optional[str] = None url: Optional[str] = None user_url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[str] = None, email: Optional[str] = None, is_disabled: Optional[bool] = None, logged_in_at: Optional[str] = None, logged_in_ip: Optional[str] = None, type: Optional[str] = None, url: Optional[str] = None, user_url: Optional[str] = None ): self.can = can self.created_at = created_at self.email = email self.is_disabled = is_disabled self.logged_in_at = logged_in_at self.logged_in_ip = logged_in_ip self.type = type self.url = url self.user_url = user_url @attr.s(auto_attribs=True, init=False) class CredentialsOIDC(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Timestamp for the creation of this credential email: EMail address is_disabled: Has this credential been disabled? logged_in_at: Timestamp for most recent login using credential oidc_user_id: OIDC OP's Unique ID for this user type: Short name for the type of this kind of credential url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[str] = None email: Optional[str] = None is_disabled: Optional[bool] = None logged_in_at: Optional[str] = None oidc_user_id: Optional[str] = None type: Optional[str] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[str] = None, email: Optional[str] = None, is_disabled: Optional[bool] = None, logged_in_at: Optional[str] = None, oidc_user_id: Optional[str] = None, type: Optional[str] = None, url: Optional[str] = None ): self.can = can self.created_at = created_at self.email = email self.is_disabled = is_disabled self.logged_in_at = logged_in_at self.oidc_user_id = oidc_user_id self.type = type self.url = url @attr.s(auto_attribs=True, init=False) class CredentialsSaml(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Timestamp for the creation of this credential email: EMail address is_disabled: Has this credential been disabled? logged_in_at: Timestamp for most recent login using credential saml_user_id: Saml IdP's Unique ID for this user type: Short name for the type of this kind of credential url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[str] = None email: Optional[str] = None is_disabled: Optional[bool] = None logged_in_at: Optional[str] = None saml_user_id: Optional[str] = None type: Optional[str] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[str] = None, email: Optional[str] = None, is_disabled: Optional[bool] = None, logged_in_at: Optional[str] = None, saml_user_id: Optional[str] = None, type: Optional[str] = None, url: Optional[str] = None ): self.can = can self.created_at = created_at self.email = email self.is_disabled = is_disabled self.logged_in_at = logged_in_at self.saml_user_id = saml_user_id self.type = type self.url = url @attr.s(auto_attribs=True, init=False) class CredentialsTotp(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Timestamp for the creation of this credential is_disabled: Has this credential been disabled? type: Short name for the type of this kind of credential verified: User has verified url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[str] = None is_disabled: Optional[bool] = None type: Optional[str] = None verified: Optional[bool] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[str] = None, is_disabled: Optional[bool] = None, type: Optional[str] = None, verified: Optional[bool] = None, url: Optional[str] = None ): self.can = can self.created_at = created_at self.is_disabled = is_disabled self.type = type self.verified = verified self.url = url @attr.s(auto_attribs=True, init=False) class CustomWelcomeEmail(model.Model): """ Attributes: can: Operations the current user is able to perform on this object enabled: If true, custom email content will replace the default body of welcome emails content: The HTML to use as custom content for welcome emails. Script elements and other potentially dangerous markup will be removed. subject: The text to appear in the email subject line. header: The text to appear in the header line of the email body. """ can: Optional[MutableMapping[str, bool]] = None enabled: Optional[bool] = None content: Optional[str] = None subject: Optional[str] = None header: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, enabled: Optional[bool] = None, content: Optional[str] = None, subject: Optional[str] = None, header: Optional[str] = None ): self.can = can self.enabled = enabled self.content = content self.subject = subject self.header = header @attr.s(auto_attribs=True, init=False) class Dashboard(model.Model): """ Attributes: can: Operations the current user is able to perform on this object content_favorite_id: Content Favorite Id content_metadata_id: Id of content metadata description: Description hidden: Is Hidden id: Unique Id model: query_timezone: Timezone in which the Dashboard will run by default. readonly: Is Read-only refresh_interval: Refresh Interval, as a time duration phrase like "2 hours 30 minutes". A number with no time units will be interpreted as whole seconds. refresh_interval_to_i: Refresh Interval in milliseconds folder: title: Dashboard Title user_id: Id of User background_color: Background color created_at: Time that the Dashboard was created. crossfilter_enabled: Enables crossfiltering in dashboards - only available in dashboards-next (beta) dashboard_elements: Elements dashboard_filters: Filters dashboard_layouts: Layouts deleted: Whether or not a dashboard is 'soft' deleted. deleted_at: Time that the Dashboard was 'soft' deleted. deleter_id: Id of User that 'soft' deleted the dashboard. edit_uri: Relative path of URI of LookML file to edit the dashboard (LookML dashboard only). favorite_count: Number of times favorited last_accessed_at: Time the dashboard was last accessed last_viewed_at: Time last viewed in the Looker web UI load_configuration: configuration option that governs how dashboard loading will happen. lookml_link_id: Links this dashboard to a particular LookML dashboard such that calling a **sync** operation on that LookML dashboard will update this dashboard to match. show_filters_bar: Show filters bar. **Security Note:** This property only affects the *cosmetic* appearance of the dashboard, not a user's ability to access data. Hiding the filters bar does **NOT** prevent users from changing filters by other means. For information on how to set up secure data access control policies, see [Control User Access to Data](https://looker.com/docs/r/api/control-access) show_title: Show title slug: Content Metadata Slug folder_id: Id of folder text_tile_text_color: Color of text on text tiles tile_background_color: Tile background color tile_text_color: Tile text color title_color: Title color view_count: Number of times viewed in the Looker web UI appearance: preferred_viewer: The preferred route for viewing this dashboard (ie: dashboards or dashboards-next) """ can: Optional[MutableMapping[str, bool]] = None content_favorite_id: Optional[int] = None content_metadata_id: Optional[int] = None description: Optional[str] = None hidden: Optional[bool] = None id: Optional[str] = None model: Optional["LookModel"] = None query_timezone: Optional[str] = None readonly: Optional[bool] = None refresh_interval: Optional[str] = None refresh_interval_to_i: Optional[int] = None folder: Optional["FolderBase"] = None title: Optional[str] = None user_id: Optional[int] = None background_color: Optional[str] = None created_at: Optional[datetime.datetime] = None crossfilter_enabled: Optional[bool] = None dashboard_elements: Optional[Sequence["DashboardElement"]] = None dashboard_filters: Optional[Sequence["DashboardFilter"]] = None dashboard_layouts: Optional[Sequence["DashboardLayout"]] = None deleted: Optional[bool] = None deleted_at: Optional[datetime.datetime] = None deleter_id: Optional[int] = None edit_uri: Optional[str] = None favorite_count: Optional[int] = None last_accessed_at: Optional[datetime.datetime] = None last_viewed_at: Optional[datetime.datetime] = None load_configuration: Optional[str] = None lookml_link_id: Optional[str] = None show_filters_bar: Optional[bool] = None show_title: Optional[bool] = None slug: Optional[str] = None folder_id: Optional[str] = None text_tile_text_color: Optional[str] = None tile_background_color: Optional[str] = None tile_text_color: Optional[str] = None title_color: Optional[str] = None view_count: Optional[int] = None appearance: Optional["DashboardAppearance"] = None preferred_viewer: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, content_favorite_id: Optional[int] = None, content_metadata_id: Optional[int] = None, description: Optional[str] = None, hidden: Optional[bool] = None, id: Optional[str] = None, model: Optional["LookModel"] = None, query_timezone: Optional[str] = None, readonly: Optional[bool] = None, refresh_interval: Optional[str] = None, refresh_interval_to_i: Optional[int] = None, folder: Optional["FolderBase"] = None, title: Optional[str] = None, user_id: Optional[int] = None, background_color: Optional[str] = None, created_at: Optional[datetime.datetime] = None, crossfilter_enabled: Optional[bool] = None, dashboard_elements: Optional[Sequence["DashboardElement"]] = None, dashboard_filters: Optional[Sequence["DashboardFilter"]] = None, dashboard_layouts: Optional[Sequence["DashboardLayout"]] = None, deleted: Optional[bool] = None, deleted_at: Optional[datetime.datetime] = None, deleter_id: Optional[int] = None, edit_uri: Optional[str] = None, favorite_count: Optional[int] = None, last_accessed_at: Optional[datetime.datetime] = None, last_viewed_at: Optional[datetime.datetime] = None, load_configuration: Optional[str] = None, lookml_link_id: Optional[str] = None, show_filters_bar: Optional[bool] = None, show_title: Optional[bool] = None, slug: Optional[str] = None, folder_id: Optional[str] = None, text_tile_text_color: Optional[str] = None, tile_background_color: Optional[str] = None, tile_text_color: Optional[str] = None, title_color: Optional[str] = None, view_count: Optional[int] = None, appearance: Optional["DashboardAppearance"] = None, preferred_viewer: Optional[str] = None ): self.can = can self.content_favorite_id = content_favorite_id self.content_metadata_id = content_metadata_id self.description = description self.hidden = hidden self.id = id self.model = model self.query_timezone = query_timezone self.readonly = readonly self.refresh_interval = refresh_interval self.refresh_interval_to_i = refresh_interval_to_i self.folder = folder self.title = title self.user_id = user_id self.background_color = background_color self.created_at = created_at self.crossfilter_enabled = crossfilter_enabled self.dashboard_elements = dashboard_elements self.dashboard_filters = dashboard_filters self.dashboard_layouts = dashboard_layouts self.deleted = deleted self.deleted_at = deleted_at self.deleter_id = deleter_id self.edit_uri = edit_uri self.favorite_count = favorite_count self.last_accessed_at = last_accessed_at self.last_viewed_at = last_viewed_at self.load_configuration = load_configuration self.lookml_link_id = lookml_link_id self.show_filters_bar = show_filters_bar self.show_title = show_title self.slug = slug self.folder_id = folder_id self.text_tile_text_color = text_tile_text_color self.tile_background_color = tile_background_color self.tile_text_color = tile_text_color self.title_color = title_color self.view_count = view_count self.appearance = appearance self.preferred_viewer = preferred_viewer @attr.s(auto_attribs=True, init=False) class DashboardAggregateTableLookml(model.Model): """ Attributes: dashboard_id: Dashboard Id aggregate_table_lookml: Aggregate Table LookML """ dashboard_id: Optional[str] = None aggregate_table_lookml: Optional[str] = None def __init__( self, *, dashboard_id: Optional[str] = None, aggregate_table_lookml: Optional[str] = None ): self.dashboard_id = dashboard_id self.aggregate_table_lookml = aggregate_table_lookml @attr.s(auto_attribs=True, init=False) class DashboardAppearance(model.Model): """ Attributes: page_side_margins: Page margin (side) width page_background_color: Background color for the dashboard tile_title_alignment: Title alignment on dashboard tiles tile_space_between: Space between tiles tile_background_color: Background color for tiles tile_shadow: Tile shadow on/off key_color: Key color """ page_side_margins: Optional[int] = None page_background_color: Optional[str] = None tile_title_alignment: Optional[str] = None tile_space_between: Optional[int] = None tile_background_color: Optional[str] = None tile_shadow: Optional[bool] = None key_color: Optional[str] = None def __init__( self, *, page_side_margins: Optional[int] = None, page_background_color: Optional[str] = None, tile_title_alignment: Optional[str] = None, tile_space_between: Optional[int] = None, tile_background_color: Optional[str] = None, tile_shadow: Optional[bool] = None, key_color: Optional[str] = None ): self.page_side_margins = page_side_margins self.page_background_color = page_background_color self.tile_title_alignment = tile_title_alignment self.tile_space_between = tile_space_between self.tile_background_color = tile_background_color self.tile_shadow = tile_shadow self.key_color = key_color @attr.s(auto_attribs=True, init=False) class DashboardBase(model.Model): """ Attributes: can: Operations the current user is able to perform on this object content_favorite_id: Content Favorite Id content_metadata_id: Id of content metadata description: Description hidden: Is Hidden id: Unique Id model: query_timezone: Timezone in which the Dashboard will run by default. readonly: Is Read-only refresh_interval: Refresh Interval, as a time duration phrase like "2 hours 30 minutes". A number with no time units will be interpreted as whole seconds. refresh_interval_to_i: Refresh Interval in milliseconds folder: title: Dashboard Title user_id: Id of User """ can: Optional[MutableMapping[str, bool]] = None content_favorite_id: Optional[int] = None content_metadata_id: Optional[int] = None description: Optional[str] = None hidden: Optional[bool] = None id: Optional[str] = None model: Optional["LookModel"] = None query_timezone: Optional[str] = None readonly: Optional[bool] = None refresh_interval: Optional[str] = None refresh_interval_to_i: Optional[int] = None folder: Optional["FolderBase"] = None title: Optional[str] = None user_id: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, content_favorite_id: Optional[int] = None, content_metadata_id: Optional[int] = None, description: Optional[str] = None, hidden: Optional[bool] = None, id: Optional[str] = None, model: Optional["LookModel"] = None, query_timezone: Optional[str] = None, readonly: Optional[bool] = None, refresh_interval: Optional[str] = None, refresh_interval_to_i: Optional[int] = None, folder: Optional["FolderBase"] = None, title: Optional[str] = None, user_id: Optional[int] = None ): self.can = can self.content_favorite_id = content_favorite_id self.content_metadata_id = content_metadata_id self.description = description self.hidden = hidden self.id = id self.model = model self.query_timezone = query_timezone self.readonly = readonly self.refresh_interval = refresh_interval self.refresh_interval_to_i = refresh_interval_to_i self.folder = folder self.title = title self.user_id = user_id @attr.s(auto_attribs=True, init=False) class DashboardElement(model.Model): """ Attributes: can: Operations the current user is able to perform on this object body_text: Text tile body text body_text_as_html: Text tile body text as Html dashboard_id: Id of Dashboard edit_uri: Relative path of URI of LookML file to edit the dashboard element (LookML dashboard only). id: Unique Id look: look_id: Id Of Look lookml_link_id: LookML link ID merge_result_id: ID of merge result note_display: Note Display note_state: Note State note_text: Note Text note_text_as_html: Note Text as Html query: query_id: Id Of Query refresh_interval: Refresh Interval refresh_interval_to_i: Refresh Interval as integer result_maker: result_maker_id: ID of the ResultMakerLookup entry. subtitle_text: Text tile subtitle text title: Title of dashboard element title_hidden: Whether title is hidden title_text: Text tile title type: Type alert_count: Count of Alerts associated to a dashboard element title_text_as_html: Text tile title text as Html subtitle_text_as_html: Text tile subtitle text as Html """ can: Optional[MutableMapping[str, bool]] = None body_text: Optional[str] = None body_text_as_html: Optional[str] = None dashboard_id: Optional[str] = None edit_uri: Optional[str] = None id: Optional[str] = None look: Optional["LookWithQuery"] = None look_id: Optional[str] = None lookml_link_id: Optional[str] = None merge_result_id: Optional[str] = None note_display: Optional[str] = None note_state: Optional[str] = None note_text: Optional[str] = None note_text_as_html: Optional[str] = None query: Optional["Query"] = None query_id: Optional[int] = None refresh_interval: Optional[str] = None refresh_interval_to_i: Optional[int] = None result_maker: Optional["ResultMakerWithIdVisConfigAndDynamicFields"] = None result_maker_id: Optional[int] = None subtitle_text: Optional[str] = None title: Optional[str] = None title_hidden: Optional[bool] = None title_text: Optional[str] = None type: Optional[str] = None alert_count: Optional[int] = None title_text_as_html: Optional[str] = None subtitle_text_as_html: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, body_text: Optional[str] = None, body_text_as_html: Optional[str] = None, dashboard_id: Optional[str] = None, edit_uri: Optional[str] = None, id: Optional[str] = None, look: Optional["LookWithQuery"] = None, look_id: Optional[str] = None, lookml_link_id: Optional[str] = None, merge_result_id: Optional[str] = None, note_display: Optional[str] = None, note_state: Optional[str] = None, note_text: Optional[str] = None, note_text_as_html: Optional[str] = None, query: Optional["Query"] = None, query_id: Optional[int] = None, refresh_interval: Optional[str] = None, refresh_interval_to_i: Optional[int] = None, result_maker: Optional["ResultMakerWithIdVisConfigAndDynamicFields"] = None, result_maker_id: Optional[int] = None, subtitle_text: Optional[str] = None, title: Optional[str] = None, title_hidden: Optional[bool] = None, title_text: Optional[str] = None, type: Optional[str] = None, alert_count: Optional[int] = None, title_text_as_html: Optional[str] = None, subtitle_text_as_html: Optional[str] = None ): self.can = can self.body_text = body_text self.body_text_as_html = body_text_as_html self.dashboard_id = dashboard_id self.edit_uri = edit_uri self.id = id self.look = look self.look_id = look_id self.lookml_link_id = lookml_link_id self.merge_result_id = merge_result_id self.note_display = note_display self.note_state = note_state self.note_text = note_text self.note_text_as_html = note_text_as_html self.query = query self.query_id = query_id self.refresh_interval = refresh_interval self.refresh_interval_to_i = refresh_interval_to_i self.result_maker = result_maker self.result_maker_id = result_maker_id self.subtitle_text = subtitle_text self.title = title self.title_hidden = title_hidden self.title_text = title_text self.type = type self.alert_count = alert_count self.title_text_as_html = title_text_as_html self.subtitle_text_as_html = subtitle_text_as_html @attr.s(auto_attribs=True, init=False) class DashboardFilter(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id dashboard_id: Id of Dashboard name: Name of filter title: Title of filter type: Type of filter: one of date, number, string, or field default_value: Default value of filter model: Model of filter (required if type = field) explore: Explore of filter (required if type = field) dimension: Dimension of filter (required if type = field) field: Field information row: Display order of this filter relative to other filters listens_to_filters: Array of listeners for faceted filters allow_multiple_values: Whether the filter allows multiple filter values required: Whether the filter requires a value to run the dashboard ui_config: The visual configuration for this filter. Used to set up how the UI for this filter should appear. """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None dashboard_id: Optional[str] = None name: Optional[str] = None title: Optional[str] = None type: Optional[str] = None default_value: Optional[str] = None model: Optional[str] = None explore: Optional[str] = None dimension: Optional[str] = None field: Optional[MutableMapping[str, Any]] = None row: Optional[int] = None listens_to_filters: Optional[Sequence[str]] = None allow_multiple_values: Optional[bool] = None required: Optional[bool] = None ui_config: Optional[MutableMapping[str, Any]] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, dashboard_id: Optional[str] = None, name: Optional[str] = None, title: Optional[str] = None, type: Optional[str] = None, default_value: Optional[str] = None, model: Optional[str] = None, explore: Optional[str] = None, dimension: Optional[str] = None, field: Optional[MutableMapping[str, Any]] = None, row: Optional[int] = None, listens_to_filters: Optional[Sequence[str]] = None, allow_multiple_values: Optional[bool] = None, required: Optional[bool] = None, ui_config: Optional[MutableMapping[str, Any]] = None ): self.can = can self.id = id self.dashboard_id = dashboard_id self.name = name self.title = title self.type = type self.default_value = default_value self.model = model self.explore = explore self.dimension = dimension self.field = field self.row = row self.listens_to_filters = listens_to_filters self.allow_multiple_values = allow_multiple_values self.required = required self.ui_config = ui_config @attr.s(auto_attribs=True, init=False) class DashboardLayout(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id dashboard_id: Id of Dashboard type: Type active: Is Active column_width: Column Width width: Width deleted: Whether or not the dashboard layout is deleted. dashboard_title: Title extracted from the dashboard this layout represents. dashboard_layout_components: Components """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None dashboard_id: Optional[str] = None type: Optional[str] = None active: Optional[bool] = None column_width: Optional[int] = None width: Optional[int] = None deleted: Optional[bool] = None dashboard_title: Optional[str] = None dashboard_layout_components: Optional[Sequence["DashboardLayoutComponent"]] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, dashboard_id: Optional[str] = None, type: Optional[str] = None, active: Optional[bool] = None, column_width: Optional[int] = None, width: Optional[int] = None, deleted: Optional[bool] = None, dashboard_title: Optional[str] = None, dashboard_layout_components: Optional[ Sequence["DashboardLayoutComponent"] ] = None ): self.can = can self.id = id self.dashboard_id = dashboard_id self.type = type self.active = active self.column_width = column_width self.width = width self.deleted = deleted self.dashboard_title = dashboard_title self.dashboard_layout_components = dashboard_layout_components @attr.s(auto_attribs=True, init=False) class DashboardLayoutComponent(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id dashboard_layout_id: Id of Dashboard Layout dashboard_element_id: Id Of Dashboard Element row: Row column: Column width: Width height: Height deleted: Whether or not the dashboard layout component is deleted element_title: Dashboard element title, extracted from the Dashboard Element. element_title_hidden: Whether or not the dashboard element title is displayed. vis_type: Visualization type, extracted from a query's vis_config """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None dashboard_layout_id: Optional[str] = None dashboard_element_id: Optional[str] = None row: Optional[int] = None column: Optional[int] = None width: Optional[int] = None height: Optional[int] = None deleted: Optional[bool] = None element_title: Optional[str] = None element_title_hidden: Optional[bool] = None vis_type: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, dashboard_layout_id: Optional[str] = None, dashboard_element_id: Optional[str] = None, row: Optional[int] = None, column: Optional[int] = None, width: Optional[int] = None, height: Optional[int] = None, deleted: Optional[bool] = None, element_title: Optional[str] = None, element_title_hidden: Optional[bool] = None, vis_type: Optional[str] = None ): self.can = can self.id = id self.dashboard_layout_id = dashboard_layout_id self.dashboard_element_id = dashboard_element_id self.row = row self.column = column self.width = width self.height = height self.deleted = deleted self.element_title = element_title self.element_title_hidden = element_title_hidden self.vis_type = vis_type @attr.s(auto_attribs=True, init=False) class DashboardLookml(model.Model): """ Attributes: dashboard_id: Id of Dashboard lookml: lookml of UDD """ dashboard_id: Optional[str] = None lookml: Optional[str] = None def __init__( self, *, dashboard_id: Optional[str] = None, lookml: Optional[str] = None ): self.dashboard_id = dashboard_id self.lookml = lookml @attr.s(auto_attribs=True, init=False) class DataActionForm(model.Model): """ Attributes: state: fields: Array of form fields. """ state: Optional["DataActionUserState"] = None fields: Optional[Sequence["DataActionFormField"]] = None def __init__( self, *, state: Optional["DataActionUserState"] = None, fields: Optional[Sequence["DataActionFormField"]] = None ): self.state = state self.fields = fields @attr.s(auto_attribs=True, init=False) class DataActionFormField(model.Model): """ Attributes: name: Name label: Human-readable label description: Description of field type: Type of field. default: Default value of the field. oauth_url: The URL for an oauth link, if type is 'oauth_link'. interactive: Whether or not a field supports interactive forms. required: Whether or not the field is required. This is a user-interface hint. A user interface displaying this form should not submit it without a value for this field. The action server must also perform this validation. options: If the form type is 'select', a list of options to be selected from. """ name: Optional[str] = None label: Optional[str] = None description: Optional[str] = None type: Optional[str] = None default: Optional[str] = None oauth_url: Optional[str] = None interactive: Optional[bool] = None required: Optional[bool] = None options: Optional[Sequence["DataActionFormSelectOption"]] = None def __init__( self, *, name: Optional[str] = None, label: Optional[str] = None, description: Optional[str] = None, type: Optional[str] = None, default: Optional[str] = None, oauth_url: Optional[str] = None, interactive: Optional[bool] = None, required: Optional[bool] = None, options: Optional[Sequence["DataActionFormSelectOption"]] = None ): self.name = name self.label = label self.description = description self.type = type self.default = default self.oauth_url = oauth_url self.interactive = interactive self.required = required self.options = options @attr.s(auto_attribs=True, init=False) class DataActionFormSelectOption(model.Model): """ Attributes: name: Name label: Human-readable label """ name: Optional[str] = None label: Optional[str] = None def __init__(self, *, name: Optional[str] = None, label: Optional[str] = None): self.name = name self.label = label @attr.s(auto_attribs=True, init=False) class DataActionRequest(model.Model): """ Attributes: action: The JSON describing the data action. This JSON should be considered opaque and should be passed through unmodified from the query result it came from. form_values: User input for any form values the data action might use. """ action: Optional[MutableMapping[str, Any]] = None form_values: Optional[MutableMapping[str, Any]] = None def __init__( self, *, action: Optional[MutableMapping[str, Any]] = None, form_values: Optional[MutableMapping[str, Any]] = None ): self.action = action self.form_values = form_values @attr.s(auto_attribs=True, init=False) class DataActionResponse(model.Model): """ Attributes: webhook_id: ID of the webhook event that sent this data action. In some error conditions, this may be null. success: Whether the data action was successful. refresh_query: When true, indicates that the client should refresh (rerun) the source query because the data may have been changed by the action. validation_errors: message: Optional message returned by the data action server describing the state of the action that took place. This can be used to implement custom failure messages. If a failure is related to a particular form field, the server should send back a validation error instead. The Looker web UI does not currently display any message if the action indicates 'success', but may do so in the future. """ webhook_id: Optional[str] = None success: Optional[bool] = None refresh_query: Optional[bool] = None validation_errors: Optional["ValidationError"] = None message: Optional[str] = None def __init__( self, *, webhook_id: Optional[str] = None, success: Optional[bool] = None, refresh_query: Optional[bool] = None, validation_errors: Optional["ValidationError"] = None, message: Optional[str] = None ): self.webhook_id = webhook_id self.success = success self.refresh_query = refresh_query self.validation_errors = validation_errors self.message = message @attr.s(auto_attribs=True, init=False) class DataActionUserState(model.Model): """ Attributes: data: User state data refresh_time: Time in seconds until the state needs to be refreshed """ data: Optional[str] = None refresh_time: Optional[int] = None def __init__( self, *, data: Optional[str] = None, refresh_time: Optional[int] = None ): self.data = data self.refresh_time = refresh_time @attr.s(auto_attribs=True, init=False) class Datagroup(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: UNIX timestamp at which this entry was created. id: Unique ID of the datagroup model_name: Name of the model containing the datagroup. Unique when combined with name. name: Name of the datagroup. Unique when combined with model_name. stale_before: UNIX timestamp before which cache entries are considered stale. Cannot be in the future. trigger_check_at: UNIX timestamp at which this entry trigger was last checked. trigger_error: The message returned with the error of the last trigger check. trigger_value: The value of the trigger when last checked. triggered_at: UNIX timestamp at which this entry became triggered. Cannot be in the future. """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[int] = None id: Optional[int] = None model_name: Optional[str] = None name: Optional[str] = None stale_before: Optional[int] = None trigger_check_at: Optional[int] = None trigger_error: Optional[str] = None trigger_value: Optional[str] = None triggered_at: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[int] = None, id: Optional[int] = None, model_name: Optional[str] = None, name: Optional[str] = None, stale_before: Optional[int] = None, trigger_check_at: Optional[int] = None, trigger_error: Optional[str] = None, trigger_value: Optional[str] = None, triggered_at: Optional[int] = None ): self.can = can self.created_at = created_at self.id = id self.model_name = model_name self.name = name self.stale_before = stale_before self.trigger_check_at = trigger_check_at self.trigger_error = trigger_error self.trigger_value = trigger_value self.triggered_at = triggered_at @attr.s(auto_attribs=True, init=False) class DBConnection(model.Model): """ Attributes: can: Operations the current user is able to perform on this object name: Name of the connection. Also used as the unique identifier dialect: snippets: SQL Runner snippets for this connection pdts_enabled: True if PDTs are enabled on this connection host: Host name/address of server port: Port number on server username: Username for server authentication password: (Write-Only) Password for server authentication uses_oauth: Whether the connection uses OAuth for authentication. certificate: (Write-Only) Base64 encoded Certificate body for server authentication (when appropriate for dialect). file_type: (Write-Only) Certificate keyfile type - .json or .p12 database: Database name db_timezone: Time zone of database query_timezone: Timezone to use in queries schema: Scheme name max_connections: Maximum number of concurrent connection to use max_billing_gigabytes: Maximum size of query in GBs (BigQuery only, can be a user_attribute name) ssl: Use SSL/TLS when connecting to server verify_ssl: Verify the SSL tmp_db_name: Name of temporary database (if used) jdbc_additional_params: Additional params to add to JDBC connection string pool_timeout: Connection Pool Timeout, in seconds dialect_name: (Read/Write) SQL Dialect name created_at: Creation date for this connection user_id: Id of user who last modified this connection configuration example: Is this an example connection? user_db_credentials: (Limited access feature) Are per user db credentials enabled. Enabling will remove previously set username and password user_attribute_fields: Fields whose values map to user attribute names maintenance_cron: Cron string specifying when maintenance such as PDT trigger checks and drops should be performed last_regen_at: Unix timestamp at start of last completed PDT trigger check process last_reap_at: Unix timestamp at start of last completed PDT reap process sql_runner_precache_tables: Precache tables in the SQL Runner after_connect_statements: SQL statements (semicolon separated) to issue after connecting to the database. Requires `custom_after_connect_statements` license feature pdt_context_override: managed: Is this connection created and managed by Looker tunnel_id: The Id of the ssh tunnel this connection uses pdt_concurrency: Maximum number of threads to use to build PDTs in parallel disable_context_comment: When disable_context_comment is true comment will not be added to SQL """ can: Optional[MutableMapping[str, bool]] = None name: Optional[str] = None dialect: Optional["Dialect"] = None snippets: Optional[Sequence["Snippet"]] = None pdts_enabled: Optional[bool] = None host: Optional[str] = None port: Optional[int] = None username: Optional[str] = None password: Optional[str] = None uses_oauth: Optional[bool] = None certificate: Optional[str] = None file_type: Optional[str] = None database: Optional[str] = None db_timezone: Optional[str] = None query_timezone: Optional[str] = None schema: Optional[str] = None max_connections: Optional[int] = None max_billing_gigabytes: Optional[str] = None ssl: Optional[bool] = None verify_ssl: Optional[bool] = None tmp_db_name: Optional[str] = None jdbc_additional_params: Optional[str] = None pool_timeout: Optional[int] = None dialect_name: Optional[str] = None created_at: Optional[str] = None user_id: Optional[str] = None example: Optional[bool] = None user_db_credentials: Optional[bool] = None user_attribute_fields: Optional[Sequence[str]] = None maintenance_cron: Optional[str] = None last_regen_at: Optional[str] = None last_reap_at: Optional[str] = None sql_runner_precache_tables: Optional[bool] = None after_connect_statements: Optional[str] = None pdt_context_override: Optional["DBConnectionOverride"] = None managed: Optional[bool] = None tunnel_id: Optional[str] = None pdt_concurrency: Optional[int] = None disable_context_comment: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, name: Optional[str] = None, dialect: Optional["Dialect"] = None, snippets: Optional[Sequence["Snippet"]] = None, pdts_enabled: Optional[bool] = None, host: Optional[str] = None, port: Optional[int] = None, username: Optional[str] = None, password: Optional[str] = None, uses_oauth: Optional[bool] = None, certificate: Optional[str] = None, file_type: Optional[str] = None, database: Optional[str] = None, db_timezone: Optional[str] = None, query_timezone: Optional[str] = None, schema: Optional[str] = None, max_connections: Optional[int] = None, max_billing_gigabytes: Optional[str] = None, ssl: Optional[bool] = None, verify_ssl: Optional[bool] = None, tmp_db_name: Optional[str] = None, jdbc_additional_params: Optional[str] = None, pool_timeout: Optional[int] = None, dialect_name: Optional[str] = None, created_at: Optional[str] = None, user_id: Optional[str] = None, example: Optional[bool] = None, user_db_credentials: Optional[bool] = None, user_attribute_fields: Optional[Sequence[str]] = None, maintenance_cron: Optional[str] = None, last_regen_at: Optional[str] = None, last_reap_at: Optional[str] = None, sql_runner_precache_tables: Optional[bool] = None, after_connect_statements: Optional[str] = None, pdt_context_override: Optional["DBConnectionOverride"] = None, managed: Optional[bool] = None, tunnel_id: Optional[str] = None, pdt_concurrency: Optional[int] = None, disable_context_comment: Optional[bool] = None ): self.can = can self.name = name self.dialect = dialect self.snippets = snippets self.pdts_enabled = pdts_enabled self.host = host self.port = port self.username = username self.password = password self.uses_oauth = uses_oauth self.certificate = certificate self.file_type = file_type self.database = database self.db_timezone = db_timezone self.query_timezone = query_timezone self.schema = schema self.max_connections = max_connections self.max_billing_gigabytes = max_billing_gigabytes self.ssl = ssl self.verify_ssl = verify_ssl self.tmp_db_name = tmp_db_name self.jdbc_additional_params = jdbc_additional_params self.pool_timeout = pool_timeout self.dialect_name = dialect_name self.created_at = created_at self.user_id = user_id self.example = example self.user_db_credentials = user_db_credentials self.user_attribute_fields = user_attribute_fields self.maintenance_cron = maintenance_cron self.last_regen_at = last_regen_at self.last_reap_at = last_reap_at self.sql_runner_precache_tables = sql_runner_precache_tables self.after_connect_statements = after_connect_statements self.pdt_context_override = pdt_context_override self.managed = managed self.tunnel_id = tunnel_id self.pdt_concurrency = pdt_concurrency self.disable_context_comment = disable_context_comment @attr.s(auto_attribs=True, init=False) class DBConnectionBase(model.Model): """ Attributes: can: Operations the current user is able to perform on this object name: Name of the connection. Also used as the unique identifier dialect: snippets: SQL Runner snippets for this connection pdts_enabled: True if PDTs are enabled on this connection """ can: Optional[MutableMapping[str, bool]] = None name: Optional[str] = None dialect: Optional["Dialect"] = None snippets: Optional[Sequence["Snippet"]] = None pdts_enabled: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, name: Optional[str] = None, dialect: Optional["Dialect"] = None, snippets: Optional[Sequence["Snippet"]] = None, pdts_enabled: Optional[bool] = None ): self.can = can self.name = name self.dialect = dialect self.snippets = snippets self.pdts_enabled = pdts_enabled @attr.s(auto_attribs=True, init=False) class DBConnectionOverride(model.Model): """ Attributes: context: Context in which to override (`pdt` is the only allowed value) host: Host name/address of server port: Port number on server username: Username for server authentication password: (Write-Only) Password for server authentication has_password: Whether or not the password is overridden in this context certificate: (Write-Only) Base64 encoded Certificate body for server authentication (when appropriate for dialect). file_type: (Write-Only) Certificate keyfile type - .json or .p12 database: Database name schema: Scheme name jdbc_additional_params: Additional params to add to JDBC connection string after_connect_statements: SQL statements (semicolon separated) to issue after connecting to the database. Requires `custom_after_connect_statements` license feature """ context: Optional[str] = None host: Optional[str] = None port: Optional[str] = None username: Optional[str] = None password: Optional[str] = None has_password: Optional[bool] = None certificate: Optional[str] = None file_type: Optional[str] = None database: Optional[str] = None schema: Optional[str] = None jdbc_additional_params: Optional[str] = None after_connect_statements: Optional[str] = None def __init__( self, *, context: Optional[str] = None, host: Optional[str] = None, port: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, has_password: Optional[bool] = None, certificate: Optional[str] = None, file_type: Optional[str] = None, database: Optional[str] = None, schema: Optional[str] = None, jdbc_additional_params: Optional[str] = None, after_connect_statements: Optional[str] = None ): self.context = context self.host = host self.port = port self.username = username self.password = password self.has_password = has_password self.certificate = certificate self.file_type = file_type self.database = database self.schema = schema self.jdbc_additional_params = jdbc_additional_params self.after_connect_statements = after_connect_statements @attr.s(auto_attribs=True, init=False) class DBConnectionTestResult(model.Model): """ Attributes: can: Operations the current user is able to perform on this object connection_string: JDBC connection string. (only populated in the 'connect' test) message: Result message of test name: Name of test status: Result code of test """ can: Optional[MutableMapping[str, bool]] = None connection_string: Optional[str] = None message: Optional[str] = None name: Optional[str] = None status: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, connection_string: Optional[str] = None, message: Optional[str] = None, name: Optional[str] = None, status: Optional[str] = None ): self.can = can self.connection_string = connection_string self.message = message self.name = name self.status = status @attr.s(auto_attribs=True, init=False) class DelegateOauthTest(model.Model): """ Attributes: name: Delegate Oauth Connection Name installation_target_id: The ID of the installation target. For Slack, this would be workspace id. installation_id: Installation ID success: Whether or not the test was successful """ name: Optional[str] = None installation_target_id: Optional[str] = None installation_id: Optional[int] = None success: Optional[bool] = None def __init__( self, *, name: Optional[str] = None, installation_target_id: Optional[str] = None, installation_id: Optional[int] = None, success: Optional[bool] = None ): self.name = name self.installation_target_id = installation_target_id self.installation_id = installation_id self.success = success class DependencyStatus(enum.Enum): """ Status of the dependencies in your project. Valid values are: "lock_optional", "lock_required", "lock_error", "install_none". """ lock_optional = "lock_optional" lock_required = "lock_required" lock_error = "lock_error" install_none = "install_none" invalid_api_enum_value = "invalid_api_enum_value" DependencyStatus.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class Dialect(model.Model): """ Attributes: name: The name of the dialect label: The human-readable label of the connection supports_cost_estimate: Whether the dialect supports query cost estimates persistent_table_indexes: PDT index columns persistent_table_sortkeys: PDT sortkey columns persistent_table_distkey: PDT distkey column supports_streaming: Suports streaming results automatically_run_sql_runner_snippets: Should SQL Runner snippets automatically be run connection_tests: Array of names of the tests that can be run on a connection using this dialect supports_inducer: Is supported with the inducer (i.e. generate from sql) supports_multiple_databases: Can multiple databases be accessed from a connection using this dialect supports_persistent_derived_tables: Whether the dialect supports allowing Looker to build persistent derived tables has_ssl_support: Does the database have client SSL support settable through the JDBC string explicitly? """ name: Optional[str] = None label: Optional[str] = None supports_cost_estimate: Optional[bool] = None persistent_table_indexes: Optional[str] = None persistent_table_sortkeys: Optional[str] = None persistent_table_distkey: Optional[str] = None supports_streaming: Optional[bool] = None automatically_run_sql_runner_snippets: Optional[bool] = None connection_tests: Optional[Sequence[str]] = None supports_inducer: Optional[bool] = None supports_multiple_databases: Optional[bool] = None supports_persistent_derived_tables: Optional[bool] = None has_ssl_support: Optional[bool] = None def __init__( self, *, name: Optional[str] = None, label: Optional[str] = None, supports_cost_estimate: Optional[bool] = None, persistent_table_indexes: Optional[str] = None, persistent_table_sortkeys: Optional[str] = None, persistent_table_distkey: Optional[str] = None, supports_streaming: Optional[bool] = None, automatically_run_sql_runner_snippets: Optional[bool] = None, connection_tests: Optional[Sequence[str]] = None, supports_inducer: Optional[bool] = None, supports_multiple_databases: Optional[bool] = None, supports_persistent_derived_tables: Optional[bool] = None, has_ssl_support: Optional[bool] = None ): self.name = name self.label = label self.supports_cost_estimate = supports_cost_estimate self.persistent_table_indexes = persistent_table_indexes self.persistent_table_sortkeys = persistent_table_sortkeys self.persistent_table_distkey = persistent_table_distkey self.supports_streaming = supports_streaming self.automatically_run_sql_runner_snippets = ( automatically_run_sql_runner_snippets ) self.connection_tests = connection_tests self.supports_inducer = supports_inducer self.supports_multiple_databases = supports_multiple_databases self.supports_persistent_derived_tables = supports_persistent_derived_tables self.has_ssl_support = has_ssl_support @attr.s(auto_attribs=True, init=False) class DialectInfo(model.Model): """ Attributes: can: Operations the current user is able to perform on this object default_max_connections: Default number max connections default_port: Default port number installed: Is the supporting driver installed label: The human-readable label of the connection label_for_database_equivalent: What the dialect calls the equivalent of a normal SQL table name: The name of the dialect supported_options: """ can: Optional[MutableMapping[str, bool]] = None default_max_connections: Optional[str] = None default_port: Optional[str] = None installed: Optional[bool] = None label: Optional[str] = None label_for_database_equivalent: Optional[str] = None name: Optional[str] = None supported_options: Optional["DialectInfoOptions"] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, default_max_connections: Optional[str] = None, default_port: Optional[str] = None, installed: Optional[bool] = None, label: Optional[str] = None, label_for_database_equivalent: Optional[str] = None, name: Optional[str] = None, supported_options: Optional["DialectInfoOptions"] = None ): self.can = can self.default_max_connections = default_max_connections self.default_port = default_port self.installed = installed self.label = label self.label_for_database_equivalent = label_for_database_equivalent self.name = name self.supported_options = supported_options @attr.s(auto_attribs=True, init=False) class DialectInfoOptions(model.Model): """ Attributes: additional_params: Has additional params support auth: Has auth support host: Has host support oauth_credentials: Has support for a service account project_name: Has project name support schema: Has schema support ssl: Has SSL support timezone: Has timezone support tmp_table: Has tmp table support username_required: Username is required """ additional_params: Optional[bool] = None auth: Optional[bool] = None host: Optional[bool] = None oauth_credentials: Optional[bool] = None project_name: Optional[bool] = None schema: Optional[bool] = None ssl: Optional[bool] = None timezone: Optional[bool] = None tmp_table: Optional[bool] = None username_required: Optional[bool] = None def __init__( self, *, additional_params: Optional[bool] = None, auth: Optional[bool] = None, host: Optional[bool] = None, oauth_credentials: Optional[bool] = None, project_name: Optional[bool] = None, schema: Optional[bool] = None, ssl: Optional[bool] = None, timezone: Optional[bool] = None, tmp_table: Optional[bool] = None, username_required: Optional[bool] = None ): self.additional_params = additional_params self.auth = auth self.host = host self.oauth_credentials = oauth_credentials self.project_name = project_name self.schema = schema self.ssl = ssl self.timezone = timezone self.tmp_table = tmp_table self.username_required = username_required @attr.s(auto_attribs=True, init=False) class DigestEmails(model.Model): """ Attributes: is_enabled: Whether or not digest emails are enabled """ is_enabled: Optional[bool] = None def __init__(self, *, is_enabled: Optional[bool] = None): self.is_enabled = is_enabled @attr.s(auto_attribs=True, init=False) class DigestEmailSend(model.Model): """ Attributes: configuration_delivered: True if content was successfully generated and delivered """ configuration_delivered: Optional[bool] = None def __init__(self, *, configuration_delivered: Optional[bool] = None): self.configuration_delivered = configuration_delivered @attr.s(auto_attribs=True, init=False) class DiscretePalette(model.Model): """ Attributes: id: Unique identity string label: Label for palette type: Type of palette colors: Array of colors in the palette """ id: Optional[str] = None label: Optional[str] = None type: Optional[str] = None colors: Optional[Sequence[str]] = None def __init__( self, *, id: Optional[str] = None, label: Optional[str] = None, type: Optional[str] = None, colors: Optional[Sequence[str]] = None ): self.id = id self.label = label self.type = type self.colors = colors @attr.s(auto_attribs=True, init=False) class EmbedParams(model.Model): """ Attributes: target_url: The complete URL of the Looker UI page to display in the embed context. For example, to display the dashboard with id 34, `target_url` would look like: `https://mycompany.looker.com:9999/dashboards/34`. `target_uri` MUST contain a scheme (HTTPS), domain name, and URL path. Port must be included if it is required to reach the Looker server from browser clients. If the Looker instance is behind a load balancer or other proxy, `target_uri` must be the public-facing domain name and port required to reach the Looker instance, not the actual internal network machine name of the Looker instance. session_length: Number of seconds the SSO embed session will be valid after the embed session is started. Defaults to 300 seconds. Maximum session length accepted is 2592000 seconds (30 days). force_logout_login: When true, the embed session will purge any residual Looker login state (such as in browser cookies) before creating a new login state with the given embed user info. Defaults to true. """ target_url: str session_length: Optional[int] = None force_logout_login: Optional[bool] = None def __init__( self, *, target_url: str, session_length: Optional[int] = None, force_logout_login: Optional[bool] = None ): self.target_url = target_url self.session_length = session_length self.force_logout_login = force_logout_login @attr.s(auto_attribs=True, init=False) class EmbedSsoParams(model.Model): """ Attributes: target_url: The complete URL of the Looker UI page to display in the embed context. For example, to display the dashboard with id 34, `target_url` would look like: `https://mycompany.looker.com:9999/dashboards/34`. `target_uri` MUST contain a scheme (HTTPS), domain name, and URL path. Port must be included if it is required to reach the Looker server from browser clients. If the Looker instance is behind a load balancer or other proxy, `target_uri` must be the public-facing domain name and port required to reach the Looker instance, not the actual internal network machine name of the Looker instance. session_length: Number of seconds the SSO embed session will be valid after the embed session is started. Defaults to 300 seconds. Maximum session length accepted is 2592000 seconds (30 days). force_logout_login: When true, the embed session will purge any residual Looker login state (such as in browser cookies) before creating a new login state with the given embed user info. Defaults to true. external_user_id: A value from an external system that uniquely identifies the embed user. Since the user_ids of Looker embed users may change with every embed session, external_user_id provides a way to assign a known, stable user identifier across multiple embed sessions. first_name: First name of the embed user. Defaults to 'Embed' if not specified last_name: Last name of the embed user. Defaults to 'User' if not specified user_timezone: Sets the user timezone for the embed user session, if the User Specific Timezones setting is enabled in the Looker admin settings. A value of `null` forces the embed user to use the Looker Application Default Timezone. You MUST omit this property from the request if the User Specific Timezones setting is disabled. Timezone values are validated against the IANA Timezone standard and can be seen in the Application Time Zone dropdown list on the Looker General Settings admin page. permissions: List of Looker permission names to grant to the embed user. Requested permissions will be filtered to permissions allowed for embed sessions. models: List of model names that the embed user may access group_ids: List of Looker group ids in which to enroll the embed user external_group_id: A unique value identifying an embed-exclusive group. Multiple embed users using the same `external_group_id` value will be able to share Looker content with each other. Content and embed users associated with the `external_group_id` will not be accessible to normal Looker users or embed users not associated with this `external_group_id`. user_attributes: A dictionary of name-value pairs associating a Looker user attribute name with a value. secret_id: Id of the embed secret to use to sign this SSO url. If specified, the value must be an id of a valid (active) secret defined in the Looker instance. If not specified, the URL will be signed with the newest active embed secret defined in the Looker instance. """ target_url: str session_length: Optional[int] = None force_logout_login: Optional[bool] = None external_user_id: Optional[str] = None first_name: Optional[str] = None last_name: Optional[str] = None user_timezone: Optional[str] = None permissions: Optional[Sequence[str]] = None models: Optional[Sequence[str]] = None group_ids: Optional[Sequence[int]] = None external_group_id: Optional[int] = None user_attributes: Optional[MutableMapping[str, Any]] = None secret_id: Optional[int] = None def __init__( self, *, target_url: str, session_length: Optional[int] = None, force_logout_login: Optional[bool] = None, external_user_id: Optional[str] = None, first_name: Optional[str] = None, last_name: Optional[str] = None, user_timezone: Optional[str] = None, permissions: Optional[Sequence[str]] = None, models: Optional[Sequence[str]] = None, group_ids: Optional[Sequence[int]] = None, external_group_id: Optional[int] = None, user_attributes: Optional[MutableMapping[str, Any]] = None, secret_id: Optional[int] = None ): self.target_url = target_url self.session_length = session_length self.force_logout_login = force_logout_login self.external_user_id = external_user_id self.first_name = first_name self.last_name = last_name self.user_timezone = user_timezone self.permissions = permissions self.models = models self.group_ids = group_ids self.external_group_id = external_group_id self.user_attributes = user_attributes self.secret_id = secret_id @attr.s(auto_attribs=True, init=False) class EmbedUrlResponse(model.Model): """ Attributes: url: The embed URL. Any modification to this string will make the URL unusable. """ url: Optional[str] = None def __init__(self, *, url: Optional[str] = None): self.url = url @attr.s(auto_attribs=True, init=False) class Error(model.Model): """ Attributes: message: Error details documentation_url: Documentation link """ message: str documentation_url: str def __init__(self, *, message: str, documentation_url: str): self.message = message self.documentation_url = documentation_url class FillStyle(enum.Enum): """ The style of dimension fill that is possible for this field. Null if no dimension fill is possible. Valid values are: "enumeration", "range". """ enumeration = "enumeration" range = "range" invalid_api_enum_value = "invalid_api_enum_value" FillStyle.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class Folder(model.Model): """ Attributes: name: Unique Name parent_id: Id of Parent. If the parent id is null, this is a root-level entry id: Unique Id content_metadata_id: Id of content metadata created_at: Time the space was created creator_id: User Id of Creator child_count: Children Count external_id: Embedder's Id if this folder was autogenerated as an embedding shared folder via 'external_group_id' in an SSO embed login is_embed: Folder is an embed folder is_embed_shared_root: Folder is the root embed shared folder is_embed_users_root: Folder is the root embed users folder is_personal: Folder is a user's personal folder is_personal_descendant: Folder is descendant of a user's personal folder is_shared_root: Folder is the root shared folder is_users_root: Folder is the root user folder can: Operations the current user is able to perform on this object dashboards: Dashboards looks: Looks """ name: str parent_id: Optional[str] = None id: Optional[str] = None content_metadata_id: Optional[int] = None created_at: Optional[datetime.datetime] = None creator_id: Optional[int] = None child_count: Optional[int] = None external_id: Optional[str] = None is_embed: Optional[bool] = None is_embed_shared_root: Optional[bool] = None is_embed_users_root: Optional[bool] = None is_personal: Optional[bool] = None is_personal_descendant: Optional[bool] = None is_shared_root: Optional[bool] = None is_users_root: Optional[bool] = None can: Optional[MutableMapping[str, bool]] = None dashboards: Optional[Sequence["DashboardBase"]] = None looks: Optional[Sequence["LookWithDashboards"]] = None def __init__( self, *, name: str, parent_id: Optional[str] = None, id: Optional[str] = None, content_metadata_id: Optional[int] = None, created_at: Optional[datetime.datetime] = None, creator_id: Optional[int] = None, child_count: Optional[int] = None, external_id: Optional[str] = None, is_embed: Optional[bool] = None, is_embed_shared_root: Optional[bool] = None, is_embed_users_root: Optional[bool] = None, is_personal: Optional[bool] = None, is_personal_descendant: Optional[bool] = None, is_shared_root: Optional[bool] = None, is_users_root: Optional[bool] = None, can: Optional[MutableMapping[str, bool]] = None, dashboards: Optional[Sequence["DashboardBase"]] = None, looks: Optional[Sequence["LookWithDashboards"]] = None ): self.name = name self.parent_id = parent_id self.id = id self.content_metadata_id = content_metadata_id self.created_at = created_at self.creator_id = creator_id self.child_count = child_count self.external_id = external_id self.is_embed = is_embed self.is_embed_shared_root = is_embed_shared_root self.is_embed_users_root = is_embed_users_root self.is_personal = is_personal self.is_personal_descendant = is_personal_descendant self.is_shared_root = is_shared_root self.is_users_root = is_users_root self.can = can self.dashboards = dashboards self.looks = looks @attr.s(auto_attribs=True, init=False) class FolderBase(model.Model): """ Attributes: name: Unique Name parent_id: Id of Parent. If the parent id is null, this is a root-level entry id: Unique Id content_metadata_id: Id of content metadata created_at: Time the folder was created creator_id: User Id of Creator child_count: Children Count external_id: Embedder's Id if this folder was autogenerated as an embedding shared folder via 'external_group_id' in an SSO embed login is_embed: Folder is an embed folder is_embed_shared_root: Folder is the root embed shared folder is_embed_users_root: Folder is the root embed users folder is_personal: Folder is a user's personal folder is_personal_descendant: Folder is descendant of a user's personal folder is_shared_root: Folder is the root shared folder is_users_root: Folder is the root user folder can: Operations the current user is able to perform on this object """ name: str parent_id: Optional[str] = None id: Optional[str] = None content_metadata_id: Optional[int] = None created_at: Optional[datetime.datetime] = None creator_id: Optional[int] = None child_count: Optional[int] = None external_id: Optional[str] = None is_embed: Optional[bool] = None is_embed_shared_root: Optional[bool] = None is_embed_users_root: Optional[bool] = None is_personal: Optional[bool] = None is_personal_descendant: Optional[bool] = None is_shared_root: Optional[bool] = None is_users_root: Optional[bool] = None can: Optional[MutableMapping[str, bool]] = None def __init__( self, *, name: str, parent_id: Optional[str] = None, id: Optional[str] = None, content_metadata_id: Optional[int] = None, created_at: Optional[datetime.datetime] = None, creator_id: Optional[int] = None, child_count: Optional[int] = None, external_id: Optional[str] = None, is_embed: Optional[bool] = None, is_embed_shared_root: Optional[bool] = None, is_embed_users_root: Optional[bool] = None, is_personal: Optional[bool] = None, is_personal_descendant: Optional[bool] = None, is_shared_root: Optional[bool] = None, is_users_root: Optional[bool] = None, can: Optional[MutableMapping[str, bool]] = None ): self.name = name self.parent_id = parent_id self.id = id self.content_metadata_id = content_metadata_id self.created_at = created_at self.creator_id = creator_id self.child_count = child_count self.external_id = external_id self.is_embed = is_embed self.is_embed_shared_root = is_embed_shared_root self.is_embed_users_root = is_embed_users_root self.is_personal = is_personal self.is_personal_descendant = is_personal_descendant self.is_shared_root = is_shared_root self.is_users_root = is_users_root self.can = can class Format(enum.Enum): """ Specifies the data format of the region information. Valid values are: "topojson", "vector_tile_region". """ topojson = "topojson" vector_tile_region = "vector_tile_region" invalid_api_enum_value = "invalid_api_enum_value" Format.__new__ = model.safe_enum__new__ class GitApplicationServerHttpScheme(enum.Enum): """ Scheme that is running on application server (for PRs, file browsing, etc.) Valid values are: "http", "https". """ http = "http" https = "https" invalid_api_enum_value = "invalid_api_enum_value" GitApplicationServerHttpScheme.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class GitBranch(model.Model): """ Attributes: can: Operations the current user is able to perform on this object name: The short name on the local. Updating `name` results in `git checkout <new_name>` remote: The name of the remote remote_name: The short name on the remote error: Name of error message: Message describing an error if present owner_name: Name of the owner of a personal branch readonly: Whether or not this branch is readonly personal: Whether or not this branch is a personal branch - readonly for all developers except the owner is_local: Whether or not a local ref exists for the branch is_remote: Whether or not a remote ref exists for the branch is_production: Whether or not this is the production branch ahead_count: Number of commits the local branch is ahead of the remote behind_count: Number of commits the local branch is behind the remote commit_at: UNIX timestamp at which this branch was last committed. ref: The resolved ref of this branch. Updating `ref` results in `git reset --hard <new_ref>``. remote_ref: The resolved ref of this branch remote. """ can: Optional[MutableMapping[str, bool]] = None name: Optional[str] = None remote: Optional[str] = None remote_name: Optional[str] = None error: Optional[str] = None message: Optional[str] = None owner_name: Optional[str] = None readonly: Optional[bool] = None personal: Optional[bool] = None is_local: Optional[bool] = None is_remote: Optional[bool] = None is_production: Optional[bool] = None ahead_count: Optional[int] = None behind_count: Optional[int] = None commit_at: Optional[int] = None ref: Optional[str] = None remote_ref: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, name: Optional[str] = None, remote: Optional[str] = None, remote_name: Optional[str] = None, error: Optional[str] = None, message: Optional[str] = None, owner_name: Optional[str] = None, readonly: Optional[bool] = None, personal: Optional[bool] = None, is_local: Optional[bool] = None, is_remote: Optional[bool] = None, is_production: Optional[bool] = None, ahead_count: Optional[int] = None, behind_count: Optional[int] = None, commit_at: Optional[int] = None, ref: Optional[str] = None, remote_ref: Optional[str] = None ): self.can = can self.name = name self.remote = remote self.remote_name = remote_name self.error = error self.message = message self.owner_name = owner_name self.readonly = readonly self.personal = personal self.is_local = is_local self.is_remote = is_remote self.is_production = is_production self.ahead_count = ahead_count self.behind_count = behind_count self.commit_at = commit_at self.ref = ref self.remote_ref = remote_ref @attr.s(auto_attribs=True, init=False) class GitConnectionTest(model.Model): """ Attributes: can: Operations the current user is able to perform on this object description: Human readable string describing the test id: A short string, uniquely naming this test """ can: Optional[MutableMapping[str, bool]] = None description: Optional[str] = None id: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, description: Optional[str] = None, id: Optional[str] = None ): self.can = can self.description = description self.id = id @attr.s(auto_attribs=True, init=False) class GitConnectionTestResult(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: A short string, uniquely naming this test message: Additional data from the test status: Either 'pass' or 'fail' """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None message: Optional[str] = None status: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, message: Optional[str] = None, status: Optional[str] = None ): self.can = can self.id = id self.message = message self.status = status @attr.s(auto_attribs=True, init=False) class GitStatus(model.Model): """ Attributes: action: Git action: add, delete, etc conflict: When true, changes to the local file conflict with the remote repository revertable: When true, the file can be reverted to an earlier state text: Git description of the action """ action: Optional[str] = None conflict: Optional[bool] = None revertable: Optional[bool] = None text: Optional[str] = None def __init__( self, *, action: Optional[str] = None, conflict: Optional[bool] = None, revertable: Optional[bool] = None, text: Optional[str] = None ): self.action = action self.conflict = conflict self.revertable = revertable self.text = text @attr.s(auto_attribs=True, init=False) class Group(model.Model): """ Attributes: can: Operations the current user is able to perform on this object can_add_to_content_metadata: Group can be used in content access controls contains_current_user: Currently logged in user is group member external_group_id: External Id group if embed group externally_managed: Group membership controlled outside of Looker id: Unique Id include_by_default: New users are added to this group by default name: Name of group user_count: Number of users included in this group """ can: Optional[MutableMapping[str, bool]] = None can_add_to_content_metadata: Optional[bool] = None contains_current_user: Optional[bool] = None external_group_id: Optional[str] = None externally_managed: Optional[bool] = None id: Optional[int] = None include_by_default: Optional[bool] = None name: Optional[str] = None user_count: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, can_add_to_content_metadata: Optional[bool] = None, contains_current_user: Optional[bool] = None, external_group_id: Optional[str] = None, externally_managed: Optional[bool] = None, id: Optional[int] = None, include_by_default: Optional[bool] = None, name: Optional[str] = None, user_count: Optional[int] = None ): self.can = can self.can_add_to_content_metadata = can_add_to_content_metadata self.contains_current_user = contains_current_user self.external_group_id = external_group_id self.externally_managed = externally_managed self.id = id self.include_by_default = include_by_default self.name = name self.user_count = user_count @attr.s(auto_attribs=True, init=False) class GroupHierarchy(model.Model): """ Attributes: can: Operations the current user is able to perform on this object can_add_to_content_metadata: Group can be used in content access controls contains_current_user: Currently logged in user is group member external_group_id: External Id group if embed group externally_managed: Group membership controlled outside of Looker id: Unique Id include_by_default: New users are added to this group by default name: Name of group user_count: Number of users included in this group parent_group_ids: IDs of parents of this group role_ids: Role IDs assigned to group """ can: Optional[MutableMapping[str, bool]] = None can_add_to_content_metadata: Optional[bool] = None contains_current_user: Optional[bool] = None external_group_id: Optional[str] = None externally_managed: Optional[bool] = None id: Optional[int] = None include_by_default: Optional[bool] = None name: Optional[str] = None user_count: Optional[int] = None parent_group_ids: Optional[Sequence[int]] = None role_ids: Optional[Sequence[int]] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, can_add_to_content_metadata: Optional[bool] = None, contains_current_user: Optional[bool] = None, external_group_id: Optional[str] = None, externally_managed: Optional[bool] = None, id: Optional[int] = None, include_by_default: Optional[bool] = None, name: Optional[str] = None, user_count: Optional[int] = None, parent_group_ids: Optional[Sequence[int]] = None, role_ids: Optional[Sequence[int]] = None ): self.can = can self.can_add_to_content_metadata = can_add_to_content_metadata self.contains_current_user = contains_current_user self.external_group_id = external_group_id self.externally_managed = externally_managed self.id = id self.include_by_default = include_by_default self.name = name self.user_count = user_count self.parent_group_ids = parent_group_ids self.role_ids = role_ids @attr.s(auto_attribs=True, init=False) class GroupIdForGroupInclusion(model.Model): """ Attributes: group_id: Id of group """ group_id: Optional[int] = None def __init__(self, *, group_id: Optional[int] = None): self.group_id = group_id @attr.s(auto_attribs=True, init=False) class GroupIdForGroupUserInclusion(model.Model): """ Attributes: user_id: Id of user """ user_id: Optional[int] = None def __init__(self, *, user_id: Optional[int] = None): self.user_id = user_id @attr.s(auto_attribs=True, init=False) class GroupSearch(model.Model): """ Attributes: can: Operations the current user is able to perform on this object can_add_to_content_metadata: Group can be used in content access controls contains_current_user: Currently logged in user is group member external_group_id: External Id group if embed group externally_managed: Group membership controlled outside of Looker id: Unique Id include_by_default: New users are added to this group by default name: Name of group user_count: Number of users included in this group roles: Roles assigned to group """ can: Optional[MutableMapping[str, bool]] = None can_add_to_content_metadata: Optional[bool] = None contains_current_user: Optional[bool] = None external_group_id: Optional[str] = None externally_managed: Optional[bool] = None id: Optional[int] = None include_by_default: Optional[bool] = None name: Optional[str] = None user_count: Optional[int] = None roles: Optional[Sequence["Role"]] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, can_add_to_content_metadata: Optional[bool] = None, contains_current_user: Optional[bool] = None, external_group_id: Optional[str] = None, externally_managed: Optional[bool] = None, id: Optional[int] = None, include_by_default: Optional[bool] = None, name: Optional[str] = None, user_count: Optional[int] = None, roles: Optional[Sequence["Role"]] = None ): self.can = can self.can_add_to_content_metadata = can_add_to_content_metadata self.contains_current_user = contains_current_user self.external_group_id = external_group_id self.externally_managed = externally_managed self.id = id self.include_by_default = include_by_default self.name = name self.user_count = user_count self.roles = roles @attr.s(auto_attribs=True, init=False) class HomepageItem(model.Model): """ Attributes: can: Operations the current user is able to perform on this object content_created_by: Name of user who created the content this item is based on content_favorite_id: Content favorite id associated with the item this content is based on content_metadata_id: Content metadata id associated with the item this content is based on content_updated_at: Last time the content that this item is based on was updated custom_description: Custom description entered by the user, if present custom_image_data_base64: (Write-Only) base64 encoded image data custom_image_url: Custom image_url entered by the user, if present custom_title: Custom title entered by the user, if present custom_url: Custom url entered by the user, if present dashboard_id: Dashboard to base this item on description: The actual description for display favorite_count: Number of times content has been favorited, if present homepage_section_id: Associated Homepage Section id: Unique Id image_url: The actual image_url for display location: The container folder name of the content look_id: Look to base this item on lookml_dashboard_id: LookML Dashboard to base this item on order: An arbitrary integer representing the sort order within the section section_fetch_time: Number of seconds it took to fetch the section this item is in title: The actual title for display url: The actual url for display use_custom_description: Whether the custom description should be used instead of the content description, if the item is associated with content use_custom_image: Whether the custom image should be used instead of the content image, if the item is associated with content use_custom_title: Whether the custom title should be used instead of the content title, if the item is associated with content use_custom_url: Whether the custom url should be used instead of the content url, if the item is associated with content view_count: Number of times content has been viewed, if present """ can: Optional[MutableMapping[str, bool]] = None content_created_by: Optional[str] = None content_favorite_id: Optional[int] = None content_metadata_id: Optional[int] = None content_updated_at: Optional[str] = None custom_description: Optional[str] = None custom_image_data_base64: Optional[str] = None custom_image_url: Optional[str] = None custom_title: Optional[str] = None custom_url: Optional[str] = None dashboard_id: Optional[int] = None description: Optional[str] = None favorite_count: Optional[int] = None homepage_section_id: Optional[int] = None id: Optional[int] = None image_url: Optional[str] = None location: Optional[str] = None look_id: Optional[int] = None lookml_dashboard_id: Optional[str] = None order: Optional[int] = None section_fetch_time: Optional[float] = None title: Optional[str] = None url: Optional[str] = None use_custom_description: Optional[bool] = None use_custom_image: Optional[bool] = None use_custom_title: Optional[bool] = None use_custom_url: Optional[bool] = None view_count: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, content_created_by: Optional[str] = None, content_favorite_id: Optional[int] = None, content_metadata_id: Optional[int] = None, content_updated_at: Optional[str] = None, custom_description: Optional[str] = None, custom_image_data_base64: Optional[str] = None, custom_image_url: Optional[str] = None, custom_title: Optional[str] = None, custom_url: Optional[str] = None, dashboard_id: Optional[int] = None, description: Optional[str] = None, favorite_count: Optional[int] = None, homepage_section_id: Optional[int] = None, id: Optional[int] = None, image_url: Optional[str] = None, location: Optional[str] = None, look_id: Optional[int] = None, lookml_dashboard_id: Optional[str] = None, order: Optional[int] = None, section_fetch_time: Optional[float] = None, title: Optional[str] = None, url: Optional[str] = None, use_custom_description: Optional[bool] = None, use_custom_image: Optional[bool] = None, use_custom_title: Optional[bool] = None, use_custom_url: Optional[bool] = None, view_count: Optional[int] = None ): self.can = can self.content_created_by = content_created_by self.content_favorite_id = content_favorite_id self.content_metadata_id = content_metadata_id self.content_updated_at = content_updated_at self.custom_description = custom_description self.custom_image_data_base64 = custom_image_data_base64 self.custom_image_url = custom_image_url self.custom_title = custom_title self.custom_url = custom_url self.dashboard_id = dashboard_id self.description = description self.favorite_count = favorite_count self.homepage_section_id = homepage_section_id self.id = id self.image_url = image_url self.location = location self.look_id = look_id self.lookml_dashboard_id = lookml_dashboard_id self.order = order self.section_fetch_time = section_fetch_time self.title = title self.url = url self.use_custom_description = use_custom_description self.use_custom_image = use_custom_image self.use_custom_title = use_custom_title self.use_custom_url = use_custom_url self.view_count = view_count @attr.s(auto_attribs=True, init=False) class HomepageSection(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Time at which this section was created. deleted_at: Time at which this section was deleted. detail_url: A URL pointing to a page showing further information about the content in the section. homepage_id: Id reference to parent homepage homepage_items: Items in the homepage section id: Unique Id is_header: Is this a header section (has no items) item_order: ids of the homepage items in the order they should be displayed title: Name of row updated_at: Time at which this section was last updated. description: Description of the content found in this section. """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[datetime.datetime] = None deleted_at: Optional[datetime.datetime] = None detail_url: Optional[str] = None homepage_id: Optional[int] = None homepage_items: Optional[Sequence["HomepageItem"]] = None id: Optional[int] = None is_header: Optional[bool] = None item_order: Optional[Sequence[int]] = None title: Optional[str] = None updated_at: Optional[datetime.datetime] = None description: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[datetime.datetime] = None, deleted_at: Optional[datetime.datetime] = None, detail_url: Optional[str] = None, homepage_id: Optional[int] = None, homepage_items: Optional[Sequence["HomepageItem"]] = None, id: Optional[int] = None, is_header: Optional[bool] = None, item_order: Optional[Sequence[int]] = None, title: Optional[str] = None, updated_at: Optional[datetime.datetime] = None, description: Optional[str] = None ): self.can = can self.created_at = created_at self.deleted_at = deleted_at self.detail_url = detail_url self.homepage_id = homepage_id self.homepage_items = homepage_items self.id = id self.is_header = is_header self.item_order = item_order self.title = title self.updated_at = updated_at self.description = description @attr.s(auto_attribs=True, init=False) class ImportedProject(model.Model): """ Attributes: name: Dependency name url: Url for a remote dependency ref: Ref for a remote dependency is_remote: Flag signifying if a dependency is remote or local """ name: Optional[str] = None url: Optional[str] = None ref: Optional[str] = None is_remote: Optional[bool] = None def __init__( self, *, name: Optional[str] = None, url: Optional[str] = None, ref: Optional[str] = None, is_remote: Optional[bool] = None ): self.name = name self.url = url self.ref = ref self.is_remote = is_remote @attr.s(auto_attribs=True, init=False) class Integration(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: ID of the integration. integration_hub_id: ID of the integration hub. label: Label for the integration. description: Description of the integration. enabled: Whether the integration is available to users. params: Array of params for the integration. supported_formats: A list of data formats the integration supports. If unspecified, the default is all data formats. Valid values are: "txt", "csv", "inline_json", "json", "json_label", "json_detail", "json_detail_lite_stream", "xlsx", "html", "wysiwyg_pdf", "assembled_pdf", "wysiwyg_png", "csv_zip". supported_action_types: A list of action types the integration supports. Valid values are: "cell", "query", "dashboard". supported_formattings: A list of formatting options the integration supports. If unspecified, defaults to all formats. Valid values are: "formatted", "unformatted". supported_visualization_formattings: A list of visualization formatting options the integration supports. If unspecified, defaults to all formats. Valid values are: "apply", "noapply". supported_download_settings: A list of all the download mechanisms the integration supports. The order of values is not significant: Looker will select the most appropriate supported download mechanism for a given query. The integration must ensure it can handle any of the mechanisms it claims to support. If unspecified, this defaults to all download setting values. Valid values are: "push", "url". icon_url: URL to an icon for the integration. uses_oauth: Whether the integration uses oauth. required_fields: A list of descriptions of required fields that this integration is compatible with. If there are multiple entries in this list, the integration requires more than one field. If unspecified, no fields will be required. delegate_oauth: Whether the integration uses delegate oauth, which allows federation between an integration installation scope specific entity (like org, group, and team, etc.) and Looker. installed_delegate_oauth_targets: Whether the integration is available to users. """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None integration_hub_id: Optional[int] = None label: Optional[str] = None description: Optional[str] = None enabled: Optional[bool] = None params: Optional[Sequence["IntegrationParam"]] = None supported_formats: Optional[Sequence["SupportedFormats"]] = None supported_action_types: Optional[Sequence["SupportedActionTypes"]] = None supported_formattings: Optional[Sequence["SupportedFormattings"]] = None supported_visualization_formattings: Optional[ Sequence["SupportedVisualizationFormattings"] ] = None supported_download_settings: Optional[Sequence["SupportedDownloadSettings"]] = None icon_url: Optional[str] = None uses_oauth: Optional[bool] = None required_fields: Optional[Sequence["IntegrationRequiredField"]] = None delegate_oauth: Optional[bool] = None installed_delegate_oauth_targets: Optional[Sequence[int]] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, integration_hub_id: Optional[int] = None, label: Optional[str] = None, description: Optional[str] = None, enabled: Optional[bool] = None, params: Optional[Sequence["IntegrationParam"]] = None, supported_formats: Optional[Sequence["SupportedFormats"]] = None, supported_action_types: Optional[Sequence["SupportedActionTypes"]] = None, supported_formattings: Optional[Sequence["SupportedFormattings"]] = None, supported_visualization_formattings: Optional[ Sequence["SupportedVisualizationFormattings"] ] = None, supported_download_settings: Optional[ Sequence["SupportedDownloadSettings"] ] = None, icon_url: Optional[str] = None, uses_oauth: Optional[bool] = None, required_fields: Optional[Sequence["IntegrationRequiredField"]] = None, delegate_oauth: Optional[bool] = None, installed_delegate_oauth_targets: Optional[Sequence[int]] = None ): self.can = can self.id = id self.integration_hub_id = integration_hub_id self.label = label self.description = description self.enabled = enabled self.params = params self.supported_formats = supported_formats self.supported_action_types = supported_action_types self.supported_formattings = supported_formattings self.supported_visualization_formattings = supported_visualization_formattings self.supported_download_settings = supported_download_settings self.icon_url = icon_url self.uses_oauth = uses_oauth self.required_fields = required_fields self.delegate_oauth = delegate_oauth self.installed_delegate_oauth_targets = installed_delegate_oauth_targets @attr.s(auto_attribs=True, init=False) class IntegrationHub(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: ID of the hub. url: URL of the hub. label: Label of the hub. official: Whether this hub is a first-party integration hub operated by Looker. fetch_error_message: An error message, present if the integration hub metadata could not be fetched. If this is present, the integration hub is unusable. authorization_token: (Write-Only) An authorization key that will be sent to the integration hub on every request. has_authorization_token: Whether the authorization_token is set for the hub. legal_agreement_signed: Whether the legal agreement message has been signed by the user. This only matters if legal_agreement_required is true. legal_agreement_required: Whether the legal terms for the integration hub are required before use. legal_agreement_text: The legal agreement text for this integration hub. """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None url: Optional[str] = None label: Optional[str] = None official: Optional[bool] = None fetch_error_message: Optional[str] = None authorization_token: Optional[str] = None has_authorization_token: Optional[bool] = None legal_agreement_signed: Optional[bool] = None legal_agreement_required: Optional[bool] = None legal_agreement_text: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, url: Optional[str] = None, label: Optional[str] = None, official: Optional[bool] = None, fetch_error_message: Optional[str] = None, authorization_token: Optional[str] = None, has_authorization_token: Optional[bool] = None, legal_agreement_signed: Optional[bool] = None, legal_agreement_required: Optional[bool] = None, legal_agreement_text: Optional[str] = None ): self.can = can self.id = id self.url = url self.label = label self.official = official self.fetch_error_message = fetch_error_message self.authorization_token = authorization_token self.has_authorization_token = has_authorization_token self.legal_agreement_signed = legal_agreement_signed self.legal_agreement_required = legal_agreement_required self.legal_agreement_text = legal_agreement_text @attr.s(auto_attribs=True, init=False) class IntegrationParam(model.Model): """ Attributes: name: Name of the parameter. label: Label of the parameter. description: Short description of the parameter. required: Whether the parameter is required to be set to use the destination. If unspecified, this defaults to false. has_value: Whether the parameter has a value set. value: The current value of the parameter. Always null if the value is sensitive. When writing, null values will be ignored. Set the value to an empty string to clear it. user_attribute_name: When present, the param's value comes from this user attribute instead of the 'value' parameter. Set to null to use the 'value'. sensitive: Whether the parameter contains sensitive data like API credentials. If unspecified, this defaults to true. per_user: When true, this parameter must be assigned to a user attribute in the admin panel (instead of a constant value), and that value may be updated by the user as part of the integration flow. delegate_oauth_url: When present, the param represents the oauth url the user will be taken to. """ name: Optional[str] = None label: Optional[str] = None description: Optional[str] = None required: Optional[bool] = None has_value: Optional[bool] = None value: Optional[str] = None user_attribute_name: Optional[str] = None sensitive: Optional[bool] = None per_user: Optional[bool] = None delegate_oauth_url: Optional[str] = None def __init__( self, *, name: Optional[str] = None, label: Optional[str] = None, description: Optional[str] = None, required: Optional[bool] = None, has_value: Optional[bool] = None, value: Optional[str] = None, user_attribute_name: Optional[str] = None, sensitive: Optional[bool] = None, per_user: Optional[bool] = None, delegate_oauth_url: Optional[str] = None ): self.name = name self.label = label self.description = description self.required = required self.has_value = has_value self.value = value self.user_attribute_name = user_attribute_name self.sensitive = sensitive self.per_user = per_user self.delegate_oauth_url = delegate_oauth_url @attr.s(auto_attribs=True, init=False) class IntegrationRequiredField(model.Model): """ Attributes: tag: Matches a field that has this tag. any_tag: If present, supercedes 'tag' and matches a field that has any of the provided tags. all_tags: If present, supercedes 'tag' and matches a field that has all of the provided tags. """ tag: Optional[str] = None any_tag: Optional[Sequence[str]] = None all_tags: Optional[Sequence[str]] = None def __init__( self, *, tag: Optional[str] = None, any_tag: Optional[Sequence[str]] = None, all_tags: Optional[Sequence[str]] = None ): self.tag = tag self.any_tag = any_tag self.all_tags = all_tags @attr.s(auto_attribs=True, init=False) class IntegrationTestResult(model.Model): """ Attributes: success: Whether or not the test was successful message: A message representing the results of the test. delegate_oauth_result: An array of connection test result for delegate oauth actions. """ success: Optional[bool] = None message: Optional[str] = None delegate_oauth_result: Optional[Sequence["DelegateOauthTest"]] = None def __init__( self, *, success: Optional[bool] = None, message: Optional[str] = None, delegate_oauth_result: Optional[Sequence["DelegateOauthTest"]] = None ): self.success = success self.message = message self.delegate_oauth_result = delegate_oauth_result @attr.s(auto_attribs=True, init=False) class InternalHelpResources(model.Model): """ Attributes: can: Operations the current user is able to perform on this object enabled: If true and internal help resources content is not blank then the link for internal help resources will be shown in the help menu and the content displayed within Looker """ can: Optional[MutableMapping[str, bool]] = None enabled: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, enabled: Optional[bool] = None ): self.can = can self.enabled = enabled @attr.s(auto_attribs=True, init=False) class InternalHelpResourcesContent(model.Model): """ Attributes: can: Operations the current user is able to perform on this object organization_name: Text to display in the help menu item which will display the internal help resources markdown_content: Content to be displayed in the internal help resources page/modal """ can: Optional[MutableMapping[str, bool]] = None organization_name: Optional[str] = None markdown_content: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, organization_name: Optional[str] = None, markdown_content: Optional[str] = None ): self.can = can self.organization_name = organization_name self.markdown_content = markdown_content @attr.s(auto_attribs=True, init=False) class LDAPConfig(model.Model): """ Attributes: can: Operations the current user is able to perform on this object alternate_email_login_allowed: Allow alternate email-based login via '/login/email' for admins and for specified users with the 'login_special_email' permission. This option is useful as a fallback during ldap setup, if ldap config problems occur later, or if you need to support some users who are not in your ldap directory. Looker email/password logins are always disabled for regular users when ldap is enabled. auth_password: (Write-Only) Password for the LDAP account used to access the LDAP server auth_requires_role: Users will not be allowed to login at all unless a role for them is found in LDAP if set to true auth_username: Distinguished name of LDAP account used to access the LDAP server connection_host: LDAP server hostname connection_port: LDAP host port connection_tls: Use Transport Layer Security connection_tls_no_verify: Do not verify peer when using TLS default_new_user_group_ids: (Write-Only) Array of ids of groups that will be applied to new users the first time they login via LDAP default_new_user_groups: (Read-only) Groups that will be applied to new users the first time they login via LDAP default_new_user_role_ids: (Write-Only) Array of ids of roles that will be applied to new users the first time they login via LDAP default_new_user_roles: (Read-only) Roles that will be applied to new users the first time they login via LDAP enabled: Enable/Disable LDAP authentication for the server force_no_page: Don't attempt to do LDAP search result paging (RFC 2696) even if the LDAP server claims to support it. groups: (Read-only) Array of mappings between LDAP Groups and Looker Roles groups_base_dn: Base dn for finding groups in LDAP searches groups_finder_type: Identifier for a strategy for how Looker will search for groups in the LDAP server groups_member_attribute: LDAP Group attribute that signifies the members of the groups. Most commonly 'member' groups_objectclasses: Optional comma-separated list of supported LDAP objectclass for groups when doing groups searches groups_user_attribute: LDAP Group attribute that signifies the user in a group. Most commonly 'dn' groups_with_role_ids: (Read/Write) Array of mappings between LDAP Groups and arrays of Looker Role ids has_auth_password: (Read-only) Has the password been set for the LDAP account used to access the LDAP server merge_new_users_by_email: Merge first-time ldap login to existing user account by email addresses. When a user logs in for the first time via ldap this option will connect this user into their existing account by finding the account with a matching email address. Otherwise a new user account will be created for the user. modified_at: When this config was last modified modified_by: User id of user who last modified this config set_roles_from_groups: Set user roles in Looker based on groups from LDAP test_ldap_password: (Write-Only) Test LDAP user password. For ldap tests only. test_ldap_user: (Write-Only) Test LDAP user login id. For ldap tests only. user_attribute_map_email: Name of user record attributes used to indicate email address field user_attribute_map_first_name: Name of user record attributes used to indicate first name user_attribute_map_last_name: Name of user record attributes used to indicate last name user_attribute_map_ldap_id: Name of user record attributes used to indicate unique record id user_attributes: (Read-only) Array of mappings between LDAP User Attributes and Looker User Attributes user_attributes_with_ids: (Read/Write) Array of mappings between LDAP User Attributes and arrays of Looker User Attribute ids user_bind_base_dn: Distinguished name of LDAP node used as the base for user searches user_custom_filter: (Optional) Custom RFC-2254 filter clause for use in finding user during login. Combined via 'and' with the other generated filter clauses. user_id_attribute_names: Name(s) of user record attributes used for matching user login id (comma separated list) user_objectclass: (Optional) Name of user record objectclass used for finding user during login id allow_normal_group_membership: Allow LDAP auth'd users to be members of non-reflected Looker groups. If 'false', user will be removed from non-reflected groups on login. allow_roles_from_normal_groups: LDAP auth'd users will be able to inherit roles from non-reflected Looker groups. allow_direct_roles: Allows roles to be directly assigned to LDAP auth'd users. url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None alternate_email_login_allowed: Optional[bool] = None auth_password: Optional[str] = None auth_requires_role: Optional[bool] = None auth_username: Optional[str] = None connection_host: Optional[str] = None connection_port: Optional[str] = None connection_tls: Optional[bool] = None connection_tls_no_verify: Optional[bool] = None default_new_user_group_ids: Optional[Sequence[int]] = None default_new_user_groups: Optional[Sequence["Group"]] = None default_new_user_role_ids: Optional[Sequence[int]] = None default_new_user_roles: Optional[Sequence["Role"]] = None enabled: Optional[bool] = None force_no_page: Optional[bool] = None groups: Optional[Sequence["LDAPGroupRead"]] = None groups_base_dn: Optional[str] = None groups_finder_type: Optional[str] = None groups_member_attribute: Optional[str] = None groups_objectclasses: Optional[str] = None groups_user_attribute: Optional[str] = None groups_with_role_ids: Optional[Sequence["LDAPGroupWrite"]] = None has_auth_password: Optional[bool] = None merge_new_users_by_email: Optional[bool] = None modified_at: Optional[str] = None modified_by: Optional[str] = None set_roles_from_groups: Optional[bool] = None test_ldap_password: Optional[str] = None test_ldap_user: Optional[str] = None user_attribute_map_email: Optional[str] = None user_attribute_map_first_name: Optional[str] = None user_attribute_map_last_name: Optional[str] = None user_attribute_map_ldap_id: Optional[str] = None user_attributes: Optional[Sequence["LDAPUserAttributeRead"]] = None user_attributes_with_ids: Optional[Sequence["LDAPUserAttributeWrite"]] = None user_bind_base_dn: Optional[str] = None user_custom_filter: Optional[str] = None user_id_attribute_names: Optional[str] = None user_objectclass: Optional[str] = None allow_normal_group_membership: Optional[bool] = None allow_roles_from_normal_groups: Optional[bool] = None allow_direct_roles: Optional[bool] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, alternate_email_login_allowed: Optional[bool] = None, auth_password: Optional[str] = None, auth_requires_role: Optional[bool] = None, auth_username: Optional[str] = None, connection_host: Optional[str] = None, connection_port: Optional[str] = None, connection_tls: Optional[bool] = None, connection_tls_no_verify: Optional[bool] = None, default_new_user_group_ids: Optional[Sequence[int]] = None, default_new_user_groups: Optional[Sequence["Group"]] = None, default_new_user_role_ids: Optional[Sequence[int]] = None, default_new_user_roles: Optional[Sequence["Role"]] = None, enabled: Optional[bool] = None, force_no_page: Optional[bool] = None, groups: Optional[Sequence["LDAPGroupRead"]] = None, groups_base_dn: Optional[str] = None, groups_finder_type: Optional[str] = None, groups_member_attribute: Optional[str] = None, groups_objectclasses: Optional[str] = None, groups_user_attribute: Optional[str] = None, groups_with_role_ids: Optional[Sequence["LDAPGroupWrite"]] = None, has_auth_password: Optional[bool] = None, merge_new_users_by_email: Optional[bool] = None, modified_at: Optional[str] = None, modified_by: Optional[str] = None, set_roles_from_groups: Optional[bool] = None, test_ldap_password: Optional[str] = None, test_ldap_user: Optional[str] = None, user_attribute_map_email: Optional[str] = None, user_attribute_map_first_name: Optional[str] = None, user_attribute_map_last_name: Optional[str] = None, user_attribute_map_ldap_id: Optional[str] = None, user_attributes: Optional[Sequence["LDAPUserAttributeRead"]] = None, user_attributes_with_ids: Optional[Sequence["LDAPUserAttributeWrite"]] = None, user_bind_base_dn: Optional[str] = None, user_custom_filter: Optional[str] = None, user_id_attribute_names: Optional[str] = None, user_objectclass: Optional[str] = None, allow_normal_group_membership: Optional[bool] = None, allow_roles_from_normal_groups: Optional[bool] = None, allow_direct_roles: Optional[bool] = None, url: Optional[str] = None ): self.can = can self.alternate_email_login_allowed = alternate_email_login_allowed self.auth_password = auth_password self.auth_requires_role = auth_requires_role self.auth_username = auth_username self.connection_host = connection_host self.connection_port = connection_port self.connection_tls = connection_tls self.connection_tls_no_verify = connection_tls_no_verify self.default_new_user_group_ids = default_new_user_group_ids self.default_new_user_groups = default_new_user_groups self.default_new_user_role_ids = default_new_user_role_ids self.default_new_user_roles = default_new_user_roles self.enabled = enabled self.force_no_page = force_no_page self.groups = groups self.groups_base_dn = groups_base_dn self.groups_finder_type = groups_finder_type self.groups_member_attribute = groups_member_attribute self.groups_objectclasses = groups_objectclasses self.groups_user_attribute = groups_user_attribute self.groups_with_role_ids = groups_with_role_ids self.has_auth_password = has_auth_password self.merge_new_users_by_email = merge_new_users_by_email self.modified_at = modified_at self.modified_by = modified_by self.set_roles_from_groups = set_roles_from_groups self.test_ldap_password = test_ldap_password self.test_ldap_user = test_ldap_user self.user_attribute_map_email = user_attribute_map_email self.user_attribute_map_first_name = user_attribute_map_first_name self.user_attribute_map_last_name = user_attribute_map_last_name self.user_attribute_map_ldap_id = user_attribute_map_ldap_id self.user_attributes = user_attributes self.user_attributes_with_ids = user_attributes_with_ids self.user_bind_base_dn = user_bind_base_dn self.user_custom_filter = user_custom_filter self.user_id_attribute_names = user_id_attribute_names self.user_objectclass = user_objectclass self.allow_normal_group_membership = allow_normal_group_membership self.allow_roles_from_normal_groups = allow_roles_from_normal_groups self.allow_direct_roles = allow_direct_roles self.url = url @attr.s(auto_attribs=True, init=False) class LDAPConfigTestIssue(model.Model): """ Attributes: severity: Severity of the issue. Error or Warning message: Message describing the issue """ severity: Optional[str] = None message: Optional[str] = None def __init__( self, *, severity: Optional[str] = None, message: Optional[str] = None ): self.severity = severity self.message = message @attr.s(auto_attribs=True, init=False) class LDAPConfigTestResult(model.Model): """ Attributes: details: Additional details for error cases issues: Array of issues/considerations about the result message: Short human readable test about the result status: Test status code: always 'success' or 'error' trace: A more detailed trace of incremental results during auth tests user: url: Link to ldap config """ details: Optional[str] = None issues: Optional[Sequence["LDAPConfigTestIssue"]] = None message: Optional[str] = None status: Optional[str] = None trace: Optional[str] = None user: Optional["LDAPUser"] = None url: Optional[str] = None def __init__( self, *, details: Optional[str] = None, issues: Optional[Sequence["LDAPConfigTestIssue"]] = None, message: Optional[str] = None, status: Optional[str] = None, trace: Optional[str] = None, user: Optional["LDAPUser"] = None, url: Optional[str] = None ): self.details = details self.issues = issues self.message = message self.status = status self.trace = trace self.user = user self.url = url @attr.s(auto_attribs=True, init=False) class LDAPGroupRead(model.Model): """ Attributes: id: Unique Id looker_group_id: Unique Id of group in Looker looker_group_name: Name of group in Looker name: Name of group in LDAP roles: Looker Roles url: Link to ldap config """ id: Optional[int] = None looker_group_id: Optional[int] = None looker_group_name: Optional[str] = None name: Optional[str] = None roles: Optional[Sequence["Role"]] = None url: Optional[str] = None def __init__( self, *, id: Optional[int] = None, looker_group_id: Optional[int] = None, looker_group_name: Optional[str] = None, name: Optional[str] = None, roles: Optional[Sequence["Role"]] = None, url: Optional[str] = None ): self.id = id self.looker_group_id = looker_group_id self.looker_group_name = looker_group_name self.name = name self.roles = roles self.url = url @attr.s(auto_attribs=True, init=False) class LDAPGroupWrite(model.Model): """ Attributes: id: Unique Id looker_group_id: Unique Id of group in Looker looker_group_name: Name of group in Looker name: Name of group in LDAP role_ids: Looker Role Ids url: Link to ldap config """ id: Optional[int] = None looker_group_id: Optional[int] = None looker_group_name: Optional[str] = None name: Optional[str] = None role_ids: Optional[Sequence[int]] = None url: Optional[str] = None def __init__( self, *, id: Optional[int] = None, looker_group_id: Optional[int] = None, looker_group_name: Optional[str] = None, name: Optional[str] = None, role_ids: Optional[Sequence[int]] = None, url: Optional[str] = None ): self.id = id self.looker_group_id = looker_group_id self.looker_group_name = looker_group_name self.name = name self.role_ids = role_ids self.url = url @attr.s(auto_attribs=True, init=False) class LDAPUser(model.Model): """ Attributes: all_emails: Array of user's email addresses and aliases for use in migration attributes: Dictionary of user's attributes (name/value) email: Primary email address first_name: First name groups: Array of user's groups (group names only) last_name: Last Name ldap_dn: LDAP's distinguished name for the user record ldap_id: LDAP's Unique ID for the user roles: Array of user's roles (role names only) url: Link to ldap config """ all_emails: Optional[Sequence[str]] = None attributes: Optional[MutableMapping[str, Any]] = None email: Optional[str] = None first_name: Optional[str] = None groups: Optional[Sequence[str]] = None last_name: Optional[str] = None ldap_dn: Optional[str] = None ldap_id: Optional[str] = None roles: Optional[Sequence[str]] = None url: Optional[str] = None def __init__( self, *, all_emails: Optional[Sequence[str]] = None, attributes: Optional[MutableMapping[str, Any]] = None, email: Optional[str] = None, first_name: Optional[str] = None, groups: Optional[Sequence[str]] = None, last_name: Optional[str] = None, ldap_dn: Optional[str] = None, ldap_id: Optional[str] = None, roles: Optional[Sequence[str]] = None, url: Optional[str] = None ): self.all_emails = all_emails self.attributes = attributes self.email = email self.first_name = first_name self.groups = groups self.last_name = last_name self.ldap_dn = ldap_dn self.ldap_id = ldap_id self.roles = roles self.url = url @attr.s(auto_attribs=True, init=False) class LDAPUserAttributeRead(model.Model): """ Attributes: name: Name of User Attribute in LDAP required: Required to be in LDAP assertion for login to be allowed to succeed user_attributes: Looker User Attributes url: Link to ldap config """ name: Optional[str] = None required: Optional[bool] = None user_attributes: Optional[Sequence["UserAttribute"]] = None url: Optional[str] = None def __init__( self, *, name: Optional[str] = None, required: Optional[bool] = None, user_attributes: Optional[Sequence["UserAttribute"]] = None, url: Optional[str] = None ): self.name = name self.required = required self.user_attributes = user_attributes self.url = url @attr.s(auto_attribs=True, init=False) class LDAPUserAttributeWrite(model.Model): """ Attributes: name: Name of User Attribute in LDAP required: Required to be in LDAP assertion for login to be allowed to succeed user_attribute_ids: Looker User Attribute Ids url: Link to ldap config """ name: Optional[str] = None required: Optional[bool] = None user_attribute_ids: Optional[Sequence[int]] = None url: Optional[str] = None def __init__( self, *, name: Optional[str] = None, required: Optional[bool] = None, user_attribute_ids: Optional[Sequence[int]] = None, url: Optional[str] = None ): self.name = name self.required = required self.user_attribute_ids = user_attribute_ids self.url = url @attr.s(auto_attribs=True, init=False) class LegacyFeature(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id name: Name description: Description enabled_locally: Whether this feature has been enabled by a user enabled: Whether this feature is currently enabled disallowed_as_of_version: Looker version where this feature became a legacy feature disable_on_upgrade_to_version: Looker version where this feature will be automatically disabled end_of_life_version: Future Looker version where this feature will be removed documentation_url: URL for documentation about this feature approximate_disable_date: Approximate date that this feature will be automatically disabled. approximate_end_of_life_date: Approximate date that this feature will be removed. has_disabled_on_upgrade: Whether this legacy feature may have been automatically disabled when upgrading to the current version. """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None name: Optional[str] = None description: Optional[str] = None enabled_locally: Optional[bool] = None enabled: Optional[bool] = None disallowed_as_of_version: Optional[str] = None disable_on_upgrade_to_version: Optional[str] = None end_of_life_version: Optional[str] = None documentation_url: Optional[str] = None approximate_disable_date: Optional[datetime.datetime] = None approximate_end_of_life_date: Optional[datetime.datetime] = None has_disabled_on_upgrade: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, name: Optional[str] = None, description: Optional[str] = None, enabled_locally: Optional[bool] = None, enabled: Optional[bool] = None, disallowed_as_of_version: Optional[str] = None, disable_on_upgrade_to_version: Optional[str] = None, end_of_life_version: Optional[str] = None, documentation_url: Optional[str] = None, approximate_disable_date: Optional[datetime.datetime] = None, approximate_end_of_life_date: Optional[datetime.datetime] = None, has_disabled_on_upgrade: Optional[bool] = None ): self.can = can self.id = id self.name = name self.description = description self.enabled_locally = enabled_locally self.enabled = enabled self.disallowed_as_of_version = disallowed_as_of_version self.disable_on_upgrade_to_version = disable_on_upgrade_to_version self.end_of_life_version = end_of_life_version self.documentation_url = documentation_url self.approximate_disable_date = approximate_disable_date self.approximate_end_of_life_date = approximate_end_of_life_date self.has_disabled_on_upgrade = has_disabled_on_upgrade class LinkedContentType(enum.Enum): """ Name of the command Valid values are: "dashboard", "lookml_dashboard". """ dashboard = "dashboard" lookml_dashboard = "lookml_dashboard" invalid_api_enum_value = "invalid_api_enum_value" LinkedContentType.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class Locale(model.Model): """ Attributes: code: Code for Locale native_name: Name of Locale in its own language english_name: Name of Locale in English """ code: Optional[str] = None native_name: Optional[str] = None english_name: Optional[str] = None def __init__( self, *, code: Optional[str] = None, native_name: Optional[str] = None, english_name: Optional[str] = None ): self.code = code self.native_name = native_name self.english_name = english_name @attr.s(auto_attribs=True, init=False) class LocalizationSettings(model.Model): """ Attributes: default_locale: Default locale for localization localization_level: Localization level - strict or permissive """ default_locale: Optional[str] = None localization_level: Optional[str] = None def __init__( self, *, default_locale: Optional[str] = None, localization_level: Optional[str] = None ): self.default_locale = default_locale self.localization_level = localization_level @attr.s(auto_attribs=True, init=False) class Look(model.Model): """ Attributes: can: Operations the current user is able to perform on this object content_metadata_id: Id of content metadata id: Unique Id title: Look Title user_id: User Id content_favorite_id: Content Favorite Id created_at: Time that the Look was created. deleted: Whether or not a look is 'soft' deleted. deleted_at: Time that the Look was deleted. deleter_id: Id of User that deleted the look. description: Description embed_url: Embed Url excel_file_url: Excel File Url favorite_count: Number of times favorited google_spreadsheet_formula: Google Spreadsheet Formula image_embed_url: Image Embed Url is_run_on_load: auto-run query when Look viewed last_accessed_at: Time that the Look was last accessed by any user last_updater_id: Id of User that last updated the look. last_viewed_at: Time last viewed in the Looker web UI model: public: Is Public public_slug: Public Slug public_url: Public Url query_id: Query Id short_url: Short Url folder: folder_id: Folder Id updated_at: Time that the Look was updated. view_count: Number of times viewed in the Looker web UI """ can: Optional[MutableMapping[str, bool]] = None content_metadata_id: Optional[int] = None id: Optional[int] = None title: Optional[str] = None user_id: Optional[int] = None content_favorite_id: Optional[int] = None created_at: Optional[datetime.datetime] = None deleted: Optional[bool] = None deleted_at: Optional[datetime.datetime] = None deleter_id: Optional[int] = None description: Optional[str] = None embed_url: Optional[str] = None excel_file_url: Optional[str] = None favorite_count: Optional[int] = None google_spreadsheet_formula: Optional[str] = None image_embed_url: Optional[str] = None is_run_on_load: Optional[bool] = None last_accessed_at: Optional[datetime.datetime] = None last_updater_id: Optional[int] = None last_viewed_at: Optional[datetime.datetime] = None model: Optional["LookModel"] = None public: Optional[bool] = None public_slug: Optional[str] = None public_url: Optional[str] = None query_id: Optional[int] = None short_url: Optional[str] = None folder: Optional["FolderBase"] = None folder_id: Optional[str] = None updated_at: Optional[datetime.datetime] = None view_count: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, content_metadata_id: Optional[int] = None, id: Optional[int] = None, title: Optional[str] = None, user_id: Optional[int] = None, content_favorite_id: Optional[int] = None, created_at: Optional[datetime.datetime] = None, deleted: Optional[bool] = None, deleted_at: Optional[datetime.datetime] = None, deleter_id: Optional[int] = None, description: Optional[str] = None, embed_url: Optional[str] = None, excel_file_url: Optional[str] = None, favorite_count: Optional[int] = None, google_spreadsheet_formula: Optional[str] = None, image_embed_url: Optional[str] = None, is_run_on_load: Optional[bool] = None, last_accessed_at: Optional[datetime.datetime] = None, last_updater_id: Optional[int] = None, last_viewed_at: Optional[datetime.datetime] = None, model: Optional["LookModel"] = None, public: Optional[bool] = None, public_slug: Optional[str] = None, public_url: Optional[str] = None, query_id: Optional[int] = None, short_url: Optional[str] = None, folder: Optional["FolderBase"] = None, folder_id: Optional[str] = None, updated_at: Optional[datetime.datetime] = None, view_count: Optional[int] = None ): self.can = can self.content_metadata_id = content_metadata_id self.id = id self.title = title self.user_id = user_id self.content_favorite_id = content_favorite_id self.created_at = created_at self.deleted = deleted self.deleted_at = deleted_at self.deleter_id = deleter_id self.description = description self.embed_url = embed_url self.excel_file_url = excel_file_url self.favorite_count = favorite_count self.google_spreadsheet_formula = google_spreadsheet_formula self.image_embed_url = image_embed_url self.is_run_on_load = is_run_on_load self.last_accessed_at = last_accessed_at self.last_updater_id = last_updater_id self.last_viewed_at = last_viewed_at self.model = model self.public = public self.public_slug = public_slug self.public_url = public_url self.query_id = query_id self.short_url = short_url self.folder = folder self.folder_id = folder_id self.updated_at = updated_at self.view_count = view_count @attr.s(auto_attribs=True, init=False) class LookBasic(model.Model): """ Attributes: can: Operations the current user is able to perform on this object content_metadata_id: Id of content metadata id: Unique Id title: Look Title user_id: User Id """ can: Optional[MutableMapping[str, bool]] = None content_metadata_id: Optional[int] = None id: Optional[int] = None title: Optional[str] = None user_id: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, content_metadata_id: Optional[int] = None, id: Optional[int] = None, title: Optional[str] = None, user_id: Optional[int] = None ): self.can = can self.content_metadata_id = content_metadata_id self.id = id self.title = title self.user_id = user_id @attr.s(auto_attribs=True, init=False) class LookmlModel(model.Model): """ Attributes: can: Operations the current user is able to perform on this object allowed_db_connection_names: Array of names of connections this model is allowed to use explores: Array of explores (if has_content) has_content: Does this model declaration have have lookml content? label: UI-friendly name for this model name: Name of the model. Also used as the unique identifier project_name: Name of project containing the model unlimited_db_connections: Is this model allowed to use all current and future connections """ can: Optional[MutableMapping[str, bool]] = None allowed_db_connection_names: Optional[Sequence[str]] = None explores: Optional[Sequence["LookmlModelNavExplore"]] = None has_content: Optional[bool] = None label: Optional[str] = None name: Optional[str] = None project_name: Optional[str] = None unlimited_db_connections: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, allowed_db_connection_names: Optional[Sequence[str]] = None, explores: Optional[Sequence["LookmlModelNavExplore"]] = None, has_content: Optional[bool] = None, label: Optional[str] = None, name: Optional[str] = None, project_name: Optional[str] = None, unlimited_db_connections: Optional[bool] = None ): self.can = can self.allowed_db_connection_names = allowed_db_connection_names self.explores = explores self.has_content = has_content self.label = label self.name = name self.project_name = project_name self.unlimited_db_connections = unlimited_db_connections @attr.s(auto_attribs=True, init=False) class LookmlModelExplore(model.Model): """ Attributes: id: Fully qualified explore name (model name plus explore name) name: Explore name description: Description label: Label title: Explore title scopes: Scopes can_total: Can Total can_develop: Can Develop LookML can_see_lookml: Can See LookML lookml_link: A URL linking to the definition of this explore in the LookML IDE. can_save: Can Save can_explain: Can Explain can_pivot_in_db: Can pivot in the DB can_subtotal: Can use subtotals has_timezone_support: Has timezone support supports_cost_estimate: Cost estimates supported connection_name: Connection name null_sort_treatment: How nulls are sorted, possible values are "low", "high", "first" and "last" files: List of model source files source_file: Primary source_file file project_name: Name of project model_name: Name of model view_name: Name of view hidden: Is hidden sql_table_name: A sql_table_name expression that defines what sql table the view/explore maps onto. Example: "prod_orders2 AS orders" in a view named orders. access_filter_fields: (DEPRECATED) Array of access filter field names access_filters: Access filters aliases: Aliases always_filter: Always filter conditionally_filter: Conditionally filter index_fields: Array of index fields sets: Sets tags: An array of arbitrary string tags provided in the model for this explore. errors: Errors fields: joins: Views joined into this explore group_label: Label used to group explores in the navigation menus supported_measure_types: An array of items describing which custom measure types are supported for creating a custom measure 'based_on' each possible dimension type. """ id: Optional[str] = None name: Optional[str] = None description: Optional[str] = None label: Optional[str] = None title: Optional[str] = None scopes: Optional[Sequence[str]] = None can_total: Optional[bool] = None can_develop: Optional[bool] = None can_see_lookml: Optional[bool] = None lookml_link: Optional[str] = None can_save: Optional[bool] = None can_explain: Optional[bool] = None can_pivot_in_db: Optional[bool] = None can_subtotal: Optional[bool] = None has_timezone_support: Optional[bool] = None supports_cost_estimate: Optional[bool] = None connection_name: Optional[str] = None null_sort_treatment: Optional[str] = None files: Optional[Sequence[str]] = None source_file: Optional[str] = None project_name: Optional[str] = None model_name: Optional[str] = None view_name: Optional[str] = None hidden: Optional[bool] = None sql_table_name: Optional[str] = None access_filter_fields: Optional[Sequence[str]] = None access_filters: Optional[Sequence["LookmlModelExploreAccessFilter"]] = None aliases: Optional[Sequence["LookmlModelExploreAlias"]] = None always_filter: Optional[Sequence["LookmlModelExploreAlwaysFilter"]] = None conditionally_filter: Optional[ Sequence["LookmlModelExploreConditionallyFilter"] ] = None index_fields: Optional[Sequence[str]] = None sets: Optional[Sequence["LookmlModelExploreSet"]] = None tags: Optional[Sequence[str]] = None errors: Optional[Sequence["LookmlModelExploreError"]] = None fields: Optional["LookmlModelExploreFieldset"] = None joins: Optional[Sequence["LookmlModelExploreJoins"]] = None group_label: Optional[str] = None supported_measure_types: Optional[ Sequence["LookmlModelExploreSupportedMeasureType"] ] = None def __init__( self, *, id: Optional[str] = None, name: Optional[str] = None, description: Optional[str] = None, label: Optional[str] = None, title: Optional[str] = None, scopes: Optional[Sequence[str]] = None, can_total: Optional[bool] = None, can_develop: Optional[bool] = None, can_see_lookml: Optional[bool] = None, lookml_link: Optional[str] = None, can_save: Optional[bool] = None, can_explain: Optional[bool] = None, can_pivot_in_db: Optional[bool] = None, can_subtotal: Optional[bool] = None, has_timezone_support: Optional[bool] = None, supports_cost_estimate: Optional[bool] = None, connection_name: Optional[str] = None, null_sort_treatment: Optional[str] = None, files: Optional[Sequence[str]] = None, source_file: Optional[str] = None, project_name: Optional[str] = None, model_name: Optional[str] = None, view_name: Optional[str] = None, hidden: Optional[bool] = None, sql_table_name: Optional[str] = None, access_filter_fields: Optional[Sequence[str]] = None, access_filters: Optional[Sequence["LookmlModelExploreAccessFilter"]] = None, aliases: Optional[Sequence["LookmlModelExploreAlias"]] = None, always_filter: Optional[Sequence["LookmlModelExploreAlwaysFilter"]] = None, conditionally_filter: Optional[ Sequence["LookmlModelExploreConditionallyFilter"] ] = None, index_fields: Optional[Sequence[str]] = None, sets: Optional[Sequence["LookmlModelExploreSet"]] = None, tags: Optional[Sequence[str]] = None, errors: Optional[Sequence["LookmlModelExploreError"]] = None, fields: Optional["LookmlModelExploreFieldset"] = None, joins: Optional[Sequence["LookmlModelExploreJoins"]] = None, group_label: Optional[str] = None, supported_measure_types: Optional[ Sequence["LookmlModelExploreSupportedMeasureType"] ] = None ): self.id = id self.name = name self.description = description self.label = label self.title = title self.scopes = scopes self.can_total = can_total self.can_develop = can_develop self.can_see_lookml = can_see_lookml self.lookml_link = lookml_link self.can_save = can_save self.can_explain = can_explain self.can_pivot_in_db = can_pivot_in_db self.can_subtotal = can_subtotal self.has_timezone_support = has_timezone_support self.supports_cost_estimate = supports_cost_estimate self.connection_name = connection_name self.null_sort_treatment = null_sort_treatment self.files = files self.source_file = source_file self.project_name = project_name self.model_name = model_name self.view_name = view_name self.hidden = hidden self.sql_table_name = sql_table_name self.access_filter_fields = access_filter_fields self.access_filters = access_filters self.aliases = aliases self.always_filter = always_filter self.conditionally_filter = conditionally_filter self.index_fields = index_fields self.sets = sets self.tags = tags self.errors = errors self.fields = fields self.joins = joins self.group_label = group_label self.supported_measure_types = supported_measure_types @attr.s(auto_attribs=True, init=False) class LookmlModelExploreAccessFilter(model.Model): """ Attributes: field: Field to be filtered user_attribute: User attribute name """ field: Optional[str] = None user_attribute: Optional[str] = None def __init__( self, *, field: Optional[str] = None, user_attribute: Optional[str] = None ): self.field = field self.user_attribute = user_attribute @attr.s(auto_attribs=True, init=False) class LookmlModelExploreAlias(model.Model): """ Attributes: name: Name value: Value """ name: Optional[str] = None value: Optional[str] = None def __init__(self, *, name: Optional[str] = None, value: Optional[str] = None): self.name = name self.value = value @attr.s(auto_attribs=True, init=False) class LookmlModelExploreAlwaysFilter(model.Model): """ Attributes: name: Name value: Value """ name: Optional[str] = None value: Optional[str] = None def __init__(self, *, name: Optional[str] = None, value: Optional[str] = None): self.name = name self.value = value @attr.s(auto_attribs=True, init=False) class LookmlModelExploreConditionallyFilter(model.Model): """ Attributes: name: Name value: Value """ name: Optional[str] = None value: Optional[str] = None def __init__(self, *, name: Optional[str] = None, value: Optional[str] = None): self.name = name self.value = value @attr.s(auto_attribs=True, init=False) class LookmlModelExploreError(model.Model): """ Attributes: message: Error Message details: Details error_pos: Error source location field_error: Is this a field error """ message: Optional[str] = None details: Optional[Any] = None error_pos: Optional[str] = None field_error: Optional[bool] = None def __init__( self, *, message: Optional[str] = None, details: Optional[Any] = None, error_pos: Optional[str] = None, field_error: Optional[bool] = None ): self.message = message self.details = details self.error_pos = error_pos self.field_error = field_error @attr.s(auto_attribs=True, init=False) class LookmlModelExploreField(model.Model): """ Attributes: align: The appropriate horizontal text alignment the values of this field should be displayed in. Valid values are: "left", "right". can_filter: Whether it's possible to filter on this field. category: Field category Valid values are: "parameter", "filter", "measure", "dimension". default_filter_value: The default value that this field uses when filtering. Null if there is no default value. description: Description enumerations: An array enumerating all the possible values that this field can contain. When null, there is no limit to the set of possible values this field can contain. error: An error message indicating a problem with the definition of this field. If there are no errors, this will be null. field_group_label: A label creating a grouping of fields. All fields with this label should be presented together when displayed in a UI. field_group_variant: When presented in a field group via field_group_label, a shorter name of the field to be displayed in that context. fill_style: The style of dimension fill that is possible for this field. Null if no dimension fill is possible. Valid values are: "enumeration", "range". fiscal_month_offset: An offset (in months) from the calendar start month to the fiscal start month defined in the LookML model this field belongs to. has_allowed_values: Whether this field has a set of allowed_values specified in LookML. hidden: Whether this field should be hidden from the user interface. is_filter: Whether this field is a filter. is_fiscal: Whether this field represents a fiscal time value. is_numeric: Whether this field is of a type that represents a numeric value. is_timeframe: Whether this field is of a type that represents a time value. can_time_filter: Whether this field can be time filtered. time_interval: label: Fully-qualified human-readable label of the field. label_from_parameter: The name of the parameter that will provide a parameterized label for this field, if available in the current context. label_short: The human-readable label of the field, without the view label. lookml_link: A URL linking to the definition of this field in the LookML IDE. map_layer: measure: Whether this field is a measure. name: Fully-qualified name of the field. strict_value_format: If yes, the field will not be localized with the user attribute number_format. Defaults to no parameter: Whether this field is a parameter. permanent: Whether this field can be removed from a query. primary_key: Whether or not the field represents a primary key. project_name: The name of the project this field is defined in. requires_refresh_on_sort: When true, it's not possible to re-sort this field's values without re-running the SQL query, due to database logic that affects the sort. scope: The LookML scope this field belongs to. The scope is typically the field's view. sortable: Whether this field can be sorted. source_file: The path portion of source_file_path. source_file_path: The fully-qualified path of the project file this field is defined in. sql: SQL expression as defined in the LookML model. The SQL syntax shown here is a representation intended for auditability, and is not neccessarily an exact match for what will ultimately be run in the database. It may contain special LookML syntax or annotations that are not valid SQL. This will be null if the current user does not have the see_lookml permission for the field's model. sql_case: An array of conditions and values that make up a SQL Case expression, as defined in the LookML model. The SQL syntax shown here is a representation intended for auditability, and is not neccessarily an exact match for what will ultimately be run in the database. It may contain special LookML syntax or annotations that are not valid SQL. This will be null if the current user does not have the see_lookml permission for the field's model. filters: Array of filter conditions defined for the measure in LookML. suggest_dimension: The name of the dimension to base suggest queries from. suggest_explore: The name of the explore to base suggest queries from. suggestable: Whether or not suggestions are possible for this field. suggestions: If available, a list of suggestions for this field. For most fields, a suggest query is a more appropriate way to get an up-to-date list of suggestions. Or use enumerations to list all the possible values. tags: An array of arbitrary string tags provided in the model for this field. type: The LookML type of the field. user_attribute_filter_types: An array of user attribute types that are allowed to be used in filters on this field. Valid values are: "advanced_filter_string", "advanced_filter_number", "advanced_filter_datetime", "string", "number", "datetime", "relative_url", "yesno", "zipcode". value_format: If specified, the LookML value format string for formatting values of this field. view: The name of the view this field belongs to. view_label: The human-readable label of the view the field belongs to. dynamic: Whether this field was specified in "dynamic_fields" and is not part of the model. week_start_day: The name of the starting day of the week. Valid values are: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday". times_used: The number of times this field has been used in queries """ align: Optional["Align"] = None can_filter: Optional[bool] = None category: Optional["Category"] = None default_filter_value: Optional[str] = None description: Optional[str] = None enumerations: Optional[Sequence["LookmlModelExploreFieldEnumeration"]] = None error: Optional[str] = None field_group_label: Optional[str] = None field_group_variant: Optional[str] = None fill_style: Optional["FillStyle"] = None fiscal_month_offset: Optional[int] = None has_allowed_values: Optional[bool] = None hidden: Optional[bool] = None is_filter: Optional[bool] = None is_fiscal: Optional[bool] = None is_numeric: Optional[bool] = None is_timeframe: Optional[bool] = None can_time_filter: Optional[bool] = None time_interval: Optional["LookmlModelExploreFieldTimeInterval"] = None label: Optional[str] = None label_from_parameter: Optional[str] = None label_short: Optional[str] = None lookml_link: Optional[str] = None map_layer: Optional["LookmlModelExploreFieldMapLayer"] = None measure: Optional[bool] = None name: Optional[str] = None strict_value_format: Optional[bool] = None parameter: Optional[bool] = None permanent: Optional[bool] = None primary_key: Optional[bool] = None project_name: Optional[str] = None requires_refresh_on_sort: Optional[bool] = None scope: Optional[str] = None sortable: Optional[bool] = None source_file: Optional[str] = None source_file_path: Optional[str] = None sql: Optional[str] = None sql_case: Optional[Sequence["LookmlModelExploreFieldSqlCase"]] = None filters: Optional[Sequence["LookmlModelExploreFieldMeasureFilters"]] = None suggest_dimension: Optional[str] = None suggest_explore: Optional[str] = None suggestable: Optional[bool] = None suggestions: Optional[Sequence[str]] = None tags: Optional[Sequence[str]] = None type: Optional[str] = None user_attribute_filter_types: Optional[Sequence["UserAttributeFilterTypes"]] = None value_format: Optional[str] = None view: Optional[str] = None view_label: Optional[str] = None dynamic: Optional[bool] = None week_start_day: Optional["WeekStartDay"] = None times_used: Optional[int] = None def __init__( self, *, align: Optional["Align"] = None, can_filter: Optional[bool] = None, category: Optional["Category"] = None, default_filter_value: Optional[str] = None, description: Optional[str] = None, enumerations: Optional[Sequence["LookmlModelExploreFieldEnumeration"]] = None, error: Optional[str] = None, field_group_label: Optional[str] = None, field_group_variant: Optional[str] = None, fill_style: Optional["FillStyle"] = None, fiscal_month_offset: Optional[int] = None, has_allowed_values: Optional[bool] = None, hidden: Optional[bool] = None, is_filter: Optional[bool] = None, is_fiscal: Optional[bool] = None, is_numeric: Optional[bool] = None, is_timeframe: Optional[bool] = None, can_time_filter: Optional[bool] = None, time_interval: Optional["LookmlModelExploreFieldTimeInterval"] = None, label: Optional[str] = None, label_from_parameter: Optional[str] = None, label_short: Optional[str] = None, lookml_link: Optional[str] = None, map_layer: Optional["LookmlModelExploreFieldMapLayer"] = None, measure: Optional[bool] = None, name: Optional[str] = None, strict_value_format: Optional[bool] = None, parameter: Optional[bool] = None, permanent: Optional[bool] = None, primary_key: Optional[bool] = None, project_name: Optional[str] = None, requires_refresh_on_sort: Optional[bool] = None, scope: Optional[str] = None, sortable: Optional[bool] = None, source_file: Optional[str] = None, source_file_path: Optional[str] = None, sql: Optional[str] = None, sql_case: Optional[Sequence["LookmlModelExploreFieldSqlCase"]] = None, filters: Optional[Sequence["LookmlModelExploreFieldMeasureFilters"]] = None, suggest_dimension: Optional[str] = None, suggest_explore: Optional[str] = None, suggestable: Optional[bool] = None, suggestions: Optional[Sequence[str]] = None, tags: Optional[Sequence[str]] = None, type: Optional[str] = None, user_attribute_filter_types: Optional[ Sequence["UserAttributeFilterTypes"] ] = None, value_format: Optional[str] = None, view: Optional[str] = None, view_label: Optional[str] = None, dynamic: Optional[bool] = None, week_start_day: Optional["WeekStartDay"] = None, times_used: Optional[int] = None ): self.align = align self.can_filter = can_filter self.category = category self.default_filter_value = default_filter_value self.description = description self.enumerations = enumerations self.error = error self.field_group_label = field_group_label self.field_group_variant = field_group_variant self.fill_style = fill_style self.fiscal_month_offset = fiscal_month_offset self.has_allowed_values = has_allowed_values self.hidden = hidden self.is_filter = is_filter self.is_fiscal = is_fiscal self.is_numeric = is_numeric self.is_timeframe = is_timeframe self.can_time_filter = can_time_filter self.time_interval = time_interval self.label = label self.label_from_parameter = label_from_parameter self.label_short = label_short self.lookml_link = lookml_link self.map_layer = map_layer self.measure = measure self.name = name self.strict_value_format = strict_value_format self.parameter = parameter self.permanent = permanent self.primary_key = primary_key self.project_name = project_name self.requires_refresh_on_sort = requires_refresh_on_sort self.scope = scope self.sortable = sortable self.source_file = source_file self.source_file_path = source_file_path self.sql = sql self.sql_case = sql_case self.filters = filters self.suggest_dimension = suggest_dimension self.suggest_explore = suggest_explore self.suggestable = suggestable self.suggestions = suggestions self.tags = tags self.type = type self.user_attribute_filter_types = user_attribute_filter_types self.value_format = value_format self.view = view self.view_label = view_label self.dynamic = dynamic self.week_start_day = week_start_day self.times_used = times_used @attr.s(auto_attribs=True, init=False) class LookmlModelExploreFieldEnumeration(model.Model): """ Attributes: label: Label value: Value """ label: Optional[str] = None value: Optional[Any] = None def __init__(self, *, label: Optional[str] = None, value: Optional[Any] = None): self.label = label self.value = value @attr.s(auto_attribs=True, init=False) class LookmlModelExploreFieldMapLayer(model.Model): """ Attributes: url: URL to the map layer resource. name: Name of the map layer, as defined in LookML. feature_key: Specifies the name of the TopoJSON object that the map layer references. If not specified, use the first object.. property_key: Selects which property from the TopoJSON data to plot against. TopoJSON supports arbitrary metadata for each region. When null, the first matching property should be used. property_label_key: Which property from the TopoJSON data to use to label the region. When null, property_key should be used. projection: The preferred geographic projection of the map layer when displayed in a visualization that supports multiple geographic projections. format: Specifies the data format of the region information. Valid values are: "topojson", "vector_tile_region". extents_json_url: Specifies the URL to a JSON file that defines the geographic extents of each region available in the map layer. This data is used to automatically center the map on the available data for visualization purposes. The JSON file must be a JSON object where the keys are the mapping value of the feature (as specified by property_key) and the values are arrays of four numbers representing the west longitude, south latitude, east longitude, and north latitude extents of the region. The object must include a key for every possible value of property_key. max_zoom_level: The minimum zoom level that the map layer may be displayed at, for visualizations that support zooming. min_zoom_level: The maximum zoom level that the map layer may be displayed at, for visualizations that support zooming. """ url: Optional[str] = None name: Optional[str] = None feature_key: Optional[str] = None property_key: Optional[str] = None property_label_key: Optional[str] = None projection: Optional[str] = None format: Optional["Format"] = None extents_json_url: Optional[str] = None max_zoom_level: Optional[int] = None min_zoom_level: Optional[int] = None def __init__( self, *, url: Optional[str] = None, name: Optional[str] = None, feature_key: Optional[str] = None, property_key: Optional[str] = None, property_label_key: Optional[str] = None, projection: Optional[str] = None, format: Optional["Format"] = None, extents_json_url: Optional[str] = None, max_zoom_level: Optional[int] = None, min_zoom_level: Optional[int] = None ): self.url = url self.name = name self.feature_key = feature_key self.property_key = property_key self.property_label_key = property_label_key self.projection = projection self.format = format self.extents_json_url = extents_json_url self.max_zoom_level = max_zoom_level self.min_zoom_level = min_zoom_level @attr.s(auto_attribs=True, init=False) class LookmlModelExploreFieldMeasureFilters(model.Model): """ Attributes: field: Filter field name condition: Filter condition value """ field: Optional[str] = None condition: Optional[str] = None def __init__(self, *, field: Optional[str] = None, condition: Optional[str] = None): self.field = field self.condition = condition @attr.s(auto_attribs=True, init=False) class LookmlModelExploreFieldset(model.Model): """ Attributes: dimensions: Array of dimensions measures: Array of measures filters: Array of filters parameters: Array of parameters """ dimensions: Optional[Sequence["LookmlModelExploreField"]] = None measures: Optional[Sequence["LookmlModelExploreField"]] = None filters: Optional[Sequence["LookmlModelExploreField"]] = None parameters: Optional[Sequence["LookmlModelExploreField"]] = None def __init__( self, *, dimensions: Optional[Sequence["LookmlModelExploreField"]] = None, measures: Optional[Sequence["LookmlModelExploreField"]] = None, filters: Optional[Sequence["LookmlModelExploreField"]] = None, parameters: Optional[Sequence["LookmlModelExploreField"]] = None ): self.dimensions = dimensions self.measures = measures self.filters = filters self.parameters = parameters @attr.s(auto_attribs=True, init=False) class LookmlModelExploreFieldSqlCase(model.Model): """ Attributes: value: SQL Case label value condition: SQL Case condition expression """ value: Optional[str] = None condition: Optional[str] = None def __init__(self, *, value: Optional[str] = None, condition: Optional[str] = None): self.value = value self.condition = condition @attr.s(auto_attribs=True, init=False) class LookmlModelExploreFieldTimeInterval(model.Model): """ Attributes: name: The type of time interval this field represents a grouping of. Valid values are: "day", "hour", "minute", "second", "millisecond", "microsecond", "week", "month", "quarter", "year". count: The number of intervals this field represents a grouping of. """ name: Optional["Name"] = None count: Optional[int] = None def __init__(self, *, name: Optional["Name"] = None, count: Optional[int] = None): self.name = name self.count = count @attr.s(auto_attribs=True, init=False) class LookmlModelExploreJoins(model.Model): """ Attributes: name: Name of this join (and name of the view to join) dependent_fields: Fields referenced by the join fields: Fields of the joined view to pull into this explore foreign_key: Name of the dimension in this explore whose value is in the primary key of the joined view from_: Name of view to join outer_only: Specifies whether all queries must use an outer join relationship: many_to_one, one_to_one, one_to_many, many_to_many required_joins: Names of joins that must always be included in SQL queries sql_foreign_key: SQL expression that produces a foreign key sql_on: SQL ON expression describing the join condition sql_table_name: SQL table name to join type: The join type: left_outer, full_outer, inner, or cross view_label: Label to display in UI selectors """ name: Optional[str] = None dependent_fields: Optional[Sequence[str]] = None fields: Optional[Sequence[str]] = None foreign_key: Optional[str] = None from_: Optional[str] = None outer_only: Optional[bool] = None relationship: Optional[str] = None required_joins: Optional[Sequence[str]] = None sql_foreign_key: Optional[str] = None sql_on: Optional[str] = None sql_table_name: Optional[str] = None type: Optional[str] = None view_label: Optional[str] = None def __init__( self, *, name: Optional[str] = None, dependent_fields: Optional[Sequence[str]] = None, fields: Optional[Sequence[str]] = None, foreign_key: Optional[str] = None, from_: Optional[str] = None, outer_only: Optional[bool] = None, relationship: Optional[str] = None, required_joins: Optional[Sequence[str]] = None, sql_foreign_key: Optional[str] = None, sql_on: Optional[str] = None, sql_table_name: Optional[str] = None, type: Optional[str] = None, view_label: Optional[str] = None ): self.name = name self.dependent_fields = dependent_fields self.fields = fields self.foreign_key = foreign_key self.from_ = from_ self.outer_only = outer_only self.relationship = relationship self.required_joins = required_joins self.sql_foreign_key = sql_foreign_key self.sql_on = sql_on self.sql_table_name = sql_table_name self.type = type self.view_label = view_label @attr.s(auto_attribs=True, init=False) class LookmlModelExploreSet(model.Model): """ Attributes: name: Name value: Value set """ name: Optional[str] = None value: Optional[Sequence[str]] = None def __init__( self, *, name: Optional[str] = None, value: Optional[Sequence[str]] = None ): self.name = name self.value = value @attr.s(auto_attribs=True, init=False) class LookmlModelExploreSupportedMeasureType(model.Model): """ Attributes: dimension_type: measure_types: """ dimension_type: Optional[str] = None measure_types: Optional[Sequence[str]] = None def __init__( self, *, dimension_type: Optional[str] = None, measure_types: Optional[Sequence[str]] = None ): self.dimension_type = dimension_type self.measure_types = measure_types @attr.s(auto_attribs=True, init=False) class LookmlModelNavExplore(model.Model): """ Attributes: name: Name of the explore description: Description for the explore label: Label for the explore hidden: Is this explore marked as hidden group_label: Label used to group explores in the navigation menus """ name: Optional[str] = None description: Optional[str] = None label: Optional[str] = None hidden: Optional[bool] = None group_label: Optional[str] = None def __init__( self, *, name: Optional[str] = None, description: Optional[str] = None, label: Optional[str] = None, hidden: Optional[bool] = None, group_label: Optional[str] = None ): self.name = name self.description = description self.label = label self.hidden = hidden self.group_label = group_label @attr.s(auto_attribs=True, init=False) class LookmlTest(model.Model): """ Attributes: can: Operations the current user is able to perform on this object model_name: Name of model containing this test. name: Name of this test. explore_name: Name of the explore this test runs a query against query_url_params: The url parameters that can be used to reproduce this test's query on an explore. file: Name of the LookML file containing this test. line: Line number of this test in LookML. """ can: Optional[MutableMapping[str, bool]] = None model_name: Optional[str] = None name: Optional[str] = None explore_name: Optional[str] = None query_url_params: Optional[str] = None file: Optional[str] = None line: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, model_name: Optional[str] = None, name: Optional[str] = None, explore_name: Optional[str] = None, query_url_params: Optional[str] = None, file: Optional[str] = None, line: Optional[int] = None ): self.can = can self.model_name = model_name self.name = name self.explore_name = explore_name self.query_url_params = query_url_params self.file = file self.line = line @attr.s(auto_attribs=True, init=False) class LookmlTestResult(model.Model): """ Attributes: can: Operations the current user is able to perform on this object model_name: Name of model containing this test. test_name: Name of this test. assertions_count: Number of assertions in this test assertions_failed: Number of assertions passed in this test errors: A list of any errors encountered by the test. warnings: A list of any warnings encountered by the test. success: True if this test passsed without errors. """ can: Optional[MutableMapping[str, bool]] = None model_name: Optional[str] = None test_name: Optional[str] = None assertions_count: Optional[int] = None assertions_failed: Optional[int] = None errors: Optional[Sequence["ProjectError"]] = None warnings: Optional[Sequence["ProjectError"]] = None success: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, model_name: Optional[str] = None, test_name: Optional[str] = None, assertions_count: Optional[int] = None, assertions_failed: Optional[int] = None, errors: Optional[Sequence["ProjectError"]] = None, warnings: Optional[Sequence["ProjectError"]] = None, success: Optional[bool] = None ): self.can = can self.model_name = model_name self.test_name = test_name self.assertions_count = assertions_count self.assertions_failed = assertions_failed self.errors = errors self.warnings = warnings self.success = success @attr.s(auto_attribs=True, init=False) class LookModel(model.Model): """ Attributes: id: Model Id label: Model Label """ id: Optional[str] = None label: Optional[str] = None def __init__(self, *, id: Optional[str] = None, label: Optional[str] = None): self.id = id self.label = label @attr.s(auto_attribs=True, init=False) class LookWithDashboards(model.Model): """ Attributes: can: Operations the current user is able to perform on this object content_metadata_id: Id of content metadata id: Unique Id title: Look Title user_id: User Id content_favorite_id: Content Favorite Id created_at: Time that the Look was created. deleted: Whether or not a look is 'soft' deleted. deleted_at: Time that the Look was deleted. deleter_id: Id of User that deleted the look. description: Description embed_url: Embed Url excel_file_url: Excel File Url favorite_count: Number of times favorited google_spreadsheet_formula: Google Spreadsheet Formula image_embed_url: Image Embed Url is_run_on_load: auto-run query when Look viewed last_accessed_at: Time that the Look was last accessed by any user last_updater_id: Id of User that last updated the look. last_viewed_at: Time last viewed in the Looker web UI model: public: Is Public public_slug: Public Slug public_url: Public Url query_id: Query Id short_url: Short Url folder: folder_id: Folder Id updated_at: Time that the Look was updated. view_count: Number of times viewed in the Looker web UI dashboards: Dashboards """ can: Optional[MutableMapping[str, bool]] = None content_metadata_id: Optional[int] = None id: Optional[int] = None title: Optional[str] = None user_id: Optional[int] = None content_favorite_id: Optional[int] = None created_at: Optional[datetime.datetime] = None deleted: Optional[bool] = None deleted_at: Optional[datetime.datetime] = None deleter_id: Optional[int] = None description: Optional[str] = None embed_url: Optional[str] = None excel_file_url: Optional[str] = None favorite_count: Optional[int] = None google_spreadsheet_formula: Optional[str] = None image_embed_url: Optional[str] = None is_run_on_load: Optional[bool] = None last_accessed_at: Optional[datetime.datetime] = None last_updater_id: Optional[int] = None last_viewed_at: Optional[datetime.datetime] = None model: Optional["LookModel"] = None public: Optional[bool] = None public_slug: Optional[str] = None public_url: Optional[str] = None query_id: Optional[int] = None short_url: Optional[str] = None folder: Optional["FolderBase"] = None folder_id: Optional[str] = None updated_at: Optional[datetime.datetime] = None view_count: Optional[int] = None dashboards: Optional[Sequence["DashboardBase"]] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, content_metadata_id: Optional[int] = None, id: Optional[int] = None, title: Optional[str] = None, user_id: Optional[int] = None, content_favorite_id: Optional[int] = None, created_at: Optional[datetime.datetime] = None, deleted: Optional[bool] = None, deleted_at: Optional[datetime.datetime] = None, deleter_id: Optional[int] = None, description: Optional[str] = None, embed_url: Optional[str] = None, excel_file_url: Optional[str] = None, favorite_count: Optional[int] = None, google_spreadsheet_formula: Optional[str] = None, image_embed_url: Optional[str] = None, is_run_on_load: Optional[bool] = None, last_accessed_at: Optional[datetime.datetime] = None, last_updater_id: Optional[int] = None, last_viewed_at: Optional[datetime.datetime] = None, model: Optional["LookModel"] = None, public: Optional[bool] = None, public_slug: Optional[str] = None, public_url: Optional[str] = None, query_id: Optional[int] = None, short_url: Optional[str] = None, folder: Optional["FolderBase"] = None, folder_id: Optional[str] = None, updated_at: Optional[datetime.datetime] = None, view_count: Optional[int] = None, dashboards: Optional[Sequence["DashboardBase"]] = None ): self.can = can self.content_metadata_id = content_metadata_id self.id = id self.title = title self.user_id = user_id self.content_favorite_id = content_favorite_id self.created_at = created_at self.deleted = deleted self.deleted_at = deleted_at self.deleter_id = deleter_id self.description = description self.embed_url = embed_url self.excel_file_url = excel_file_url self.favorite_count = favorite_count self.google_spreadsheet_formula = google_spreadsheet_formula self.image_embed_url = image_embed_url self.is_run_on_load = is_run_on_load self.last_accessed_at = last_accessed_at self.last_updater_id = last_updater_id self.last_viewed_at = last_viewed_at self.model = model self.public = public self.public_slug = public_slug self.public_url = public_url self.query_id = query_id self.short_url = short_url self.folder = folder self.folder_id = folder_id self.updated_at = updated_at self.view_count = view_count self.dashboards = dashboards @attr.s(auto_attribs=True, init=False) class LookWithQuery(model.Model): """ Attributes: can: Operations the current user is able to perform on this object content_metadata_id: Id of content metadata id: Unique Id title: Look Title user_id: User Id content_favorite_id: Content Favorite Id created_at: Time that the Look was created. deleted: Whether or not a look is 'soft' deleted. deleted_at: Time that the Look was deleted. deleter_id: Id of User that deleted the look. description: Description embed_url: Embed Url excel_file_url: Excel File Url favorite_count: Number of times favorited google_spreadsheet_formula: Google Spreadsheet Formula image_embed_url: Image Embed Url is_run_on_load: auto-run query when Look viewed last_accessed_at: Time that the Look was last accessed by any user last_updater_id: Id of User that last updated the look. last_viewed_at: Time last viewed in the Looker web UI model: public: Is Public public_slug: Public Slug public_url: Public Url query_id: Query Id short_url: Short Url folder: folder_id: Folder Id updated_at: Time that the Look was updated. view_count: Number of times viewed in the Looker web UI query: url: Url """ can: Optional[MutableMapping[str, bool]] = None content_metadata_id: Optional[int] = None id: Optional[int] = None title: Optional[str] = None user_id: Optional[int] = None content_favorite_id: Optional[int] = None created_at: Optional[datetime.datetime] = None deleted: Optional[bool] = None deleted_at: Optional[datetime.datetime] = None deleter_id: Optional[int] = None description: Optional[str] = None embed_url: Optional[str] = None excel_file_url: Optional[str] = None favorite_count: Optional[int] = None google_spreadsheet_formula: Optional[str] = None image_embed_url: Optional[str] = None is_run_on_load: Optional[bool] = None last_accessed_at: Optional[datetime.datetime] = None last_updater_id: Optional[int] = None last_viewed_at: Optional[datetime.datetime] = None model: Optional["LookModel"] = None public: Optional[bool] = None public_slug: Optional[str] = None public_url: Optional[str] = None query_id: Optional[int] = None short_url: Optional[str] = None folder: Optional["FolderBase"] = None folder_id: Optional[str] = None updated_at: Optional[datetime.datetime] = None view_count: Optional[int] = None query: Optional["Query"] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, content_metadata_id: Optional[int] = None, id: Optional[int] = None, title: Optional[str] = None, user_id: Optional[int] = None, content_favorite_id: Optional[int] = None, created_at: Optional[datetime.datetime] = None, deleted: Optional[bool] = None, deleted_at: Optional[datetime.datetime] = None, deleter_id: Optional[int] = None, description: Optional[str] = None, embed_url: Optional[str] = None, excel_file_url: Optional[str] = None, favorite_count: Optional[int] = None, google_spreadsheet_formula: Optional[str] = None, image_embed_url: Optional[str] = None, is_run_on_load: Optional[bool] = None, last_accessed_at: Optional[datetime.datetime] = None, last_updater_id: Optional[int] = None, last_viewed_at: Optional[datetime.datetime] = None, model: Optional["LookModel"] = None, public: Optional[bool] = None, public_slug: Optional[str] = None, public_url: Optional[str] = None, query_id: Optional[int] = None, short_url: Optional[str] = None, folder: Optional["FolderBase"] = None, folder_id: Optional[str] = None, updated_at: Optional[datetime.datetime] = None, view_count: Optional[int] = None, query: Optional["Query"] = None, url: Optional[str] = None ): self.can = can self.content_metadata_id = content_metadata_id self.id = id self.title = title self.user_id = user_id self.content_favorite_id = content_favorite_id self.created_at = created_at self.deleted = deleted self.deleted_at = deleted_at self.deleter_id = deleter_id self.description = description self.embed_url = embed_url self.excel_file_url = excel_file_url self.favorite_count = favorite_count self.google_spreadsheet_formula = google_spreadsheet_formula self.image_embed_url = image_embed_url self.is_run_on_load = is_run_on_load self.last_accessed_at = last_accessed_at self.last_updater_id = last_updater_id self.last_viewed_at = last_viewed_at self.model = model self.public = public self.public_slug = public_slug self.public_url = public_url self.query_id = query_id self.short_url = short_url self.folder = folder self.folder_id = folder_id self.updated_at = updated_at self.view_count = view_count self.query = query self.url = url @attr.s(auto_attribs=True, init=False) class Manifest(model.Model): """ Attributes: can: Operations the current user is able to perform on this object name: Manifest project name imports: Imports for a project localization_settings: """ can: Optional[MutableMapping[str, bool]] = None name: Optional[str] = None imports: Optional[Sequence["ImportedProject"]] = None localization_settings: Optional["LocalizationSettings"] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, name: Optional[str] = None, imports: Optional[Sequence["ImportedProject"]] = None, localization_settings: Optional["LocalizationSettings"] = None ): self.can = can self.name = name self.imports = imports self.localization_settings = localization_settings @attr.s(auto_attribs=True, init=False) class MergeFields(model.Model): """ Attributes: field_name: Field name to map onto in the merged results source_field_name: Field name from the source query """ field_name: Optional[str] = None source_field_name: Optional[str] = None def __init__( self, *, field_name: Optional[str] = None, source_field_name: Optional[str] = None ): self.field_name = field_name self.source_field_name = source_field_name @attr.s(auto_attribs=True, init=False) class MergeQuery(model.Model): """ Attributes: can: Operations the current user is able to perform on this object column_limit: Column Limit dynamic_fields: Dynamic Fields id: Unique Id pivots: Pivots result_maker_id: Unique to get results sorts: Sorts source_queries: Source Queries defining the results to be merged. total: Total vis_config: Visualization Config """ can: Optional[MutableMapping[str, bool]] = None column_limit: Optional[str] = None dynamic_fields: Optional[str] = None id: Optional[str] = None pivots: Optional[Sequence[str]] = None result_maker_id: Optional[int] = None sorts: Optional[Sequence[str]] = None source_queries: Optional[Sequence["MergeQuerySourceQuery"]] = None total: Optional[bool] = None vis_config: Optional[MutableMapping[str, Any]] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, column_limit: Optional[str] = None, dynamic_fields: Optional[str] = None, id: Optional[str] = None, pivots: Optional[Sequence[str]] = None, result_maker_id: Optional[int] = None, sorts: Optional[Sequence[str]] = None, source_queries: Optional[Sequence["MergeQuerySourceQuery"]] = None, total: Optional[bool] = None, vis_config: Optional[MutableMapping[str, Any]] = None ): self.can = can self.column_limit = column_limit self.dynamic_fields = dynamic_fields self.id = id self.pivots = pivots self.result_maker_id = result_maker_id self.sorts = sorts self.source_queries = source_queries self.total = total self.vis_config = vis_config @attr.s(auto_attribs=True, init=False) class MergeQuerySourceQuery(model.Model): """ Attributes: merge_fields: An array defining which fields of the source query are mapped onto fields of the merge query name: Display name query_id: Id of the query to merge """ merge_fields: Optional[Sequence["MergeFields"]] = None name: Optional[str] = None query_id: Optional[int] = None def __init__( self, *, merge_fields: Optional[Sequence["MergeFields"]] = None, name: Optional[str] = None, query_id: Optional[int] = None ): self.merge_fields = merge_fields self.name = name self.query_id = query_id @attr.s(auto_attribs=True, init=False) class ModelFieldSuggestions(model.Model): """ Attributes: suggestions: List of suggestions error: Error message from_cache: True if result came from the cache hit_limit: True if this was a hit limit used_calcite_materialization: True if calcite was used """ suggestions: Optional[Sequence[str]] = None error: Optional[str] = None from_cache: Optional[bool] = None hit_limit: Optional[bool] = None used_calcite_materialization: Optional[bool] = None def __init__( self, *, suggestions: Optional[Sequence[str]] = None, error: Optional[str] = None, from_cache: Optional[bool] = None, hit_limit: Optional[bool] = None, used_calcite_materialization: Optional[bool] = None ): self.suggestions = suggestions self.error = error self.from_cache = from_cache self.hit_limit = hit_limit self.used_calcite_materialization = used_calcite_materialization @attr.s(auto_attribs=True, init=False) class ModelSet(model.Model): """ Attributes: can: Operations the current user is able to perform on this object all_access: built_in: id: Unique Id models: name: Name of ModelSet url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None all_access: Optional[bool] = None built_in: Optional[bool] = None id: Optional[int] = None models: Optional[Sequence[str]] = None name: Optional[str] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, all_access: Optional[bool] = None, built_in: Optional[bool] = None, id: Optional[int] = None, models: Optional[Sequence[str]] = None, name: Optional[str] = None, url: Optional[str] = None ): self.can = can self.all_access = all_access self.built_in = built_in self.id = id self.models = models self.name = name self.url = url @attr.s(auto_attribs=True, init=False) class ModelsNotValidated(model.Model): """ Attributes: name: Model name project_file_id: Project file """ name: Optional[str] = None project_file_id: Optional[str] = None def __init__( self, *, name: Optional[str] = None, project_file_id: Optional[str] = None ): self.name = name self.project_file_id = project_file_id class Name(enum.Enum): """ The type of time interval this field represents a grouping of. Valid values are: "day", "hour", "minute", "second", "millisecond", "microsecond", "week", "month", "quarter", "year". """ day = "day" hour = "hour" minute = "minute" second = "second" millisecond = "millisecond" microsecond = "microsecond" week = "week" month = "month" quarter = "quarter" year = "year" invalid_api_enum_value = "invalid_api_enum_value" Name.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class OauthClientApp(model.Model): """ Attributes: can: Operations the current user is able to perform on this object client_guid: The globally unique id of this application redirect_uri: The uri with which this application will receive an auth code by browser redirect. display_name: The application's display name description: A description of the application that will be displayed to users enabled: When enabled is true, OAuth2 and API requests will be accepted from this app. When false, all requests from this app will be refused. group_id: If set, only Looker users who are members of this group can use this web app with Looker. If group_id is not set, any Looker user may use this app to access this Looker instance tokens_invalid_before: All auth codes, access tokens, and refresh tokens issued for this application prior to this date-time for ALL USERS will be invalid. activated_users: All users who have been activated to use this app """ can: Optional[MutableMapping[str, bool]] = None client_guid: Optional[str] = None redirect_uri: Optional[str] = None display_name: Optional[str] = None description: Optional[str] = None enabled: Optional[bool] = None group_id: Optional[int] = None tokens_invalid_before: Optional[datetime.datetime] = None activated_users: Optional[Sequence["UserPublic"]] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, client_guid: Optional[str] = None, redirect_uri: Optional[str] = None, display_name: Optional[str] = None, description: Optional[str] = None, enabled: Optional[bool] = None, group_id: Optional[int] = None, tokens_invalid_before: Optional[datetime.datetime] = None, activated_users: Optional[Sequence["UserPublic"]] = None ): self.can = can self.client_guid = client_guid self.redirect_uri = redirect_uri self.display_name = display_name self.description = description self.enabled = enabled self.group_id = group_id self.tokens_invalid_before = tokens_invalid_before self.activated_users = activated_users @attr.s(auto_attribs=True, init=False) class OIDCConfig(model.Model): """ Attributes: can: Operations the current user is able to perform on this object alternate_email_login_allowed: Allow alternate email-based login via '/login/email' for admins and for specified users with the 'login_special_email' permission. This option is useful as a fallback during ldap setup, if ldap config problems occur later, or if you need to support some users who are not in your ldap directory. Looker email/password logins are always disabled for regular users when ldap is enabled. audience: OpenID Provider Audience auth_requires_role: Users will not be allowed to login at all unless a role for them is found in OIDC if set to true authorization_endpoint: OpenID Provider Authorization Url default_new_user_group_ids: (Write-Only) Array of ids of groups that will be applied to new users the first time they login via OIDC default_new_user_groups: (Read-only) Groups that will be applied to new users the first time they login via OIDC default_new_user_role_ids: (Write-Only) Array of ids of roles that will be applied to new users the first time they login via OIDC default_new_user_roles: (Read-only) Roles that will be applied to new users the first time they login via OIDC enabled: Enable/Disable OIDC authentication for the server groups: (Read-only) Array of mappings between OIDC Groups and Looker Roles groups_attribute: Name of user record attributes used to indicate groups. Used when 'groups_finder_type' is set to 'grouped_attribute_values' groups_with_role_ids: (Read/Write) Array of mappings between OIDC Groups and arrays of Looker Role ids identifier: Relying Party Identifier (provided by OpenID Provider) issuer: OpenID Provider Issuer modified_at: When this config was last modified modified_by: User id of user who last modified this config new_user_migration_types: Merge first-time oidc login to existing user account by email addresses. When a user logs in for the first time via oidc this option will connect this user into their existing account by finding the account with a matching email address by testing the given types of credentials for existing users. Otherwise a new user account will be created for the user. This list (if provided) must be a comma separated list of string like 'email,ldap,google' scopes: Array of scopes to request. secret: (Write-Only) Relying Party Secret (provided by OpenID Provider) set_roles_from_groups: Set user roles in Looker based on groups from OIDC test_slug: Slug to identify configurations that are created in order to run a OIDC config test token_endpoint: OpenID Provider Token Url user_attribute_map_email: Name of user record attributes used to indicate email address field user_attribute_map_first_name: Name of user record attributes used to indicate first name user_attribute_map_last_name: Name of user record attributes used to indicate last name user_attributes: (Read-only) Array of mappings between OIDC User Attributes and Looker User Attributes user_attributes_with_ids: (Read/Write) Array of mappings between OIDC User Attributes and arrays of Looker User Attribute ids userinfo_endpoint: OpenID Provider User Information Url allow_normal_group_membership: Allow OIDC auth'd users to be members of non-reflected Looker groups. If 'false', user will be removed from non-reflected groups on login. allow_roles_from_normal_groups: OIDC auth'd users will inherit roles from non-reflected Looker groups. allow_direct_roles: Allows roles to be directly assigned to OIDC auth'd users. url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None alternate_email_login_allowed: Optional[bool] = None audience: Optional[str] = None auth_requires_role: Optional[bool] = None authorization_endpoint: Optional[str] = None default_new_user_group_ids: Optional[Sequence[int]] = None default_new_user_groups: Optional[Sequence["Group"]] = None default_new_user_role_ids: Optional[Sequence[int]] = None default_new_user_roles: Optional[Sequence["Role"]] = None enabled: Optional[bool] = None groups: Optional[Sequence["OIDCGroupRead"]] = None groups_attribute: Optional[str] = None groups_with_role_ids: Optional[Sequence["OIDCGroupWrite"]] = None identifier: Optional[str] = None issuer: Optional[str] = None modified_at: Optional[datetime.datetime] = None modified_by: Optional[int] = None new_user_migration_types: Optional[str] = None scopes: Optional[Sequence[str]] = None secret: Optional[str] = None set_roles_from_groups: Optional[bool] = None test_slug: Optional[str] = None token_endpoint: Optional[str] = None user_attribute_map_email: Optional[str] = None user_attribute_map_first_name: Optional[str] = None user_attribute_map_last_name: Optional[str] = None user_attributes: Optional[Sequence["OIDCUserAttributeRead"]] = None user_attributes_with_ids: Optional[Sequence["OIDCUserAttributeWrite"]] = None userinfo_endpoint: Optional[str] = None allow_normal_group_membership: Optional[bool] = None allow_roles_from_normal_groups: Optional[bool] = None allow_direct_roles: Optional[bool] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, alternate_email_login_allowed: Optional[bool] = None, audience: Optional[str] = None, auth_requires_role: Optional[bool] = None, authorization_endpoint: Optional[str] = None, default_new_user_group_ids: Optional[Sequence[int]] = None, default_new_user_groups: Optional[Sequence["Group"]] = None, default_new_user_role_ids: Optional[Sequence[int]] = None, default_new_user_roles: Optional[Sequence["Role"]] = None, enabled: Optional[bool] = None, groups: Optional[Sequence["OIDCGroupRead"]] = None, groups_attribute: Optional[str] = None, groups_with_role_ids: Optional[Sequence["OIDCGroupWrite"]] = None, identifier: Optional[str] = None, issuer: Optional[str] = None, modified_at: Optional[datetime.datetime] = None, modified_by: Optional[int] = None, new_user_migration_types: Optional[str] = None, scopes: Optional[Sequence[str]] = None, secret: Optional[str] = None, set_roles_from_groups: Optional[bool] = None, test_slug: Optional[str] = None, token_endpoint: Optional[str] = None, user_attribute_map_email: Optional[str] = None, user_attribute_map_first_name: Optional[str] = None, user_attribute_map_last_name: Optional[str] = None, user_attributes: Optional[Sequence["OIDCUserAttributeRead"]] = None, user_attributes_with_ids: Optional[Sequence["OIDCUserAttributeWrite"]] = None, userinfo_endpoint: Optional[str] = None, allow_normal_group_membership: Optional[bool] = None, allow_roles_from_normal_groups: Optional[bool] = None, allow_direct_roles: Optional[bool] = None, url: Optional[str] = None ): self.can = can self.alternate_email_login_allowed = alternate_email_login_allowed self.audience = audience self.auth_requires_role = auth_requires_role self.authorization_endpoint = authorization_endpoint self.default_new_user_group_ids = default_new_user_group_ids self.default_new_user_groups = default_new_user_groups self.default_new_user_role_ids = default_new_user_role_ids self.default_new_user_roles = default_new_user_roles self.enabled = enabled self.groups = groups self.groups_attribute = groups_attribute self.groups_with_role_ids = groups_with_role_ids self.identifier = identifier self.issuer = issuer self.modified_at = modified_at self.modified_by = modified_by self.new_user_migration_types = new_user_migration_types self.scopes = scopes self.secret = secret self.set_roles_from_groups = set_roles_from_groups self.test_slug = test_slug self.token_endpoint = token_endpoint self.user_attribute_map_email = user_attribute_map_email self.user_attribute_map_first_name = user_attribute_map_first_name self.user_attribute_map_last_name = user_attribute_map_last_name self.user_attributes = user_attributes self.user_attributes_with_ids = user_attributes_with_ids self.userinfo_endpoint = userinfo_endpoint self.allow_normal_group_membership = allow_normal_group_membership self.allow_roles_from_normal_groups = allow_roles_from_normal_groups self.allow_direct_roles = allow_direct_roles self.url = url @attr.s(auto_attribs=True, init=False) class OIDCGroupRead(model.Model): """ Attributes: id: Unique Id looker_group_id: Unique Id of group in Looker looker_group_name: Name of group in Looker name: Name of group in OIDC roles: Looker Roles """ id: Optional[int] = None looker_group_id: Optional[int] = None looker_group_name: Optional[str] = None name: Optional[str] = None roles: Optional[Sequence["Role"]] = None def __init__( self, *, id: Optional[int] = None, looker_group_id: Optional[int] = None, looker_group_name: Optional[str] = None, name: Optional[str] = None, roles: Optional[Sequence["Role"]] = None ): self.id = id self.looker_group_id = looker_group_id self.looker_group_name = looker_group_name self.name = name self.roles = roles @attr.s(auto_attribs=True, init=False) class OIDCGroupWrite(model.Model): """ Attributes: id: Unique Id looker_group_id: Unique Id of group in Looker looker_group_name: Name of group in Looker name: Name of group in OIDC role_ids: Looker Role Ids """ id: Optional[int] = None looker_group_id: Optional[int] = None looker_group_name: Optional[str] = None name: Optional[str] = None role_ids: Optional[Sequence[int]] = None def __init__( self, *, id: Optional[int] = None, looker_group_id: Optional[int] = None, looker_group_name: Optional[str] = None, name: Optional[str] = None, role_ids: Optional[Sequence[int]] = None ): self.id = id self.looker_group_id = looker_group_id self.looker_group_name = looker_group_name self.name = name self.role_ids = role_ids @attr.s(auto_attribs=True, init=False) class OIDCUserAttributeRead(model.Model): """ Attributes: name: Name of User Attribute in OIDC required: Required to be in OIDC assertion for login to be allowed to succeed user_attributes: Looker User Attributes """ name: Optional[str] = None required: Optional[bool] = None user_attributes: Optional[Sequence["UserAttribute"]] = None def __init__( self, *, name: Optional[str] = None, required: Optional[bool] = None, user_attributes: Optional[Sequence["UserAttribute"]] = None ): self.name = name self.required = required self.user_attributes = user_attributes @attr.s(auto_attribs=True, init=False) class OIDCUserAttributeWrite(model.Model): """ Attributes: name: Name of User Attribute in OIDC required: Required to be in OIDC assertion for login to be allowed to succeed user_attribute_ids: Looker User Attribute Ids """ name: Optional[str] = None required: Optional[bool] = None user_attribute_ids: Optional[Sequence[int]] = None def __init__( self, *, name: Optional[str] = None, required: Optional[bool] = None, user_attribute_ids: Optional[Sequence[int]] = None ): self.name = name self.required = required self.user_attribute_ids = user_attribute_ids @attr.s(auto_attribs=True, init=False) class PasswordConfig(model.Model): """ Attributes: can: Operations the current user is able to perform on this object min_length: Minimum number of characters required for a new password. Must be between 7 and 100 require_numeric: Require at least one numeric character require_upperlower: Require at least one uppercase and one lowercase letter require_special: Require at least one special character """ can: Optional[MutableMapping[str, bool]] = None min_length: Optional[int] = None require_numeric: Optional[bool] = None require_upperlower: Optional[bool] = None require_special: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, min_length: Optional[int] = None, require_numeric: Optional[bool] = None, require_upperlower: Optional[bool] = None, require_special: Optional[bool] = None ): self.can = can self.min_length = min_length self.require_numeric = require_numeric self.require_upperlower = require_upperlower self.require_special = require_special @attr.s(auto_attribs=True, init=False) class Permission(model.Model): """ Attributes: can: Operations the current user is able to perform on this object permission: Permission symbol parent: Dependency parent symbol description: Description """ can: Optional[MutableMapping[str, bool]] = None permission: Optional[str] = None parent: Optional[str] = None description: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, permission: Optional[str] = None, parent: Optional[str] = None, description: Optional[str] = None ): self.can = can self.permission = permission self.parent = parent self.description = description @attr.s(auto_attribs=True, init=False) class PermissionSet(model.Model): """ Attributes: can: Operations the current user is able to perform on this object all_access: built_in: id: Unique Id name: Name of PermissionSet permissions: url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None all_access: Optional[bool] = None built_in: Optional[bool] = None id: Optional[int] = None name: Optional[str] = None permissions: Optional[Sequence[str]] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, all_access: Optional[bool] = None, built_in: Optional[bool] = None, id: Optional[int] = None, name: Optional[str] = None, permissions: Optional[Sequence[str]] = None, url: Optional[str] = None ): self.can = can self.all_access = all_access self.built_in = built_in self.id = id self.name = name self.permissions = permissions self.url = url class PermissionType(enum.Enum): """ Type of permission: "view" or "edit" Valid values are: "view", "edit". """ view = "view" edit = "edit" invalid_api_enum_value = "invalid_api_enum_value" PermissionType.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class Project(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Project Id name: Project display name uses_git: If true the project is configured with a git repository git_remote_url: Git remote repository url git_username: Git username for HTTPS authentication. (For production only, if using user attributes.) git_password: (Write-Only) Git password for HTTPS authentication. (For production only, if using user attributes.) git_username_user_attribute: User attribute name for username in per-user HTTPS authentication. git_password_user_attribute: User attribute name for password in per-user HTTPS authentication. git_service_name: Name of the git service provider git_application_server_http_port: Port that HTTP(S) application server is running on (for PRs, file browsing, etc.) git_application_server_http_scheme: Scheme that is running on application server (for PRs, file browsing, etc.) Valid values are: "http", "https". deploy_secret: (Write-Only) Optional secret token with which to authenticate requests to the webhook deploy endpoint. If not set, endpoint is unauthenticated. unset_deploy_secret: (Write-Only) When true, unsets the deploy secret to allow unauthenticated access to the webhook deploy endpoint. pull_request_mode: The git pull request policy for this project. Valid values are: "off", "links", "recommended", "required". validation_required: Validation policy: If true, the project must pass validation checks before project changes can be committed to the git repository git_release_mgmt_enabled: If true, advanced git release management is enabled for this project allow_warnings: Validation policy: If true, the project can be committed with warnings when `validation_required` is true. (`allow_warnings` does nothing if `validation_required` is false). is_example: If true the project is an example project and cannot be modified dependency_status: Status of dependencies in your manifest & lockfile """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None name: Optional[str] = None uses_git: Optional[bool] = None git_remote_url: Optional[str] = None git_username: Optional[str] = None git_password: Optional[str] = None git_username_user_attribute: Optional[str] = None git_password_user_attribute: Optional[str] = None git_service_name: Optional[str] = None git_application_server_http_port: Optional[int] = None git_application_server_http_scheme: Optional[ "GitApplicationServerHttpScheme" ] = None deploy_secret: Optional[str] = None unset_deploy_secret: Optional[bool] = None pull_request_mode: Optional["PullRequestMode"] = None validation_required: Optional[bool] = None git_release_mgmt_enabled: Optional[bool] = None allow_warnings: Optional[bool] = None is_example: Optional[bool] = None dependency_status: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, name: Optional[str] = None, uses_git: Optional[bool] = None, git_remote_url: Optional[str] = None, git_username: Optional[str] = None, git_password: Optional[str] = None, git_username_user_attribute: Optional[str] = None, git_password_user_attribute: Optional[str] = None, git_service_name: Optional[str] = None, git_application_server_http_port: Optional[int] = None, git_application_server_http_scheme: Optional[ "GitApplicationServerHttpScheme" ] = None, deploy_secret: Optional[str] = None, unset_deploy_secret: Optional[bool] = None, pull_request_mode: Optional["PullRequestMode"] = None, validation_required: Optional[bool] = None, git_release_mgmt_enabled: Optional[bool] = None, allow_warnings: Optional[bool] = None, is_example: Optional[bool] = None, dependency_status: Optional[str] = None ): self.can = can self.id = id self.name = name self.uses_git = uses_git self.git_remote_url = git_remote_url self.git_username = git_username self.git_password = git_password self.git_username_user_attribute = git_username_user_attribute self.git_password_user_attribute = git_password_user_attribute self.git_service_name = git_service_name self.git_application_server_http_port = git_application_server_http_port self.git_application_server_http_scheme = git_application_server_http_scheme self.deploy_secret = deploy_secret self.unset_deploy_secret = unset_deploy_secret self.pull_request_mode = pull_request_mode self.validation_required = validation_required self.git_release_mgmt_enabled = git_release_mgmt_enabled self.allow_warnings = allow_warnings self.is_example = is_example self.dependency_status = dependency_status @attr.s(auto_attribs=True, init=False) class ProjectError(model.Model): """ Attributes: code: A stable token that uniquely identifies this class of error, ignoring parameter values. Error message text may vary due to parameters or localization, but error codes do not. For example, a "File not found" error will have the same error code regardless of the filename in question or the user's display language severity: Severity: fatal, error, warning, info, success kind: Error classification: syntax, deprecation, model_configuration, etc message: Error message which may contain information such as dashboard or model names that may be considered sensitive in some use cases. Avoid storing or sending this message outside of Looker field_name: The field associated with this error file_path: Name of the file containing this error line_number: Line number in the file of this error model_id: The model associated with this error explore: The explore associated with this error help_url: A link to Looker documentation about this error params: Error parameters sanitized_message: A version of the error message that does not contain potentially sensitive information. Suitable for situations in which messages are stored or sent to consumers outside of Looker, such as external logs. Sanitized messages will display "(?)" where sensitive information would appear in the corresponding non-sanitized message """ code: Optional[str] = None severity: Optional[str] = None kind: Optional[str] = None message: Optional[str] = None field_name: Optional[str] = None file_path: Optional[str] = None line_number: Optional[int] = None model_id: Optional[str] = None explore: Optional[str] = None help_url: Optional[str] = None params: Optional[MutableMapping[str, Any]] = None sanitized_message: Optional[str] = None def __init__( self, *, code: Optional[str] = None, severity: Optional[str] = None, kind: Optional[str] = None, message: Optional[str] = None, field_name: Optional[str] = None, file_path: Optional[str] = None, line_number: Optional[int] = None, model_id: Optional[str] = None, explore: Optional[str] = None, help_url: Optional[str] = None, params: Optional[MutableMapping[str, Any]] = None, sanitized_message: Optional[str] = None ): self.code = code self.severity = severity self.kind = kind self.message = message self.field_name = field_name self.file_path = file_path self.line_number = line_number self.model_id = model_id self.explore = explore self.help_url = help_url self.params = params self.sanitized_message = sanitized_message @attr.s(auto_attribs=True, init=False) class ProjectFile(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: An opaque token uniquely identifying a file within a project. Avoid parsing or decomposing the text of this token. This token is stable within a Looker release but may change between Looker releases path: Path, file name, and extension of the file relative to the project root directory title: Display name type: File type: model, view, etc extension: The extension of the file: .view.lkml, .model.lkml, etc mime_type: File mime type editable: State of editability for the file. git_status: """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None path: Optional[str] = None title: Optional[str] = None type: Optional[str] = None extension: Optional[str] = None mime_type: Optional[str] = None editable: Optional[bool] = None git_status: Optional["GitStatus"] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, path: Optional[str] = None, title: Optional[str] = None, type: Optional[str] = None, extension: Optional[str] = None, mime_type: Optional[str] = None, editable: Optional[bool] = None, git_status: Optional["GitStatus"] = None ): self.can = can self.id = id self.path = path self.title = title self.type = type self.extension = extension self.mime_type = mime_type self.editable = editable self.git_status = git_status @attr.s(auto_attribs=True, init=False) class ProjectValidation(model.Model): """ Attributes: errors: A list of project errors project_digest: A hash value computed from the project's current state models_not_validated: A list of models which were not fully validated computation_time: Duration of project validation in seconds """ errors: Optional[Sequence["ProjectError"]] = None project_digest: Optional[str] = None models_not_validated: Optional[Sequence["ModelsNotValidated"]] = None computation_time: Optional[float] = None def __init__( self, *, errors: Optional[Sequence["ProjectError"]] = None, project_digest: Optional[str] = None, models_not_validated: Optional[Sequence["ModelsNotValidated"]] = None, computation_time: Optional[float] = None ): self.errors = errors self.project_digest = project_digest self.models_not_validated = models_not_validated self.computation_time = computation_time @attr.s(auto_attribs=True, init=False) class ProjectValidationCache(model.Model): """ Attributes: errors: A list of project errors project_digest: A hash value computed from the project's current state models_not_validated: A list of models which were not fully validated computation_time: Duration of project validation in seconds stale: If true, the cached project validation results are no longer accurate because the project has changed since the cached results were calculated """ errors: Optional[Sequence["ProjectError"]] = None project_digest: Optional[str] = None models_not_validated: Optional[Sequence["ModelsNotValidated"]] = None computation_time: Optional[float] = None stale: Optional[bool] = None def __init__( self, *, errors: Optional[Sequence["ProjectError"]] = None, project_digest: Optional[str] = None, models_not_validated: Optional[Sequence["ModelsNotValidated"]] = None, computation_time: Optional[float] = None, stale: Optional[bool] = None ): self.errors = errors self.project_digest = project_digest self.models_not_validated = models_not_validated self.computation_time = computation_time self.stale = stale @attr.s(auto_attribs=True, init=False) class ProjectWorkspace(model.Model): """ Attributes: can: Operations the current user is able to perform on this object project_id: The id of the project workspace_id: The id of the local workspace containing the project files git_status: The status of the local git directory git_head: Git head revision name dependency_status: Status of the dependencies in your project. Valid values are: "lock_optional", "lock_required", "lock_error", "install_none". git_branch: lookml_type: The lookml syntax used by all files in this project """ can: Optional[MutableMapping[str, bool]] = None project_id: Optional[str] = None workspace_id: Optional[str] = None git_status: Optional[str] = None git_head: Optional[str] = None dependency_status: Optional["DependencyStatus"] = None git_branch: Optional["GitBranch"] = None lookml_type: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, project_id: Optional[str] = None, workspace_id: Optional[str] = None, git_status: Optional[str] = None, git_head: Optional[str] = None, dependency_status: Optional["DependencyStatus"] = None, git_branch: Optional["GitBranch"] = None, lookml_type: Optional[str] = None ): self.can = can self.project_id = project_id self.workspace_id = workspace_id self.git_status = git_status self.git_head = git_head self.dependency_status = dependency_status self.git_branch = git_branch self.lookml_type = lookml_type class PullRequestMode(enum.Enum): """ The git pull request policy for this project. Valid values are: "off", "links", "recommended", "required". """ off = "off" links = "links" recommended = "recommended" required = "required" invalid_api_enum_value = "invalid_api_enum_value" PullRequestMode.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class Query(model.Model): """ Attributes: model: Model view: Explore Name can: Operations the current user is able to perform on this object id: Unique Id fields: Fields pivots: Pivots fill_fields: Fill Fields filters: Filters filter_expression: Filter Expression sorts: Sorting for the query results. Use the format `["view.field", ...]` to sort on fields in ascending order. Use the format `["view.field desc", ...]` to sort on fields in descending order. Use `["__UNSORTED__"]` (2 underscores before and after) to disable sorting entirely. Empty sorts `[]` will trigger a default sort. limit: Limit column_limit: Column Limit total: Total row_total: Raw Total subtotals: Fields on which to run subtotals vis_config: Visualization configuration properties. These properties are typically opaque and differ based on the type of visualization used. There is no specified set of allowed keys. The values can be any type supported by JSON. A "type" key with a string value is often present, and is used by Looker to determine which visualization to present. Visualizations ignore unknown vis_config properties. filter_config: The filter_config represents the state of the filter UI on the explore page for a given query. When running a query via the Looker UI, this parameter takes precedence over "filters". When creating a query or modifying an existing query, "filter_config" should be set to null. Setting it to any other value could cause unexpected filtering behavior. The format should be considered opaque. visible_ui_sections: Visible UI Sections slug: Slug dynamic_fields: Dynamic Fields client_id: Client Id: used to generate shortened explore URLs. If set by client, must be a unique 22 character alphanumeric string. Otherwise one will be generated. share_url: Share Url expanded_share_url: Expanded Share Url url: Expanded Url query_timezone: Query Timezone has_table_calculations: Has Table Calculations """ model: str view: str can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None fields: Optional[Sequence[str]] = None pivots: Optional[Sequence[str]] = None fill_fields: Optional[Sequence[str]] = None filters: Optional[MutableMapping[str, Any]] = None filter_expression: Optional[str] = None sorts: Optional[Sequence[str]] = None limit: Optional[str] = None column_limit: Optional[str] = None total: Optional[bool] = None row_total: Optional[str] = None subtotals: Optional[Sequence[str]] = None vis_config: Optional[MutableMapping[str, Any]] = None filter_config: Optional[MutableMapping[str, Any]] = None visible_ui_sections: Optional[str] = None slug: Optional[str] = None dynamic_fields: Optional[str] = None client_id: Optional[str] = None share_url: Optional[str] = None expanded_share_url: Optional[str] = None url: Optional[str] = None query_timezone: Optional[str] = None has_table_calculations: Optional[bool] = None def __init__( self, *, model: str, view: str, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, fields: Optional[Sequence[str]] = None, pivots: Optional[Sequence[str]] = None, fill_fields: Optional[Sequence[str]] = None, filters: Optional[MutableMapping[str, Any]] = None, filter_expression: Optional[str] = None, sorts: Optional[Sequence[str]] = None, limit: Optional[str] = None, column_limit: Optional[str] = None, total: Optional[bool] = None, row_total: Optional[str] = None, subtotals: Optional[Sequence[str]] = None, vis_config: Optional[MutableMapping[str, Any]] = None, filter_config: Optional[MutableMapping[str, Any]] = None, visible_ui_sections: Optional[str] = None, slug: Optional[str] = None, dynamic_fields: Optional[str] = None, client_id: Optional[str] = None, share_url: Optional[str] = None, expanded_share_url: Optional[str] = None, url: Optional[str] = None, query_timezone: Optional[str] = None, has_table_calculations: Optional[bool] = None ): self.model = model self.view = view self.can = can self.id = id self.fields = fields self.pivots = pivots self.fill_fields = fill_fields self.filters = filters self.filter_expression = filter_expression self.sorts = sorts self.limit = limit self.column_limit = column_limit self.total = total self.row_total = row_total self.subtotals = subtotals self.vis_config = vis_config self.filter_config = filter_config self.visible_ui_sections = visible_ui_sections self.slug = slug self.dynamic_fields = dynamic_fields self.client_id = client_id self.share_url = share_url self.expanded_share_url = expanded_share_url self.url = url self.query_timezone = query_timezone self.has_table_calculations = has_table_calculations @attr.s(auto_attribs=True, init=False) class QueryTask(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id query_id: Id of query query: generate_links: whether or not to generate links in the query response. force_production: Use production models to run query (even is user is in dev mode). path_prefix: Prefix to use for drill links. cache: Whether or not to use the cache server_table_calcs: Whether or not to run table calculations on the server cache_only: Retrieve any results from cache even if the results have expired. cache_key: cache key used to cache query. status: Status of query task. source: Source of query task. runtime: Runtime of prior queries. rebuild_pdts: Rebuild PDTS used in query. result_source: Source of the results of the query. look_id: Id of look associated with query. dashboard_id: Id of dashboard associated with query. result_format: The data format of the query results. """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None query_id: Optional[int] = None query: Optional["Query"] = None generate_links: Optional[bool] = None force_production: Optional[bool] = None path_prefix: Optional[str] = None cache: Optional[bool] = None server_table_calcs: Optional[bool] = None cache_only: Optional[bool] = None cache_key: Optional[str] = None status: Optional[str] = None source: Optional[str] = None runtime: Optional[float] = None rebuild_pdts: Optional[bool] = None result_source: Optional[str] = None look_id: Optional[int] = None dashboard_id: Optional[str] = None result_format: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, query_id: Optional[int] = None, query: Optional["Query"] = None, generate_links: Optional[bool] = None, force_production: Optional[bool] = None, path_prefix: Optional[str] = None, cache: Optional[bool] = None, server_table_calcs: Optional[bool] = None, cache_only: Optional[bool] = None, cache_key: Optional[str] = None, status: Optional[str] = None, source: Optional[str] = None, runtime: Optional[float] = None, rebuild_pdts: Optional[bool] = None, result_source: Optional[str] = None, look_id: Optional[int] = None, dashboard_id: Optional[str] = None, result_format: Optional[str] = None ): self.can = can self.id = id self.query_id = query_id self.query = query self.generate_links = generate_links self.force_production = force_production self.path_prefix = path_prefix self.cache = cache self.server_table_calcs = server_table_calcs self.cache_only = cache_only self.cache_key = cache_key self.status = status self.source = source self.runtime = runtime self.rebuild_pdts = rebuild_pdts self.result_source = result_source self.look_id = look_id self.dashboard_id = dashboard_id self.result_format = result_format @attr.s(auto_attribs=True, init=False) class RenderTask(model.Model): """ Attributes: can: Operations the current user is able to perform on this object created_at: Date/Time render task was created dashboard_filters: Filter values to apply to the dashboard queries, in URL query format dashboard_id: Id of dashboard to render dashboard_style: Dashboard layout style: single_column or tiled finalized_at: Date/Time render task was completed height: Output height in pixels. Flowed layouts may ignore this value. id: Id of this render task look_id: Id of look to render lookml_dashboard_id: Id of lookml dashboard to render query_id: Id of query to render query_runtime: Number of seconds elapsed running queries render_runtime: Number of seconds elapsed rendering data result_format: Output format: pdf, png, or jpg runtime: Total seconds elapsed for render task status: Render task status: enqueued_for_query, querying, enqueued_for_render, rendering, success, failure status_detail: Additional information about the current status user_id: The user account permissions in which the render task will execute width: Output width in pixels """ can: Optional[MutableMapping[str, bool]] = None created_at: Optional[str] = None dashboard_filters: Optional[str] = None dashboard_id: Optional[int] = None dashboard_style: Optional[str] = None finalized_at: Optional[str] = None height: Optional[int] = None id: Optional[str] = None look_id: Optional[int] = None lookml_dashboard_id: Optional[str] = None query_id: Optional[int] = None query_runtime: Optional[float] = None render_runtime: Optional[float] = None result_format: Optional[str] = None runtime: Optional[float] = None status: Optional[str] = None status_detail: Optional[str] = None user_id: Optional[int] = None width: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, created_at: Optional[str] = None, dashboard_filters: Optional[str] = None, dashboard_id: Optional[int] = None, dashboard_style: Optional[str] = None, finalized_at: Optional[str] = None, height: Optional[int] = None, id: Optional[str] = None, look_id: Optional[int] = None, lookml_dashboard_id: Optional[str] = None, query_id: Optional[int] = None, query_runtime: Optional[float] = None, render_runtime: Optional[float] = None, result_format: Optional[str] = None, runtime: Optional[float] = None, status: Optional[str] = None, status_detail: Optional[str] = None, user_id: Optional[int] = None, width: Optional[int] = None ): self.can = can self.created_at = created_at self.dashboard_filters = dashboard_filters self.dashboard_id = dashboard_id self.dashboard_style = dashboard_style self.finalized_at = finalized_at self.height = height self.id = id self.look_id = look_id self.lookml_dashboard_id = lookml_dashboard_id self.query_id = query_id self.query_runtime = query_runtime self.render_runtime = render_runtime self.result_format = result_format self.runtime = runtime self.status = status self.status_detail = status_detail self.user_id = user_id self.width = width @attr.s(auto_attribs=True, init=False) class RepositoryCredential(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id root_project_id: Root project Id remote_url: Git remote repository url git_username: Git username for HTTPS authentication. git_password: (Write-Only) Git password for HTTPS authentication. ssh_public_key: Public deploy key for SSH authentication. is_configured: Whether the credentials have been configured for the Git Repository. """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None root_project_id: Optional[str] = None remote_url: Optional[str] = None git_username: Optional[str] = None git_password: Optional[str] = None ssh_public_key: Optional[str] = None is_configured: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, root_project_id: Optional[str] = None, remote_url: Optional[str] = None, git_username: Optional[str] = None, git_password: Optional[str] = None, ssh_public_key: Optional[str] = None, is_configured: Optional[bool] = None ): self.can = can self.id = id self.root_project_id = root_project_id self.remote_url = remote_url self.git_username = git_username self.git_password = git_password self.ssh_public_key = ssh_public_key self.is_configured = is_configured class ResultFormat(enum.Enum): """ Desired async query result format. Valid values are: "inline_json", "json", "json_detail", "json_fe", "csv", "html", "md", "txt", "xlsx", "gsxml". """ inline_json = "inline_json" json = "json" json_detail = "json_detail" json_fe = "json_fe" csv = "csv" html = "html" md = "md" txt = "txt" xlsx = "xlsx" gsxml = "gsxml" invalid_api_enum_value = "invalid_api_enum_value" ResultFormat.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class ResultMakerFilterables(model.Model): """ Attributes: model: The model this filterable comes from (used for field suggestions). view: The view this filterable comes from (used for field suggestions). name: The name of the filterable thing (Query or Merged Results). listen: array of dashboard_filter_name: and field: objects. """ model: Optional[str] = None view: Optional[str] = None name: Optional[str] = None listen: Optional[Sequence["ResultMakerFilterablesListen"]] = None def __init__( self, *, model: Optional[str] = None, view: Optional[str] = None, name: Optional[str] = None, listen: Optional[Sequence["ResultMakerFilterablesListen"]] = None ): self.model = model self.view = view self.name = name self.listen = listen @attr.s(auto_attribs=True, init=False) class ResultMakerFilterablesListen(model.Model): """ Attributes: dashboard_filter_name: The name of a dashboard filter to listen to. field: The name of the field in the filterable to filter with the value of the dashboard filter. """ dashboard_filter_name: Optional[str] = None field: Optional[str] = None def __init__( self, *, dashboard_filter_name: Optional[str] = None, field: Optional[str] = None ): self.dashboard_filter_name = dashboard_filter_name self.field = field @attr.s(auto_attribs=True, init=False) class ResultMakerWithIdVisConfigAndDynamicFields(model.Model): """ Attributes: id: Unique Id. dynamic_fields: JSON string of dynamic field information. filterables: array of items that can be filtered and information about them. sorts: Sorts of the constituent Look, Query, or Merge Query merge_result_id: ID of merge result if this is a merge_result. total: Total of the constituent Look, Query, or Merge Query query_id: ID of query if this is a query. sql_query_id: ID of SQL Query if this is a SQL Runner Query query: vis_config: Vis config of the constituent Query, or Merge Query. """ id: Optional[int] = None dynamic_fields: Optional[str] = None filterables: Optional[Sequence["ResultMakerFilterables"]] = None sorts: Optional[Sequence[str]] = None merge_result_id: Optional[str] = None total: Optional[bool] = None query_id: Optional[int] = None sql_query_id: Optional[str] = None query: Optional["Query"] = None vis_config: Optional[MutableMapping[str, Any]] = None def __init__( self, *, id: Optional[int] = None, dynamic_fields: Optional[str] = None, filterables: Optional[Sequence["ResultMakerFilterables"]] = None, sorts: Optional[Sequence[str]] = None, merge_result_id: Optional[str] = None, total: Optional[bool] = None, query_id: Optional[int] = None, sql_query_id: Optional[str] = None, query: Optional["Query"] = None, vis_config: Optional[MutableMapping[str, Any]] = None ): self.id = id self.dynamic_fields = dynamic_fields self.filterables = filterables self.sorts = sorts self.merge_result_id = merge_result_id self.total = total self.query_id = query_id self.sql_query_id = sql_query_id self.query = query self.vis_config = vis_config @attr.s(auto_attribs=True, init=False) class Role(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id name: Name of Role permission_set: permission_set_id: (Write-Only) Id of permission set model_set: model_set_id: (Write-Only) Id of model set url: Link to get this item users_url: Link to get list of users with this role """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None name: Optional[str] = None permission_set: Optional["PermissionSet"] = None permission_set_id: Optional[int] = None model_set: Optional["ModelSet"] = None model_set_id: Optional[int] = None url: Optional[str] = None users_url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, name: Optional[str] = None, permission_set: Optional["PermissionSet"] = None, permission_set_id: Optional[int] = None, model_set: Optional["ModelSet"] = None, model_set_id: Optional[int] = None, url: Optional[str] = None, users_url: Optional[str] = None ): self.can = can self.id = id self.name = name self.permission_set = permission_set self.permission_set_id = permission_set_id self.model_set = model_set self.model_set_id = model_set_id self.url = url self.users_url = users_url @attr.s(auto_attribs=True, init=False) class RunningQueries(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id user: query: sql_query: look: created_at: Date/Time Query was initiated completed_at: Date/Time Query was completed query_id: Query Id source: Source (look, dashboard, queryrunner, explore, etc.) node_id: Node Id slug: Slug query_task_id: ID of a Query Task cache_key: Cache Key connection_name: Connection dialect: Dialect connection_id: Connection ID message: Additional Information(Error message or verbose status) status: Status description runtime: Number of seconds elapsed running the Query sql: SQL text of the query as run """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None user: Optional["UserPublic"] = None query: Optional["Query"] = None sql_query: Optional["SqlQuery"] = None look: Optional["LookBasic"] = None created_at: Optional[str] = None completed_at: Optional[str] = None query_id: Optional[str] = None source: Optional[str] = None node_id: Optional[str] = None slug: Optional[str] = None query_task_id: Optional[str] = None cache_key: Optional[str] = None connection_name: Optional[str] = None dialect: Optional[str] = None connection_id: Optional[str] = None message: Optional[str] = None status: Optional[str] = None runtime: Optional[float] = None sql: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, user: Optional["UserPublic"] = None, query: Optional["Query"] = None, sql_query: Optional["SqlQuery"] = None, look: Optional["LookBasic"] = None, created_at: Optional[str] = None, completed_at: Optional[str] = None, query_id: Optional[str] = None, source: Optional[str] = None, node_id: Optional[str] = None, slug: Optional[str] = None, query_task_id: Optional[str] = None, cache_key: Optional[str] = None, connection_name: Optional[str] = None, dialect: Optional[str] = None, connection_id: Optional[str] = None, message: Optional[str] = None, status: Optional[str] = None, runtime: Optional[float] = None, sql: Optional[str] = None ): self.can = can self.id = id self.user = user self.query = query self.sql_query = sql_query self.look = look self.created_at = created_at self.completed_at = completed_at self.query_id = query_id self.source = source self.node_id = node_id self.slug = slug self.query_task_id = query_task_id self.cache_key = cache_key self.connection_name = connection_name self.dialect = dialect self.connection_id = connection_id self.message = message self.status = status self.runtime = runtime self.sql = sql @attr.s(auto_attribs=True, init=False) class SamlConfig(model.Model): """ Attributes: can: Operations the current user is able to perform on this object enabled: Enable/Disable Saml authentication for the server idp_cert: Identity Provider Certificate (provided by IdP) idp_url: Identity Provider Url (provided by IdP) idp_issuer: Identity Provider Issuer (provided by IdP) idp_audience: Identity Provider Audience (set in IdP config). Optional in Looker. Set this only if you want Looker to validate the audience value returned by the IdP. allowed_clock_drift: Count of seconds of clock drift to allow when validating timestamps of assertions. user_attribute_map_email: Name of user record attributes used to indicate email address field user_attribute_map_first_name: Name of user record attributes used to indicate first name user_attribute_map_last_name: Name of user record attributes used to indicate last name new_user_migration_types: Merge first-time saml login to existing user account by email addresses. When a user logs in for the first time via saml this option will connect this user into their existing account by finding the account with a matching email address by testing the given types of credentials for existing users. Otherwise a new user account will be created for the user. This list (if provided) must be a comma separated list of string like 'email,ldap,google' alternate_email_login_allowed: Allow alternate email-based login via '/login/email' for admins and for specified users with the 'login_special_email' permission. This option is useful as a fallback during ldap setup, if ldap config problems occur later, or if you need to support some users who are not in your ldap directory. Looker email/password logins are always disabled for regular users when ldap is enabled. test_slug: Slug to identify configurations that are created in order to run a Saml config test modified_at: When this config was last modified modified_by: User id of user who last modified this config default_new_user_roles: (Read-only) Roles that will be applied to new users the first time they login via Saml default_new_user_groups: (Read-only) Groups that will be applied to new users the first time they login via Saml default_new_user_role_ids: (Write-Only) Array of ids of roles that will be applied to new users the first time they login via Saml default_new_user_group_ids: (Write-Only) Array of ids of groups that will be applied to new users the first time they login via Saml set_roles_from_groups: Set user roles in Looker based on groups from Saml groups_attribute: Name of user record attributes used to indicate groups. Used when 'groups_finder_type' is set to 'grouped_attribute_values' groups: (Read-only) Array of mappings between Saml Groups and Looker Roles groups_with_role_ids: (Read/Write) Array of mappings between Saml Groups and arrays of Looker Role ids auth_requires_role: Users will not be allowed to login at all unless a role for them is found in Saml if set to true user_attributes: (Read-only) Array of mappings between Saml User Attributes and Looker User Attributes user_attributes_with_ids: (Read/Write) Array of mappings between Saml User Attributes and arrays of Looker User Attribute ids groups_finder_type: Identifier for a strategy for how Looker will find groups in the SAML response. One of ['grouped_attribute_values', 'individual_attributes'] groups_member_value: Value for group attribute used to indicate membership. Used when 'groups_finder_type' is set to 'individual_attributes' bypass_login_page: Bypass the login page when user authentication is required. Redirect to IdP immediately instead. allow_normal_group_membership: Allow SAML auth'd users to be members of non-reflected Looker groups. If 'false', user will be removed from non-reflected groups on login. allow_roles_from_normal_groups: SAML auth'd users will inherit roles from non-reflected Looker groups. allow_direct_roles: Allows roles to be directly assigned to SAML auth'd users. url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None enabled: Optional[bool] = None idp_cert: Optional[str] = None idp_url: Optional[str] = None idp_issuer: Optional[str] = None idp_audience: Optional[str] = None allowed_clock_drift: Optional[int] = None user_attribute_map_email: Optional[str] = None user_attribute_map_first_name: Optional[str] = None user_attribute_map_last_name: Optional[str] = None new_user_migration_types: Optional[str] = None alternate_email_login_allowed: Optional[bool] = None test_slug: Optional[str] = None modified_at: Optional[str] = None modified_by: Optional[str] = None default_new_user_roles: Optional[Sequence["Role"]] = None default_new_user_groups: Optional[Sequence["Group"]] = None default_new_user_role_ids: Optional[Sequence[int]] = None default_new_user_group_ids: Optional[Sequence[int]] = None set_roles_from_groups: Optional[bool] = None groups_attribute: Optional[str] = None groups: Optional[Sequence["SamlGroupRead"]] = None groups_with_role_ids: Optional[Sequence["SamlGroupWrite"]] = None auth_requires_role: Optional[bool] = None user_attributes: Optional[Sequence["SamlUserAttributeRead"]] = None user_attributes_with_ids: Optional[Sequence["SamlUserAttributeWrite"]] = None groups_finder_type: Optional[str] = None groups_member_value: Optional[str] = None bypass_login_page: Optional[bool] = None allow_normal_group_membership: Optional[bool] = None allow_roles_from_normal_groups: Optional[bool] = None allow_direct_roles: Optional[bool] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, enabled: Optional[bool] = None, idp_cert: Optional[str] = None, idp_url: Optional[str] = None, idp_issuer: Optional[str] = None, idp_audience: Optional[str] = None, allowed_clock_drift: Optional[int] = None, user_attribute_map_email: Optional[str] = None, user_attribute_map_first_name: Optional[str] = None, user_attribute_map_last_name: Optional[str] = None, new_user_migration_types: Optional[str] = None, alternate_email_login_allowed: Optional[bool] = None, test_slug: Optional[str] = None, modified_at: Optional[str] = None, modified_by: Optional[str] = None, default_new_user_roles: Optional[Sequence["Role"]] = None, default_new_user_groups: Optional[Sequence["Group"]] = None, default_new_user_role_ids: Optional[Sequence[int]] = None, default_new_user_group_ids: Optional[Sequence[int]] = None, set_roles_from_groups: Optional[bool] = None, groups_attribute: Optional[str] = None, groups: Optional[Sequence["SamlGroupRead"]] = None, groups_with_role_ids: Optional[Sequence["SamlGroupWrite"]] = None, auth_requires_role: Optional[bool] = None, user_attributes: Optional[Sequence["SamlUserAttributeRead"]] = None, user_attributes_with_ids: Optional[Sequence["SamlUserAttributeWrite"]] = None, groups_finder_type: Optional[str] = None, groups_member_value: Optional[str] = None, bypass_login_page: Optional[bool] = None, allow_normal_group_membership: Optional[bool] = None, allow_roles_from_normal_groups: Optional[bool] = None, allow_direct_roles: Optional[bool] = None, url: Optional[str] = None ): self.can = can self.enabled = enabled self.idp_cert = idp_cert self.idp_url = idp_url self.idp_issuer = idp_issuer self.idp_audience = idp_audience self.allowed_clock_drift = allowed_clock_drift self.user_attribute_map_email = user_attribute_map_email self.user_attribute_map_first_name = user_attribute_map_first_name self.user_attribute_map_last_name = user_attribute_map_last_name self.new_user_migration_types = new_user_migration_types self.alternate_email_login_allowed = alternate_email_login_allowed self.test_slug = test_slug self.modified_at = modified_at self.modified_by = modified_by self.default_new_user_roles = default_new_user_roles self.default_new_user_groups = default_new_user_groups self.default_new_user_role_ids = default_new_user_role_ids self.default_new_user_group_ids = default_new_user_group_ids self.set_roles_from_groups = set_roles_from_groups self.groups_attribute = groups_attribute self.groups = groups self.groups_with_role_ids = groups_with_role_ids self.auth_requires_role = auth_requires_role self.user_attributes = user_attributes self.user_attributes_with_ids = user_attributes_with_ids self.groups_finder_type = groups_finder_type self.groups_member_value = groups_member_value self.bypass_login_page = bypass_login_page self.allow_normal_group_membership = allow_normal_group_membership self.allow_roles_from_normal_groups = allow_roles_from_normal_groups self.allow_direct_roles = allow_direct_roles self.url = url @attr.s(auto_attribs=True, init=False) class SamlGroupRead(model.Model): """ Attributes: id: Unique Id looker_group_id: Unique Id of group in Looker looker_group_name: Name of group in Looker name: Name of group in Saml roles: Looker Roles url: Link to saml config """ id: Optional[int] = None looker_group_id: Optional[int] = None looker_group_name: Optional[str] = None name: Optional[str] = None roles: Optional[Sequence["Role"]] = None url: Optional[str] = None def __init__( self, *, id: Optional[int] = None, looker_group_id: Optional[int] = None, looker_group_name: Optional[str] = None, name: Optional[str] = None, roles: Optional[Sequence["Role"]] = None, url: Optional[str] = None ): self.id = id self.looker_group_id = looker_group_id self.looker_group_name = looker_group_name self.name = name self.roles = roles self.url = url @attr.s(auto_attribs=True, init=False) class SamlGroupWrite(model.Model): """ Attributes: id: Unique Id looker_group_id: Unique Id of group in Looker looker_group_name: Name of group in Looker name: Name of group in Saml role_ids: Looker Role Ids url: Link to saml config """ id: Optional[int] = None looker_group_id: Optional[int] = None looker_group_name: Optional[str] = None name: Optional[str] = None role_ids: Optional[Sequence[int]] = None url: Optional[str] = None def __init__( self, *, id: Optional[int] = None, looker_group_id: Optional[int] = None, looker_group_name: Optional[str] = None, name: Optional[str] = None, role_ids: Optional[Sequence[int]] = None, url: Optional[str] = None ): self.id = id self.looker_group_id = looker_group_id self.looker_group_name = looker_group_name self.name = name self.role_ids = role_ids self.url = url @attr.s(auto_attribs=True, init=False) class SamlMetadataParseResult(model.Model): """ Attributes: can: Operations the current user is able to perform on this object idp_issuer: Identify Provider Issuer idp_url: Identify Provider Url idp_cert: Identify Provider Certificate """ can: Optional[MutableMapping[str, bool]] = None idp_issuer: Optional[str] = None idp_url: Optional[str] = None idp_cert: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, idp_issuer: Optional[str] = None, idp_url: Optional[str] = None, idp_cert: Optional[str] = None ): self.can = can self.idp_issuer = idp_issuer self.idp_url = idp_url self.idp_cert = idp_cert @attr.s(auto_attribs=True, init=False) class SamlUserAttributeRead(model.Model): """ Attributes: name: Name of User Attribute in Saml required: Required to be in Saml assertion for login to be allowed to succeed user_attributes: Looker User Attributes url: Link to saml config """ name: Optional[str] = None required: Optional[bool] = None user_attributes: Optional[Sequence["UserAttribute"]] = None url: Optional[str] = None def __init__( self, *, name: Optional[str] = None, required: Optional[bool] = None, user_attributes: Optional[Sequence["UserAttribute"]] = None, url: Optional[str] = None ): self.name = name self.required = required self.user_attributes = user_attributes self.url = url @attr.s(auto_attribs=True, init=False) class SamlUserAttributeWrite(model.Model): """ Attributes: name: Name of User Attribute in Saml required: Required to be in Saml assertion for login to be allowed to succeed user_attribute_ids: Looker User Attribute Ids url: Link to saml config """ name: Optional[str] = None required: Optional[bool] = None user_attribute_ids: Optional[Sequence[int]] = None url: Optional[str] = None def __init__( self, *, name: Optional[str] = None, required: Optional[bool] = None, user_attribute_ids: Optional[Sequence[int]] = None, url: Optional[str] = None ): self.name = name self.required = required self.user_attribute_ids = user_attribute_ids self.url = url @attr.s(auto_attribs=True, init=False) class ScheduledPlan(model.Model): """ Attributes: name: Name of this scheduled plan user_id: User Id which owns this scheduled plan run_as_recipient: Whether schedule is run as recipient (only applicable for email recipients) enabled: Whether the ScheduledPlan is enabled look_id: Id of a look dashboard_id: Id of a dashboard lookml_dashboard_id: Id of a LookML dashboard filters_string: Query string to run look or dashboard with dashboard_filters: (DEPRECATED) Alias for filters_string field require_results: Delivery should occur if running the dashboard or look returns results require_no_results: Delivery should occur if the dashboard look does not return results require_change: Delivery should occur if data have changed since the last run send_all_results: Will run an unlimited query and send all results. crontab: Vixie-Style crontab specification when to run datagroup: Name of a datagroup; if specified will run when datagroup triggered (can't be used with cron string) timezone: Timezone for interpreting the specified crontab (default is Looker instance timezone) query_id: Query id scheduled_plan_destination: Scheduled plan destinations run_once: Whether the plan in question should only be run once (usually for testing) include_links: Whether links back to Looker should be included in this ScheduledPlan pdf_paper_size: The size of paper the PDF should be formatted to fit. Valid values are: "letter", "legal", "tabloid", "a0", "a1", "a2", "a3", "a4", "a5". pdf_landscape: Whether the PDF should be formatted for landscape orientation embed: Whether this schedule is in an embed context or not color_theme: Color scheme of the dashboard if applicable long_tables: Whether or not to expand table vis to full length inline_table_width: The pixel width at which we render the inline table visualizations id: Unique Id created_at: Date and time when ScheduledPlan was created updated_at: Date and time when ScheduledPlan was last updated title: Title user: next_run_at: When the ScheduledPlan will next run (null if running once) last_run_at: When the ScheduledPlan was last run can: Operations the current user is able to perform on this object """ name: Optional[str] = None user_id: Optional[int] = None run_as_recipient: Optional[bool] = None enabled: Optional[bool] = None look_id: Optional[int] = None dashboard_id: Optional[int] = None lookml_dashboard_id: Optional[str] = None filters_string: Optional[str] = None dashboard_filters: Optional[str] = None require_results: Optional[bool] = None require_no_results: Optional[bool] = None require_change: Optional[bool] = None send_all_results: Optional[bool] = None crontab: Optional[str] = None datagroup: Optional[str] = None timezone: Optional[str] = None query_id: Optional[str] = None scheduled_plan_destination: Optional[Sequence["ScheduledPlanDestination"]] = None run_once: Optional[bool] = None include_links: Optional[bool] = None pdf_paper_size: Optional[str] = None pdf_landscape: Optional[bool] = None embed: Optional[bool] = None color_theme: Optional[str] = None long_tables: Optional[bool] = None inline_table_width: Optional[int] = None id: Optional[int] = None created_at: Optional[datetime.datetime] = None updated_at: Optional[datetime.datetime] = None title: Optional[str] = None user: Optional["UserPublic"] = None next_run_at: Optional[datetime.datetime] = None last_run_at: Optional[datetime.datetime] = None can: Optional[MutableMapping[str, bool]] = None def __init__( self, *, name: Optional[str] = None, user_id: Optional[int] = None, run_as_recipient: Optional[bool] = None, enabled: Optional[bool] = None, look_id: Optional[int] = None, dashboard_id: Optional[int] = None, lookml_dashboard_id: Optional[str] = None, filters_string: Optional[str] = None, dashboard_filters: Optional[str] = None, require_results: Optional[bool] = None, require_no_results: Optional[bool] = None, require_change: Optional[bool] = None, send_all_results: Optional[bool] = None, crontab: Optional[str] = None, datagroup: Optional[str] = None, timezone: Optional[str] = None, query_id: Optional[str] = None, scheduled_plan_destination: Optional[ Sequence["ScheduledPlanDestination"] ] = None, run_once: Optional[bool] = None, include_links: Optional[bool] = None, pdf_paper_size: Optional[str] = None, pdf_landscape: Optional[bool] = None, embed: Optional[bool] = None, color_theme: Optional[str] = None, long_tables: Optional[bool] = None, inline_table_width: Optional[int] = None, id: Optional[int] = None, created_at: Optional[datetime.datetime] = None, updated_at: Optional[datetime.datetime] = None, title: Optional[str] = None, user: Optional["UserPublic"] = None, next_run_at: Optional[datetime.datetime] = None, last_run_at: Optional[datetime.datetime] = None, can: Optional[MutableMapping[str, bool]] = None ): self.name = name self.user_id = user_id self.run_as_recipient = run_as_recipient self.enabled = enabled self.look_id = look_id self.dashboard_id = dashboard_id self.lookml_dashboard_id = lookml_dashboard_id self.filters_string = filters_string self.dashboard_filters = dashboard_filters self.require_results = require_results self.require_no_results = require_no_results self.require_change = require_change self.send_all_results = send_all_results self.crontab = crontab self.datagroup = datagroup self.timezone = timezone self.query_id = query_id self.scheduled_plan_destination = scheduled_plan_destination self.run_once = run_once self.include_links = include_links self.pdf_paper_size = pdf_paper_size self.pdf_landscape = pdf_landscape self.embed = embed self.color_theme = color_theme self.long_tables = long_tables self.inline_table_width = inline_table_width self.id = id self.created_at = created_at self.updated_at = updated_at self.title = title self.user = user self.next_run_at = next_run_at self.last_run_at = last_run_at self.can = can @attr.s(auto_attribs=True, init=False) class ScheduledPlanDestination(model.Model): """ Attributes: id: Unique Id scheduled_plan_id: Id of a scheduled plan you own format: The data format to send to the given destination. Supported formats vary by destination, but include: "txt", "csv", "inline_json", "json", "json_detail", "xlsx", "html", "wysiwyg_pdf", "assembled_pdf", "wysiwyg_png" apply_formatting: Are values formatted? (containing currency symbols, digit separators, etc. apply_vis: Whether visualization options are applied to the results. address: Address for recipient. For email e.g. 'user@example.com'. For webhooks e.g. 'https://domain/path'. For Amazon S3 e.g. 's3://bucket-name/path/'. For SFTP e.g. 'sftp://host-name/path/'. looker_recipient: Whether the recipient is a Looker user on the current instance (only applicable for email recipients) type: Type of the address ('email', 'webhook', 's3', or 'sftp') parameters: JSON object containing parameters for external scheduling. For Amazon S3, this requires keys and values for access_key_id and region. For SFTP, this requires a key and value for username. secret_parameters: (Write-Only) JSON object containing secret parameters for external scheduling. For Amazon S3, this requires a key and value for secret_access_key. For SFTP, this requires a key and value for password. message: Optional message to be included in scheduled emails """ id: Optional[int] = None scheduled_plan_id: Optional[int] = None format: Optional[str] = None apply_formatting: Optional[bool] = None apply_vis: Optional[bool] = None address: Optional[str] = None looker_recipient: Optional[bool] = None type: Optional[str] = None parameters: Optional[str] = None secret_parameters: Optional[str] = None message: Optional[str] = None def __init__( self, *, id: Optional[int] = None, scheduled_plan_id: Optional[int] = None, format: Optional[str] = None, apply_formatting: Optional[bool] = None, apply_vis: Optional[bool] = None, address: Optional[str] = None, looker_recipient: Optional[bool] = None, type: Optional[str] = None, parameters: Optional[str] = None, secret_parameters: Optional[str] = None, message: Optional[str] = None ): self.id = id self.scheduled_plan_id = scheduled_plan_id self.format = format self.apply_formatting = apply_formatting self.apply_vis = apply_vis self.address = address self.looker_recipient = looker_recipient self.type = type self.parameters = parameters self.secret_parameters = secret_parameters self.message = message @attr.s(auto_attribs=True, init=False) class Schema(model.Model): """ Attributes: name: Schema name is_default: True if this is the default schema """ name: Optional[str] = None is_default: Optional[bool] = None def __init__( self, *, name: Optional[str] = None, is_default: Optional[bool] = None ): self.name = name self.is_default = is_default @attr.s(auto_attribs=True, init=False) class SchemaColumn(model.Model): """ Attributes: name: Schema item name sql_escaped_name: Full name of item schema_name: Name of schema data_type_database: SQL dialect data type data_type: Data type data_type_looker: Looker data type description: SQL data type column_size: Column data size snippets: SQL Runner snippets for this connection """ name: Optional[str] = None sql_escaped_name: Optional[str] = None schema_name: Optional[str] = None data_type_database: Optional[str] = None data_type: Optional[str] = None data_type_looker: Optional[str] = None description: Optional[str] = None column_size: Optional[int] = None snippets: Optional[Sequence["Snippet"]] = None def __init__( self, *, name: Optional[str] = None, sql_escaped_name: Optional[str] = None, schema_name: Optional[str] = None, data_type_database: Optional[str] = None, data_type: Optional[str] = None, data_type_looker: Optional[str] = None, description: Optional[str] = None, column_size: Optional[int] = None, snippets: Optional[Sequence["Snippet"]] = None ): self.name = name self.sql_escaped_name = sql_escaped_name self.schema_name = schema_name self.data_type_database = data_type_database self.data_type = data_type self.data_type_looker = data_type_looker self.description = description self.column_size = column_size self.snippets = snippets @attr.s(auto_attribs=True, init=False) class SchemaColumns(model.Model): """ Attributes: name: Schema item name sql_escaped_name: Full name of item schema_name: Name of schema columns: Columns for this schema """ name: Optional[str] = None sql_escaped_name: Optional[str] = None schema_name: Optional[str] = None columns: Optional[Sequence["SchemaColumn"]] = None def __init__( self, *, name: Optional[str] = None, sql_escaped_name: Optional[str] = None, schema_name: Optional[str] = None, columns: Optional[Sequence["SchemaColumn"]] = None ): self.name = name self.sql_escaped_name = sql_escaped_name self.schema_name = schema_name self.columns = columns @attr.s(auto_attribs=True, init=False) class SchemaTable(model.Model): """ Attributes: name: Schema item name sql_escaped_name: Full name of item schema_name: Name of schema rows: Number of data rows external: External reference??? snippets: SQL Runner snippets for connection """ name: Optional[str] = None sql_escaped_name: Optional[str] = None schema_name: Optional[str] = None rows: Optional[int] = None external: Optional[str] = None snippets: Optional[Sequence["Snippet"]] = None def __init__( self, *, name: Optional[str] = None, sql_escaped_name: Optional[str] = None, schema_name: Optional[str] = None, rows: Optional[int] = None, external: Optional[str] = None, snippets: Optional[Sequence["Snippet"]] = None ): self.name = name self.sql_escaped_name = sql_escaped_name self.schema_name = schema_name self.rows = rows self.external = external self.snippets = snippets @attr.s(auto_attribs=True, init=False) class SchemaTables(model.Model): """ Attributes: name: Schema name is_default: True if this is the default schema tables: Tables for this schema """ name: Optional[str] = None is_default: Optional[bool] = None tables: Optional[Sequence["SchemaTable"]] = None def __init__( self, *, name: Optional[str] = None, is_default: Optional[bool] = None, tables: Optional[Sequence["SchemaTable"]] = None ): self.name = name self.is_default = is_default self.tables = tables @attr.s(auto_attribs=True, init=False) class Session(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id ip_address: IP address of user when this session was initiated browser: User's browser type operating_system: User's Operating System city: City component of user location (derived from IP address) state: State component of user location (derived from IP address) country: Country component of user location (derived from IP address) credentials_type: Type of credentials used for logging in this session extended_at: Time when this session was last extended by the user extended_count: Number of times this session was extended sudo_user_id: Actual user in the case when this session represents one user sudo'ing as another created_at: Time when this session was initiated expires_at: Time when this session will expire url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None ip_address: Optional[str] = None browser: Optional[str] = None operating_system: Optional[str] = None city: Optional[str] = None state: Optional[str] = None country: Optional[str] = None credentials_type: Optional[str] = None extended_at: Optional[str] = None extended_count: Optional[int] = None sudo_user_id: Optional[int] = None created_at: Optional[str] = None expires_at: Optional[str] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, ip_address: Optional[str] = None, browser: Optional[str] = None, operating_system: Optional[str] = None, city: Optional[str] = None, state: Optional[str] = None, country: Optional[str] = None, credentials_type: Optional[str] = None, extended_at: Optional[str] = None, extended_count: Optional[int] = None, sudo_user_id: Optional[int] = None, created_at: Optional[str] = None, expires_at: Optional[str] = None, url: Optional[str] = None ): self.can = can self.id = id self.ip_address = ip_address self.browser = browser self.operating_system = operating_system self.city = city self.state = state self.country = country self.credentials_type = credentials_type self.extended_at = extended_at self.extended_count = extended_count self.sudo_user_id = sudo_user_id self.created_at = created_at self.expires_at = expires_at self.url = url @attr.s(auto_attribs=True, init=False) class SessionConfig(model.Model): """ Attributes: can: Operations the current user is able to perform on this object allow_persistent_sessions: Allow users to have persistent sessions when they login session_minutes: Number of minutes for user sessions. Must be between 5 and 43200 unlimited_sessions_per_user: Allow users to have an unbounded number of concurrent sessions (otherwise, users will be limited to only one session at a time). use_inactivity_based_logout: Enforce session logout for sessions that are inactive for 15 minutes. track_session_location: Track location of session when user logs in. """ can: Optional[MutableMapping[str, bool]] = None allow_persistent_sessions: Optional[bool] = None session_minutes: Optional[int] = None unlimited_sessions_per_user: Optional[bool] = None use_inactivity_based_logout: Optional[bool] = None track_session_location: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, allow_persistent_sessions: Optional[bool] = None, session_minutes: Optional[int] = None, unlimited_sessions_per_user: Optional[bool] = None, use_inactivity_based_logout: Optional[bool] = None, track_session_location: Optional[bool] = None ): self.can = can self.allow_persistent_sessions = allow_persistent_sessions self.session_minutes = session_minutes self.unlimited_sessions_per_user = unlimited_sessions_per_user self.use_inactivity_based_logout = use_inactivity_based_logout self.track_session_location = track_session_location @attr.s(auto_attribs=True, init=False) class Snippet(model.Model): """ Attributes: name: Name of the snippet label: Label of the snippet sql: SQL text of the snippet """ name: Optional[str] = None label: Optional[str] = None sql: Optional[str] = None def __init__( self, *, name: Optional[str] = None, label: Optional[str] = None, sql: Optional[str] = None ): self.name = name self.label = label self.sql = sql @attr.s(auto_attribs=True, init=False) class SqlQuery(model.Model): """ Attributes: can: Operations the current user is able to perform on this object slug: The identifier of the SQL query last_runtime: Number of seconds this query took to run the most recent time it was run run_count: Number of times this query has been run browser_limit: Maximum number of rows this query will display on the SQL Runner page sql: SQL query text last_run_at: The most recent time this query was run connection: model_name: Model name this query uses creator: explore_url: Explore page URL for this SQL query plaintext: Should this query be rendered as plain text vis_config: Visualization configuration properties. These properties are typically opaque and differ based on the type of visualization used. There is no specified set of allowed keys. The values can be any type supported by JSON. A "type" key with a string value is often present, and is used by Looker to determine which visualization to present. Visualizations ignore unknown vis_config properties. result_maker_id: ID of the ResultMakerLookup entry. """ can: Optional[MutableMapping[str, bool]] = None slug: Optional[str] = None last_runtime: Optional[float] = None run_count: Optional[int] = None browser_limit: Optional[int] = None sql: Optional[str] = None last_run_at: Optional[str] = None connection: Optional["DBConnectionBase"] = None model_name: Optional[str] = None creator: Optional["UserPublic"] = None explore_url: Optional[str] = None plaintext: Optional[bool] = None vis_config: Optional[MutableMapping[str, Any]] = None result_maker_id: Optional[int] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, slug: Optional[str] = None, last_runtime: Optional[float] = None, run_count: Optional[int] = None, browser_limit: Optional[int] = None, sql: Optional[str] = None, last_run_at: Optional[str] = None, connection: Optional["DBConnectionBase"] = None, model_name: Optional[str] = None, creator: Optional["UserPublic"] = None, explore_url: Optional[str] = None, plaintext: Optional[bool] = None, vis_config: Optional[MutableMapping[str, Any]] = None, result_maker_id: Optional[int] = None ): self.can = can self.slug = slug self.last_runtime = last_runtime self.run_count = run_count self.browser_limit = browser_limit self.sql = sql self.last_run_at = last_run_at self.connection = connection self.model_name = model_name self.creator = creator self.explore_url = explore_url self.plaintext = plaintext self.vis_config = vis_config self.result_maker_id = result_maker_id @attr.s(auto_attribs=True, init=False) class SqlQueryCreate(model.Model): """ Attributes: connection_name: Name of the db connection on which to run this query connection_id: (DEPRECATED) Use `connection_name` instead model_name: Name of LookML Model (this or `connection_id` required) sql: SQL query vis_config: Visualization configuration properties. These properties are typically opaque and differ based on the type of visualization used. There is no specified set of allowed keys. The values can be any type supported by JSON. A "type" key with a string value is often present, and is used by Looker to determine which visualization to present. Visualizations ignore unknown vis_config properties. """ connection_name: Optional[str] = None connection_id: Optional[str] = None model_name: Optional[str] = None sql: Optional[str] = None vis_config: Optional[MutableMapping[str, Any]] = None def __init__( self, *, connection_name: Optional[str] = None, connection_id: Optional[str] = None, model_name: Optional[str] = None, sql: Optional[str] = None, vis_config: Optional[MutableMapping[str, Any]] = None ): self.connection_name = connection_name self.connection_id = connection_id self.model_name = model_name self.sql = sql self.vis_config = vis_config @attr.s(auto_attribs=True, init=False) class SshPublicKey(model.Model): """ Attributes: public_key: The SSH public key created for this instance """ public_key: Optional[str] = None def __init__(self, *, public_key: Optional[str] = None): self.public_key = public_key @attr.s(auto_attribs=True, init=False) class SshServer(model.Model): """ Attributes: ssh_server_id: A unique id used to identify this SSH Server ssh_server_name: The name to identify this SSH Server ssh_server_host: The hostname or ip address of the SSH Server ssh_server_port: The port to connect to on the SSH Server ssh_server_user: The username used to connect to the SSH Server finger_print: The md5 fingerprint used to identify the SSH Server sha_finger_print: The SHA fingerprint used to identify the SSH Server public_key: The SSH public key created for this instance status: The current connection status to this SSH Server """ ssh_server_id: Optional[str] = None ssh_server_name: Optional[str] = None ssh_server_host: Optional[str] = None ssh_server_port: Optional[int] = None ssh_server_user: Optional[str] = None finger_print: Optional[str] = None sha_finger_print: Optional[str] = None public_key: Optional[str] = None status: Optional[str] = None def __init__( self, *, ssh_server_id: Optional[str] = None, ssh_server_name: Optional[str] = None, ssh_server_host: Optional[str] = None, ssh_server_port: Optional[int] = None, ssh_server_user: Optional[str] = None, finger_print: Optional[str] = None, sha_finger_print: Optional[str] = None, public_key: Optional[str] = None, status: Optional[str] = None ): self.ssh_server_id = ssh_server_id self.ssh_server_name = ssh_server_name self.ssh_server_host = ssh_server_host self.ssh_server_port = ssh_server_port self.ssh_server_user = ssh_server_user self.finger_print = finger_print self.sha_finger_print = sha_finger_print self.public_key = public_key self.status = status @attr.s(auto_attribs=True, init=False) class SshTunnel(model.Model): """ Attributes: tunnel_id: Unique ID for the tunnel ssh_server_id: SSH Server ID ssh_server_name: SSH Server name ssh_server_host: SSH Server Hostname or IP Address ssh_server_port: SSH Server port ssh_server_user: Username used to connect to the SSH Server last_attempt: Time of last connect attempt local_host_port: Localhost Port used by the Looker instance to connect to the remote DB database_host: Hostname or IP Address of the Database Server database_port: Port that the Database Server is listening on status: Current connection status for this Tunnel """ tunnel_id: Optional[str] = None ssh_server_id: Optional[str] = None ssh_server_name: Optional[str] = None ssh_server_host: Optional[str] = None ssh_server_port: Optional[int] = None ssh_server_user: Optional[str] = None last_attempt: Optional[str] = None local_host_port: Optional[int] = None database_host: Optional[str] = None database_port: Optional[int] = None status: Optional[str] = None def __init__( self, *, tunnel_id: Optional[str] = None, ssh_server_id: Optional[str] = None, ssh_server_name: Optional[str] = None, ssh_server_host: Optional[str] = None, ssh_server_port: Optional[int] = None, ssh_server_user: Optional[str] = None, last_attempt: Optional[str] = None, local_host_port: Optional[int] = None, database_host: Optional[str] = None, database_port: Optional[int] = None, status: Optional[str] = None ): self.tunnel_id = tunnel_id self.ssh_server_id = ssh_server_id self.ssh_server_name = ssh_server_name self.ssh_server_host = ssh_server_host self.ssh_server_port = ssh_server_port self.ssh_server_user = ssh_server_user self.last_attempt = last_attempt self.local_host_port = local_host_port self.database_host = database_host self.database_port = database_port self.status = status class SupportedActionTypes(enum.Enum): """ A list of action types the integration supports. Valid values are: "cell", "query", "dashboard". """ cell = "cell" query = "query" dashboard = "dashboard" invalid_api_enum_value = "invalid_api_enum_value" SupportedActionTypes.__new__ = model.safe_enum__new__ class SupportedDownloadSettings(enum.Enum): """ A list of all the download mechanisms the integration supports. The order of values is not significant: Looker will select the most appropriate supported download mechanism for a given query. The integration must ensure it can handle any of the mechanisms it claims to support. If unspecified, this defaults to all download setting values. Valid values are: "push", "url". """ push = "push" url = "url" invalid_api_enum_value = "invalid_api_enum_value" SupportedDownloadSettings.__new__ = model.safe_enum__new__ class SupportedFormats(enum.Enum): """ A list of data formats the integration supports. If unspecified, the default is all data formats. Valid values are: "txt", "csv", "inline_json", "json", "json_label", "json_detail", "json_detail_lite_stream", "xlsx", "html", "wysiwyg_pdf", "assembled_pdf", "wysiwyg_png", "csv_zip". """ txt = "txt" csv = "csv" inline_json = "inline_json" json = "json" json_label = "json_label" json_detail = "json_detail" json_detail_lite_stream = "json_detail_lite_stream" xlsx = "xlsx" html = "html" wysiwyg_pdf = "wysiwyg_pdf" assembled_pdf = "assembled_pdf" wysiwyg_png = "wysiwyg_png" csv_zip = "csv_zip" invalid_api_enum_value = "invalid_api_enum_value" SupportedFormats.__new__ = model.safe_enum__new__ class SupportedFormattings(enum.Enum): """ A list of formatting options the integration supports. If unspecified, defaults to all formats. Valid values are: "formatted", "unformatted". """ formatted = "formatted" unformatted = "unformatted" invalid_api_enum_value = "invalid_api_enum_value" SupportedFormattings.__new__ = model.safe_enum__new__ class SupportedVisualizationFormattings(enum.Enum): """ A list of visualization formatting options the integration supports. If unspecified, defaults to all formats. Valid values are: "apply", "noapply". """ apply = "apply" noapply = "noapply" invalid_api_enum_value = "invalid_api_enum_value" SupportedVisualizationFormattings.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class Theme(model.Model): """ Attributes: can: Operations the current user is able to perform on this object begin_at: Timestamp for when this theme becomes active. Null=always end_at: Timestamp for when this theme expires. Null=never id: Unique Id name: Name of theme. Can only be alphanumeric and underscores. settings: """ can: Optional[MutableMapping[str, bool]] = None begin_at: Optional[datetime.datetime] = None end_at: Optional[datetime.datetime] = None id: Optional[int] = None name: Optional[str] = None settings: Optional["ThemeSettings"] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, begin_at: Optional[datetime.datetime] = None, end_at: Optional[datetime.datetime] = None, id: Optional[int] = None, name: Optional[str] = None, settings: Optional["ThemeSettings"] = None ): self.can = can self.begin_at = begin_at self.end_at = end_at self.id = id self.name = name self.settings = settings @attr.s(auto_attribs=True, init=False) class ThemeSettings(model.Model): """ Attributes: background_color: Default background color base_font_size: Base font size for scaling fonts color_collection_id: Optional. ID of color collection to use with the theme. Use an empty string for none. font_color: Default font color font_family: Primary font family font_source: Source specification for font info_button_color: Info button color primary_button_color: Primary button color show_filters_bar: Toggle to show filters. Defaults to true. show_title: Toggle to show the title. Defaults to true. text_tile_text_color: Text color for text tiles tile_background_color: Background color for tiles tile_text_color: Text color for tiles title_color: Color for titles warn_button_color: Warning button color tile_title_alignment: The text alignment of tile titles (New Dashboards) tile_shadow: Toggles the tile shadow (New Dashboards) """ background_color: Optional[str] = None base_font_size: Optional[str] = None color_collection_id: Optional[str] = None font_color: Optional[str] = None font_family: Optional[str] = None font_source: Optional[str] = None info_button_color: Optional[str] = None primary_button_color: Optional[str] = None show_filters_bar: Optional[bool] = None show_title: Optional[bool] = None text_tile_text_color: Optional[str] = None tile_background_color: Optional[str] = None tile_text_color: Optional[str] = None title_color: Optional[str] = None warn_button_color: Optional[str] = None tile_title_alignment: Optional[str] = None tile_shadow: Optional[bool] = None def __init__( self, *, background_color: Optional[str] = None, base_font_size: Optional[str] = None, color_collection_id: Optional[str] = None, font_color: Optional[str] = None, font_family: Optional[str] = None, font_source: Optional[str] = None, info_button_color: Optional[str] = None, primary_button_color: Optional[str] = None, show_filters_bar: Optional[bool] = None, show_title: Optional[bool] = None, text_tile_text_color: Optional[str] = None, tile_background_color: Optional[str] = None, tile_text_color: Optional[str] = None, title_color: Optional[str] = None, warn_button_color: Optional[str] = None, tile_title_alignment: Optional[str] = None, tile_shadow: Optional[bool] = None ): self.background_color = background_color self.base_font_size = base_font_size self.color_collection_id = color_collection_id self.font_color = font_color self.font_family = font_family self.font_source = font_source self.info_button_color = info_button_color self.primary_button_color = primary_button_color self.show_filters_bar = show_filters_bar self.show_title = show_title self.text_tile_text_color = text_tile_text_color self.tile_background_color = tile_background_color self.tile_text_color = tile_text_color self.title_color = title_color self.warn_button_color = warn_button_color self.tile_title_alignment = tile_title_alignment self.tile_shadow = tile_shadow @attr.s(auto_attribs=True, init=False) class Timezone(model.Model): """ Attributes: value: Timezone label: Description of timezone group: Timezone group (e.g Common, Other, etc.) """ value: Optional[str] = None label: Optional[str] = None group: Optional[str] = None def __init__( self, *, value: Optional[str] = None, label: Optional[str] = None, group: Optional[str] = None ): self.value = value self.label = label self.group = group @attr.s(auto_attribs=True, init=False) class UpdateCommand(model.Model): """ Attributes: name: Name of the command description: Description of the command """ name: Optional[str] = None description: Optional[str] = None def __init__( self, *, name: Optional[str] = None, description: Optional[str] = None ): self.name = name self.description = description @attr.s(auto_attribs=True, init=False) class UpdateFolder(model.Model): """ Attributes: name: Unique Name parent_id: Id of Parent. If the parent id is null, this is a root-level entry """ name: Optional[str] = None parent_id: Optional[str] = None def __init__(self, *, name: Optional[str] = None, parent_id: Optional[str] = None): self.name = name self.parent_id = parent_id @attr.s(auto_attribs=True, init=False) class User(model.Model): """ Attributes: can: Operations the current user is able to perform on this object avatar_url: URL for the avatar image (may be generic) avatar_url_without_sizing: URL for the avatar image (may be generic), does not specify size credentials_api3: API 3 credentials credentials_email: credentials_embed: Embed credentials credentials_google: credentials_ldap: credentials_looker_openid: credentials_oidc: credentials_saml: credentials_totp: display_name: Full name for display (available only if both first_name and last_name are set) email: EMail address embed_group_space_id: (Embed only) ID of user's group space based on the external_group_id optionally specified during embed user login first_name: First name group_ids: Array of ids of the groups for this user home_folder_id: ID string for user's home folder id: Unique Id is_disabled: Account has been disabled last_name: Last name locale: User's preferred locale. User locale takes precedence over Looker's system-wide default locale. Locale determines language of display strings and date and numeric formatting in API responses. Locale string must be a 2 letter language code or a combination of language code and region code: 'en' or 'en-US', for example. looker_versions: Array of strings representing the Looker versions that this user has used (this only goes back as far as '3.54.0') models_dir_validated: User's dev workspace has been checked for presence of applicable production projects personal_folder_id: ID of user's personal folder presumed_looker_employee: User is identified as an employee of Looker role_ids: Array of ids of the roles for this user sessions: Active sessions ui_state: Per user dictionary of undocumented state information owned by the Looker UI. verified_looker_employee: User is identified as an employee of Looker who has been verified via Looker corporate authentication roles_externally_managed: User's roles are managed by an external directory like SAML or LDAP and can not be changed directly. allow_direct_roles: User can be directly assigned a role. allow_normal_group_membership: User can be a direct member of a normal Looker group. allow_roles_from_normal_groups: User can inherit roles from a normal Looker group. url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None avatar_url: Optional[str] = None avatar_url_without_sizing: Optional[str] = None credentials_api3: Optional[Sequence["CredentialsApi3"]] = None credentials_email: Optional["CredentialsEmail"] = None credentials_embed: Optional[Sequence["CredentialsEmbed"]] = None credentials_google: Optional["CredentialsGoogle"] = None credentials_ldap: Optional["CredentialsLDAP"] = None credentials_looker_openid: Optional["CredentialsLookerOpenid"] = None credentials_oidc: Optional["CredentialsOIDC"] = None credentials_saml: Optional["CredentialsSaml"] = None credentials_totp: Optional["CredentialsTotp"] = None display_name: Optional[str] = None email: Optional[str] = None embed_group_space_id: Optional[int] = None first_name: Optional[str] = None group_ids: Optional[Sequence[int]] = None home_folder_id: Optional[str] = None id: Optional[int] = None is_disabled: Optional[bool] = None last_name: Optional[str] = None locale: Optional[str] = None looker_versions: Optional[Sequence[str]] = None models_dir_validated: Optional[bool] = None personal_folder_id: Optional[int] = None presumed_looker_employee: Optional[bool] = None role_ids: Optional[Sequence[int]] = None sessions: Optional[Sequence["Session"]] = None ui_state: Optional[MutableMapping[str, Any]] = None verified_looker_employee: Optional[bool] = None roles_externally_managed: Optional[bool] = None allow_direct_roles: Optional[bool] = None allow_normal_group_membership: Optional[bool] = None allow_roles_from_normal_groups: Optional[bool] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, avatar_url: Optional[str] = None, avatar_url_without_sizing: Optional[str] = None, credentials_api3: Optional[Sequence["CredentialsApi3"]] = None, credentials_email: Optional["CredentialsEmail"] = None, credentials_embed: Optional[Sequence["CredentialsEmbed"]] = None, credentials_google: Optional["CredentialsGoogle"] = None, credentials_ldap: Optional["CredentialsLDAP"] = None, credentials_looker_openid: Optional["CredentialsLookerOpenid"] = None, credentials_oidc: Optional["CredentialsOIDC"] = None, credentials_saml: Optional["CredentialsSaml"] = None, credentials_totp: Optional["CredentialsTotp"] = None, display_name: Optional[str] = None, email: Optional[str] = None, embed_group_space_id: Optional[int] = None, first_name: Optional[str] = None, group_ids: Optional[Sequence[int]] = None, home_folder_id: Optional[str] = None, id: Optional[int] = None, is_disabled: Optional[bool] = None, last_name: Optional[str] = None, locale: Optional[str] = None, looker_versions: Optional[Sequence[str]] = None, models_dir_validated: Optional[bool] = None, personal_folder_id: Optional[int] = None, presumed_looker_employee: Optional[bool] = None, role_ids: Optional[Sequence[int]] = None, sessions: Optional[Sequence["Session"]] = None, ui_state: Optional[MutableMapping[str, Any]] = None, verified_looker_employee: Optional[bool] = None, roles_externally_managed: Optional[bool] = None, allow_direct_roles: Optional[bool] = None, allow_normal_group_membership: Optional[bool] = None, allow_roles_from_normal_groups: Optional[bool] = None, url: Optional[str] = None ): self.can = can self.avatar_url = avatar_url self.avatar_url_without_sizing = avatar_url_without_sizing self.credentials_api3 = credentials_api3 self.credentials_email = credentials_email self.credentials_embed = credentials_embed self.credentials_google = credentials_google self.credentials_ldap = credentials_ldap self.credentials_looker_openid = credentials_looker_openid self.credentials_oidc = credentials_oidc self.credentials_saml = credentials_saml self.credentials_totp = credentials_totp self.display_name = display_name self.email = email self.embed_group_space_id = embed_group_space_id self.first_name = first_name self.group_ids = group_ids self.home_folder_id = home_folder_id self.id = id self.is_disabled = is_disabled self.last_name = last_name self.locale = locale self.looker_versions = looker_versions self.models_dir_validated = models_dir_validated self.personal_folder_id = personal_folder_id self.presumed_looker_employee = presumed_looker_employee self.role_ids = role_ids self.sessions = sessions self.ui_state = ui_state self.verified_looker_employee = verified_looker_employee self.roles_externally_managed = roles_externally_managed self.allow_direct_roles = allow_direct_roles self.allow_normal_group_membership = allow_normal_group_membership self.allow_roles_from_normal_groups = allow_roles_from_normal_groups self.url = url @attr.s(auto_attribs=True, init=False) class UserAttribute(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id name: Name of user attribute label: Human-friendly label for user attribute type: Type of user attribute ("string", "number", "datetime", "yesno", "zipcode") default_value: Default value for when no value is set on the user is_system: Attribute is a system default is_permanent: Attribute is permanent and cannot be deleted value_is_hidden: If true, users will not be able to view values of this attribute user_can_view: Non-admin users can see the values of their attributes and use them in filters user_can_edit: Users can change the value of this attribute for themselves hidden_value_domain_whitelist: Destinations to which a hidden attribute may be sent. Once set, cannot be edited. """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None name: Optional[str] = None label: Optional[str] = None type: Optional[str] = None default_value: Optional[str] = None is_system: Optional[bool] = None is_permanent: Optional[bool] = None value_is_hidden: Optional[bool] = None user_can_view: Optional[bool] = None user_can_edit: Optional[bool] = None hidden_value_domain_whitelist: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, name: Optional[str] = None, label: Optional[str] = None, type: Optional[str] = None, default_value: Optional[str] = None, is_system: Optional[bool] = None, is_permanent: Optional[bool] = None, value_is_hidden: Optional[bool] = None, user_can_view: Optional[bool] = None, user_can_edit: Optional[bool] = None, hidden_value_domain_whitelist: Optional[str] = None ): self.can = can self.id = id self.name = name self.label = label self.type = type self.default_value = default_value self.is_system = is_system self.is_permanent = is_permanent self.value_is_hidden = value_is_hidden self.user_can_view = user_can_view self.user_can_edit = user_can_edit self.hidden_value_domain_whitelist = hidden_value_domain_whitelist class UserAttributeFilterTypes(enum.Enum): """ An array of user attribute types that are allowed to be used in filters on this field. Valid values are: "advanced_filter_string", "advanced_filter_number", "advanced_filter_datetime", "string", "number", "datetime", "relative_url", "yesno", "zipcode". """ advanced_filter_string = "advanced_filter_string" advanced_filter_number = "advanced_filter_number" advanced_filter_datetime = "advanced_filter_datetime" string = "string" number = "number" datetime = "datetime" relative_url = "relative_url" yesno = "yesno" zipcode = "zipcode" invalid_api_enum_value = "invalid_api_enum_value" UserAttributeFilterTypes.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class UserAttributeGroupValue(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id of this group-attribute relation group_id: Id of group user_attribute_id: Id of user attribute value_is_hidden: If true, the "value" field will be null, because the attribute settings block access to this value rank: Precedence for resolving value for user value: Value of user attribute for group """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None group_id: Optional[int] = None user_attribute_id: Optional[int] = None value_is_hidden: Optional[bool] = None rank: Optional[int] = None value: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, group_id: Optional[int] = None, user_attribute_id: Optional[int] = None, value_is_hidden: Optional[bool] = None, rank: Optional[int] = None, value: Optional[str] = None ): self.can = can self.id = id self.group_id = group_id self.user_attribute_id = user_attribute_id self.value_is_hidden = value_is_hidden self.rank = rank self.value = value @attr.s(auto_attribs=True, init=False) class UserAttributeWithValue(model.Model): """ Attributes: can: Operations the current user is able to perform on this object name: Name of user attribute label: Human-friendly label for user attribute rank: Precedence for setting value on user (lowest wins) value: Value of attribute for user user_id: Id of User user_can_edit: Can the user set this value value_is_hidden: If true, the "value" field will be null, because the attribute settings block access to this value user_attribute_id: Id of User Attribute source: How user got this value for this attribute hidden_value_domain_whitelist: If this user attribute is hidden, whitelist of destinations to which it may be sent. """ can: Optional[MutableMapping[str, bool]] = None name: Optional[str] = None label: Optional[str] = None rank: Optional[int] = None value: Optional[str] = None user_id: Optional[int] = None user_can_edit: Optional[bool] = None value_is_hidden: Optional[bool] = None user_attribute_id: Optional[int] = None source: Optional[str] = None hidden_value_domain_whitelist: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, name: Optional[str] = None, label: Optional[str] = None, rank: Optional[int] = None, value: Optional[str] = None, user_id: Optional[int] = None, user_can_edit: Optional[bool] = None, value_is_hidden: Optional[bool] = None, user_attribute_id: Optional[int] = None, source: Optional[str] = None, hidden_value_domain_whitelist: Optional[str] = None ): self.can = can self.name = name self.label = label self.rank = rank self.value = value self.user_id = user_id self.user_can_edit = user_can_edit self.value_is_hidden = value_is_hidden self.user_attribute_id = user_attribute_id self.source = source self.hidden_value_domain_whitelist = hidden_value_domain_whitelist @attr.s(auto_attribs=True, init=False) class UserLoginLockout(model.Model): """ Attributes: can: Operations the current user is able to perform on this object key: Hash of user's client id auth_type: Authentication method for login failures ip: IP address of most recent failed attempt user_id: User ID remote_id: Remote ID of user if using LDAP full_name: User's name email: Email address associated with the user's account fail_count: Number of failures that triggered the lockout lockout_at: Time when lockout was triggered """ can: Optional[MutableMapping[str, bool]] = None key: Optional[str] = None auth_type: Optional[str] = None ip: Optional[str] = None user_id: Optional[int] = None remote_id: Optional[str] = None full_name: Optional[str] = None email: Optional[str] = None fail_count: Optional[int] = None lockout_at: Optional[datetime.datetime] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, key: Optional[str] = None, auth_type: Optional[str] = None, ip: Optional[str] = None, user_id: Optional[int] = None, remote_id: Optional[str] = None, full_name: Optional[str] = None, email: Optional[str] = None, fail_count: Optional[int] = None, lockout_at: Optional[datetime.datetime] = None ): self.can = can self.key = key self.auth_type = auth_type self.ip = ip self.user_id = user_id self.remote_id = remote_id self.full_name = full_name self.email = email self.fail_count = fail_count self.lockout_at = lockout_at @attr.s(auto_attribs=True, init=False) class UserPublic(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id first_name: First Name last_name: Last Name display_name: Full name for display (available only if both first_name and last_name are set) avatar_url: URL for the avatar image (may be generic) url: Link to get this item """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None first_name: Optional[str] = None last_name: Optional[str] = None display_name: Optional[str] = None avatar_url: Optional[str] = None url: Optional[str] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, first_name: Optional[str] = None, last_name: Optional[str] = None, display_name: Optional[str] = None, avatar_url: Optional[str] = None, url: Optional[str] = None ): self.can = can self.id = id self.first_name = first_name self.last_name = last_name self.display_name = display_name self.avatar_url = avatar_url self.url = url @attr.s(auto_attribs=True, init=False) class ValidationError(model.Model): """ Attributes: message: Error details documentation_url: Documentation link errors: Error detail array """ message: str documentation_url: str errors: Optional[Sequence["ValidationErrorDetail"]] = None def __init__( self, *, message: str, documentation_url: str, errors: Optional[Sequence["ValidationErrorDetail"]] = None ): self.message = message self.documentation_url = documentation_url self.errors = errors @attr.s(auto_attribs=True, init=False) class ValidationErrorDetail(model.Model): """ Attributes: documentation_url: Documentation link field: Field with error code: Error code message: Error info message """ documentation_url: str field: Optional[str] = None code: Optional[str] = None message: Optional[str] = None def __init__( self, *, documentation_url: str, field: Optional[str] = None, code: Optional[str] = None, message: Optional[str] = None ): self.documentation_url = documentation_url self.field = field self.code = code self.message = message class WeekStartDay(enum.Enum): """ The name of the starting day of the week. Valid values are: "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday". """ monday = "monday" tuesday = "tuesday" wednesday = "wednesday" thursday = "thursday" friday = "friday" saturday = "saturday" sunday = "sunday" invalid_api_enum_value = "invalid_api_enum_value" WeekStartDay.__new__ = model.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class WelcomeEmailTest(model.Model): """ Attributes: content: The content that would be sent in the body of a custom welcome email subject: The subject that would be sent for the custom welcome email header: The header that would be sent in the body of a custom welcome email """ content: Optional[str] = None subject: Optional[str] = None header: Optional[str] = None def __init__( self, *, content: Optional[str] = None, subject: Optional[str] = None, header: Optional[str] = None ): self.content = content self.subject = subject self.header = header @attr.s(auto_attribs=True, init=False) class WhitelabelConfiguration(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: Unique Id logo_file: Customer logo image. Expected base64 encoded data (write-only) logo_url: Logo image url (read-only) favicon_file: Custom favicon image. Expected base64 encoded data (write-only) favicon_url: Favicon image url (read-only) default_title: Default page title show_help_menu: Boolean to toggle showing help menus show_docs: Boolean to toggle showing docs show_email_sub_options: Boolean to toggle showing email subscription options. allow_looker_mentions: Boolean to toggle mentions of Looker in emails allow_looker_links: Boolean to toggle links to Looker in emails custom_welcome_email_advanced: Allow subject line and email heading customization in customized emails” setup_mentions: Remove the word Looker from appearing in the account setup page alerts_logo: Remove Looker logo from Alerts alerts_links: Remove Looker links from Alerts folders_mentions: Remove Looker mentions in home folder page when you don’t have any items saved """ can: Optional[MutableMapping[str, bool]] = None id: Optional[int] = None logo_file: Optional[str] = None logo_url: Optional[str] = None favicon_file: Optional[str] = None favicon_url: Optional[str] = None default_title: Optional[str] = None show_help_menu: Optional[bool] = None show_docs: Optional[bool] = None show_email_sub_options: Optional[bool] = None allow_looker_mentions: Optional[bool] = None allow_looker_links: Optional[bool] = None custom_welcome_email_advanced: Optional[bool] = None setup_mentions: Optional[bool] = None alerts_logo: Optional[bool] = None alerts_links: Optional[bool] = None folders_mentions: Optional[bool] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[int] = None, logo_file: Optional[str] = None, logo_url: Optional[str] = None, favicon_file: Optional[str] = None, favicon_url: Optional[str] = None, default_title: Optional[str] = None, show_help_menu: Optional[bool] = None, show_docs: Optional[bool] = None, show_email_sub_options: Optional[bool] = None, allow_looker_mentions: Optional[bool] = None, allow_looker_links: Optional[bool] = None, custom_welcome_email_advanced: Optional[bool] = None, setup_mentions: Optional[bool] = None, alerts_logo: Optional[bool] = None, alerts_links: Optional[bool] = None, folders_mentions: Optional[bool] = None ): self.can = can self.id = id self.logo_file = logo_file self.logo_url = logo_url self.favicon_file = favicon_file self.favicon_url = favicon_url self.default_title = default_title self.show_help_menu = show_help_menu self.show_docs = show_docs self.show_email_sub_options = show_email_sub_options self.allow_looker_mentions = allow_looker_mentions self.allow_looker_links = allow_looker_links self.custom_welcome_email_advanced = custom_welcome_email_advanced self.setup_mentions = setup_mentions self.alerts_logo = alerts_logo self.alerts_links = alerts_links self.folders_mentions = folders_mentions @attr.s(auto_attribs=True, init=False) class Workspace(model.Model): """ Attributes: can: Operations the current user is able to perform on this object id: The unique id of this user workspace. Predefined workspace ids include "production" and "dev" projects: The local state of each project in the workspace """ can: Optional[MutableMapping[str, bool]] = None id: Optional[str] = None projects: Optional[Sequence["Project"]] = None def __init__( self, *, can: Optional[MutableMapping[str, bool]] = None, id: Optional[str] = None, projects: Optional[Sequence["Project"]] = None ): self.can = can self.id = id self.projects = projects @attr.s(auto_attribs=True, init=False) class WriteApiSession(model.Model): """ Dynamically generated writeable type for ApiSession removes properties: can, sudo_user_id Attributes: workspace_id: The id of active workspace for this session """ workspace_id: Optional[str] = None def __init__(self, *, workspace_id: Optional[str] = None): self.workspace_id = workspace_id @attr.s(auto_attribs=True, init=False) class WriteBackupConfiguration(model.Model): """ Dynamically generated writeable type for BackupConfiguration removes properties: can, url Attributes: type: Type of backup: looker-s3 or custom-s3 custom_s3_bucket: Name of bucket for custom-s3 backups custom_s3_bucket_region: Name of region where the bucket is located custom_s3_key: (Write-Only) AWS S3 key used for custom-s3 backups custom_s3_secret: (Write-Only) AWS S3 secret used for custom-s3 backups """ type: Optional[str] = None custom_s3_bucket: Optional[str] = None custom_s3_bucket_region: Optional[str] = None custom_s3_key: Optional[str] = None custom_s3_secret: Optional[str] = None def __init__( self, *, type: Optional[str] = None, custom_s3_bucket: Optional[str] = None, custom_s3_bucket_region: Optional[str] = None, custom_s3_key: Optional[str] = None, custom_s3_secret: Optional[str] = None ): self.type = type self.custom_s3_bucket = custom_s3_bucket self.custom_s3_bucket_region = custom_s3_bucket_region self.custom_s3_key = custom_s3_key self.custom_s3_secret = custom_s3_secret @attr.s(auto_attribs=True, init=False) class WriteBoard(model.Model): """ Dynamically generated writeable type for Board removes properties: can, content_metadata_id, created_at, board_sections, id, updated_at, user_id, primary_homepage Attributes: deleted_at: Date of board deletion description: Description of the board section_order: ids of the board sections in the order they should be displayed title: Title of the board """ deleted_at: Optional[datetime.datetime] = None description: Optional[str] = None section_order: Optional[Sequence[int]] = None title: Optional[str] = None def __init__( self, *, deleted_at: Optional[datetime.datetime] = None, description: Optional[str] = None, section_order: Optional[Sequence[int]] = None, title: Optional[str] = None ): self.deleted_at = deleted_at self.description = description self.section_order = section_order self.title = title @attr.s(auto_attribs=True, init=False) class WriteBoardItem(model.Model): """ Dynamically generated writeable type for BoardItem removes properties: can, content_created_by, content_favorite_id, content_metadata_id, content_updated_at, description, favorite_count, id, location, title, url, view_count Attributes: dashboard_id: Dashboard to base this item on board_section_id: Associated Board Section look_id: Look to base this item on lookml_dashboard_id: LookML Dashboard to base this item on order: An arbitrary integer representing the sort order within the section """ dashboard_id: Optional[int] = None board_section_id: Optional[int] = None look_id: Optional[int] = None lookml_dashboard_id: Optional[str] = None order: Optional[int] = None def __init__( self, *, dashboard_id: Optional[int] = None, board_section_id: Optional[int] = None, look_id: Optional[int] = None, lookml_dashboard_id: Optional[str] = None, order: Optional[int] = None ): self.dashboard_id = dashboard_id self.board_section_id = board_section_id self.look_id = look_id self.lookml_dashboard_id = lookml_dashboard_id self.order = order @attr.s(auto_attribs=True, init=False) class WriteBoardSection(model.Model): """ Dynamically generated writeable type for BoardSection removes properties: can, created_at, board_items, id, updated_at Attributes: deleted_at: Time at which this section was deleted. description: Description of the content found in this section. board_id: Id reference to parent board item_order: ids of the board items in the order they should be displayed title: Name of row """ deleted_at: Optional[datetime.datetime] = None description: Optional[str] = None board_id: Optional[int] = None item_order: Optional[Sequence[int]] = None title: Optional[str] = None def __init__( self, *, deleted_at: Optional[datetime.datetime] = None, description: Optional[str] = None, board_id: Optional[int] = None, item_order: Optional[Sequence[int]] = None, title: Optional[str] = None ): self.deleted_at = deleted_at self.description = description self.board_id = board_id self.item_order = item_order self.title = title @attr.s(auto_attribs=True, init=False) class WriteColorCollection(model.Model): """ Dynamically generated writeable type for ColorCollection removes properties: id Attributes: label: Label of color collection categoricalPalettes: Array of categorical palette definitions sequentialPalettes: Array of discrete palette definitions divergingPalettes: Array of diverging palette definitions """ label: Optional[str] = None categoricalPalettes: Optional[Sequence["DiscretePalette"]] = None sequentialPalettes: Optional[Sequence["ContinuousPalette"]] = None divergingPalettes: Optional[Sequence["ContinuousPalette"]] = None def __init__( self, *, label: Optional[str] = None, categoricalPalettes: Optional[Sequence["DiscretePalette"]] = None, sequentialPalettes: Optional[Sequence["ContinuousPalette"]] = None, divergingPalettes: Optional[Sequence["ContinuousPalette"]] = None ): self.label = label self.categoricalPalettes = categoricalPalettes self.sequentialPalettes = sequentialPalettes self.divergingPalettes = divergingPalettes @attr.s(auto_attribs=True, init=False) class WriteCommand(model.Model): """ Dynamically generated writeable type for Command removes properties: id, author_id Attributes: name: Name of the command description: Description of the command linked_content_id: Id of the content associated with the command linked_content_type: Name of the command Valid values are: "dashboard", "lookml_dashboard". """ name: Optional[str] = None description: Optional[str] = None linked_content_id: Optional[str] = None linked_content_type: Optional["LinkedContentType"] = None def __init__( self, *, name: Optional[str] = None, description: Optional[str] = None, linked_content_id: Optional[str] = None, linked_content_type: Optional["LinkedContentType"] = None ): self.name = name self.description = description self.linked_content_id = linked_content_id self.linked_content_type = linked_content_type @attr.s(auto_attribs=True, init=False) class WriteContentFavorite(model.Model): """ Dynamically generated writeable type for ContentFavorite removes properties: id, look_id, dashboard_id, board_id Attributes: user_id: User Id which owns this ContentFavorite content_metadata_id: Content Metadata Id associated with this ContentFavorite look: dashboard: """ user_id: Optional[int] = None content_metadata_id: Optional[int] = None look: Optional["WriteLookBasic"] = None dashboard: Optional["WriteDashboardBase"] = None def __init__( self, *, user_id: Optional[int] = None, content_metadata_id: Optional[int] = None, look: Optional["WriteLookBasic"] = None, dashboard: Optional["WriteDashboardBase"] = None ): self.user_id = user_id self.content_metadata_id = content_metadata_id self.look = look self.dashboard = dashboard @attr.s(auto_attribs=True, init=False) class WriteContentMeta(model.Model): """ Dynamically generated writeable type for ContentMeta removes properties: can, id, name, parent_id, dashboard_id, look_id, folder_id, content_type, inheriting_id, slug Attributes: inherits: Whether content inherits its access levels from parent """ inherits: Optional[bool] = None def __init__(self, *, inherits: Optional[bool] = None): self.inherits = inherits @attr.s(auto_attribs=True, init=False) class WriteCreateDashboardFilter(model.Model): """ Dynamically generated writeable type for CreateDashboardFilter removes properties: id, field Attributes: dashboard_id: Id of Dashboard name: Name of filter title: Title of filter type: Type of filter: one of date, number, string, or field default_value: Default value of filter model: Model of filter (required if type = field) explore: Explore of filter (required if type = field) dimension: Dimension of filter (required if type = field) row: Display order of this filter relative to other filters listens_to_filters: Array of listeners for faceted filters allow_multiple_values: Whether the filter allows multiple filter values required: Whether the filter requires a value to run the dashboard ui_config: The visual configuration for this filter. Used to set up how the UI for this filter should appear. """ dashboard_id: str name: str title: str type: str default_value: Optional[str] = None model: Optional[str] = None explore: Optional[str] = None dimension: Optional[str] = None row: Optional[int] = None listens_to_filters: Optional[Sequence[str]] = None allow_multiple_values: Optional[bool] = None required: Optional[bool] = None ui_config: Optional[MutableMapping[str, Any]] = None def __init__( self, *, dashboard_id: str, name: str, title: str, type: str, default_value: Optional[str] = None, model: Optional[str] = None, explore: Optional[str] = None, dimension: Optional[str] = None, row: Optional[int] = None, listens_to_filters: Optional[Sequence[str]] = None, allow_multiple_values: Optional[bool] = None, required: Optional[bool] = None, ui_config: Optional[MutableMapping[str, Any]] = None ): self.dashboard_id = dashboard_id self.name = name self.title = title self.type = type self.default_value = default_value self.model = model self.explore = explore self.dimension = dimension self.row = row self.listens_to_filters = listens_to_filters self.allow_multiple_values = allow_multiple_values self.required = required self.ui_config = ui_config @attr.s(auto_attribs=True, init=False) class WriteCreateQueryTask(model.Model): """ Dynamically generated writeable type for CreateQueryTask removes properties: can Attributes: query_id: Id of query to run result_format: Desired async query result format. Valid values are: "inline_json", "json", "json_detail", "json_fe", "csv", "html", "md", "txt", "xlsx", "gsxml". source: Source of query task deferred: Create the task but defer execution look_id: Id of look associated with query. dashboard_id: Id of dashboard associated with query. """ query_id: int result_format: "ResultFormat" source: Optional[str] = None deferred: Optional[bool] = None look_id: Optional[int] = None dashboard_id: Optional[str] = None __annotations__ = { "query_id": int, "result_format": ForwardRef("ResultFormat"), "source": Optional[str], "deferred": Optional[bool], "look_id": Optional[int], "dashboard_id": Optional[str], } def __init__( self, *, query_id: int, result_format: "ResultFormat", source: Optional[str] = None, deferred: Optional[bool] = None, look_id: Optional[int] = None, dashboard_id: Optional[str] = None ): self.query_id = query_id self.result_format = result_format self.source = source self.deferred = deferred self.look_id = look_id self.dashboard_id = dashboard_id @attr.s(auto_attribs=True, init=False) class WriteCredentialsEmail(model.Model): """ Dynamically generated writeable type for CredentialsEmail removes properties: can, created_at, is_disabled, logged_in_at, password_reset_url, type, url, user_url Attributes: email: EMail address used for user login forced_password_reset_at_next_login: Force the user to change their password upon their next login """ email: Optional[str] = None forced_password_reset_at_next_login: Optional[bool] = None def __init__( self, *, email: Optional[str] = None, forced_password_reset_at_next_login: Optional[bool] = None ): self.email = email self.forced_password_reset_at_next_login = forced_password_reset_at_next_login @attr.s(auto_attribs=True, init=False) class WriteCustomWelcomeEmail(model.Model): """ Dynamically generated writeable type for CustomWelcomeEmail removes properties: can Attributes: enabled: If true, custom email content will replace the default body of welcome emails content: The HTML to use as custom content for welcome emails. Script elements and other potentially dangerous markup will be removed. subject: The text to appear in the email subject line. header: The text to appear in the header line of the email body. """ enabled: Optional[bool] = None content: Optional[str] = None subject: Optional[str] = None header: Optional[str] = None def __init__( self, *, enabled: Optional[bool] = None, content: Optional[str] = None, subject: Optional[str] = None, header: Optional[str] = None ): self.enabled = enabled self.content = content self.subject = subject self.header = header @attr.s(auto_attribs=True, init=False) class WriteDashboard(model.Model): """ Dynamically generated writeable type for Dashboard removes properties: can, content_favorite_id, content_metadata_id, id, model, readonly, refresh_interval_to_i, user_id, created_at, dashboard_elements, dashboard_filters, dashboard_layouts, deleted_at, deleter_id, edit_uri, favorite_count, last_accessed_at, last_viewed_at, view_count Attributes: description: Description hidden: Is Hidden query_timezone: Timezone in which the Dashboard will run by default. refresh_interval: Refresh Interval, as a time duration phrase like "2 hours 30 minutes". A number with no time units will be interpreted as whole seconds. folder: title: Dashboard Title background_color: Background color crossfilter_enabled: Enables crossfiltering in dashboards - only available in dashboards-next (beta) deleted: Whether or not a dashboard is 'soft' deleted. load_configuration: configuration option that governs how dashboard loading will happen. lookml_link_id: Links this dashboard to a particular LookML dashboard such that calling a **sync** operation on that LookML dashboard will update this dashboard to match. show_filters_bar: Show filters bar. **Security Note:** This property only affects the *cosmetic* appearance of the dashboard, not a user's ability to access data. Hiding the filters bar does **NOT** prevent users from changing filters by other means. For information on how to set up secure data access control policies, see [Control User Access to Data](https://looker.com/docs/r/api/control-access) show_title: Show title slug: Content Metadata Slug folder_id: Id of folder text_tile_text_color: Color of text on text tiles tile_background_color: Tile background color tile_text_color: Tile text color title_color: Title color appearance: preferred_viewer: The preferred route for viewing this dashboard (ie: dashboards or dashboards-next) """ description: Optional[str] = None hidden: Optional[bool] = None query_timezone: Optional[str] = None refresh_interval: Optional[str] = None folder: Optional["WriteFolderBase"] = None title: Optional[str] = None background_color: Optional[str] = None crossfilter_enabled: Optional[bool] = None deleted: Optional[bool] = None load_configuration: Optional[str] = None lookml_link_id: Optional[str] = None show_filters_bar: Optional[bool] = None show_title: Optional[bool] = None slug: Optional[str] = None folder_id: Optional[str] = None text_tile_text_color: Optional[str] = None tile_background_color: Optional[str] = None tile_text_color: Optional[str] = None title_color: Optional[str] = None appearance: Optional["DashboardAppearance"] = None preferred_viewer: Optional[str] = None def __init__( self, *, description: Optional[str] = None, hidden: Optional[bool] = None, query_timezone: Optional[str] = None, refresh_interval: Optional[str] = None, folder: Optional["WriteFolderBase"] = None, title: Optional[str] = None, background_color: Optional[str] = None, crossfilter_enabled: Optional[bool] = None, deleted: Optional[bool] = None, load_configuration: Optional[str] = None, lookml_link_id: Optional[str] = None, show_filters_bar: Optional[bool] = None, show_title: Optional[bool] = None, slug: Optional[str] = None, folder_id: Optional[str] = None, text_tile_text_color: Optional[str] = None, tile_background_color: Optional[str] = None, tile_text_color: Optional[str] = None, title_color: Optional[str] = None, appearance: Optional["DashboardAppearance"] = None, preferred_viewer: Optional[str] = None ): self.description = description self.hidden = hidden self.query_timezone = query_timezone self.refresh_interval = refresh_interval self.folder = folder self.title = title self.background_color = background_color self.crossfilter_enabled = crossfilter_enabled self.deleted = deleted self.load_configuration = load_configuration self.lookml_link_id = lookml_link_id self.show_filters_bar = show_filters_bar self.show_title = show_title self.slug = slug self.folder_id = folder_id self.text_tile_text_color = text_tile_text_color self.tile_background_color = tile_background_color self.tile_text_color = tile_text_color self.title_color = title_color self.appearance = appearance self.preferred_viewer = preferred_viewer @attr.s(auto_attribs=True, init=False) class WriteDashboardBase(model.Model): """ Dynamically generated writeable type for DashboardBase removes properties: can, content_favorite_id, content_metadata_id, description, hidden, id, model, query_timezone, readonly, refresh_interval, refresh_interval_to_i, title, user_id Attributes: folder: """ folder: Optional["WriteFolderBase"] = None def __init__(self, *, folder: Optional["WriteFolderBase"] = None): self.folder = folder @attr.s(auto_attribs=True, init=False) class WriteDashboardElement(model.Model): """ Dynamically generated writeable type for DashboardElement removes properties: can, body_text_as_html, edit_uri, id, lookml_link_id, note_text_as_html, refresh_interval_to_i, alert_count, title_text_as_html, subtitle_text_as_html Attributes: body_text: Text tile body text dashboard_id: Id of Dashboard look: look_id: Id Of Look merge_result_id: ID of merge result note_display: Note Display note_state: Note State note_text: Note Text query: query_id: Id Of Query refresh_interval: Refresh Interval result_maker: result_maker_id: ID of the ResultMakerLookup entry. subtitle_text: Text tile subtitle text title: Title of dashboard element title_hidden: Whether title is hidden title_text: Text tile title type: Type """ body_text: Optional[str] = None dashboard_id: Optional[str] = None look: Optional["WriteLookWithQuery"] = None look_id: Optional[str] = None merge_result_id: Optional[str] = None note_display: Optional[str] = None note_state: Optional[str] = None note_text: Optional[str] = None query: Optional["WriteQuery"] = None query_id: Optional[int] = None refresh_interval: Optional[str] = None result_maker: Optional["WriteResultMakerWithIdVisConfigAndDynamicFields"] = None result_maker_id: Optional[int] = None subtitle_text: Optional[str] = None title: Optional[str] = None title_hidden: Optional[bool] = None title_text: Optional[str] = None type: Optional[str] = None def __init__( self, *, body_text: Optional[str] = None, dashboard_id: Optional[str] = None, look: Optional["WriteLookWithQuery"] = None, look_id: Optional[str] = None, merge_result_id: Optional[str] = None, note_display: Optional[str] = None, note_state: Optional[str] = None, note_text: Optional[str] = None, query: Optional["WriteQuery"] = None, query_id: Optional[int] = None, refresh_interval: Optional[str] = None, result_maker: Optional[ "WriteResultMakerWithIdVisConfigAndDynamicFields" ] = None, result_maker_id: Optional[int] = None, subtitle_text: Optional[str] = None, title: Optional[str] = None, title_hidden: Optional[bool] = None, title_text: Optional[str] = None, type: Optional[str] = None ): self.body_text = body_text self.dashboard_id = dashboard_id self.look = look self.look_id = look_id self.merge_result_id = merge_result_id self.note_display = note_display self.note_state = note_state self.note_text = note_text self.query = query self.query_id = query_id self.refresh_interval = refresh_interval self.result_maker = result_maker self.result_maker_id = result_maker_id self.subtitle_text = subtitle_text self.title = title self.title_hidden = title_hidden self.title_text = title_text self.type = type @attr.s(auto_attribs=True, init=False) class WriteDashboardFilter(model.Model): """ Dynamically generated writeable type for DashboardFilter removes properties: can, id, dashboard_id, field Attributes: name: Name of filter title: Title of filter type: Type of filter: one of date, number, string, or field default_value: Default value of filter model: Model of filter (required if type = field) explore: Explore of filter (required if type = field) dimension: Dimension of filter (required if type = field) row: Display order of this filter relative to other filters listens_to_filters: Array of listeners for faceted filters allow_multiple_values: Whether the filter allows multiple filter values required: Whether the filter requires a value to run the dashboard ui_config: The visual configuration for this filter. Used to set up how the UI for this filter should appear. """ name: Optional[str] = None title: Optional[str] = None type: Optional[str] = None default_value: Optional[str] = None model: Optional[str] = None explore: Optional[str] = None dimension: Optional[str] = None row: Optional[int] = None listens_to_filters: Optional[Sequence[str]] = None allow_multiple_values: Optional[bool] = None required: Optional[bool] = None ui_config: Optional[MutableMapping[str, Any]] = None def __init__( self, *, name: Optional[str] = None, title: Optional[str] = None, type: Optional[str] = None, default_value: Optional[str] = None, model: Optional[str] = None, explore: Optional[str] = None, dimension: Optional[str] = None, row: Optional[int] = None, listens_to_filters: Optional[Sequence[str]] = None, allow_multiple_values: Optional[bool] = None, required: Optional[bool] = None, ui_config: Optional[MutableMapping[str, Any]] = None ): self.name = name self.title = title self.type = type self.default_value = default_value self.model = model self.explore = explore self.dimension = dimension self.row = row self.listens_to_filters = listens_to_filters self.allow_multiple_values = allow_multiple_values self.required = required self.ui_config = ui_config @attr.s(auto_attribs=True, init=False) class WriteDashboardLayout(model.Model): """ Dynamically generated writeable type for DashboardLayout removes properties: can, id, deleted, dashboard_title, dashboard_layout_components Attributes: dashboard_id: Id of Dashboard type: Type active: Is Active column_width: Column Width width: Width """ dashboard_id: Optional[str] = None type: Optional[str] = None active: Optional[bool] = None column_width: Optional[int] = None width: Optional[int] = None def __init__( self, *, dashboard_id: Optional[str] = None, type: Optional[str] = None, active: Optional[bool] = None, column_width: Optional[int] = None, width: Optional[int] = None ): self.dashboard_id = dashboard_id self.type = type self.active = active self.column_width = column_width self.width = width @attr.s(auto_attribs=True, init=False) class WriteDashboardLayoutComponent(model.Model): """ Dynamically generated writeable type for DashboardLayoutComponent removes properties: can, id, deleted, element_title, element_title_hidden, vis_type Attributes: dashboard_layout_id: Id of Dashboard Layout dashboard_element_id: Id Of Dashboard Element row: Row column: Column width: Width height: Height """ dashboard_layout_id: Optional[str] = None dashboard_element_id: Optional[str] = None row: Optional[int] = None column: Optional[int] = None width: Optional[int] = None height: Optional[int] = None def __init__( self, *, dashboard_layout_id: Optional[str] = None, dashboard_element_id: Optional[str] = None, row: Optional[int] = None, column: Optional[int] = None, width: Optional[int] = None, height: Optional[int] = None ): self.dashboard_layout_id = dashboard_layout_id self.dashboard_element_id = dashboard_element_id self.row = row self.column = column self.width = width self.height = height @attr.s(auto_attribs=True, init=False) class WriteDatagroup(model.Model): """ Dynamically generated writeable type for Datagroup removes properties: can, created_at, id, model_name, name, trigger_check_at, trigger_error, trigger_value Attributes: stale_before: UNIX timestamp before which cache entries are considered stale. Cannot be in the future. triggered_at: UNIX timestamp at which this entry became triggered. Cannot be in the future. """ stale_before: Optional[int] = None triggered_at: Optional[int] = None def __init__( self, *, stale_before: Optional[int] = None, triggered_at: Optional[int] = None ): self.stale_before = stale_before self.triggered_at = triggered_at @attr.s(auto_attribs=True, init=False) class WriteDBConnection(model.Model): """ Dynamically generated writeable type for DBConnection removes properties: can, dialect, snippets, pdts_enabled, uses_oauth, created_at, user_id, example, last_regen_at, last_reap_at, managed Attributes: name: Name of the connection. Also used as the unique identifier host: Host name/address of server port: Port number on server username: Username for server authentication password: (Write-Only) Password for server authentication certificate: (Write-Only) Base64 encoded Certificate body for server authentication (when appropriate for dialect). file_type: (Write-Only) Certificate keyfile type - .json or .p12 database: Database name db_timezone: Time zone of database query_timezone: Timezone to use in queries schema: Scheme name max_connections: Maximum number of concurrent connection to use max_billing_gigabytes: Maximum size of query in GBs (BigQuery only, can be a user_attribute name) ssl: Use SSL/TLS when connecting to server verify_ssl: Verify the SSL tmp_db_name: Name of temporary database (if used) jdbc_additional_params: Additional params to add to JDBC connection string pool_timeout: Connection Pool Timeout, in seconds dialect_name: (Read/Write) SQL Dialect name user_db_credentials: (Limited access feature) Are per user db credentials enabled. Enabling will remove previously set username and password user_attribute_fields: Fields whose values map to user attribute names maintenance_cron: Cron string specifying when maintenance such as PDT trigger checks and drops should be performed sql_runner_precache_tables: Precache tables in the SQL Runner after_connect_statements: SQL statements (semicolon separated) to issue after connecting to the database. Requires `custom_after_connect_statements` license feature pdt_context_override: tunnel_id: The Id of the ssh tunnel this connection uses pdt_concurrency: Maximum number of threads to use to build PDTs in parallel disable_context_comment: When disable_context_comment is true comment will not be added to SQL """ name: Optional[str] = None host: Optional[str] = None port: Optional[int] = None username: Optional[str] = None password: Optional[str] = None certificate: Optional[str] = None file_type: Optional[str] = None database: Optional[str] = None db_timezone: Optional[str] = None query_timezone: Optional[str] = None schema: Optional[str] = None max_connections: Optional[int] = None max_billing_gigabytes: Optional[str] = None ssl: Optional[bool] = None verify_ssl: Optional[bool] = None tmp_db_name: Optional[str] = None jdbc_additional_params: Optional[str] = None pool_timeout: Optional[int] = None dialect_name: Optional[str] = None user_db_credentials: Optional[bool] = None user_attribute_fields: Optional[Sequence[str]] = None maintenance_cron: Optional[str] = None sql_runner_precache_tables: Optional[bool] = None after_connect_statements: Optional[str] = None pdt_context_override: Optional["WriteDBConnectionOverride"] = None tunnel_id: Optional[str] = None pdt_concurrency: Optional[int] = None disable_context_comment: Optional[bool] = None def __init__( self, *, name: Optional[str] = None, host: Optional[str] = None, port: Optional[int] = None, username: Optional[str] = None, password: Optional[str] = None, certificate: Optional[str] = None, file_type: Optional[str] = None, database: Optional[str] = None, db_timezone: Optional[str] = None, query_timezone: Optional[str] = None, schema: Optional[str] = None, max_connections: Optional[int] = None, max_billing_gigabytes: Optional[str] = None, ssl: Optional[bool] = None, verify_ssl: Optional[bool] = None, tmp_db_name: Optional[str] = None, jdbc_additional_params: Optional[str] = None, pool_timeout: Optional[int] = None, dialect_name: Optional[str] = None, user_db_credentials: Optional[bool] = None, user_attribute_fields: Optional[Sequence[str]] = None, maintenance_cron: Optional[str] = None, sql_runner_precache_tables: Optional[bool] = None, after_connect_statements: Optional[str] = None, pdt_context_override: Optional["WriteDBConnectionOverride"] = None, tunnel_id: Optional[str] = None, pdt_concurrency: Optional[int] = None, disable_context_comment: Optional[bool] = None ): self.name = name self.host = host self.port = port self.username = username self.password = password self.certificate = certificate self.file_type = file_type self.database = database self.db_timezone = db_timezone self.query_timezone = query_timezone self.schema = schema self.max_connections = max_connections self.max_billing_gigabytes = max_billing_gigabytes self.ssl = ssl self.verify_ssl = verify_ssl self.tmp_db_name = tmp_db_name self.jdbc_additional_params = jdbc_additional_params self.pool_timeout = pool_timeout self.dialect_name = dialect_name self.user_db_credentials = user_db_credentials self.user_attribute_fields = user_attribute_fields self.maintenance_cron = maintenance_cron self.sql_runner_precache_tables = sql_runner_precache_tables self.after_connect_statements = after_connect_statements self.pdt_context_override = pdt_context_override self.tunnel_id = tunnel_id self.pdt_concurrency = pdt_concurrency self.disable_context_comment = disable_context_comment @attr.s(auto_attribs=True, init=False) class WriteDBConnectionOverride(model.Model): """ Dynamically generated writeable type for DBConnectionOverride removes properties: has_password Attributes: context: Context in which to override (`pdt` is the only allowed value) host: Host name/address of server port: Port number on server username: Username for server authentication password: (Write-Only) Password for server authentication certificate: (Write-Only) Base64 encoded Certificate body for server authentication (when appropriate for dialect). file_type: (Write-Only) Certificate keyfile type - .json or .p12 database: Database name schema: Scheme name jdbc_additional_params: Additional params to add to JDBC connection string after_connect_statements: SQL statements (semicolon separated) to issue after connecting to the database. Requires `custom_after_connect_statements` license feature """ context: Optional[str] = None host: Optional[str] = None port: Optional[str] = None username: Optional[str] = None password: Optional[str] = None certificate: Optional[str] = None file_type: Optional[str] = None database: Optional[str] = None schema: Optional[str] = None jdbc_additional_params: Optional[str] = None after_connect_statements: Optional[str] = None def __init__( self, *, context: Optional[str] = None, host: Optional[str] = None, port: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, certificate: Optional[str] = None, file_type: Optional[str] = None, database: Optional[str] = None, schema: Optional[str] = None, jdbc_additional_params: Optional[str] = None, after_connect_statements: Optional[str] = None ): self.context = context self.host = host self.port = port self.username = username self.password = password self.certificate = certificate self.file_type = file_type self.database = database self.schema = schema self.jdbc_additional_params = jdbc_additional_params self.after_connect_statements = after_connect_statements @attr.s(auto_attribs=True, init=False) class WriteFolderBase(model.Model): """ Dynamically generated writeable type for FolderBase removes properties: id, content_metadata_id, created_at, creator_id, child_count, external_id, is_embed, is_embed_shared_root, is_embed_users_root, is_personal, is_personal_descendant, is_shared_root, is_users_root, can Attributes: name: Unique Name parent_id: Id of Parent. If the parent id is null, this is a root-level entry """ name: str parent_id: Optional[str] = None def __init__(self, *, name: str, parent_id: Optional[str] = None): self.name = name self.parent_id = parent_id @attr.s(auto_attribs=True, init=False) class WriteGitBranch(model.Model): """ Dynamically generated writeable type for GitBranch removes properties: can, remote, remote_name, error, message, owner_name, readonly, personal, is_local, is_remote, is_production, ahead_count, behind_count, commit_at, remote_ref Attributes: name: The short name on the local. Updating `name` results in `git checkout <new_name>` ref: The resolved ref of this branch. Updating `ref` results in `git reset --hard <new_ref>``. """ name: Optional[str] = None ref: Optional[str] = None def __init__(self, *, name: Optional[str] = None, ref: Optional[str] = None): self.name = name self.ref = ref @attr.s(auto_attribs=True, init=False) class WriteGroup(model.Model): """ Dynamically generated writeable type for Group removes properties: can, contains_current_user, external_group_id, externally_managed, id, include_by_default, user_count Attributes: can_add_to_content_metadata: Group can be used in content access controls name: Name of group """ can_add_to_content_metadata: Optional[bool] = None name: Optional[str] = None def __init__( self, *, can_add_to_content_metadata: Optional[bool] = None, name: Optional[str] = None ): self.can_add_to_content_metadata = can_add_to_content_metadata self.name = name @attr.s(auto_attribs=True, init=False) class WriteIntegration(model.Model): """ Dynamically generated writeable type for Integration removes properties: can, id, integration_hub_id, label, description, supported_formats, supported_action_types, supported_formattings, supported_visualization_formattings, supported_download_settings, icon_url, uses_oauth, required_fields, delegate_oauth Attributes: enabled: Whether the integration is available to users. params: Array of params for the integration. installed_delegate_oauth_targets: Whether the integration is available to users. """ enabled: Optional[bool] = None params: Optional[Sequence["IntegrationParam"]] = None installed_delegate_oauth_targets: Optional[Sequence[int]] = None def __init__( self, *, enabled: Optional[bool] = None, params: Optional[Sequence["IntegrationParam"]] = None, installed_delegate_oauth_targets: Optional[Sequence[int]] = None ): self.enabled = enabled self.params = params self.installed_delegate_oauth_targets = installed_delegate_oauth_targets @attr.s(auto_attribs=True, init=False) class WriteIntegrationHub(model.Model): """ Dynamically generated writeable type for IntegrationHub removes properties: can, id, label, official, fetch_error_message, has_authorization_token, legal_agreement_signed, legal_agreement_required, legal_agreement_text Attributes: url: URL of the hub. authorization_token: (Write-Only) An authorization key that will be sent to the integration hub on every request. """ url: Optional[str] = None authorization_token: Optional[str] = None def __init__( self, *, url: Optional[str] = None, authorization_token: Optional[str] = None ): self.url = url self.authorization_token = authorization_token @attr.s(auto_attribs=True, init=False) class WriteInternalHelpResources(model.Model): """ Dynamically generated writeable type for InternalHelpResources removes properties: can Attributes: enabled: If true and internal help resources content is not blank then the link for internal help resources will be shown in the help menu and the content displayed within Looker """ enabled: Optional[bool] = None def __init__(self, *, enabled: Optional[bool] = None): self.enabled = enabled @attr.s(auto_attribs=True, init=False) class WriteInternalHelpResourcesContent(model.Model): """ Dynamically generated writeable type for InternalHelpResourcesContent removes properties: can Attributes: organization_name: Text to display in the help menu item which will display the internal help resources markdown_content: Content to be displayed in the internal help resources page/modal """ organization_name: Optional[str] = None markdown_content: Optional[str] = None def __init__( self, *, organization_name: Optional[str] = None, markdown_content: Optional[str] = None ): self.organization_name = organization_name self.markdown_content = markdown_content @attr.s(auto_attribs=True, init=False) class WriteLDAPConfig(model.Model): """ Dynamically generated writeable type for LDAPConfig removes properties: can, default_new_user_groups, default_new_user_roles, groups, has_auth_password, modified_at, modified_by, user_attributes, url Attributes: alternate_email_login_allowed: Allow alternate email-based login via '/login/email' for admins and for specified users with the 'login_special_email' permission. This option is useful as a fallback during ldap setup, if ldap config problems occur later, or if you need to support some users who are not in your ldap directory. Looker email/password logins are always disabled for regular users when ldap is enabled. auth_password: (Write-Only) Password for the LDAP account used to access the LDAP server auth_requires_role: Users will not be allowed to login at all unless a role for them is found in LDAP if set to true auth_username: Distinguished name of LDAP account used to access the LDAP server connection_host: LDAP server hostname connection_port: LDAP host port connection_tls: Use Transport Layer Security connection_tls_no_verify: Do not verify peer when using TLS default_new_user_group_ids: (Write-Only) Array of ids of groups that will be applied to new users the first time they login via LDAP default_new_user_role_ids: (Write-Only) Array of ids of roles that will be applied to new users the first time they login via LDAP enabled: Enable/Disable LDAP authentication for the server force_no_page: Don't attempt to do LDAP search result paging (RFC 2696) even if the LDAP server claims to support it. groups_base_dn: Base dn for finding groups in LDAP searches groups_finder_type: Identifier for a strategy for how Looker will search for groups in the LDAP server groups_member_attribute: LDAP Group attribute that signifies the members of the groups. Most commonly 'member' groups_objectclasses: Optional comma-separated list of supported LDAP objectclass for groups when doing groups searches groups_user_attribute: LDAP Group attribute that signifies the user in a group. Most commonly 'dn' groups_with_role_ids: (Read/Write) Array of mappings between LDAP Groups and arrays of Looker Role ids merge_new_users_by_email: Merge first-time ldap login to existing user account by email addresses. When a user logs in for the first time via ldap this option will connect this user into their existing account by finding the account with a matching email address. Otherwise a new user account will be created for the user. set_roles_from_groups: Set user roles in Looker based on groups from LDAP test_ldap_password: (Write-Only) Test LDAP user password. For ldap tests only. test_ldap_user: (Write-Only) Test LDAP user login id. For ldap tests only. user_attribute_map_email: Name of user record attributes used to indicate email address field user_attribute_map_first_name: Name of user record attributes used to indicate first name user_attribute_map_last_name: Name of user record attributes used to indicate last name user_attribute_map_ldap_id: Name of user record attributes used to indicate unique record id user_attributes_with_ids: (Read/Write) Array of mappings between LDAP User Attributes and arrays of Looker User Attribute ids user_bind_base_dn: Distinguished name of LDAP node used as the base for user searches user_custom_filter: (Optional) Custom RFC-2254 filter clause for use in finding user during login. Combined via 'and' with the other generated filter clauses. user_id_attribute_names: Name(s) of user record attributes used for matching user login id (comma separated list) user_objectclass: (Optional) Name of user record objectclass used for finding user during login id allow_normal_group_membership: Allow LDAP auth'd users to be members of non-reflected Looker groups. If 'false', user will be removed from non-reflected groups on login. allow_roles_from_normal_groups: LDAP auth'd users will be able to inherit roles from non-reflected Looker groups. allow_direct_roles: Allows roles to be directly assigned to LDAP auth'd users. """ alternate_email_login_allowed: Optional[bool] = None auth_password: Optional[str] = None auth_requires_role: Optional[bool] = None auth_username: Optional[str] = None connection_host: Optional[str] = None connection_port: Optional[str] = None connection_tls: Optional[bool] = None connection_tls_no_verify: Optional[bool] = None default_new_user_group_ids: Optional[Sequence[int]] = None default_new_user_role_ids: Optional[Sequence[int]] = None enabled: Optional[bool] = None force_no_page: Optional[bool] = None groups_base_dn: Optional[str] = None groups_finder_type: Optional[str] = None groups_member_attribute: Optional[str] = None groups_objectclasses: Optional[str] = None groups_user_attribute: Optional[str] = None groups_with_role_ids: Optional[Sequence["LDAPGroupWrite"]] = None merge_new_users_by_email: Optional[bool] = None set_roles_from_groups: Optional[bool] = None test_ldap_password: Optional[str] = None test_ldap_user: Optional[str] = None user_attribute_map_email: Optional[str] = None user_attribute_map_first_name: Optional[str] = None user_attribute_map_last_name: Optional[str] = None user_attribute_map_ldap_id: Optional[str] = None user_attributes_with_ids: Optional[Sequence["LDAPUserAttributeWrite"]] = None user_bind_base_dn: Optional[str] = None user_custom_filter: Optional[str] = None user_id_attribute_names: Optional[str] = None user_objectclass: Optional[str] = None allow_normal_group_membership: Optional[bool] = None allow_roles_from_normal_groups: Optional[bool] = None allow_direct_roles: Optional[bool] = None def __init__( self, *, alternate_email_login_allowed: Optional[bool] = None, auth_password: Optional[str] = None, auth_requires_role: Optional[bool] = None, auth_username: Optional[str] = None, connection_host: Optional[str] = None, connection_port: Optional[str] = None, connection_tls: Optional[bool] = None, connection_tls_no_verify: Optional[bool] = None, default_new_user_group_ids: Optional[Sequence[int]] = None, default_new_user_role_ids: Optional[Sequence[int]] = None, enabled: Optional[bool] = None, force_no_page: Optional[bool] = None, groups_base_dn: Optional[str] = None, groups_finder_type: Optional[str] = None, groups_member_attribute: Optional[str] = None, groups_objectclasses: Optional[str] = None, groups_user_attribute: Optional[str] = None, groups_with_role_ids: Optional[Sequence["LDAPGroupWrite"]] = None, merge_new_users_by_email: Optional[bool] = None, set_roles_from_groups: Optional[bool] = None, test_ldap_password: Optional[str] = None, test_ldap_user: Optional[str] = None, user_attribute_map_email: Optional[str] = None, user_attribute_map_first_name: Optional[str] = None, user_attribute_map_last_name: Optional[str] = None, user_attribute_map_ldap_id: Optional[str] = None, user_attributes_with_ids: Optional[Sequence["LDAPUserAttributeWrite"]] = None, user_bind_base_dn: Optional[str] = None, user_custom_filter: Optional[str] = None, user_id_attribute_names: Optional[str] = None, user_objectclass: Optional[str] = None, allow_normal_group_membership: Optional[bool] = None, allow_roles_from_normal_groups: Optional[bool] = None, allow_direct_roles: Optional[bool] = None ): self.alternate_email_login_allowed = alternate_email_login_allowed self.auth_password = auth_password self.auth_requires_role = auth_requires_role self.auth_username = auth_username self.connection_host = connection_host self.connection_port = connection_port self.connection_tls = connection_tls self.connection_tls_no_verify = connection_tls_no_verify self.default_new_user_group_ids = default_new_user_group_ids self.default_new_user_role_ids = default_new_user_role_ids self.enabled = enabled self.force_no_page = force_no_page self.groups_base_dn = groups_base_dn self.groups_finder_type = groups_finder_type self.groups_member_attribute = groups_member_attribute self.groups_objectclasses = groups_objectclasses self.groups_user_attribute = groups_user_attribute self.groups_with_role_ids = groups_with_role_ids self.merge_new_users_by_email = merge_new_users_by_email self.set_roles_from_groups = set_roles_from_groups self.test_ldap_password = test_ldap_password self.test_ldap_user = test_ldap_user self.user_attribute_map_email = user_attribute_map_email self.user_attribute_map_first_name = user_attribute_map_first_name self.user_attribute_map_last_name = user_attribute_map_last_name self.user_attribute_map_ldap_id = user_attribute_map_ldap_id self.user_attributes_with_ids = user_attributes_with_ids self.user_bind_base_dn = user_bind_base_dn self.user_custom_filter = user_custom_filter self.user_id_attribute_names = user_id_attribute_names self.user_objectclass = user_objectclass self.allow_normal_group_membership = allow_normal_group_membership self.allow_roles_from_normal_groups = allow_roles_from_normal_groups self.allow_direct_roles = allow_direct_roles @attr.s(auto_attribs=True, init=False) class WriteLegacyFeature(model.Model): """ Dynamically generated writeable type for LegacyFeature removes properties: can, id, name, description, enabled, disallowed_as_of_version, disable_on_upgrade_to_version, end_of_life_version, documentation_url, approximate_disable_date, approximate_end_of_life_date, has_disabled_on_upgrade Attributes: enabled_locally: Whether this feature has been enabled by a user """ enabled_locally: Optional[bool] = None def __init__(self, *, enabled_locally: Optional[bool] = None): self.enabled_locally = enabled_locally @attr.s(auto_attribs=True, init=False) class WriteLookBasic(model.Model): """ Dynamically generated writeable type for LookBasic removes properties: can, content_metadata_id, id, title Attributes: user_id: User Id """ user_id: Optional[int] = None def __init__(self, *, user_id: Optional[int] = None): self.user_id = user_id @attr.s(auto_attribs=True, init=False) class WriteLookmlModel(model.Model): """ Dynamically generated writeable type for LookmlModel removes properties: can, explores, has_content, label Attributes: allowed_db_connection_names: Array of names of connections this model is allowed to use name: Name of the model. Also used as the unique identifier project_name: Name of project containing the model unlimited_db_connections: Is this model allowed to use all current and future connections """ allowed_db_connection_names: Optional[Sequence[str]] = None name: Optional[str] = None project_name: Optional[str] = None unlimited_db_connections: Optional[bool] = None def __init__( self, *, allowed_db_connection_names: Optional[Sequence[str]] = None, name: Optional[str] = None, project_name: Optional[str] = None, unlimited_db_connections: Optional[bool] = None ): self.allowed_db_connection_names = allowed_db_connection_names self.name = name self.project_name = project_name self.unlimited_db_connections = unlimited_db_connections @attr.s(auto_attribs=True, init=False) class WriteLookWithQuery(model.Model): """ Dynamically generated writeable type for LookWithQuery removes properties: can, content_metadata_id, id, content_favorite_id, created_at, deleted_at, deleter_id, embed_url, excel_file_url, favorite_count, google_spreadsheet_formula, image_embed_url, last_accessed_at, last_updater_id, last_viewed_at, model, public_slug, public_url, short_url, updated_at, view_count, url Attributes: title: Look Title user_id: User Id deleted: Whether or not a look is 'soft' deleted. description: Description is_run_on_load: auto-run query when Look viewed public: Is Public query_id: Query Id folder: folder_id: Folder Id query: """ title: Optional[str] = None user_id: Optional[int] = None deleted: Optional[bool] = None description: Optional[str] = None is_run_on_load: Optional[bool] = None public: Optional[bool] = None query_id: Optional[int] = None folder: Optional["WriteFolderBase"] = None folder_id: Optional[str] = None query: Optional["WriteQuery"] = None def __init__( self, *, title: Optional[str] = None, user_id: Optional[int] = None, deleted: Optional[bool] = None, description: Optional[str] = None, is_run_on_load: Optional[bool] = None, public: Optional[bool] = None, query_id: Optional[int] = None, folder: Optional["WriteFolderBase"] = None, folder_id: Optional[str] = None, query: Optional["WriteQuery"] = None ): self.title = title self.user_id = user_id self.deleted = deleted self.description = description self.is_run_on_load = is_run_on_load self.public = public self.query_id = query_id self.folder = folder self.folder_id = folder_id self.query = query @attr.s(auto_attribs=True, init=False) class WriteMergeQuery(model.Model): """ Dynamically generated writeable type for MergeQuery removes properties: can, id, result_maker_id Attributes: column_limit: Column Limit dynamic_fields: Dynamic Fields pivots: Pivots sorts: Sorts source_queries: Source Queries defining the results to be merged. total: Total vis_config: Visualization Config """ column_limit: Optional[str] = None dynamic_fields: Optional[str] = None pivots: Optional[Sequence[str]] = None sorts: Optional[Sequence[str]] = None source_queries: Optional[Sequence["MergeQuerySourceQuery"]] = None total: Optional[bool] = None vis_config: Optional[MutableMapping[str, Any]] = None def __init__( self, *, column_limit: Optional[str] = None, dynamic_fields: Optional[str] = None, pivots: Optional[Sequence[str]] = None, sorts: Optional[Sequence[str]] = None, source_queries: Optional[Sequence["MergeQuerySourceQuery"]] = None, total: Optional[bool] = None, vis_config: Optional[MutableMapping[str, Any]] = None ): self.column_limit = column_limit self.dynamic_fields = dynamic_fields self.pivots = pivots self.sorts = sorts self.source_queries = source_queries self.total = total self.vis_config = vis_config @attr.s(auto_attribs=True, init=False) class WriteModelSet(model.Model): """ Dynamically generated writeable type for ModelSet removes properties: can, all_access, built_in, id, url Attributes: models: name: Name of ModelSet """ models: Optional[Sequence[str]] = None name: Optional[str] = None def __init__( self, *, models: Optional[Sequence[str]] = None, name: Optional[str] = None ): self.models = models self.name = name @attr.s(auto_attribs=True, init=False) class WriteOauthClientApp(model.Model): """ Dynamically generated writeable type for OauthClientApp removes properties: can, client_guid, tokens_invalid_before, activated_users Attributes: redirect_uri: The uri with which this application will receive an auth code by browser redirect. display_name: The application's display name description: A description of the application that will be displayed to users enabled: When enabled is true, OAuth2 and API requests will be accepted from this app. When false, all requests from this app will be refused. group_id: If set, only Looker users who are members of this group can use this web app with Looker. If group_id is not set, any Looker user may use this app to access this Looker instance """ redirect_uri: Optional[str] = None display_name: Optional[str] = None description: Optional[str] = None enabled: Optional[bool] = None group_id: Optional[int] = None def __init__( self, *, redirect_uri: Optional[str] = None, display_name: Optional[str] = None, description: Optional[str] = None, enabled: Optional[bool] = None, group_id: Optional[int] = None ): self.redirect_uri = redirect_uri self.display_name = display_name self.description = description self.enabled = enabled self.group_id = group_id @attr.s(auto_attribs=True, init=False) class WriteOIDCConfig(model.Model): """ Dynamically generated writeable type for OIDCConfig removes properties: can, default_new_user_groups, default_new_user_roles, groups, modified_at, modified_by, test_slug, user_attributes, url Attributes: alternate_email_login_allowed: Allow alternate email-based login via '/login/email' for admins and for specified users with the 'login_special_email' permission. This option is useful as a fallback during ldap setup, if ldap config problems occur later, or if you need to support some users who are not in your ldap directory. Looker email/password logins are always disabled for regular users when ldap is enabled. audience: OpenID Provider Audience auth_requires_role: Users will not be allowed to login at all unless a role for them is found in OIDC if set to true authorization_endpoint: OpenID Provider Authorization Url default_new_user_group_ids: (Write-Only) Array of ids of groups that will be applied to new users the first time they login via OIDC default_new_user_role_ids: (Write-Only) Array of ids of roles that will be applied to new users the first time they login via OIDC enabled: Enable/Disable OIDC authentication for the server groups_attribute: Name of user record attributes used to indicate groups. Used when 'groups_finder_type' is set to 'grouped_attribute_values' groups_with_role_ids: (Read/Write) Array of mappings between OIDC Groups and arrays of Looker Role ids identifier: Relying Party Identifier (provided by OpenID Provider) issuer: OpenID Provider Issuer new_user_migration_types: Merge first-time oidc login to existing user account by email addresses. When a user logs in for the first time via oidc this option will connect this user into their existing account by finding the account with a matching email address by testing the given types of credentials for existing users. Otherwise a new user account will be created for the user. This list (if provided) must be a comma separated list of string like 'email,ldap,google' scopes: Array of scopes to request. secret: (Write-Only) Relying Party Secret (provided by OpenID Provider) set_roles_from_groups: Set user roles in Looker based on groups from OIDC token_endpoint: OpenID Provider Token Url user_attribute_map_email: Name of user record attributes used to indicate email address field user_attribute_map_first_name: Name of user record attributes used to indicate first name user_attribute_map_last_name: Name of user record attributes used to indicate last name user_attributes_with_ids: (Read/Write) Array of mappings between OIDC User Attributes and arrays of Looker User Attribute ids userinfo_endpoint: OpenID Provider User Information Url allow_normal_group_membership: Allow OIDC auth'd users to be members of non-reflected Looker groups. If 'false', user will be removed from non-reflected groups on login. allow_roles_from_normal_groups: OIDC auth'd users will inherit roles from non-reflected Looker groups. allow_direct_roles: Allows roles to be directly assigned to OIDC auth'd users. """ alternate_email_login_allowed: Optional[bool] = None audience: Optional[str] = None auth_requires_role: Optional[bool] = None authorization_endpoint: Optional[str] = None default_new_user_group_ids: Optional[Sequence[int]] = None default_new_user_role_ids: Optional[Sequence[int]] = None enabled: Optional[bool] = None groups_attribute: Optional[str] = None groups_with_role_ids: Optional[Sequence["OIDCGroupWrite"]] = None identifier: Optional[str] = None issuer: Optional[str] = None new_user_migration_types: Optional[str] = None scopes: Optional[Sequence[str]] = None secret: Optional[str] = None set_roles_from_groups: Optional[bool] = None token_endpoint: Optional[str] = None user_attribute_map_email: Optional[str] = None user_attribute_map_first_name: Optional[str] = None user_attribute_map_last_name: Optional[str] = None user_attributes_with_ids: Optional[Sequence["OIDCUserAttributeWrite"]] = None userinfo_endpoint: Optional[str] = None allow_normal_group_membership: Optional[bool] = None allow_roles_from_normal_groups: Optional[bool] = None allow_direct_roles: Optional[bool] = None def __init__( self, *, alternate_email_login_allowed: Optional[bool] = None, audience: Optional[str] = None, auth_requires_role: Optional[bool] = None, authorization_endpoint: Optional[str] = None, default_new_user_group_ids: Optional[Sequence[int]] = None, default_new_user_role_ids: Optional[Sequence[int]] = None, enabled: Optional[bool] = None, groups_attribute: Optional[str] = None, groups_with_role_ids: Optional[Sequence["OIDCGroupWrite"]] = None, identifier: Optional[str] = None, issuer: Optional[str] = None, new_user_migration_types: Optional[str] = None, scopes: Optional[Sequence[str]] = None, secret: Optional[str] = None, set_roles_from_groups: Optional[bool] = None, token_endpoint: Optional[str] = None, user_attribute_map_email: Optional[str] = None, user_attribute_map_first_name: Optional[str] = None, user_attribute_map_last_name: Optional[str] = None, user_attributes_with_ids: Optional[Sequence["OIDCUserAttributeWrite"]] = None, userinfo_endpoint: Optional[str] = None, allow_normal_group_membership: Optional[bool] = None, allow_roles_from_normal_groups: Optional[bool] = None, allow_direct_roles: Optional[bool] = None ): self.alternate_email_login_allowed = alternate_email_login_allowed self.audience = audience self.auth_requires_role = auth_requires_role self.authorization_endpoint = authorization_endpoint self.default_new_user_group_ids = default_new_user_group_ids self.default_new_user_role_ids = default_new_user_role_ids self.enabled = enabled self.groups_attribute = groups_attribute self.groups_with_role_ids = groups_with_role_ids self.identifier = identifier self.issuer = issuer self.new_user_migration_types = new_user_migration_types self.scopes = scopes self.secret = secret self.set_roles_from_groups = set_roles_from_groups self.token_endpoint = token_endpoint self.user_attribute_map_email = user_attribute_map_email self.user_attribute_map_first_name = user_attribute_map_first_name self.user_attribute_map_last_name = user_attribute_map_last_name self.user_attributes_with_ids = user_attributes_with_ids self.userinfo_endpoint = userinfo_endpoint self.allow_normal_group_membership = allow_normal_group_membership self.allow_roles_from_normal_groups = allow_roles_from_normal_groups self.allow_direct_roles = allow_direct_roles @attr.s(auto_attribs=True, init=False) class WritePasswordConfig(model.Model): """ Dynamically generated writeable type for PasswordConfig removes properties: can Attributes: min_length: Minimum number of characters required for a new password. Must be between 7 and 100 require_numeric: Require at least one numeric character require_upperlower: Require at least one uppercase and one lowercase letter require_special: Require at least one special character """ min_length: Optional[int] = None require_numeric: Optional[bool] = None require_upperlower: Optional[bool] = None require_special: Optional[bool] = None def __init__( self, *, min_length: Optional[int] = None, require_numeric: Optional[bool] = None, require_upperlower: Optional[bool] = None, require_special: Optional[bool] = None ): self.min_length = min_length self.require_numeric = require_numeric self.require_upperlower = require_upperlower self.require_special = require_special @attr.s(auto_attribs=True, init=False) class WritePermissionSet(model.Model): """ Dynamically generated writeable type for PermissionSet removes properties: can, all_access, built_in, id, url Attributes: name: Name of PermissionSet permissions: """ name: Optional[str] = None permissions: Optional[Sequence[str]] = None def __init__( self, *, name: Optional[str] = None, permissions: Optional[Sequence[str]] = None ): self.name = name self.permissions = permissions @attr.s(auto_attribs=True, init=False) class WriteProject(model.Model): """ Dynamically generated writeable type for Project removes properties: can, id, uses_git, is_example Attributes: name: Project display name git_remote_url: Git remote repository url git_username: Git username for HTTPS authentication. (For production only, if using user attributes.) git_password: (Write-Only) Git password for HTTPS authentication. (For production only, if using user attributes.) git_username_user_attribute: User attribute name for username in per-user HTTPS authentication. git_password_user_attribute: User attribute name for password in per-user HTTPS authentication. git_service_name: Name of the git service provider git_application_server_http_port: Port that HTTP(S) application server is running on (for PRs, file browsing, etc.) git_application_server_http_scheme: Scheme that is running on application server (for PRs, file browsing, etc.) Valid values are: "http", "https". deploy_secret: (Write-Only) Optional secret token with which to authenticate requests to the webhook deploy endpoint. If not set, endpoint is unauthenticated. unset_deploy_secret: (Write-Only) When true, unsets the deploy secret to allow unauthenticated access to the webhook deploy endpoint. pull_request_mode: The git pull request policy for this project. Valid values are: "off", "links", "recommended", "required". validation_required: Validation policy: If true, the project must pass validation checks before project changes can be committed to the git repository git_release_mgmt_enabled: If true, advanced git release management is enabled for this project allow_warnings: Validation policy: If true, the project can be committed with warnings when `validation_required` is true. (`allow_warnings` does nothing if `validation_required` is false). dependency_status: Status of dependencies in your manifest & lockfile """ name: Optional[str] = None git_remote_url: Optional[str] = None git_username: Optional[str] = None git_password: Optional[str] = None git_username_user_attribute: Optional[str] = None git_password_user_attribute: Optional[str] = None git_service_name: Optional[str] = None git_application_server_http_port: Optional[int] = None git_application_server_http_scheme: Optional[ "GitApplicationServerHttpScheme" ] = None deploy_secret: Optional[str] = None unset_deploy_secret: Optional[bool] = None pull_request_mode: Optional["PullRequestMode"] = None validation_required: Optional[bool] = None git_release_mgmt_enabled: Optional[bool] = None allow_warnings: Optional[bool] = None dependency_status: Optional[str] = None def __init__( self, *, name: Optional[str] = None, git_remote_url: Optional[str] = None, git_username: Optional[str] = None, git_password: Optional[str] = None, git_username_user_attribute: Optional[str] = None, git_password_user_attribute: Optional[str] = None, git_service_name: Optional[str] = None, git_application_server_http_port: Optional[int] = None, git_application_server_http_scheme: Optional[ "GitApplicationServerHttpScheme" ] = None, deploy_secret: Optional[str] = None, unset_deploy_secret: Optional[bool] = None, pull_request_mode: Optional["PullRequestMode"] = None, validation_required: Optional[bool] = None, git_release_mgmt_enabled: Optional[bool] = None, allow_warnings: Optional[bool] = None, dependency_status: Optional[str] = None ): self.name = name self.git_remote_url = git_remote_url self.git_username = git_username self.git_password = git_password self.git_username_user_attribute = git_username_user_attribute self.git_password_user_attribute = git_password_user_attribute self.git_service_name = git_service_name self.git_application_server_http_port = git_application_server_http_port self.git_application_server_http_scheme = git_application_server_http_scheme self.deploy_secret = deploy_secret self.unset_deploy_secret = unset_deploy_secret self.pull_request_mode = pull_request_mode self.validation_required = validation_required self.git_release_mgmt_enabled = git_release_mgmt_enabled self.allow_warnings = allow_warnings self.dependency_status = dependency_status @attr.s(auto_attribs=True, init=False) class WriteQuery(model.Model): """ Dynamically generated writeable type for Query removes properties: can, id, slug, share_url, expanded_share_url, url, has_table_calculations Attributes: model: Model view: Explore Name fields: Fields pivots: Pivots fill_fields: Fill Fields filters: Filters filter_expression: Filter Expression sorts: Sorting for the query results. Use the format `["view.field", ...]` to sort on fields in ascending order. Use the format `["view.field desc", ...]` to sort on fields in descending order. Use `["__UNSORTED__"]` (2 underscores before and after) to disable sorting entirely. Empty sorts `[]` will trigger a default sort. limit: Limit column_limit: Column Limit total: Total row_total: Raw Total subtotals: Fields on which to run subtotals vis_config: Visualization configuration properties. These properties are typically opaque and differ based on the type of visualization used. There is no specified set of allowed keys. The values can be any type supported by JSON. A "type" key with a string value is often present, and is used by Looker to determine which visualization to present. Visualizations ignore unknown vis_config properties. filter_config: The filter_config represents the state of the filter UI on the explore page for a given query. When running a query via the Looker UI, this parameter takes precedence over "filters". When creating a query or modifying an existing query, "filter_config" should be set to null. Setting it to any other value could cause unexpected filtering behavior. The format should be considered opaque. visible_ui_sections: Visible UI Sections dynamic_fields: Dynamic Fields client_id: Client Id: used to generate shortened explore URLs. If set by client, must be a unique 22 character alphanumeric string. Otherwise one will be generated. query_timezone: Query Timezone """ model: str view: str fields: Optional[Sequence[str]] = None pivots: Optional[Sequence[str]] = None fill_fields: Optional[Sequence[str]] = None filters: Optional[MutableMapping[str, Any]] = None filter_expression: Optional[str] = None sorts: Optional[Sequence[str]] = None limit: Optional[str] = None column_limit: Optional[str] = None total: Optional[bool] = None row_total: Optional[str] = None subtotals: Optional[Sequence[str]] = None vis_config: Optional[MutableMapping[str, Any]] = None filter_config: Optional[MutableMapping[str, Any]] = None visible_ui_sections: Optional[str] = None dynamic_fields: Optional[str] = None client_id: Optional[str] = None query_timezone: Optional[str] = None def __init__( self, *, model: str, view: str, fields: Optional[Sequence[str]] = None, pivots: Optional[Sequence[str]] = None, fill_fields: Optional[Sequence[str]] = None, filters: Optional[MutableMapping[str, Any]] = None, filter_expression: Optional[str] = None, sorts: Optional[Sequence[str]] = None, limit: Optional[str] = None, column_limit: Optional[str] = None, total: Optional[bool] = None, row_total: Optional[str] = None, subtotals: Optional[Sequence[str]] = None, vis_config: Optional[MutableMapping[str, Any]] = None, filter_config: Optional[MutableMapping[str, Any]] = None, visible_ui_sections: Optional[str] = None, dynamic_fields: Optional[str] = None, client_id: Optional[str] = None, query_timezone: Optional[str] = None ): self.model = model self.view = view self.fields = fields self.pivots = pivots self.fill_fields = fill_fields self.filters = filters self.filter_expression = filter_expression self.sorts = sorts self.limit = limit self.column_limit = column_limit self.total = total self.row_total = row_total self.subtotals = subtotals self.vis_config = vis_config self.filter_config = filter_config self.visible_ui_sections = visible_ui_sections self.dynamic_fields = dynamic_fields self.client_id = client_id self.query_timezone = query_timezone @attr.s(auto_attribs=True, init=False) class WriteRepositoryCredential(model.Model): """ Dynamically generated writeable type for RepositoryCredential removes properties: can, id, root_project_id, remote_url, is_configured Attributes: git_username: Git username for HTTPS authentication. git_password: (Write-Only) Git password for HTTPS authentication. ssh_public_key: Public deploy key for SSH authentication. """ git_username: Optional[str] = None git_password: Optional[str] = None ssh_public_key: Optional[str] = None def __init__( self, *, git_username: Optional[str] = None, git_password: Optional[str] = None, ssh_public_key: Optional[str] = None ): self.git_username = git_username self.git_password = git_password self.ssh_public_key = ssh_public_key @attr.s(auto_attribs=True, init=False) class WriteResultMakerWithIdVisConfigAndDynamicFields(model.Model): """ Dynamically generated writeable type for ResultMakerWithIdVisConfigAndDynamicFields removes properties: id, dynamic_fields, filterables, sorts, merge_result_id, total, query_id, sql_query_id, vis_config Attributes: query: """ query: Optional["WriteQuery"] = None def __init__(self, *, query: Optional["WriteQuery"] = None): self.query = query @attr.s(auto_attribs=True, init=False) class WriteRole(model.Model): """ Dynamically generated writeable type for Role removes properties: can, id, url, users_url Attributes: name: Name of Role permission_set: permission_set_id: (Write-Only) Id of permission set model_set: model_set_id: (Write-Only) Id of model set """ name: Optional[str] = None permission_set: Optional["WritePermissionSet"] = None permission_set_id: Optional[int] = None model_set: Optional["WriteModelSet"] = None model_set_id: Optional[int] = None def __init__( self, *, name: Optional[str] = None, permission_set: Optional["WritePermissionSet"] = None, permission_set_id: Optional[int] = None, model_set: Optional["WriteModelSet"] = None, model_set_id: Optional[int] = None ): self.name = name self.permission_set = permission_set self.permission_set_id = permission_set_id self.model_set = model_set self.model_set_id = model_set_id @attr.s(auto_attribs=True, init=False) class WriteSamlConfig(model.Model): """ Dynamically generated writeable type for SamlConfig removes properties: can, test_slug, modified_at, modified_by, default_new_user_roles, default_new_user_groups, groups, user_attributes, url Attributes: enabled: Enable/Disable Saml authentication for the server idp_cert: Identity Provider Certificate (provided by IdP) idp_url: Identity Provider Url (provided by IdP) idp_issuer: Identity Provider Issuer (provided by IdP) idp_audience: Identity Provider Audience (set in IdP config). Optional in Looker. Set this only if you want Looker to validate the audience value returned by the IdP. allowed_clock_drift: Count of seconds of clock drift to allow when validating timestamps of assertions. user_attribute_map_email: Name of user record attributes used to indicate email address field user_attribute_map_first_name: Name of user record attributes used to indicate first name user_attribute_map_last_name: Name of user record attributes used to indicate last name new_user_migration_types: Merge first-time saml login to existing user account by email addresses. When a user logs in for the first time via saml this option will connect this user into their existing account by finding the account with a matching email address by testing the given types of credentials for existing users. Otherwise a new user account will be created for the user. This list (if provided) must be a comma separated list of string like 'email,ldap,google' alternate_email_login_allowed: Allow alternate email-based login via '/login/email' for admins and for specified users with the 'login_special_email' permission. This option is useful as a fallback during ldap setup, if ldap config problems occur later, or if you need to support some users who are not in your ldap directory. Looker email/password logins are always disabled for regular users when ldap is enabled. default_new_user_role_ids: (Write-Only) Array of ids of roles that will be applied to new users the first time they login via Saml default_new_user_group_ids: (Write-Only) Array of ids of groups that will be applied to new users the first time they login via Saml set_roles_from_groups: Set user roles in Looker based on groups from Saml groups_attribute: Name of user record attributes used to indicate groups. Used when 'groups_finder_type' is set to 'grouped_attribute_values' groups_with_role_ids: (Read/Write) Array of mappings between Saml Groups and arrays of Looker Role ids auth_requires_role: Users will not be allowed to login at all unless a role for them is found in Saml if set to true user_attributes_with_ids: (Read/Write) Array of mappings between Saml User Attributes and arrays of Looker User Attribute ids groups_finder_type: Identifier for a strategy for how Looker will find groups in the SAML response. One of ['grouped_attribute_values', 'individual_attributes'] groups_member_value: Value for group attribute used to indicate membership. Used when 'groups_finder_type' is set to 'individual_attributes' bypass_login_page: Bypass the login page when user authentication is required. Redirect to IdP immediately instead. allow_normal_group_membership: Allow SAML auth'd users to be members of non-reflected Looker groups. If 'false', user will be removed from non-reflected groups on login. allow_roles_from_normal_groups: SAML auth'd users will inherit roles from non-reflected Looker groups. allow_direct_roles: Allows roles to be directly assigned to SAML auth'd users. """ enabled: Optional[bool] = None idp_cert: Optional[str] = None idp_url: Optional[str] = None idp_issuer: Optional[str] = None idp_audience: Optional[str] = None allowed_clock_drift: Optional[int] = None user_attribute_map_email: Optional[str] = None user_attribute_map_first_name: Optional[str] = None user_attribute_map_last_name: Optional[str] = None new_user_migration_types: Optional[str] = None alternate_email_login_allowed: Optional[bool] = None default_new_user_role_ids: Optional[Sequence[int]] = None default_new_user_group_ids: Optional[Sequence[int]] = None set_roles_from_groups: Optional[bool] = None groups_attribute: Optional[str] = None groups_with_role_ids: Optional[Sequence["SamlGroupWrite"]] = None auth_requires_role: Optional[bool] = None user_attributes_with_ids: Optional[Sequence["SamlUserAttributeWrite"]] = None groups_finder_type: Optional[str] = None groups_member_value: Optional[str] = None bypass_login_page: Optional[bool] = None allow_normal_group_membership: Optional[bool] = None allow_roles_from_normal_groups: Optional[bool] = None allow_direct_roles: Optional[bool] = None def __init__( self, *, enabled: Optional[bool] = None, idp_cert: Optional[str] = None, idp_url: Optional[str] = None, idp_issuer: Optional[str] = None, idp_audience: Optional[str] = None, allowed_clock_drift: Optional[int] = None, user_attribute_map_email: Optional[str] = None, user_attribute_map_first_name: Optional[str] = None, user_attribute_map_last_name: Optional[str] = None, new_user_migration_types: Optional[str] = None, alternate_email_login_allowed: Optional[bool] = None, default_new_user_role_ids: Optional[Sequence[int]] = None, default_new_user_group_ids: Optional[Sequence[int]] = None, set_roles_from_groups: Optional[bool] = None, groups_attribute: Optional[str] = None, groups_with_role_ids: Optional[Sequence["SamlGroupWrite"]] = None, auth_requires_role: Optional[bool] = None, user_attributes_with_ids: Optional[Sequence["SamlUserAttributeWrite"]] = None, groups_finder_type: Optional[str] = None, groups_member_value: Optional[str] = None, bypass_login_page: Optional[bool] = None, allow_normal_group_membership: Optional[bool] = None, allow_roles_from_normal_groups: Optional[bool] = None, allow_direct_roles: Optional[bool] = None ): self.enabled = enabled self.idp_cert = idp_cert self.idp_url = idp_url self.idp_issuer = idp_issuer self.idp_audience = idp_audience self.allowed_clock_drift = allowed_clock_drift self.user_attribute_map_email = user_attribute_map_email self.user_attribute_map_first_name = user_attribute_map_first_name self.user_attribute_map_last_name = user_attribute_map_last_name self.new_user_migration_types = new_user_migration_types self.alternate_email_login_allowed = alternate_email_login_allowed self.default_new_user_role_ids = default_new_user_role_ids self.default_new_user_group_ids = default_new_user_group_ids self.set_roles_from_groups = set_roles_from_groups self.groups_attribute = groups_attribute self.groups_with_role_ids = groups_with_role_ids self.auth_requires_role = auth_requires_role self.user_attributes_with_ids = user_attributes_with_ids self.groups_finder_type = groups_finder_type self.groups_member_value = groups_member_value self.bypass_login_page = bypass_login_page self.allow_normal_group_membership = allow_normal_group_membership self.allow_roles_from_normal_groups = allow_roles_from_normal_groups self.allow_direct_roles = allow_direct_roles @attr.s(auto_attribs=True, init=False) class WriteScheduledPlan(model.Model): """ Dynamically generated writeable type for ScheduledPlan removes properties: id, created_at, updated_at, title, user, next_run_at, last_run_at, can Attributes: name: Name of this scheduled plan user_id: User Id which owns this scheduled plan run_as_recipient: Whether schedule is run as recipient (only applicable for email recipients) enabled: Whether the ScheduledPlan is enabled look_id: Id of a look dashboard_id: Id of a dashboard lookml_dashboard_id: Id of a LookML dashboard filters_string: Query string to run look or dashboard with dashboard_filters: (DEPRECATED) Alias for filters_string field require_results: Delivery should occur if running the dashboard or look returns results require_no_results: Delivery should occur if the dashboard look does not return results require_change: Delivery should occur if data have changed since the last run send_all_results: Will run an unlimited query and send all results. crontab: Vixie-Style crontab specification when to run datagroup: Name of a datagroup; if specified will run when datagroup triggered (can't be used with cron string) timezone: Timezone for interpreting the specified crontab (default is Looker instance timezone) query_id: Query id scheduled_plan_destination: Scheduled plan destinations run_once: Whether the plan in question should only be run once (usually for testing) include_links: Whether links back to Looker should be included in this ScheduledPlan pdf_paper_size: The size of paper the PDF should be formatted to fit. Valid values are: "letter", "legal", "tabloid", "a0", "a1", "a2", "a3", "a4", "a5". pdf_landscape: Whether the PDF should be formatted for landscape orientation embed: Whether this schedule is in an embed context or not color_theme: Color scheme of the dashboard if applicable long_tables: Whether or not to expand table vis to full length inline_table_width: The pixel width at which we render the inline table visualizations """ name: Optional[str] = None user_id: Optional[int] = None run_as_recipient: Optional[bool] = None enabled: Optional[bool] = None look_id: Optional[int] = None dashboard_id: Optional[int] = None lookml_dashboard_id: Optional[str] = None filters_string: Optional[str] = None dashboard_filters: Optional[str] = None require_results: Optional[bool] = None require_no_results: Optional[bool] = None require_change: Optional[bool] = None send_all_results: Optional[bool] = None crontab: Optional[str] = None datagroup: Optional[str] = None timezone: Optional[str] = None query_id: Optional[str] = None scheduled_plan_destination: Optional[Sequence["ScheduledPlanDestination"]] = None run_once: Optional[bool] = None include_links: Optional[bool] = None pdf_paper_size: Optional[str] = None pdf_landscape: Optional[bool] = None embed: Optional[bool] = None color_theme: Optional[str] = None long_tables: Optional[bool] = None inline_table_width: Optional[int] = None def __init__( self, *, name: Optional[str] = None, user_id: Optional[int] = None, run_as_recipient: Optional[bool] = None, enabled: Optional[bool] = None, look_id: Optional[int] = None, dashboard_id: Optional[int] = None, lookml_dashboard_id: Optional[str] = None, filters_string: Optional[str] = None, dashboard_filters: Optional[str] = None, require_results: Optional[bool] = None, require_no_results: Optional[bool] = None, require_change: Optional[bool] = None, send_all_results: Optional[bool] = None, crontab: Optional[str] = None, datagroup: Optional[str] = None, timezone: Optional[str] = None, query_id: Optional[str] = None, scheduled_plan_destination: Optional[ Sequence["ScheduledPlanDestination"] ] = None, run_once: Optional[bool] = None, include_links: Optional[bool] = None, pdf_paper_size: Optional[str] = None, pdf_landscape: Optional[bool] = None, embed: Optional[bool] = None, color_theme: Optional[str] = None, long_tables: Optional[bool] = None, inline_table_width: Optional[int] = None ): self.name = name self.user_id = user_id self.run_as_recipient = run_as_recipient self.enabled = enabled self.look_id = look_id self.dashboard_id = dashboard_id self.lookml_dashboard_id = lookml_dashboard_id self.filters_string = filters_string self.dashboard_filters = dashboard_filters self.require_results = require_results self.require_no_results = require_no_results self.require_change = require_change self.send_all_results = send_all_results self.crontab = crontab self.datagroup = datagroup self.timezone = timezone self.query_id = query_id self.scheduled_plan_destination = scheduled_plan_destination self.run_once = run_once self.include_links = include_links self.pdf_paper_size = pdf_paper_size self.pdf_landscape = pdf_landscape self.embed = embed self.color_theme = color_theme self.long_tables = long_tables self.inline_table_width = inline_table_width @attr.s(auto_attribs=True, init=False) class WriteSessionConfig(model.Model): """ Dynamically generated writeable type for SessionConfig removes properties: can Attributes: allow_persistent_sessions: Allow users to have persistent sessions when they login session_minutes: Number of minutes for user sessions. Must be between 5 and 43200 unlimited_sessions_per_user: Allow users to have an unbounded number of concurrent sessions (otherwise, users will be limited to only one session at a time). use_inactivity_based_logout: Enforce session logout for sessions that are inactive for 15 minutes. track_session_location: Track location of session when user logs in. """ allow_persistent_sessions: Optional[bool] = None session_minutes: Optional[int] = None unlimited_sessions_per_user: Optional[bool] = None use_inactivity_based_logout: Optional[bool] = None track_session_location: Optional[bool] = None def __init__( self, *, allow_persistent_sessions: Optional[bool] = None, session_minutes: Optional[int] = None, unlimited_sessions_per_user: Optional[bool] = None, use_inactivity_based_logout: Optional[bool] = None, track_session_location: Optional[bool] = None ): self.allow_persistent_sessions = allow_persistent_sessions self.session_minutes = session_minutes self.unlimited_sessions_per_user = unlimited_sessions_per_user self.use_inactivity_based_logout = use_inactivity_based_logout self.track_session_location = track_session_location @attr.s(auto_attribs=True, init=False) class WriteSshServer(model.Model): """ Dynamically generated writeable type for SshServer removes properties: ssh_server_id, finger_print, sha_finger_print, public_key, status Attributes: ssh_server_name: The name to identify this SSH Server ssh_server_host: The hostname or ip address of the SSH Server ssh_server_port: The port to connect to on the SSH Server ssh_server_user: The username used to connect to the SSH Server """ ssh_server_name: Optional[str] = None ssh_server_host: Optional[str] = None ssh_server_port: Optional[int] = None ssh_server_user: Optional[str] = None def __init__( self, *, ssh_server_name: Optional[str] = None, ssh_server_host: Optional[str] = None, ssh_server_port: Optional[int] = None, ssh_server_user: Optional[str] = None ): self.ssh_server_name = ssh_server_name self.ssh_server_host = ssh_server_host self.ssh_server_port = ssh_server_port self.ssh_server_user = ssh_server_user @attr.s(auto_attribs=True, init=False) class WriteSshTunnel(model.Model): """ Dynamically generated writeable type for SshTunnel removes properties: tunnel_id, ssh_server_name, ssh_server_host, ssh_server_port, ssh_server_user, last_attempt, local_host_port, status Attributes: ssh_server_id: SSH Server ID database_host: Hostname or IP Address of the Database Server database_port: Port that the Database Server is listening on """ ssh_server_id: Optional[str] = None database_host: Optional[str] = None database_port: Optional[int] = None def __init__( self, *, ssh_server_id: Optional[str] = None, database_host: Optional[str] = None, database_port: Optional[int] = None ): self.ssh_server_id = ssh_server_id self.database_host = database_host self.database_port = database_port @attr.s(auto_attribs=True, init=False) class WriteTheme(model.Model): """ Dynamically generated writeable type for Theme removes properties: can, id Attributes: begin_at: Timestamp for when this theme becomes active. Null=always end_at: Timestamp for when this theme expires. Null=never name: Name of theme. Can only be alphanumeric and underscores. settings: """ begin_at: Optional[datetime.datetime] = None end_at: Optional[datetime.datetime] = None name: Optional[str] = None settings: Optional["ThemeSettings"] = None def __init__( self, *, begin_at: Optional[datetime.datetime] = None, end_at: Optional[datetime.datetime] = None, name: Optional[str] = None, settings: Optional["ThemeSettings"] = None ): self.begin_at = begin_at self.end_at = end_at self.name = name self.settings = settings @attr.s(auto_attribs=True, init=False) class WriteUser(model.Model): """ Dynamically generated writeable type for User removes properties: can, avatar_url, avatar_url_without_sizing, credentials_api3, credentials_embed, credentials_google, credentials_ldap, credentials_looker_openid, credentials_oidc, credentials_saml, credentials_totp, display_name, email, embed_group_space_id, group_ids, id, looker_versions, personal_folder_id, presumed_looker_employee, role_ids, sessions, verified_looker_employee, roles_externally_managed, allow_direct_roles, allow_normal_group_membership, allow_roles_from_normal_groups, url Attributes: credentials_email: first_name: First name home_folder_id: ID string for user's home folder is_disabled: Account has been disabled last_name: Last name locale: User's preferred locale. User locale takes precedence over Looker's system-wide default locale. Locale determines language of display strings and date and numeric formatting in API responses. Locale string must be a 2 letter language code or a combination of language code and region code: 'en' or 'en-US', for example. models_dir_validated: User's dev workspace has been checked for presence of applicable production projects ui_state: Per user dictionary of undocumented state information owned by the Looker UI. """ credentials_email: Optional["WriteCredentialsEmail"] = None first_name: Optional[str] = None home_folder_id: Optional[str] = None is_disabled: Optional[bool] = None last_name: Optional[str] = None locale: Optional[str] = None models_dir_validated: Optional[bool] = None ui_state: Optional[MutableMapping[str, Any]] = None def __init__( self, *, credentials_email: Optional["WriteCredentialsEmail"] = None, first_name: Optional[str] = None, home_folder_id: Optional[str] = None, is_disabled: Optional[bool] = None, last_name: Optional[str] = None, locale: Optional[str] = None, models_dir_validated: Optional[bool] = None, ui_state: Optional[MutableMapping[str, Any]] = None ): self.credentials_email = credentials_email self.first_name = first_name self.home_folder_id = home_folder_id self.is_disabled = is_disabled self.last_name = last_name self.locale = locale self.models_dir_validated = models_dir_validated self.ui_state = ui_state @attr.s(auto_attribs=True, init=False) class WriteUserAttribute(model.Model): """ Dynamically generated writeable type for UserAttribute removes properties: can, id, is_system, is_permanent Attributes: name: Name of user attribute label: Human-friendly label for user attribute type: Type of user attribute ("string", "number", "datetime", "yesno", "zipcode") default_value: Default value for when no value is set on the user value_is_hidden: If true, users will not be able to view values of this attribute user_can_view: Non-admin users can see the values of their attributes and use them in filters user_can_edit: Users can change the value of this attribute for themselves hidden_value_domain_whitelist: Destinations to which a hidden attribute may be sent. Once set, cannot be edited. """ name: Optional[str] = None label: Optional[str] = None type: Optional[str] = None default_value: Optional[str] = None value_is_hidden: Optional[bool] = None user_can_view: Optional[bool] = None user_can_edit: Optional[bool] = None hidden_value_domain_whitelist: Optional[str] = None def __init__( self, *, name: Optional[str] = None, label: Optional[str] = None, type: Optional[str] = None, default_value: Optional[str] = None, value_is_hidden: Optional[bool] = None, user_can_view: Optional[bool] = None, user_can_edit: Optional[bool] = None, hidden_value_domain_whitelist: Optional[str] = None ): self.name = name self.label = label self.type = type self.default_value = default_value self.value_is_hidden = value_is_hidden self.user_can_view = user_can_view self.user_can_edit = user_can_edit self.hidden_value_domain_whitelist = hidden_value_domain_whitelist @attr.s(auto_attribs=True, init=False) class WriteUserAttributeWithValue(model.Model): """ Dynamically generated writeable type for UserAttributeWithValue removes properties: can, name, label, rank, user_id, user_can_edit, value_is_hidden, user_attribute_id, source, hidden_value_domain_whitelist Attributes: value: Value of attribute for user """ value: Optional[str] = None def __init__(self, *, value: Optional[str] = None): self.value = value @attr.s(auto_attribs=True, init=False) class WriteWhitelabelConfiguration(model.Model): """ Dynamically generated writeable type for WhitelabelConfiguration removes properties: can, id, logo_url, favicon_url Attributes: logo_file: Customer logo image. Expected base64 encoded data (write-only) favicon_file: Custom favicon image. Expected base64 encoded data (write-only) default_title: Default page title show_help_menu: Boolean to toggle showing help menus show_docs: Boolean to toggle showing docs show_email_sub_options: Boolean to toggle showing email subscription options. allow_looker_mentions: Boolean to toggle mentions of Looker in emails allow_looker_links: Boolean to toggle links to Looker in emails custom_welcome_email_advanced: Allow subject line and email heading customization in customized emails” setup_mentions: Remove the word Looker from appearing in the account setup page alerts_logo: Remove Looker logo from Alerts alerts_links: Remove Looker links from Alerts folders_mentions: Remove Looker mentions in home folder page when you don’t have any items saved """ logo_file: Optional[str] = None favicon_file: Optional[str] = None default_title: Optional[str] = None show_help_menu: Optional[bool] = None show_docs: Optional[bool] = None show_email_sub_options: Optional[bool] = None allow_looker_mentions: Optional[bool] = None allow_looker_links: Optional[bool] = None custom_welcome_email_advanced: Optional[bool] = None setup_mentions: Optional[bool] = None alerts_logo: Optional[bool] = None alerts_links: Optional[bool] = None folders_mentions: Optional[bool] = None def __init__( self, *, logo_file: Optional[str] = None, favicon_file: Optional[str] = None, default_title: Optional[str] = None, show_help_menu: Optional[bool] = None, show_docs: Optional[bool] = None, show_email_sub_options: Optional[bool] = None, allow_looker_mentions: Optional[bool] = None, allow_looker_links: Optional[bool] = None, custom_welcome_email_advanced: Optional[bool] = None, setup_mentions: Optional[bool] = None, alerts_logo: Optional[bool] = None, alerts_links: Optional[bool] = None, folders_mentions: Optional[bool] = None ): self.logo_file = logo_file self.favicon_file = favicon_file self.default_title = default_title self.show_help_menu = show_help_menu self.show_docs = show_docs self.show_email_sub_options = show_email_sub_options self.allow_looker_mentions = allow_looker_mentions self.allow_looker_links = allow_looker_links self.custom_welcome_email_advanced = custom_welcome_email_advanced self.setup_mentions = setup_mentions self.alerts_logo = alerts_logo self.alerts_links = alerts_links self.folders_mentions = folders_mentions # The following cattrs structure hook registrations are a workaround # for https://github.com/Tinche/cattrs/pull/42 Once this issue is resolved # these calls will be removed. import functools # noqa:E402 forward_ref_structure_hook = functools.partial( sr.forward_ref_structure_hook, globals(), sr.converter40 ) translate_keys_structure_hook = functools.partial( sr.translate_keys_structure_hook, sr.converter40 ) sr.converter40.register_structure_hook( ForwardRef("AccessToken"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Align"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ApiSession"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ApiVersion"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ApiVersionElement"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("BackupConfiguration"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Board"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("BoardItem"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("BoardSection"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Category"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ColorCollection"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ColorStop"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ColumnSearch"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Command"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ConnectionFeatures"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentFavorite"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentMeta"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentMetaGroupUser"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidation"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidationAlert"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidationDashboard"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidationDashboardElement"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidationDashboardFilter"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidationError"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidationFolder"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidationLook"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidationLookMLDashboard"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidationLookMLDashboardElement"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidationScheduledPlan"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentValidatorError"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContentView"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ContinuousPalette"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CostEstimate"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CreateCostEstimate"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CreateDashboardFilter"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CreateDashboardRenderTask"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CreateFolder"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CreateQueryTask"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CredentialsApi3"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CredentialsEmail"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CredentialsEmbed"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CredentialsGoogle"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CredentialsLDAP"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CredentialsLookerOpenid"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CredentialsOIDC"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CredentialsSaml"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CredentialsTotp"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("CustomWelcomeEmail"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Dashboard"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DashboardAggregateTableLookml"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DashboardAppearance"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DashboardBase"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DashboardElement"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DashboardFilter"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DashboardLayout"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DashboardLayoutComponent"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DashboardLookml"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DataActionForm"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DataActionFormField"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DataActionFormSelectOption"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DataActionRequest"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DataActionResponse"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DataActionUserState"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Datagroup"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DBConnection"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DBConnectionBase"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DBConnectionOverride"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DBConnectionTestResult"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DelegateOauthTest"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DependencyStatus"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Dialect"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DialectInfo"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DialectInfoOptions"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DigestEmails"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DigestEmailSend"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("DiscretePalette"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("EmbedParams"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("EmbedSsoParams"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("EmbedUrlResponse"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Error"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("FillStyle"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Folder"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("FolderBase"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Format"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("GitApplicationServerHttpScheme"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("GitBranch"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("GitConnectionTest"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("GitConnectionTestResult"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("GitStatus"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Group"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("GroupHierarchy"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("GroupIdForGroupInclusion"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("GroupIdForGroupUserInclusion"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("GroupSearch"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("HomepageItem"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("HomepageSection"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ImportedProject"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Integration"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("IntegrationHub"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("IntegrationParam"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("IntegrationRequiredField"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("IntegrationTestResult"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("InternalHelpResources"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("InternalHelpResourcesContent"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LDAPConfig"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LDAPConfigTestIssue"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LDAPConfigTestResult"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LDAPGroupRead"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LDAPGroupWrite"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LDAPUser"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LDAPUserAttributeRead"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LDAPUserAttributeWrite"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LegacyFeature"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LinkedContentType"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Locale"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LocalizationSettings"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Look"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookBasic"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModel"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExplore"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreAccessFilter"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreAlias"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreAlwaysFilter"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreConditionallyFilter"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreError"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreField"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreFieldEnumeration"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreFieldMapLayer"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreFieldMeasureFilters"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreFieldset"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreFieldSqlCase"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreFieldTimeInterval"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreJoins"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( LookmlModelExploreJoins, # type: ignore translate_keys_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreSet"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelExploreSupportedMeasureType"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlModelNavExplore"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlTest"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookmlTestResult"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookModel"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookWithDashboards"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("LookWithQuery"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Manifest"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("MergeFields"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("MergeQuery"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("MergeQuerySourceQuery"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ModelFieldSuggestions"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ModelSet"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ModelsNotValidated"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Name"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("OauthClientApp"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("OIDCConfig"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("OIDCGroupRead"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("OIDCGroupWrite"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("OIDCUserAttributeRead"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("OIDCUserAttributeWrite"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("PasswordConfig"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Permission"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("PermissionSet"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("PermissionType"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Project"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ProjectError"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ProjectFile"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ProjectValidation"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ProjectValidationCache"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ProjectWorkspace"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("PullRequestMode"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Query"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("QueryTask"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("RenderTask"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("RepositoryCredential"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ResultFormat"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ResultMakerFilterables"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ResultMakerFilterablesListen"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ResultMakerWithIdVisConfigAndDynamicFields"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Role"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("RunningQueries"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SamlConfig"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SamlGroupRead"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SamlGroupWrite"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SamlMetadataParseResult"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SamlUserAttributeRead"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SamlUserAttributeWrite"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ScheduledPlan"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ScheduledPlanDestination"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Schema"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SchemaColumn"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SchemaColumns"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SchemaTable"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SchemaTables"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Session"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SessionConfig"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Snippet"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SqlQuery"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SqlQueryCreate"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SshPublicKey"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SshServer"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SshTunnel"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SupportedActionTypes"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SupportedDownloadSettings"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SupportedFormats"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SupportedFormattings"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("SupportedVisualizationFormattings"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Theme"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ThemeSettings"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Timezone"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("UpdateCommand"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("UpdateFolder"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("User"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("UserAttribute"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("UserAttributeFilterTypes"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("UserAttributeGroupValue"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("UserAttributeWithValue"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("UserLoginLockout"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("UserPublic"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ValidationError"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("ValidationErrorDetail"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WeekStartDay"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WelcomeEmailTest"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WhitelabelConfiguration"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("Workspace"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteApiSession"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteBackupConfiguration"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteBoard"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteBoardItem"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteBoardSection"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteColorCollection"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteCommand"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteContentFavorite"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteContentMeta"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteCreateDashboardFilter"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteCreateQueryTask"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteCredentialsEmail"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteCustomWelcomeEmail"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteDashboard"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteDashboardBase"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteDashboardElement"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteDashboardFilter"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteDashboardLayout"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteDashboardLayoutComponent"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteDatagroup"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteDBConnection"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteDBConnectionOverride"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteFolderBase"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteGitBranch"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteGroup"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteIntegration"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteIntegrationHub"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteInternalHelpResources"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteInternalHelpResourcesContent"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteLDAPConfig"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteLegacyFeature"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteLookBasic"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteLookmlModel"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteLookWithQuery"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteMergeQuery"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteModelSet"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteOauthClientApp"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteOIDCConfig"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WritePasswordConfig"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WritePermissionSet"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteProject"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteQuery"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteRepositoryCredential"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteResultMakerWithIdVisConfigAndDynamicFields"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteRole"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteSamlConfig"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteScheduledPlan"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteSessionConfig"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteSshServer"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteSshTunnel"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteTheme"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteUser"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteUserAttribute"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteUserAttributeWithValue"), # type: ignore forward_ref_structure_hook, # type:ignore ) sr.converter40.register_structure_hook( ForwardRef("WriteWhitelabelConfiguration"), # type: ignore forward_ref_structure_hook, # type:ignore )
looker-open-source/jk-sandbox
python/looker_sdk/sdk/api40/models.py
Python
mit
531,823
"""Locate the data files in the eggs to open""" "Special thanks to https://github.com/OrkoHunter/ping-me/tree/master/ping_me/data" import os import sys def we_are_frozen(): return hasattr(sys, "frozen") def modeule_path(): encoding = sys.getfilesystemencoding() if we_are_frozen(): return os.path.dirname(unicode(sys.executable, encoding)) return os.path.dirname(unicode(__file__, encoding))
TwistingTwists/sms
data/module_locator.py
Python
apache-2.0
418
# Copyright 2011-2013 James McCauley # # 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. # This file is loosely based on the discovery component in NOX. """ This module discovers the connectivity between OpenFlow switches by sending out LLDP packets. To be notified of this information, listen to LinkEvents on core.openflow_discovery. It's possible that some of this should be abstracted out into a generic Discovery module, or a Discovery superclass. """ from pox.lib.revent import * from pox.lib.recoco import Timer from pox.lib.util import dpid_to_str, str_to_bool from pox.core import core import pox.openflow.libopenflow_01 as of import pox.lib.packet as pkt import struct import time from collections import namedtuple from random import shuffle, random log = core.getLogger() class LLDPAndBroadcastSender (object): """ Sends out discovery packets """ SendItem = namedtuple("LLDPSenderItem", ('dpid','port_num','packet')) #NOTE: This class keeps the packets to send in a flat list, which makes # adding/removing them on switch join/leave or (especially) port # status changes relatively expensive. Could easily be improved. # Maximum times to run the timer per second _sends_per_sec = 15 def __init__ (self, send_cycle_time, ttl = 120): """ Initialize an LLDP packet sender send_cycle_time is the time (in seconds) that this sender will take to send every discovery packet. Thus, it should be the link timeout interval at most. ttl is the time (in seconds) for which a receiving LLDP agent should consider the rest of the data to be valid. We don't use this, but other LLDP agents might. Can't be 0 (this means revoke). """ # Packets remaining to be sent in this cycle self._this_cycle = [] # Packets we've already sent in this cycle self._next_cycle = [] # Packets to send in a batch self._send_chunk_size = 1 self._timer = None self._ttl = ttl self._send_cycle_time = send_cycle_time core.listen_to_dependencies(self) def _handle_openflow_PortStatus (self, event): """ Track changes to switch ports """ if event.added: self.add_port(event.dpid, event.port, event.ofp.desc.hw_addr) elif event.deleted: self.del_port(event.dpid, event.port) def _handle_openflow_ConnectionUp (self, event): self.del_switch(event.dpid, set_timer = False) ports = [(p.port_no, p.hw_addr) for p in event.ofp.ports] for port_num, port_addr in ports: self.add_port(event.dpid, port_num, port_addr, set_timer = False) self._set_timer() def _handle_openflow_ConnectionDown (self, event): self.del_switch(event.dpid) def del_switch (self, dpid, set_timer = True): self._this_cycle = [p for p in self._this_cycle if p.dpid != dpid] self._next_cycle = [p for p in self._next_cycle if p.dpid != dpid] if set_timer: self._set_timer() def del_port (self, dpid, port_num, set_timer = True): if port_num > of.OFPP_MAX: return self._this_cycle = [p for p in self._this_cycle if p.dpid != dpid or p.port_num != port_num] self._next_cycle = [p for p in self._next_cycle if p.dpid != dpid or p.port_num != port_num] if set_timer: self._set_timer() def add_port (self, dpid, port_num, port_addr, set_timer = True): if port_num > of.OFPP_MAX: return self.del_port(dpid, port_num, set_timer = False) self._next_cycle.append(LLDPAndBroadcastSender.SendItem(dpid, port_num, self.create_packet_out(dpid, port_num, port_addr, 'lldp'))) self._next_cycle.append(LLDPAndBroadcastSender.SendItem(dpid, port_num, self.create_packet_out(dpid, port_num, port_addr, 'broadcast'))) if set_timer: self._set_timer() def _set_timer (self): if self._timer: self._timer.cancel() self._timer = None num_packets = len(self._this_cycle) + len(self._next_cycle) if num_packets == 0: return self._send_chunk_size = 1 # One at a time interval = self._send_cycle_time / float(num_packets) if interval < 1.0 / self._sends_per_sec: # Would require too many sends per sec -- send more than one at once interval = 1.0 / self._sends_per_sec chunk = float(num_packets) / self._send_cycle_time / self._sends_per_sec self._send_chunk_size = chunk self._timer = Timer(interval, self._timer_handler, recurring=True) def _timer_handler (self): """ Called by a timer to actually send packets. Picks the first packet off this cycle's list, sends it, and then puts it on the next-cycle list. When this cycle's list is empty, starts the next cycle. """ num = int(self._send_chunk_size) fpart = self._send_chunk_size - num if random() < fpart: num += 1 for _ in range(num): if len(self._this_cycle) == 0: self._this_cycle = self._next_cycle self._next_cycle = [] #shuffle(self._this_cycle) item = self._this_cycle.pop(0) self._next_cycle.append(item) core.openflow.sendToDPID(item.dpid, item.packet) def create_packet_out (self, dpid, port_num, port_addr,packet_type): """ Create an ofp_packet_out containing a discovery packet """ if packet_type == 'lldp': eth = self._create_discovery_packet(dpid, port_num, port_addr, self._ttl) elif packet_type == 'broadcast': eth = self._create_broadcast_discovery_packet(dpid, port_num, port_addr, 120) else: return None log.warning('Not the broadcast or the lldp') po = of.ofp_packet_out(action = of.ofp_action_output(port=port_num)) po.data = eth.pack() return po.pack() @staticmethod def _create_discovery_packet (dpid, port_num, port_addr, ttl): """ Build discovery packet """ chassis_id = pkt.chassis_id(subtype=pkt.chassis_id.SUB_LOCAL) chassis_id.id = bytes('dpid:' + hex(long(dpid))[2:-1]) # Maybe this should be a MAC. But a MAC of what? Local port, maybe? port_id = pkt.port_id(subtype=pkt.port_id.SUB_PORT, id=str(port_num)) ttl = pkt.ttl(ttl = ttl) sysdesc = pkt.system_description() sysdesc.payload = bytes('dpid:' + hex(long(dpid))[2:-1]) discovery_packet = pkt.lldp() discovery_packet.tlvs.append(chassis_id) discovery_packet.tlvs.append(port_id) discovery_packet.tlvs.append(ttl) discovery_packet.tlvs.append(sysdesc) discovery_packet.tlvs.append(pkt.end_tlv()) eth = pkt.ethernet(type=pkt.ethernet.LLDP_TYPE) eth.src = port_addr eth.dst = pkt.ETHERNET.LLDP_MULTICAST eth.payload = discovery_packet return eth @staticmethod def _create_broadcast_discovery_packet (dpid, port_num, port_addr, ttl): chassis_id = pkt.chassis_id(subtype=pkt.chassis_id.SUB_LOCAL) chassis_id.id = bytes('dpid:' + hex(long(dpid))[2:-1]) # Maybe this should be a MAC. But a MAC of what? Local port, maybe? port_id = pkt.port_id(subtype=pkt.port_id.SUB_PORT, id=str(port_num)) ttl = pkt.ttl(ttl = ttl) sysdesc = pkt.system_description() sysdesc.payload = bytes('dpid:' + hex(long(dpid))[2:-1]) discovery_packet = pkt.lldp() discovery_packet.tlvs.append(chassis_id) discovery_packet.tlvs.append(port_id) discovery_packet.tlvs.append(ttl) discovery_packet.tlvs.append(sysdesc) discovery_packet.tlvs.append(pkt.end_tlv()) eth = pkt.ethernet(type=pkt.ethernet.LLDP_TYPE) eth.src = port_addr eth.dst = pkt.ETHERNET.ETHER_BROADCAST eth.payload = discovery_packet return eth class LinkEvent (Event): """ Link up/down event """ def __init__ (self, add, link, event = None): self.link = link self.added = add self.removed = not add self.event = event # PacketIn which caused this, if any def port_for_dpid (self, dpid): if self.link.dpid1 == dpid: return self.link.port1 if self.link.dpid2 == dpid: return self.link.port2 return None class LinkBase(object): def __init__(self,dpid1,port1,dpid2,port2,link_type,available): self.dpid1 = dpid1 self.port1 = port1 self.dpid2 = dpid2 self.port2 = port2 self.link_type = link_type self.available = available class Link (LinkBase): @property def uni (self): """ Returns a "unidirectional" version of this link The unidirectional versions of symmetric keys will be equal """ pairs = list(self.end) pairs.sort() return Link(pairs[0][0],pairs[0][1],pairs[1][0],pairs[1][1]) @property def end (self): return ((self.dpid1,self.port1),(self.dpid2,self.port2)) def __str__ (self): return "%s.%s -> %s.%s and link_type is %s, available is %s" %(self.dpid1, self.port1, self.dpid2, self.port2,self.link_type,self.available) def __repr__ (self): return "Link(dpid1=%s,port1=%s, dpid2=%s,port2=%s,type=%s,available=%s)" % (self.dpid1, self.port1, self.dpid2, self.port2,self.link_type,self.available) def __eq__(self, other): return other.dpid1 == self.dpid1 and other.dpid2 == self.dpid2 and \ other.port1 == self.port1 and other.port2 == self.port2 def __hash__(self): return self.dpid1 + self.dpid2 + self.port1 + self.port2 class Discovery (EventMixin): """ Component that attempts to discover network toplogy. Sends out specially-crafted LLDP packets, and monitors their arrival. """ _flow_priority = 65000 # Priority of LLDP-catching flow (if any) _link_timeout = 10 # How long until we consider a link dead _timeout_check_period = 5 # How often to check for timeouts _eventMixin_events = set([ LinkEvent, ]) _core_name = "openflow_discovery" # we want to be core.openflow_discovery Link = Link def __init__ (self, install_flow = True, explicit_drop = True, link_timeout = None, eat_early_packets = False): self._eat_early_packets = eat_early_packets self._explicit_drop = explicit_drop self._install_flow = install_flow if link_timeout: self._link_timeout = link_timeout self.adjacency = {} # From Link to time.time() stamp self.link_attribute = {} self._sender = LLDPAndBroadcastSender(self.send_cycle_time) # Listen with a high priority (mostly so we get PacketIns early) core.listen_to_dependencies(self, listen_args={'openflow':{'priority':0xffffffff}}) Timer(self._timeout_check_period, self._expire_links, recurring=True) @property def send_cycle_time (self): return self._link_timeout / 2.0 def install_flow (self, con_or_dpid, priority = None): if priority is None: priority = self._flow_priority if isinstance(con_or_dpid, (int,long)): con = core.openflow.connections.get(con_or_dpid) if con is None: log.warn("Can't install flow for %s", dpid_to_str(con_or_dpid)) return False else: con = con_or_dpid match = of.ofp_match(dl_type = pkt.ethernet.LLDP_TYPE, dl_dst = pkt.ETHERNET.LLDP_MULTICAST) msg = of.ofp_flow_mod() msg.priority = priority msg.match = match msg.actions.append(of.ofp_action_output(port = of.OFPP_CONTROLLER)) con.send(msg) return True def _handle_openflow_ConnectionUp (self, event): if self._install_flow: # Make sure we get appropriate traffic log.debug("Installing flow for %s", dpid_to_str(event.dpid)) self.install_flow(event.connection) def _handle_openflow_ConnectionDown (self, event): # Delete all links on this switch self._delete_links([link for link in self.adjacency if link.dpid1 == event.dpid or link.dpid2 == event.dpid]) def _expire_links (self): """ Remove apparently dead links """ now = time.time() expired = [link for link,timestamp in self.adjacency.iteritems() if timestamp + self._link_timeout < now] if expired: for link in expired: log.info('link timeout: %s', link) self._delete_links(expired) def _handle_openflow_PacketIn (self, event): """ Receive and process LLDP packets """ packet = event.parsed if (packet.effective_ethertype != pkt.ethernet.LLDP_TYPE or (packet.dst != pkt.ETHERNET.LLDP_MULTICAST and packet.dst != pkt.ETHERNET.ETHER_BROADCAST)): if not self._eat_early_packets: return if not event.connection.connect_time: return enable_time = time.time() - self.send_cycle_time - 1 if event.connection.connect_time > enable_time: return EventHalt return if (packet.effective_ethertype == pkt.ethernet.LLDP_TYPE and packet.dst == pkt.ETHERNET.LLDP_MULTICAST or pkt.ETHERNET.ETHER_BROADCAST): link_type = 'lldp' if packet.dst == pkt.ETHERNET.LLDP_MULTICAST else 'broadcast' if self._explicit_drop: if event.ofp.buffer_id is not None: log.debug("Dropping LLDP packet %i", event.ofp.buffer_id) msg = of.ofp_packet_out() msg.buffer_id = event.ofp.buffer_id msg.in_port = event.port event.connection.send(msg) lldph = packet.find(pkt.lldp) if lldph is None or not lldph.parsed: log.error("LLDP packet could not be parsed") return EventHalt if len(lldph.tlvs) < 3: log.error("LLDP packet without required three TLVs") return EventHalt if lldph.tlvs[0].tlv_type != pkt.lldp.CHASSIS_ID_TLV: log.error("LLDP packet TLV 1 not CHASSIS_ID") return EventHalt if lldph.tlvs[1].tlv_type != pkt.lldp.PORT_ID_TLV: log.error("LLDP packet TLV 2 not PORT_ID") return EventHalt if lldph.tlvs[2].tlv_type != pkt.lldp.TTL_TLV: log.error("LLDP packet TLV 3 not TTL") return EventHalt def lookInSysDesc (): r = None for t in lldph.tlvs[3:]: if t.tlv_type == pkt.lldp.SYSTEM_DESC_TLV: # This is our favored way... for line in t.payload.split('\n'): if line.startswith('dpid:'): try: return int(line[5:], 16) except: pass if len(t.payload) == 8: # Maybe it's a FlowVisor LLDP... # Do these still exist? try: return struct.unpack("!Q", t.payload)[0] except: pass return None originatorDPID = lookInSysDesc() if originatorDPID == None: # We'll look in the CHASSIS ID if lldph.tlvs[0].subtype == pkt.chassis_id.SUB_LOCAL: if lldph.tlvs[0].id.startswith('dpid:'): # This is how NOX does it at the time of writing try: originatorDPID = int(lldph.tlvs[0].id[5:], 16) except: pass if originatorDPID == None: if lldph.tlvs[0].subtype == pkt.chassis_id.SUB_MAC: # Last ditch effort -- we'll hope the DPID was small enough # to fit into an ethernet address if len(lldph.tlvs[0].id) == 6: try: s = lldph.tlvs[0].id originatorDPID = struct.unpack("!Q",'\x00\x00' + s)[0] except: pass if originatorDPID == None: log.warning("Couldn't find a DPID in the LLDP packet") return EventHalt if originatorDPID not in core.openflow.connections: log.info('Received LLDP packet from unknown switch') return EventHalt # Get port number from port TLV if lldph.tlvs[1].subtype != pkt.port_id.SUB_PORT: log.warning("Thought we found a DPID, but packet didn't have a port") return EventHalt originatorPort = None if lldph.tlvs[1].id.isdigit(): # We expect it to be a decimal value originatorPort = int(lldph.tlvs[1].id) elif len(lldph.tlvs[1].id) == 2: # Maybe it's a 16 bit port number... try: originatorPort = struct.unpack("!H", lldph.tlvs[1].id)[0] except: pass if originatorPort is None: log.warning("Thought we found a DPID, but port number didn't " + "make sense") return EventHalt if (event.dpid, event.port) == (originatorDPID, originatorPort): log.warning("Port received its own LLDP packet; ignoring") return EventHalt link = Discovery.Link(originatorDPID, originatorPort, event.dpid, event.port,link_type, available=True) if link not in self.adjacency: self.adjacency[link] = time.time() self.link_attribute[link] = link log.info('link detected: %s and the type is %s', link, link.link_type) self.raiseEventNoErrors(LinkEvent, True, link, event) else: if link.link_type is self.link_attribute[link].link_type: self.adjacency[link] = time.time() elif link.link_type is 'broadcast' and self.link_attribute[link].link_type is 'lldp': pass elif link.link_type is 'lldp' and self.link_attribute[link].link_type is 'broadcast': self.link_attribute[link] = link self.raiseEventNoErrors(LinkEvent,False,link) del self.adjacency[link] self.adjacency[link] = time.time() self.raiseEventNoErrors(LinkEvent,True,link,event) # Just update timestam return EventHalt # Probably nobody else needs this event def _delete_links (self, links): for link in links: self.raiseEventNoErrors(LinkEvent, False, link) for link in links: self.adjacency.pop(link, None) def is_edge_port (self, dpid, port): """ Return True if given port does not connect to another switch """ for link in self.adjacency: if link.dpid1 == dpid and link.port1 == port: return False if link.dpid2 == dpid and link.port2 == port: return False return True def _is_broadcast_port (self,dpid,port): for link in self.adjacency: if link.dpid1 == dpid and link.port1 == port and link.link_type =='broadcast': return True if link.dpid2 == dpid and link.port2 == port and link.link_type == 'broadcast': return True return False def launch (no_flow = False, explicit_drop = True, link_timeout = None, eat_early_packets = False): explicit_drop = str_to_bool(explicit_drop) eat_early_packets = str_to_bool(eat_early_packets) install_flow = not str_to_bool(no_flow) if link_timeout: link_timeout = int(link_timeout) core.registerNew(Discovery, explicit_drop=explicit_drop, install_flow=install_flow, link_timeout=link_timeout, eat_early_packets=eat_early_packets)
timhuanggithub/MyPOX
pox/openflow/discovery.py
Python
apache-2.0
19,024
# coding:utf-8 import logging import numpy as np from scipy.linalg import svd from mla.base import BaseEstimator np.random.seed(1000) class PCA(BaseEstimator): y_required = False def __init__(self, n_components, solver="svd"): """Principal component analysis (PCA) implementation. Transforms a dataset of possibly correlated values into n linearly uncorrelated components. The components are ordered such that the first has the largest possible variance and each following component as the largest possible variance given the previous components. This causes the early components to contain most of the variability in the dataset. Parameters ---------- n_components : int solver : str, default 'svd' {'svd', 'eigen'} """ self.solver = solver self.n_components = n_components self.components = None self.mean = None def fit(self, X, y=None): self.mean = np.mean(X, axis=0) self._decompose(X) def _decompose(self, X): # Mean centering X = X.copy() X -= self.mean if self.solver == "svd": _, s, Vh = svd(X, full_matrices=True) elif self.solver == "eigen": s, Vh = np.linalg.eig(np.cov(X.T)) Vh = Vh.T s_squared = s ** 2 variance_ratio = s_squared / s_squared.sum() logging.info("Explained variance ratio: %s" % (variance_ratio[0: self.n_components])) self.components = Vh[0: self.n_components] def transform(self, X): X = X.copy() X -= self.mean return np.dot(X, self.components.T) def _predict(self, X=None): return self.transform(X)
rushter/MLAlgorithms
mla/pca.py
Python
mit
1,758
# -*- coding: utf-8 -*- import itertools from lxml import html from lxml import etree from odm.catalogs.utils import metautils from odm.catalogs.CatalogReader import CatalogReader verbose = False rooturl = u'http://www.bochum.de' url = u'/opendata/datensaetze/nav/75F9RD294BOLD' def findfilesanddata(html): # Start to get the data for each dataset tables = html.xpath('//table') # Tables with captions contain info, tables with no caption and no border contain the files datatables = [] filetables = [] for table in tables: # We append the text because for some reason the objects are weird and contain data from elsewhere in the page if len(table.xpath('caption')) == 1: datatables.append(etree.tostring(table)) if (verbose): print 'Found table of data' if len(table.xpath('caption')) == 0 and len(table.xpath('@border')) > 0 and table.xpath('@border')[0] == '0': if (verbose): print 'Found table of files' filetables.append(etree.tostring(table)) return datatables, filetables def get_datasets(data): # Get the number of datasets datasets = data.xpath('//body//h2/text()') # Maybe it's there, maybe it isn't if 'Inhaltsverzeichnis' in datasets: datasets.remove('Inhaltsverzeichnis') return datasets def get_categorie_urls(): if (verbose): print u'Reading page of categories: ' + rooturl + url data = html.parse(rooturl + url) # Get the first spanned URL in each cell. There must be a way to do this all in one xpath query cat_sites = data.xpath('//body//table//td') cat_urls = [] for cat_site in cat_sites: cat_site_url = cat_site.xpath('span[1]/a/@href')[0] if 'neueste-datensaetze' not in cat_site_url: cat_urls.append(cat_site_url) if (verbose): print str(len(cat_urls)) + ' categories found' return cat_urls def get_categorie_content(category_link): # Get the page allrecords = [] parser = etree.HTMLParser(encoding='utf-8') data = etree.parse(rooturl + category_link, parser) # Get the category category = data.xpath('/html/body/div/div[5]/div/div[1]//h1/text()')[0].strip() # category = urllib.unquote(category).decode('utf8') if (verbose): print 'Category: ' + ascii_only(category) datasets = get_datasets(data) numdatasets = len(datasets) if (verbose): print 'There are ' + str(numdatasets) + ' datasets' # Now get the html for each one. This is painful. # The bit of html concerning the datasets: corehtml = data.xpath('//div[@id=\'ContentBlock\']')[0] # First try to split by the horizontal rules. This usually works, but not always datasetparts = etree.tostring(corehtml).split('<hr id="hr') if (verbose): print 'Found ' + str(len(datasetparts)) + ' datasets by splitting by hr elements with ids' if len(datasetparts) != numdatasets: if (verbose): print 'This doesn\'t match. Trying with links to TOC' # If there is TOC, this works. There isn\'t always one. datasetparts = etree.tostring(corehtml).split('nach oben') del datasetparts[len(datasetparts) - 1] for index in range(0, len(datasetparts)): datasetparts[index] = datasetparts[index] + '</a>' if (verbose): print 'Found ' + str(len(datasetparts)) + ' datasets by splitting by links to TOC' if len(datasetparts) != numdatasets: if (verbose): print 'Well, that didn\'t work either. Giving up' print 'Exciting because of a serious error - turn on verbose in the code to find out what dataset is causing the problem' exit() else: if numdatasets > 1: for index in range(1, len(datasetparts)): # That split makes for bad HTML. Make it better. datasetparts[index] = '<hr id="hr' + datasetparts[index] count = 1 for datasetpart in datasetparts: data = etree.HTML(datasetpart) record = {} record['city'] = 'bochum' record['categories'] = [] record['categories'].append(category) datasets = get_datasets(data) record['title'] = datasets[0] if (verbose): print 'Parsing dataset ' + ascii_only(record['title']) if 'noch im Aufbau' in record['title']: # Nothing to see here if (verbose): print 'Empty category' continue record['url'] = rooturl + category_link + '#par' + str(count) count += 1 datatables, filetables = findfilesanddata(data) if len(datatables) == 0: if (verbose): print 'This record contains no data... checking for link to another page...' checkforsubpage = data.xpath('//span//a') for link in checkforsubpage: if (verbose): print etree.tostring(link) if len(link.xpath('text()')) > 0 and u'zu den Daten' in link.xpath('text()')[0]: testurl = link.xpath('@href')[0] if (verbose): print 'Following/updating URL: ' + rooturl + testurl record['url'] = rooturl + testurl datatables, filetables = findfilesanddata(html.parse(rooturl + testurl)) # get the data on the files, and get each link in it record['filelist'] = [] for table in filetables: record['filelist'].extend([(rooturl + x) for x in etree.HTML(table).xpath('//a/@href')]) record['formats'] = set() record['spatial'] = False for file in record['filelist']: formatarray = file.split('/')[-1].split('.') format = 'Unknown' if len(formatarray)>1: format = formatarray[1].upper().split('?')[0] elif 'WMS' in formatarray[0]: format = 'WMS' elif 'WFS' in formatarray[0]: format = 'WFS' record['formats'].add(format) if (format.upper() in metautils.geoformats): record['spatial'] = True record['formats'] = list(record['formats']) if len(datatables) > 1: if (verbose): print 'ERROR: More than one data table' print 'Exciting because of a serious error - turn on verbose in the code to find out what dataset is causing the problem' exit() elif len(datatables) == 0: if (verbose): print 'ERROR: No data table' print 'Exciting because of a serious error - turn on verbose in the code to find out what dataset is causing the problem' exit() # parse the data table by row if (verbose): print 'Reading datatable...' rowelements = etree.HTML(datatables[0]).xpath('//tr') for row in rowelements: if len(row.xpath('td[1]/text()')) == 0: continue key = row.xpath('td[1]/text()')[0] if (verbose): print ascii_only(key) if len(row.xpath('td[2]/text()')) != 0: val = row.xpath('td[2]/text()')[0] elif len(row.xpath('td[2]//a')) != 0: val = row.xpath('td[2]//a/text()')[0] else: if (verbose): print 'ERROR: Missing value' print 'Exciting because of a serious error - turn on verbose in the code to find out what dataset is causing the problem' exit() if (verbose): print ascii_only('Parsing key ' + key.replace(':', '') + ' with value ' + val) if u'veröffentlicht' in key: record['publisher'] = val elif u'geändert' in key: record['temporalextent'] = val.split(' ')[2] elif u'Lizenz' in key: record['licenseshort'] = metautils.long_license_to_short(val) record['open'] = metautils.isopen(record['licenseshort']) elif u'Webseite' in key: record['website'] = row.xpath('td[2]//a/@href')[0] # keep, as 'original' metadata if 'http://' not in record['website']: record['website'] = rooturl + record['website'] elif u'Kontakt' in key: record['contact'] = rooturl + row.xpath('td[2]//a/@href')[0] allrecords.append(record) return allrecords def remove_multiples(allrecords): # Find things in multiple categories recordsdict = {} for record in allrecords: if record['title'] not in recordsdict: recordsdict[record['title']] = record else: if (verbose): print ascii_only(record['title']) + ' in ' + ascii_only(str(record['categories'])) + ' is already in ' + ascii_only(str(recordsdict[record['title']]['categories'])) + '. Transferring category.' recordsdict[record['title']]['categories'].extend(record['categories']) return recordsdict.values() def ascii_only(text): return ''.join(i for i in text if ord(i)<128) + ' (ascii only)' class BochumReader(CatalogReader): def info(self): return { 'name': 'bochum_harvester', 'title': u'bochum.de', 'description': '' } def gather(self): cat_urls = get_categorie_urls() cat_recs = map(get_categorie_content, cat_urls) all_recs = list(itertools.chain(*cat_recs)) all_recs = remove_multiples(all_recs) return all_recs # Everthing is done in the gather stage right now, # since I don't know, the right method to prevent adding duplicates, # at this point def fetch(self, d): return d def import_data(self, record): # Expand categories record['originating_portal'] = "bochum.de/opendata" record['metadata'] = record.copy() record['source'] = 'd' record['description'] = None record['costs'] = None record['metadata_xml'] = None record['accepted'] = True odm_cats = map(lambda x: metautils.govDataLongToODM(x, checkAll=True)[0], record['categories']) if len(odm_cats) > 0: record['categories'] = odm_cats else: record['categories'] = ['Noch nicht kategorisiert'] return record
mattfullerton/odm-catalogreaders
odm/catalogs/portals/bochum.py
Python
mit
10,194
import sys import _rawffi from _ctypes.basics import _CData, _CDataMeta, keepalive_key,\ store_reference, ensure_objects, CArgObject from _ctypes.array import Array from _ctypes.pointer import _Pointer import inspect def names_and_fields(self, _fields_, superclass, anonymous_fields=None): # _fields_: list of (name, ctype, [optional_bitfield]) if isinstance(_fields_, tuple): _fields_ = list(_fields_) for f in _fields_: tp = f[1] if not isinstance(tp, _CDataMeta): raise TypeError("Expected CData subclass, got %s" % (tp,)) if isinstance(tp, StructOrUnionMeta): tp._make_final() if len(f) == 3: if (not hasattr(tp, '_type_') or not isinstance(tp._type_, str) or tp._type_ not in "iIhHbBlLqQ"): #XXX: are those all types? # we just dont get the type name # in the interp level thrown TypeError # from rawffi if there are more raise TypeError('bit fields not allowed for type ' + tp.__name__) all_fields = [] for cls in reversed(inspect.getmro(superclass)): # The first field comes from the most base class all_fields.extend(getattr(cls, '_fields_', [])) all_fields.extend(_fields_) names = [f[0] for f in all_fields] rawfields = [] for f in all_fields: if len(f) > 2: rawfields.append((f[0], f[1]._ffishape_, f[2])) else: rawfields.append((f[0], f[1]._ffishape_)) _set_shape(self, rawfields, self._is_union) fields = {} for i, field in enumerate(all_fields): name = field[0] value = field[1] is_bitfield = (len(field) == 3) fields[name] = Field(name, self._ffistruct_.fieldoffset(name), self._ffistruct_.fieldsize(name), value, i, is_bitfield) if anonymous_fields: resnames = [] for i, field in enumerate(all_fields): name = field[0] value = field[1] is_bitfield = (len(field) == 3) startpos = self._ffistruct_.fieldoffset(name) if name in anonymous_fields: for subname in value._names_: resnames.append(subname) subfield = getattr(value, subname) relpos = startpos + subfield.offset subvalue = subfield.ctype fields[subname] = Field(subname, relpos, subvalue._sizeofinstances(), subvalue, i, is_bitfield, inside_anon_field=fields[name]) else: resnames.append(name) names = resnames self._names_ = names for name, field in fields.items(): setattr(self, name, field) class Field(object): def __init__(self, name, offset, size, ctype, num, is_bitfield, inside_anon_field=None): self.__dict__['name'] = name self.__dict__['offset'] = offset self.__dict__['size'] = size self.__dict__['ctype'] = ctype self.__dict__['num'] = num self.__dict__['is_bitfield'] = is_bitfield self.__dict__['inside_anon_field'] = inside_anon_field def __setattr__(self, name, value): raise AttributeError(name) def __repr__(self): return "<Field '%s' offset=%d size=%d>" % (self.name, self.offset, self.size) def __get__(self, obj, cls=None): if obj is None: return self if self.inside_anon_field is not None: return getattr(self.inside_anon_field.__get__(obj), self.name) if self.is_bitfield: # bitfield member, use direct access return obj._buffer.__getattr__(self.name) else: fieldtype = self.ctype offset = self.num suba = obj._subarray(fieldtype, self.name) return fieldtype._CData_output(suba, obj, offset) def __set__(self, obj, value): if self.inside_anon_field is not None: setattr(self.inside_anon_field.__get__(obj), self.name, value) return fieldtype = self.ctype cobj = fieldtype.from_param(value) key = keepalive_key(self.num) if issubclass(fieldtype, _Pointer) and isinstance(cobj, Array): # if our value is an Array we need the whole thing alive store_reference(obj, key, cobj) elif ensure_objects(cobj) is not None: store_reference(obj, key, cobj._objects) arg = cobj._get_buffer_value() if fieldtype._fficompositesize_ is not None: from ctypes import memmove dest = obj._buffer.fieldaddress(self.name) memmove(dest, arg, fieldtype._fficompositesize_) else: obj._buffer.__setattr__(self.name, arg) def _set_shape(tp, rawfields, is_union=False): tp._ffistruct_ = _rawffi.Structure(rawfields, is_union, getattr(tp, '_pack_', 0)) tp._ffiargshape_ = tp._ffishape_ = (tp._ffistruct_, 1) tp._fficompositesize_ = tp._ffistruct_.size def struct_setattr(self, name, value): if name == '_fields_': if self.__dict__.get('_fields_', None) is not None: raise AttributeError("_fields_ is final") if self in [f[1] for f in value]: raise AttributeError("Structure or union cannot contain itself") names_and_fields( self, value, self.__bases__[0], self.__dict__.get('_anonymous_', None)) _CDataMeta.__setattr__(self, '_fields_', value) return _CDataMeta.__setattr__(self, name, value) class StructOrUnionMeta(_CDataMeta): def __new__(self, name, cls, typedict): res = type.__new__(self, name, cls, typedict) if "_abstract_" in typedict: return res cls = cls or (object,) if isinstance(cls[0], StructOrUnionMeta): cls[0]._make_final() if '_pack_' in typedict: if not 0 <= typedict['_pack_'] < 2**31: raise ValueError("_pack_ must be a non-negative integer") if '_fields_' in typedict: if not hasattr(typedict.get('_anonymous_', []), '__iter__'): raise TypeError("Anonymous field must be iterable") for item in typedict.get('_anonymous_', []): if item not in dict(typedict['_fields_']): raise AttributeError("Anonymous field not found") names_and_fields( res, typedict['_fields_'], cls[0], typedict.get('_anonymous_', None)) return res def _make_final(self): if self is StructOrUnion: return if '_fields_' not in self.__dict__: self._fields_ = [] # As a side-effet, this also sets the ffishape. __setattr__ = struct_setattr def from_address(self, address): instance = StructOrUnion.__new__(self) if isinstance(address, _rawffi.StructureInstance): address = address.buffer # fix the address: turn it into as unsigned, in case it is negative address = address & (sys.maxsize * 2 + 1) instance.__dict__['_buffer'] = self._ffistruct_.fromaddress(address) return instance def _sizeofinstances(self): if not hasattr(self, '_ffistruct_'): return 0 return self._ffistruct_.size def _alignmentofinstances(self): return self._ffistruct_.alignment def from_param(self, value): if isinstance(value, tuple): try: value = self(*value) except Exception as e: # XXX CPython does not even respect the exception type raise RuntimeError("(%s) %s: %s" % (self.__name__, type(e), e)) return _CDataMeta.from_param(self, value) def _CData_output(self, resarray, base=None, index=-1): res = StructOrUnion.__new__(self) ffistruct = self._ffistruct_.fromaddress(resarray.buffer) res.__dict__['_buffer'] = ffistruct res.__dict__['_base'] = base res.__dict__['_index'] = index return res def _CData_retval(self, resbuffer): res = StructOrUnion.__new__(self) res.__dict__['_buffer'] = resbuffer res.__dict__['_base'] = None res.__dict__['_index'] = -1 return res class StructOrUnion(_CData, metaclass=StructOrUnionMeta): def __new__(cls, *args, **kwds): self = super(_CData, cls).__new__(cls, *args, **kwds) if '_abstract_' in cls.__dict__: raise TypeError("abstract class") if hasattr(cls, '_ffistruct_'): self.__dict__['_buffer'] = self._ffistruct_(autofree=True) return self def __init__(self, *args, **kwds): type(self)._make_final() if len(args) > len(self._names_): raise TypeError("too many initializers") for name, arg in zip(self._names_, args): if name in kwds: raise TypeError("duplicate value for argument %r" % ( name,)) self.__setattr__(name, arg) for name, arg in kwds.items(): self.__setattr__(name, arg) def _subarray(self, fieldtype, name): """Return a _rawffi array of length 1 whose address is the same as the address of the field 'name' of self.""" address = self._buffer.fieldaddress(name) A = _rawffi.Array(fieldtype._ffishape_) return A.fromaddress(address, 1) def _get_buffer_for_param(self): return self def _get_buffer_value(self): return self._buffer.buffer def _to_ffi_param(self): return self._buffer class StructureMeta(StructOrUnionMeta): _is_union = False class Structure(StructOrUnion, metaclass=StructureMeta): pass
timm/timmnix
pypy3-v5.5.0-linux64/lib_pypy/_ctypes/structure.py
Python
mit
10,129
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2015 ADHOC SA (http://www.adhoc.com.ar) # 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 Affero 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/>. # ############################################################################## { 'name': 'Portal Account Summary', 'version': '1.0', 'category': '', 'sequence': 14, 'summary': '', 'description': """ Portal Account Summary ====================== """, 'author': 'ADHOC SA', 'website': 'www.adhoc.com.ar', 'images': [ ], 'depends': [ 'account_partner_account_summary', 'portal', 'report_aeroo_portal_fix', 'portal_partner_fix', ], 'data': [ 'account_summary_view.xml', ], 'demo': [ ], 'test': [ ], 'installable': True, 'auto_install': False, 'application': False, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
maljac/odoo-addons
portal_account_summary/__openerp__.py
Python
agpl-3.0
1,638
import smtplib import email.mime.text mail_host = "" # "smtp.xxx.com" mail_user = "" # "xxx@xxx.com" mail_pass = "" # "xxx" mail_postfix = "" # "xxx.com" mailto_list = [""] # ["xxx@xxx.com"] def send_mail(to_list, sub, content): me = "hello"+"<"+mail_user+"@"+mail_postfix+">" msg = email.mime.text.MIMEText(content, _subtype='plain', _charset='gb2312') msg['Subject'] = sub msg['From'] = me msg['To'] = ";".join(to_list) try: server = smtplib.SMTP() server.connect(mail_host) server.login(mail_user, mail_pass) server.sendmail(me, to_list, msg.as_string()) server.close() return True except Exception, e: print str(e) return False if __name__ == '__main__': if send_mail(mailto_list, "hello", "hello world"): print "Success" else: print "Failed"
followcat/predator
tools/mail.py
Python
lgpl-3.0
884
def calcETA (dict) oETA = 0 for key in dict route = dict [key] for path in route oETA += path.ETA return oETA
haohanshi/HackCMU217
calcETA.py
Python
mit
130
<<<<<<< HEAD <<<<<<< HEAD # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for print. Change: 'print' into 'print()' 'print ...' into 'print(...)' 'print ... ,' into 'print(..., end=" ")' 'print >>x, ...' into 'print(..., file=x)' No changes are applied if print_function is imported from __future__ """ # Local imports from .. import patcomp from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Name, Call, Comma, String, is_tuple parend_expr = patcomp.compile_pattern( """atom< '(' [atom|STRING|NAME] ')' >""" ) class FixPrint(fixer_base.BaseFix): BM_compatible = True PATTERN = """ simple_stmt< any* bare='print' any* > | print_stmt """ def transform(self, node, results): assert results bare_print = results.get("bare") if bare_print: # Special-case print all by itself bare_print.replace(Call(Name("print"), [], prefix=bare_print.prefix)) return assert node.children[0] == Name("print") args = node.children[1:] if len(args) == 1 and parend_expr.match(args[0]): # We don't want to keep sticking parens around an # already-parenthesised expression. return sep = end = file = None if args and args[-1] == Comma(): args = args[:-1] end = " " if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"): assert len(args) >= 2 file = args[1].clone() args = args[3:] # Strip a possible comma after the file expression # Now synthesize a print(args, sep=..., end=..., file=...) node. l_args = [arg.clone() for arg in args] if l_args: l_args[0].prefix = "" if sep is not None or end is not None or file is not None: if sep is not None: self.add_kwarg(l_args, "sep", String(repr(sep))) if end is not None: self.add_kwarg(l_args, "end", String(repr(end))) if file is not None: self.add_kwarg(l_args, "file", file) n_stmt = Call(Name("print"), l_args) n_stmt.prefix = node.prefix return n_stmt def add_kwarg(self, l_nodes, s_kwd, n_expr): # XXX All this prefix-setting may lose comments (though rarely) n_expr.prefix = "" n_argument = pytree.Node(self.syms.argument, (Name(s_kwd), pytree.Leaf(token.EQUAL, "="), n_expr)) if l_nodes: l_nodes.append(Comma()) n_argument.prefix = " " l_nodes.append(n_argument) ======= # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for print. Change: 'print' into 'print()' 'print ...' into 'print(...)' 'print ... ,' into 'print(..., end=" ")' 'print >>x, ...' into 'print(..., file=x)' No changes are applied if print_function is imported from __future__ """ # Local imports from .. import patcomp from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Name, Call, Comma, String, is_tuple parend_expr = patcomp.compile_pattern( """atom< '(' [atom|STRING|NAME] ')' >""" ) class FixPrint(fixer_base.BaseFix): BM_compatible = True PATTERN = """ simple_stmt< any* bare='print' any* > | print_stmt """ def transform(self, node, results): assert results bare_print = results.get("bare") if bare_print: # Special-case print all by itself bare_print.replace(Call(Name("print"), [], prefix=bare_print.prefix)) return assert node.children[0] == Name("print") args = node.children[1:] if len(args) == 1 and parend_expr.match(args[0]): # We don't want to keep sticking parens around an # already-parenthesised expression. return sep = end = file = None if args and args[-1] == Comma(): args = args[:-1] end = " " if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"): assert len(args) >= 2 file = args[1].clone() args = args[3:] # Strip a possible comma after the file expression # Now synthesize a print(args, sep=..., end=..., file=...) node. l_args = [arg.clone() for arg in args] if l_args: l_args[0].prefix = "" if sep is not None or end is not None or file is not None: if sep is not None: self.add_kwarg(l_args, "sep", String(repr(sep))) if end is not None: self.add_kwarg(l_args, "end", String(repr(end))) if file is not None: self.add_kwarg(l_args, "file", file) n_stmt = Call(Name("print"), l_args) n_stmt.prefix = node.prefix return n_stmt def add_kwarg(self, l_nodes, s_kwd, n_expr): # XXX All this prefix-setting may lose comments (though rarely) n_expr.prefix = "" n_argument = pytree.Node(self.syms.argument, (Name(s_kwd), pytree.Leaf(token.EQUAL, "="), n_expr)) if l_nodes: l_nodes.append(Comma()) n_argument.prefix = " " l_nodes.append(n_argument) >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453 ======= # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. """Fixer for print. Change: 'print' into 'print()' 'print ...' into 'print(...)' 'print ... ,' into 'print(..., end=" ")' 'print >>x, ...' into 'print(..., file=x)' No changes are applied if print_function is imported from __future__ """ # Local imports from .. import patcomp from .. import pytree from ..pgen2 import token from .. import fixer_base from ..fixer_util import Name, Call, Comma, String, is_tuple parend_expr = patcomp.compile_pattern( """atom< '(' [atom|STRING|NAME] ')' >""" ) class FixPrint(fixer_base.BaseFix): BM_compatible = True PATTERN = """ simple_stmt< any* bare='print' any* > | print_stmt """ def transform(self, node, results): assert results bare_print = results.get("bare") if bare_print: # Special-case print all by itself bare_print.replace(Call(Name("print"), [], prefix=bare_print.prefix)) return assert node.children[0] == Name("print") args = node.children[1:] if len(args) == 1 and parend_expr.match(args[0]): # We don't want to keep sticking parens around an # already-parenthesised expression. return sep = end = file = None if args and args[-1] == Comma(): args = args[:-1] end = " " if args and args[0] == pytree.Leaf(token.RIGHTSHIFT, ">>"): assert len(args) >= 2 file = args[1].clone() args = args[3:] # Strip a possible comma after the file expression # Now synthesize a print(args, sep=..., end=..., file=...) node. l_args = [arg.clone() for arg in args] if l_args: l_args[0].prefix = "" if sep is not None or end is not None or file is not None: if sep is not None: self.add_kwarg(l_args, "sep", String(repr(sep))) if end is not None: self.add_kwarg(l_args, "end", String(repr(end))) if file is not None: self.add_kwarg(l_args, "file", file) n_stmt = Call(Name("print"), l_args) n_stmt.prefix = node.prefix return n_stmt def add_kwarg(self, l_nodes, s_kwd, n_expr): # XXX All this prefix-setting may lose comments (though rarely) n_expr.prefix = "" n_argument = pytree.Node(self.syms.argument, (Name(s_kwd), pytree.Leaf(token.EQUAL, "="), n_expr)) if l_nodes: l_nodes.append(Comma()) n_argument.prefix = " " l_nodes.append(n_argument) >>>>>>> b875702c9c06ab5012e52ff4337439b03918f453
ArcherSys/ArcherSys
Lib/lib2to3/fixes/fix_print.py
Python
mit
8,702
""" Helper module that can load whatever version of the json module is available. Plugins can just import the methods from this module. Also allows date and datetime objects to be encoded/decoded. """ import datetime from collections.abc import Iterable, Mapping from contextlib import suppress from typing import Any, Union from flexget.plugin import DependencyError try: import simplejson as json except ImportError: try: import json # type: ignore # python/mypy#1153 except ImportError: try: # Google Appengine offers simplejson via django from django.utils import simplejson as json # type: ignore except ImportError: raise DependencyError(missing='simplejson') DATE_FMT = '%Y-%m-%d' ISO8601_FMT = '%Y-%m-%dT%H:%M:%SZ' class DTDecoder(json.JSONDecoder): def decode(self, obj, **kwargs): # The built-in `json` library will `unicode` strings, except for empty strings. patch this for # consistency so that `unicode` is always returned. if obj == b'': return '' if isinstance(obj, str): dt_str = obj.strip('"') try: return datetime.datetime.strptime(dt_str, ISO8601_FMT) except (ValueError, TypeError): with suppress(ValueError, TypeError): return datetime.datetime.strptime(dt_str, DATE_FMT) return super().decode(obj, **kwargs) def _datetime_encoder(obj: Union[datetime.datetime, datetime.date]) -> str: if isinstance(obj, datetime.datetime): return obj.strftime(ISO8601_FMT) elif isinstance(obj, datetime.date): return obj.strftime(DATE_FMT) raise TypeError def _datetime_decoder(dict_: dict) -> dict: for key, value in dict_.items(): # The built-in `json` library will `unicode` strings, except for empty strings. patch this for # consistency so that `unicode` is always returned. if value == b'': dict_[key] = '' continue try: datetime_obj = datetime.datetime.strptime(value, ISO8601_FMT) dict_[key] = datetime_obj except (ValueError, TypeError): with suppress(ValueError, TypeError): date_obj = datetime.datetime.strptime(value, DATE_FMT) dict_[key] = date_obj.date() return dict_ def _empty_unicode_decoder(dict_: dict) -> dict: for key, value in dict_.items(): # The built-in `json` library will `unicode` strings, except for empty strings. patch this for # consistency so that `unicode` is always returned. if value == b'': dict_[key] = '' return dict_ def dumps(*args, **kwargs) -> str: if kwargs.pop('encode_datetime', False): kwargs['default'] = _datetime_encoder return json.dumps(*args, **kwargs) def dump(*args, **kwargs) -> None: if kwargs.pop('encode_datetime', False): kwargs['default'] = _datetime_encoder return json.dump(*args, **kwargs) def loads(*args, **kwargs) -> Any: """ :param bool decode_datetime: If `True`, dates in ISO8601 format will be deserialized to :class:`datetime.datetime` objects. """ if kwargs.pop('decode_datetime', False): kwargs['object_hook'] = _datetime_decoder kwargs['cls'] = DTDecoder else: kwargs['object_hook'] = _empty_unicode_decoder return json.loads(*args, **kwargs) def load(*args, **kwargs) -> Any: """ :param bool decode_datetime: If `True`, dates in ISO8601 format will be deserialized to :class:`datetime.datetime` objects. """ if kwargs.pop('decode_datetime', False): kwargs['object_hook'] = _datetime_decoder kwargs['cls'] = DTDecoder else: kwargs['object_hook'] = _empty_unicode_decoder return json.load(*args, **kwargs) def coerce(obj) -> Union[str, int, float, bool, dict, list, None]: """ Coerce a data structure to a JSON serializable form. Will recursively go through data structure, and attempt to turn anything not JSON serializable into a string. """ if isinstance(obj, (str, int, float, bool, type(None))): return obj if isinstance(obj, datetime.datetime): return obj.strftime(ISO8601_FMT) if isinstance(obj, datetime.date): return obj.strftime(DATE_FMT) if isinstance(obj, Mapping): return {k: coerce(v) for k, v in obj.items()} if isinstance(obj, Iterable): return [coerce(v) for v in obj] try: return str(obj) except Exception: return 'NOT JSON SERIALIZABLE'
Flexget/Flexget
flexget/utils/json.py
Python
mit
4,634
"""Setup config file to package SIP Processing BLock Controller library.""" from setuptools import setup from sip_pbc.release import __version__ with open('README.md', 'r') as file: LONG_DESCRIPTION = file.read() setup(name='skasip-pbc', version=__version__, author='SKA SDP SIP team.', description='SIP Processing Block Controller library.', long_description=LONG_DESCRIPTION, long_description_content_type='text/markdown', url='https://github.com/SKA-ScienceDataProcessor/integration-prototype' '/tree/master/sip/execution_control/processing_block_controller', packages=['sip_pbc'], install_requires=[ 'skasip-config-db>=1.2.2', 'skasip-docker-swarm>=1.0.10', 'skasip-logging>=1.0.14', 'redis==2.10.6', 'jinja2>=2.10.1', 'celery==4.2.1', 'PyYAML==4.2b4' ], zip_safe=False, classifiers=[ "Programming Language :: Python :: 3 :: Only", "Development Status :: 1 - Planning", "License :: OSI Approved :: BSD License" ] )
SKA-ScienceDataProcessor/integration-prototype
sip/execution_control/processing_block_controller/setup.py
Python
bsd-3-clause
1,115
# coding=utf-8 import pytest @pytest.fixture def dns_sd(): from pymachinetalk import dns_sd return dns_sd @pytest.fixture def sd(): from pymachinetalk import dns_sd sd = dns_sd.ServiceDiscovery() return sd def test_registeringServicesFromServiceContainerWorks(dns_sd, sd): service = dns_sd.Service() discoverable = dns_sd.ServiceContainer() discoverable.services.append(service) sd.register(discoverable) assert service in sd.services def test_registeringServiceDirectlyWorks(dns_sd, sd): service = dns_sd.Service() sd.register(service) assert service in sd.services def test_registeringAnythingElseFails(sd): item = object() try: sd.register(item) except TypeError: assert True assert item not in sd.services def test_registeringWhenRunningThrowsError(dns_sd, sd): service = dns_sd.Service() def dummy(): pass sd._start_discovery = dummy sd.start() try: sd.register(service) except RuntimeError: assert True assert service not in sd.services def test_unregisteringServiceDirectlyWorks(dns_sd, sd): service = dns_sd.Service() sd.register(service) sd.unregister(service) assert service not in sd.services def test_unregisteringServicesFromServiceContainerWorks(dns_sd, sd): service = dns_sd.Service() discoverable = dns_sd.ServiceContainer() discoverable.services.append(service) sd.register(discoverable) sd.unregister(discoverable) assert service not in sd.services def test_unregisteringAnythingElseFails(sd): item = 34 try: sd.unregister(item) except TypeError: assert True assert item not in sd.services def test_unregisteringWhenRunningThrowsError(dns_sd, sd): service = dns_sd.Service() def dummy(): pass sd._start_discovery = dummy sd.start() try: sd.unregister(service) except RuntimeError: assert True assert service not in sd.services class ServiceInfoFactory(object): def create( self, base_type='machinekit', domain='local', sd_protocol='tcp', name='Hugo on Franz', service=b'halrcomp', uuid=b'12345678', host='127.0.0.1', protocol='tcp', port=12345, version=0, properties=None, server='127.0.0.1', address=None, ): from zeroconf import ServiceInfo typestring = '_%s._%s.%s.' % (base_type, sd_protocol, domain) dsn = b'%s://%s:%i' % (protocol.encode(), host.encode(), port) if properties is None: properties = { b'uuid': uuid, b'service': service, b'dsn': dsn, b'version': version, } return ServiceInfo( type_=typestring, name='%s %s.%s' % (name, host, typestring), properties=properties, address=(address or host).encode(), port=port, server=server, ) @pytest.fixture def zeroconf(mocker): from zeroconf import Zeroconf service_info = ServiceInfoFactory().create() zeroconf_stub = mocker.stub(name='get_service_info') zeroconf_stub.return_value = service_info stub_object = Zeroconf() stub_object.get_service_info = zeroconf_stub return stub_object @pytest.fixture def zeroconf_without_service_info(mocker): from zeroconf import Zeroconf zeroconf_stub = mocker.stub(name='get_service_info') zeroconf_stub.return_value = None stub_object = Zeroconf() stub_object.get_service_info = zeroconf_stub return stub_object def test_serviceDiscoveredUpdatesRegisteredServices(dns_sd, sd, zeroconf): service = dns_sd.Service(type_='halrcomp') sd.register(service) sd.add_service( zeroconf, '_machinekit._tcp.local.', 'Foo on Bar 127.0.0.1._machinekit._tcp.local.', ) assert service.ready is True def test_serviceDisappearedUpdatesRegisteredServices(dns_sd, sd, zeroconf): service = dns_sd.Service(type_='halrcomp') sd.register(service) sd.add_service( zeroconf, '_machinekit._tcp.local.', 'Foo on Bar 127.0.0.1._machinekit._tcp.local.', ) sd.remove_service( zeroconf, '_machinekit._tcp.local.', 'Foo on Bar 127.0.0.1._machinekit._tcp.local.', ) assert service.ready is False def test_stoppingServiceDiscoveryResetsAllServices(dns_sd, sd, zeroconf): service1 = dns_sd.Service(type_='halrcomp') sd.register(service1) service2 = dns_sd.Service(type_='halrcmd') sd.register(service2) sd.browser = object() # dummy sd.add_service( zeroconf, '_machinekit._tcp.local.', 'Foo on Bar 127.0.0.1._machinekit._tcp.local.', ) sd.stop() assert service1.ready is False assert service2.ready is False def test_serviceDiscoveredWithoutServiceInfoDoesNotUpdateRegisteredServices( dns_sd, sd, zeroconf_without_service_info ): service = dns_sd.Service(type_='halrcomp') sd.register(service) sd.add_service( zeroconf_without_service_info, '_machinekit._tcp.local.', 'Foo on Bar 127.0.0.1._machinekit._tcp.local.', ) assert service.ready is False def test_serviceDisappearedWithoutServiceInfoDoesNotUpdateRegisteredServices( dns_sd, sd, zeroconf_without_service_info ): service = dns_sd.Service(type_='halrcomp') sd.register(service) service.ready = True sd.remove_service( zeroconf_without_service_info, '_machinekit._tcp.local.', 'Foo on Bar 127.0.0.1._machinekit._tcp.local.', ) assert service.ready is True def test_serviceInfoSetsAllRelevantValuesOfService(dns_sd): service = dns_sd.Service(type_='halrcomp') service_info = ServiceInfoFactory().create( name='Foo on Bar', uuid=b'987654321', version=5, host='10.0.0.10', protocol='tcp', port=12456, server='sandybox.local', ) service.add_service_info(service_info) assert service.uri == 'tcp://10.0.0.10:12456' assert service.name == service_info.name assert service.uuid == '987654321' assert service.version == 5 assert service.host_name == 'sandybox.local' assert service.host_address == '10.0.0.10' def test_serviceInfoResolvesLocalHostnameIfMatched(dns_sd): service = dns_sd.Service(type_='halrcomp') service_info = ServiceInfoFactory().create( host='sandybox.local', protocol='tcp', port=12456, server='sandybox.local', address='10.0.0.10', ) service.add_service_info(service_info) assert service.uri == 'tcp://10.0.0.10:12456' def test_serviceInfoRetursRawUriIfHostnameIsNotMatched(dns_sd): service = dns_sd.Service(type_='halrcomp') service_info = ServiceInfoFactory().create( host='thinkpad.local', protocol='tcp', port=12456, server='sandybox.local', address='10.0.0.10', ) service.add_service_info(service_info) assert service.uri == 'tcp://thinkpad.local:12456' def test_serviceInfoWithIncompleteValuesIsIgnoredByService(dns_sd): service = dns_sd.Service(type_='launcher') service_info = ServiceInfoFactory().create(properties={}) service.add_service_info(service_info) assert service.uri == '' assert service.uuid == '' assert service.version == b'' def test_removingServiceInfoResetsAllRelevantValuesOfService(dns_sd): service = dns_sd.Service(type_='blahus') service_info = ServiceInfoFactory().create() service.add_service_info(service_info) service.remove_service_info(service_info) assert service.uri == '' assert service.name == '' assert service.uuid == '' assert service.version == 0 assert service.host_name == '' assert service.host_address == '' def test_clearingServiceInfosResetsValuesOfService(dns_sd): service = dns_sd.Service(type_='foobar') service.add_service_info(ServiceInfoFactory().create()) service.add_service_info(ServiceInfoFactory().create()) service.clear_service_infos() assert service.ready is False assert service.uri == '' def test_settingReadyPropertyOfServiceTriggersCallback(dns_sd): cb_called = [False] def cb(_): cb_called[0] = True service = dns_sd.Service(type_='halrcomp') service.on_ready_changed.append(cb) service_info = ServiceInfoFactory().create() service.add_service_info(service_info) assert cb_called[0] is True def test_discoverableAddingServiceWorks(dns_sd): discoverable = dns_sd.ServiceContainer() service = dns_sd.Service(type_='foo') discoverable.add_service(service) assert service in discoverable.services def test_discoverableAddingAnythingElseFails(dns_sd): discoverable = dns_sd.ServiceContainer() item = object() try: discoverable.add_service(item) assert False except TypeError: assert True assert item not in discoverable.services def test_discoverableRemovingServiceWorks(dns_sd): discoverable = dns_sd.ServiceContainer() service = dns_sd.Service(type_='foo') discoverable.add_service(service) discoverable.remove_service(service) assert service not in discoverable.services def test_discoverableRemvoingAnythingElseFails(dns_sd): discoverable = dns_sd.ServiceContainer() item = object() try: discoverable.remove_service(item) assert False except TypeError: assert True assert item not in discoverable.services def test_discoverableAllServicesReadySetServicesReady(dns_sd): discoverable = dns_sd.ServiceContainer() service1 = dns_sd.Service(type_='foo') discoverable.add_service(service1) service2 = dns_sd.Service(type_='bar') discoverable.add_service(service2) service1.ready = True service2.ready = True assert discoverable.services_ready is True def test_discoverableNotAllServicesReadyUnsetsServicesReady(dns_sd): discoverable = dns_sd.ServiceContainer() service1 = dns_sd.Service(type_='foo') discoverable.add_service(service1) service2 = dns_sd.Service(type_='bar') discoverable.add_service(service2) service1.ready = True service2.ready = True service1.ready = False assert discoverable.services_ready is False def test_discoverableServicesReadyChangedCallsCallback(dns_sd): cb_called = [False] def cb(_): cb_called[0] = True discoverable = dns_sd.ServiceContainer() discoverable.on_services_ready_changed.append(cb) discoverable.services_ready = True assert cb_called[0] is True def test_serviceDiscoveryFilterAcceptCorrectUuid(dns_sd): service_info = ServiceInfoFactory().create(uuid=b'987654321') filter = dns_sd.ServiceDiscoveryFilter(txt_records={b'uuid': b'987654321'}) assert filter.matches_service_info(service_info) is True def test_serviceDiscoveryFilterRejectWrongUuid(dns_sd): service_info = ServiceInfoFactory().create(uuid=b'123456789') filter = dns_sd.ServiceDiscoveryFilter(txt_records={b'uuid': b'987654321'}) assert filter.matches_service_info(service_info) is False def test_serviceDiscoveryFilterAcceptFuzzyName(dns_sd): service_info = ServiceInfoFactory().create(name='Hello World') filter = dns_sd.ServiceDiscoveryFilter(name='Hello') assert filter.matches_service_info(service_info) is True def test_serviceDiscoveryFilterAcceptExactMatchingName(dns_sd): service_info = ServiceInfoFactory().create(name='Foo') filter = dns_sd.ServiceDiscoveryFilter(name='Foo') assert filter.matches_service_info(service_info) is True def test_serviceDiscoveryFilterRejectNonMatchingName(dns_sd): service_info = ServiceInfoFactory().create(name='Carolus Rex') filter = dns_sd.ServiceDiscoveryFilter(name='Adolfus Maximus') assert filter.matches_service_info(service_info) is False def test_serviceDiscoveryFilterPassingWrongObjectFails(dns_sd): filter = dns_sd.ServiceDiscoveryFilter() try: filter.matches_service_info(object()) assert False except TypeError: assert True def test_serviceDiscoveryFiltersOutDiscoveredServiceWithWrongUuid(dns_sd, sd, zeroconf): service = dns_sd.Service(type_='halrcomp') sd.register(service) sd.filter = dns_sd.ServiceDiscoveryFilter(txt_records={b'uuid': b'87654321'}) sd.add_service( zeroconf, '_machinekit._tcp.local.', 'Machinekit on MyBox 12.0.0.1._machinekit._tcp.local.', ) assert service.ready is False def test_serviceDiscoveryFiltersInDiscoveredServiceWithCorrectUuid( dns_sd, sd, zeroconf ): service = dns_sd.Service(type_='halrcomp') sd.register(service) sd.filter = dns_sd.ServiceDiscoveryFilter(txt_records={b'uuid': b'12345678'}) sd.add_service( zeroconf, '_machinekit._tcp.local.', 'SuperPrint 192.168.7.2._machinekit._tcp.local.', ) assert service.ready is True def test_serviceDiscoveryFiltersInDisappearedServiceWithCorrectUuid( dns_sd, sd, zeroconf ): service = dns_sd.Service(type_='halrcomp') sd.register(service) sd.filter = dns_sd.ServiceDiscoveryFilter(txt_records={b'uuid': b'12345678'}) sd.add_service( zeroconf, '_machinekit._tcp.local.', 'SuperPrint 192.168.7.2._machinekit._tcp.local.', ) sd.remove_service( zeroconf, '_machinekit._tcp.local.', 'SuperPrint 192.168.7.2._machinekit._tcp.local.', ) assert service.ready is False
strahlex/pymachinetalk
pymachinetalk/tests/test_dns_sd.py
Python
mit
13,743
# -*- encoding: utf-8 -*- from shapely.wkt import loads as wkt_loads import dsl from . import FixtureTest class TestCranes(FixtureTest): def test_crane_landuse_line(self): self.generate_fixtures(dsl.way(1842715060, wkt_loads('POINT (0.6785997623748069 51.43672148243049)'), {u'source': u'openstreetmap.org', u'man_made': u'crane'}),dsl.way(173458931, wkt_loads('LINESTRING (0.6867062493302298 51.43649709368218, 0.6785997623748069 51.43672148243049)'), {u'source': u'openstreetmap.org', u'man_made': u'crane', u'crane:type': u'portal_crane'})) # noqa self.assert_has_feature( 16, 32891, 21813, 'landuse', {'id': 173458931, 'kind': 'crane', 'min_zoom': 16, 'sort_rank': 272}) def test_crane_pois(self): self.generate_fixtures(dsl.way(1842715058, wkt_loads('POINT (0.6785790112917439 51.43642978244269)'), {u'source': u'openstreetmap.org', u'man_made': u'crane'})) # noqa self.assert_has_feature( 16, 32891, 21813, 'pois', {'id': 1842715058, 'kind': 'crane', 'min_zoom': 16})
mapzen/vector-datasource
integration-test/1417-cranes.py
Python
mit
1,083
# -*- coding: utf-8 -*- from __future__ import unicode_literals # do this when > 1.6!!! # from django.db import migrations, models from gazetteer.models import GazSource,GazSourceConfig,LocationTypeField,CodeFieldConfig,NameFieldConfig from skosxl.models import Concept, Scheme, MapRelation from gazetteer.settings import TARGET_NAMESPACE_FT def load_base_ft(): (sch,created) = Scheme.objects.get_or_create(uri=TARGET_NAMESPACE_FT[:-1], defaults = { 'pref_label' :"Gaz Feature types" }) try: (ft,created) = Concept.objects.get_or_create(term="ADMIN", defaults = { 'pref_label' :"Populated Place", 'definition':"Populated place"} , scheme = sch) except: pass # now set up cross references from NGA feature types namespace # now set up harvest config def load_ft_mappings() : pass def load_config() : try: GazSourceConfig.objects.filter(name="TM_WorldBoundaries").delete() except: pass config=GazSourceConfig.objects.create(lat_field="lat", name="TM_WorldBoundaries", long_field="lon") NameFieldConfig.objects.create(config=config,language="en", as_default=True, languageNamespace="", field="name", languageField="") LocationTypeField.objects.create(field='"ADMIN"',namespace=TARGET_NAMESPACE_FT, config=config) CodeFieldConfig.objects.create(config=config,field="iso3",namespace="http://mapstory.org/id/countries/iso3") CodeFieldConfig.objects.create(config=config,field="iso2",namespace="http://mapstory.org/id/countries/iso2") CodeFieldConfig.objects.create(config=config,field="un",namespace="http://mapstory.org/id/countries/un") CodeFieldConfig.objects.create(config=config,field="fips",namespace="http://mapstory.org/id/countries/fips") (s,created) = GazSource.objects.get_or_create(source="tm_world_borders", config=config, source_type="mapstory") print (s,created) """ class Migration(migrations.Migration): initial = True dependencies = [ #('yourappname', '0001_initial'), ] operations = [ migrations.RunPython(load_ft_mappings), migrations.RunPython(load_config), ] """
rob-metalinkage/django-gazetteer
gazetteer/fixtures/mapstory_tm_world_config.py
Python
cc0-1.0
2,139
import os import re import sys import subprocess # Use the official chef lex file # Compile from source each time path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'swedish_chef.l') COMPILE_CMD = "lex -o /tmp/swedish_chef.c {0} && cc /tmp/swedish_chef.c -o /tmp/swedish_chef -ll".format(path) subprocess.Popen(COMPILE_CMD, stdout=subprocess.PIPE, shell=True).wait() RUN_CMD = "/tmp/swedish_chef" def filter(text): """ >>> filter("Turn flash on.") 'Toorn flesh oon.' >>> filter("Cancel") 'Cuncel' >>> filter("card.io") 'cerd.iu' """ p = subprocess.Popen(RUN_CMD, stdout=subprocess.PIPE, stdin=subprocess.PIPE) stdout, stderr = p.communicate(input=text) return stdout if __name__ == "__main__": import doctest doctest.testmod()
chanelcici/card-io-ios-source
scripts/string_scripts/swedish_chef/swedish_chef.py
Python
mit
799
import wave import struct BPM = 320.0 BEAT_LENGTH = 60.0 / BPM START_BEAT = 80.0 # beat 80 is the 'huh' of the first 'uuh-huh' START_TIME = START_BEAT * BEAT_LENGTH BEAT_COUNT = 16.0 CLIP_LENGTH = BEAT_LENGTH * BEAT_COUNT FRAME_RATE = 50.0 FRAME_LENGTH = 1 / FRAME_RATE FRAME_COUNT = int(FRAME_RATE * CLIP_LENGTH) PICK_RANGE = 0.008 # the duration of the span over which we pick our 32 samples each frame PICK_INTERVAL = PICK_RANGE / 32 wav = wave.open('clips/kisskill_wipmix2_leadin.wav') SAMPLE_RATE = wav.getframerate() for frame in range(0, FRAME_COUNT): frame_offset = START_TIME + (frame * FRAME_LENGTH) for pick in range(0, 32): pick_offset = frame_offset + (pick * PICK_INTERVAL) wav.setpos(int(pick_offset * SAMPLE_RATE)) v1, v2 = struct.unpack('<hh', wav.readframes(1)) v = (v1 + v2) / 2 print "\tdb %d" % ((v / 5000) + 12) print
gasman/kisskill
scripts/oscilloscope.py
Python
mit
859
import unittest import ROOT class TVector3Len(unittest.TestCase): """ Test for the pythonization that allows to get the size of a TVector3 (always 3) by calling `len` on it. """ # Tests def test_len(self): v = ROOT.TVector3(1., 2., 3.) self.assertEqual(len(v), 3) if __name__ == '__main__': unittest.main()
root-mirror/root
bindings/pyroot/pythonizations/test/tvector3_len.py
Python
lgpl-2.1
357
# -*- coding: utf-8 -*- import argparse import logging import os import socket import sys from smart_qq_bot.config import COOKIE_FILE from smart_qq_bot.logger import logger from smart_qq_bot.app import bot, plugin_manager from smart_qq_bot.handler import MessageObserver from smart_qq_bot.messages import mk_msg from smart_qq_bot.excpetions import ServerResponseEmpty def patch(): reload(sys) sys.setdefaultencoding("utf-8") def clean_cookie(): if os.path.isfile(COOKIE_FILE): os.remove(COOKIE_FILE) logger.info("Cookie file removed.") def main_loop(no_gui=False, new_user=False): patch() logger.setLevel(logging.INFO) logger.info("Initializing...") plugin_manager.load_plugin() if new_user: clean_cookie() bot.login(no_gui) observer = MessageObserver(bot) while True: try: msg_list = bot.check_msg() if msg_list is not None: observer.handle_msg_list( [mk_msg(msg) for msg in msg_list] ) except ServerResponseEmpty: continue except (socket.timeout, IOError): logger.warning("Message pooling timeout, retrying...") except Exception: logger.exception("Exception occurs when checking msg.") def run(): parser = argparse.ArgumentParser() parser.add_argument( "--no-gui", action="store_true", default=False, help="Whether display QRCode with tk and PIL." ) parser.add_argument( "--new-user", action="store_true", default=False, help="Logout old user first(by clean the cookie file.)" ) args = parser.parse_args() main_loop(**vars(args)) if __name__ == "__main__": run()
BlinkTunnel/SmartQQBot
src/smart_qq_bot/main.py
Python
gpl-3.0
1,781
__author__ = 'lat9wj' from helper import * greeting("hello")
luket4/cs3240-labdemo
hello.py
Python
mit
61
# -*- coding: windows-1252 -*- ''' From BIFF8 on, strings are always stored using UTF-16LE text encoding. The character array is a sequence of 16-bit values4. Additionally it is possible to use a compressed format, which omits the high bytes of all characters, if they are all zero. The following tables describe the standard format of the entire string, but in many records the strings differ from this format. This will be mentioned separately. It is possible (but not required) to store Rich-Text formatting information and Asian phonetic information inside a Unicode string. This results in four different ways to store a string. The character array is not zero-terminated. The string consists of the character count (as usual an 8-bit value or a 16-bit value), option flags, the character array and optional formatting information. If the string is empty, sometimes the option flags field will not occur. This is mentioned at the respective place. Offset Size Contents 0 1 or 2 Length of the string (character count, ln) 1 or 2 1 Option flags: Bit Mask Contents 0 01H Character compression (ccompr): 0 = Compressed (8-bit characters) 1 = Uncompressed (16-bit characters) 2 04H Asian phonetic settings (phonetic): 0 = Does not contain Asian phonetic settings 1 = Contains Asian phonetic settings 3 08H Rich-Text settings (richtext): 0 = Does not contain Rich-Text settings 1 = Contains Rich-Text settings [2 or 3] 2 (optional, only if richtext=1) Number of Rich-Text formatting runs (rt) [var.] 4 (optional, only if phonetic=1) Size of Asian phonetic settings block (in bytes, sz) var. ln or 2·ln Character array (8-bit characters or 16-bit characters, dependent on ccompr) [var.] 4·rt (optional, only if richtext=1) List of rt formatting runs [var.] sz (optional, only if phonetic=1) Asian Phonetic Settings Block ''' from .compat import unicode, unicode_type from struct import pack def upack2(s, encoding='ascii'): # If not unicode, make it so. if isinstance(s, unicode_type): us = s else: us = unicode(s, encoding) # Limit is based on number of content characters # (not on number of bytes in packed result) len_us = len(us) if len_us > 32767: raise Exception('String longer than 32767 characters') try: encs = us.encode('latin1') # Success here means all chars are in U+0000 to U+00FF # inclusive, meaning that we can use "compressed format". flag = 0 n_items = len_us except UnicodeEncodeError: encs = us.encode('utf_16_le') flag = 1 n_items = len(encs) // 2 # n_items is the number of "double byte characters" i.e. MS C wchars # Can't use len(us). # len(u"\U0001D400") -> 1 on a wide-unicode build # and 2 on a narrow-unicode build. # We need n_items == 2 in this case. return pack('<HB', n_items, flag) + encs def upack2rt(rt, encoding='ascii'): us = u'' fr = '' offset = 0 # convert rt strings to unicode if not already unicode # also generate the formatting run for the styles added for s, fontx in rt: if not isinstance(s, unicode_type): s = unicode(s, encoding) us += s if fontx is not None: # code in Rows.py ensures that # fontx can be None only for the first piece fr += pack('<HH', offset, fontx) # offset is the number of MS C wchar characters. # That is 1 if c <= u'\uFFFF' else 2 offset += len(s.encode('utf_16_le')) // 2 num_fr = len(fr) // 4 # ensure result is int if offset > 32767: raise Exception('String longer than 32767 characters') try: encs = us.encode('latin1') # Success here means all chars are in U+0000 to U+00FF # inclusive, meaning that we can use "compressed format". flag = 0 | 8 n_items = len(encs) except UnicodeEncodeError: encs = us.encode('utf_16_le') flag = 1 | 8 n_items = len(encs) // 2 # see comments in upack2 function above return pack('<HBH', n_items, flag, num_fr) + encs, fr def upack1(s, encoding='ascii'): # Same as upack2(), but with a one-byte length field. if isinstance(s, unicode_type): us = s else: us = unicode(s, encoding) len_us = len(us) if len_us > 255: raise Exception('String longer than 255 characters') try: encs = us.encode('latin1') flag = 0 n_items = len_us except UnicodeEncodeError: encs = us.encode('utf_16_le') flag = 1 n_items = len(encs) // 2 return pack('<BB', n_items, flag) + encs
jlaniau/conquests
xlwt/UnicodeUtils.py
Python
gpl-3.0
5,032
from django.db.models import Q from rest_framework.generics import ( ListAPIView, RetrieveAPIView, DestroyAPIView, CreateAPIView, RetrieveUpdateAPIView ) from rest_framework.filters import OrderingFilter from .paginations import PostLimitOffsetPagination from rest_framework.permissions import ( AllowAny, IsAdminUser, ) from .serializers import ( PostListSerializer, PostDetailSerializer, PostCreateUpdateSerializer ) from posts.models import Post from .permissions import IsOwnerOrReadOnly class PostCreateAPIView(CreateAPIView): queryset = Post.objects.all() serializer_class = PostCreateUpdateSerializer permission_classes = [IsAdminUser] def perform_create(self, serializer): serializer.save(user=self.request.user) class PostDetailAPIView(RetrieveAPIView): queryset = Post.objects.all() serializer_class = PostDetailSerializer permission_classes = [AllowAny] lookup_field = "slug" # for reference # lookup_url_kwarg = "abc" class PostDeleteAPIView(DestroyAPIView): queryset = Post.objects.all() serializer_class = PostDetailSerializer permission_classes = [IsOwnerOrReadOnly] lookup_field = "slug" class PostUpdateAPIView(RetrieveUpdateAPIView): queryset = Post.objects.all() serializer_class = PostCreateUpdateSerializer lookup_field = "slug" permission_classes = [IsOwnerOrReadOnly] class PostListAPIView(ListAPIView): serializer_class = PostListSerializer filter_backends = [OrderingFilter] permission_classes = [AllowAny] pagination_class = PostLimitOffsetPagination def get_queryset(self, *args, **kwargs): query_list = Post.objects.all() query = self.request.GET.get("q") if query: query_list = query_list.filter( Q(title__icontains=query) | Q(user__first_name__icontains=query) | Q(user__last_name__icontains=query) | Q(content__icontains=query) ).distinct() return query_list
BigBorg/Blog
Blog/posts/api/views.py
Python
gpl-3.0
2,049
#-*- coding: utf-8 -*- from . import register from spirit.models.topic_notification import TopicNotification from spirit.forms.topic_notification import NotificationForm @register.assignment_tag() def has_topic_notifications(user): return TopicNotification.objects.for_access(user=user)\ .filter(is_read=False)\ .exists() @register.inclusion_tag('spirit/topic_notification/_form.html') def render_notification_form(user, topic, next=None): try: notification = TopicNotification.objects.get(user=user, topic=topic) except TopicNotification.DoesNotExist: notification = None initial = {} if notification: initial['is_active'] = not notification.is_active form = NotificationForm(initial=initial) return {'form': form, 'topic_id': topic.pk, 'notification': notification, 'next': next}
Si-elegans/Web-based_GUI_Tools
spirit/templatetags/tags/topic_notification.py
Python
apache-2.0
858
#!/usr/bin/python # -*- coding: utf-8 -*- import sys, re text_pattern = re.compile(r'<ref>(.*?)<\/ref>\s*<dev>(.*?)\|<\/dev>') printVerse = len(sys.argv) > 3 and sys.argv[3] == 'verse' with open(sys.argv[1]) as input_file, open(sys.argv[2], 'w') as output_file: for line in input_file: match = text_pattern.search(line) if match: verse = match.group(1) sentence_text = match.group(2) in_cvb = 0 words = [] for word in sentence_text.split(): if word.startswith('<cvb>'): word = word[5:] in_cvb = 1 curr_cvb = in_cvb if word.endswith('</cvb>'): word = word[:-6] in_cvb = 0 words.append(word+'_'+str(curr_cvb)) if printVerse: output_file.write(verse+' ') output_file.write(' '.join(words)+'\n') else: sys.stderr.write('Non matching line: '+line)
rjawor/tagging
vw/to_data_format.py
Python
mit
820
#!/usr/bin/env python3 # # Copyright (c) 2014-2016 Matthias Klumpp <mak@debian.org> # # 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; either # version 3.0 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program. import os import gzip import logging as log import zlib import cairo import gi gi.require_version('Rsvg', '2.0') from gi.repository import Rsvg from configparser import ConfigParser from PIL import Image from io import StringIO, BytesIO from .component import IconSize, IconType from .debfile import DebFile from .contentsfile import parse_contents_file class Theme: def __init__(self, name, deb_fname): self.name = name self.directories = list() deb = DebFile(deb_fname) indexdata = str(deb.get_file_data(os.path.join('usr/share/icons', name, 'index.theme')), 'utf-8') index = ConfigParser(allow_no_value=True, strict=False, interpolation=None) index.optionxform = str # don't lower-case option names index.readfp(StringIO(indexdata)) for section in index.sections(): size = index.getint(section, 'Size', fallback=None) context = index.get(section, 'Context', fallback=None) if not size: continue themedir = { 'path': section, 'type': index.get(section, 'Type', fallback='Threshold'), 'size': size, 'minsize': index.getint(section, 'MinSize', fallback=size), 'maxsize': index.getint(section, 'MaxSize', fallback=size), 'threshold': index.getint(section, 'Threshold', fallback=2) } self.directories.append(themedir) def _directory_matches_size(self, themedir, size): if themedir['type'] == 'Fixed': return size == themedir['size'] elif themedir['type'] == 'Scalable': return themedir['minsize'] <= size <= themedir['maxsize'] elif themedir['type'] == 'Threshold': return themedir['size'] - themedir['threshold'] <= size <= themedir['size'] + themedir['threshold'] def matching_icon_filenames(self, name, size): ''' Returns an iteratable of possible icon filenames that match 'name' and 'size'. ''' for themedir in self.directories: if self._directory_matches_size(themedir, size): # best filetype needs to come first to be preferred, only types allowed by the spec are handled at all for extension in ('png', 'svgz', 'svg', 'xpm'): yield 'usr/share/icons/{}/{}/{}.{}'.format(self.name, themedir['path'], name, extension) class IconHandler: ''' An IconHandler, using a Contents-<arch>.gz file present in Debian archive mirrors to find icons not already present in the package file itself. ''' def __init__(self, suite_name, archive_component, arch_name, archive_mirror_dir, icon_theme=None, base_suite_name=None): self._component = archive_component self._mirror_dir = archive_mirror_dir self._themes = list() self._icon_files = dict() self._wanted_icon_sizes = [IconSize(64), IconSize(128)], # Preseeded theme names. # * prioritize hicolor, because that's where apps often install their upstream icon # * then look at the theme given in the config file # * allow Breeze icon theme, needed to support KDE apps (they have no icon at all, otherwise...) # * in rare events, GNOME needs the same treatment, so special-case Adwaita as well # * We need at least one icon theme to provide the default XDG icon spec stock icons. # A fair take would be to select them between KDE and GNOME at random, but for consistency and # because everyone hates unpredictable behavior, we sort alphabetically and prefer Adwaita over Breeze. self._theme_names = ['hicolor'] if icon_theme: self._theme_names.append(icon_theme) self._theme_names.extend(['Adwaita', 'breeze']) # load the 'main' component of the base suite, in case the given suite depends on it if base_suite_name: self._load_contents_data(arch_name, base_suite_name, 'main') self._load_contents_data(arch_name, suite_name, archive_component) # always load the "main" component too, as this holds the icon themes, usually self._load_contents_data(arch_name, suite_name, "main") # FIXME: On Ubuntu, also include the universe component to find more icons, since # they have split the default iconsets for KDE/GNOME apps between main/universe. universe_cfname = os.path.join(self._mirror_dir, "dists", suite_name, "universe", "Contents-%s.gz" % (arch_name)) if os.path.isfile(universe_cfname): self._load_contents_data(arch_name, suite_name, "universe") loaded_themes = set(theme.name for theme in self._themes) missing = set(self._theme_names) - loaded_themes for theme in missing: log.info("Removing theme '%s' from seeded theme-names: Theme not found." % (theme)) def set_wanted_icon_sizes(self, icon_size_strv): self._wanted_icon_sizes = list() for strsize in icon_size_strv: self._wanted_icon_sizes.append(IconSize(strsize)) def _load_contents_data(self, arch_name, suite_name, component): # load and preprocess the large file. # we don't show mercy to memory here, we just want the icon lookup to be fast, # so we need to cache the data. for fname, pkg in parse_contents_file(self._mirror_dir, suite_name, component, arch_name): if fname.startswith('usr/share/pixmaps/'): self._icon_files[fname] = pkg continue for name in self._theme_names: if fname == 'usr/share/icons/{}/index.theme'.format(name): self._themes.append(Theme(name, pkg.filename)) elif fname.startswith('usr/share/icons/{}'.format(name)): self._icon_files[fname] = pkg def _possible_icon_filenames(self, icon, size): for theme in self._themes: for fname in theme.matching_icon_filenames(icon, size): yield fname # the most favorable file extension needs to come first to prefer it for extension in ('png', 'jpg', 'svgz', 'svg', 'gif', 'ico', 'xpm'): yield 'usr/share/pixmaps/{}.{}'.format(icon, extension) def _find_icons(self, icon_name, sizes, pkg=None): ''' Looks up 'icon' with 'size' in popular icon themes according to the XDG icon theme spec. ''' size_map_flist = dict() for size in sizes: for fname in self._possible_icon_filenames(icon_name, size): if pkg: # we are supposed to search in one particular package if fname in pkg.debfile.get_filelist(): size_map_flist[size] = { 'icon_fname': fname, 'pkg': pkg } break else: # global search pkg = self._icon_files.get(fname) if pkg: size_map_flist[size] = { 'icon_fname': fname, 'pkg': pkg } break return size_map_flist def fetch_icon(self, cpt, pkg, cpt_export_path): ''' Searches for icon if absolute path to an icon is not given. Component with invalid icons are ignored ''' if not cpt.has_icon(): # if we don't know an icon-name or path, just return without error return True icon_str = cpt.get_icon(IconType.CACHED) cpt.set_icon(IconType.CACHED, None) success = False last_icon = False if icon_str.startswith("/"): if icon_str[1:] in pkg.debfile.get_filelist(): return self._store_icon(pkg, cpt, cpt_export_path, icon_str[1:], IconSize(64)) else: icon_str = os.path.basename(icon_str) # Small hack: Strip .png from icon files to make the XDG and Pixmap finder # work properly, which add their own icon extensions and find the most suitable icon. if icon_str.endswith('.png'): icon_str = icon_str[:-4] def search_store_xdg_icon(epkg=None): icon_dict = self._find_icons(icon_str, self._wanted_icon_sizes, epkg) if not icon_dict: return False, None icon_stored = False last_icon_name = None for size in self._wanted_icon_sizes: info = icon_dict.get(size) if not info: # the size we want wasn't found, can we downscale a larger one? for asize, data in icon_dict.items(): if asize < size: continue info = data break if not info: # we give up continue last_icon_name = info['icon_fname'] if self._icon_allowed(last_icon_name): icon_stored = self._store_icon(info['pkg'], cpt, cpt_export_path, last_icon_name, size) or icon_stored else: # the found icon is not suitable, but maybe a larger one is available that we can downscale? for asize, data in icon_dict.items(): if asize <= size: continue info = data break if self._icon_allowed(info['icon_fname']): icon_stored = self._store_icon(info['pkg'], cpt, cpt_export_path, info['icon_fname'], size) or icon_stored last_icon_name = info['icon_fname'] return icon_stored, last_icon_name # search for the right icon iside the current package success, last_icon = search_store_xdg_icon(pkg) if not success and not cpt.has_ignore_reason(): # search in all packages success, last_icon_2 = search_store_xdg_icon() if not last_icon: last_icon = last_icon_2 if success: # we found a valid stock icon, so set that additionally to the cached one cpt.set_icon(IconType.STOCK, icon_str) else: if last_icon and not self._icon_allowed(last_icon): cpt.add_hint("icon-format-unsupported", {'icon_fname': os.path.basename(last_icon)}) if not success and not last_icon: cpt.add_hint("icon-not-found", {'icon_fname': icon_str}) return False return True def _icon_allowed(self, icon): ''' Check if the icon is an icon we actually can and want to handle. ''' if icon.lower().endswith(('.png', '.svg', '.gif', '.svgz', '.jpg')): return True return False def _render_svg_to_png(self, data, store_path, width, height): ''' Uses cairosvg to render svg data to png data. ''' img = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height) ctx = cairo.Context(img) handle = Rsvg.Handle() svg = handle.new_from_data(data) wscale = float(width)/float(svg.props.width) hscale = float(height)/float(svg.props.height) ctx.scale(wscale, hscale); svg.render_cairo(ctx) img.write_to_png(store_path) def _store_icon(self, pkg, cpt, cpt_export_path, icon_path, size): ''' Extracts the icon from the deb package and stores it in the cache. Ensures the stored icon always has the size given in "size", and renders vectorgraphics if necessary. ''' # don't store an icon if we are already ignoring this component if cpt.has_ignore_reason(): return False svgicon = False if not self._icon_allowed(icon_path): cpt.add_hint("icon-format-unsupported", {'icon_fname': os.path.basename(icon_path)}) return False if not os.path.exists(pkg.filename): return False path = cpt.build_media_path(cpt_export_path, "icons/%s" % (str(size))) icon_name = "%s_%s" % (cpt.pkgname, os.path.basename(icon_path)) icon_name_orig = icon_name icon_name = icon_name.replace(".svgz", ".png") icon_name = icon_name.replace(".svg", ".png") icon_store_location = "{0}/{1}".format(path, icon_name) if os.path.exists(icon_store_location): # we already extracted that icon, skip the extraction step # change scalable vector graphics to their .png extension cpt.set_icon(IconType.CACHED, icon_name) return True # filepath is checked because icon can reside in another binary # eg amarok's icon is in amarok-data icon_data = None try: deb = pkg.debfile icon_data = deb.get_file_data(icon_path) except Exception as e: cpt.add_hint("deb-extract-error", {'fname': icon_name, 'pkg_fname': os.path.basename(pkg.filename), 'error': str(e)}) return False if not icon_data: cpt.add_hint("deb-extract-error", {'fname': icon_name, 'pkg_fname': os.path.basename(pkg.filename), 'error': "Icon data was empty. The icon might be a symbolic link pointing at a file outside of this package. " "Please do not do that and instead place the icons in their appropriate directories in <code>/usr/share/icons/hicolor/</code>."}) return False # FIXME: Maybe close the debfile again to not leak FDs? Could hurt performance though. if icon_name_orig.endswith(".svg"): svgicon = True elif icon_name_orig.endswith(".svgz"): svgicon = True try: icon_data = zlib.decompress(bytes(icon_data), 15+32) except Exception as e: cpt.add_hint("svgz-decompress-error", {'icon_fname': icon_name, 'error': str(e)}) return False if not os.path.exists(path): os.makedirs(path) # set the cached icon name in our metadata cpt.set_icon(IconType.CACHED, icon_name) if svgicon: # render the SVG to a bitmap self._render_svg_to_png(icon_data, icon_store_location, int(size), int(size)) return True else: # we don't trust upstream to have the right icon size present, and therefore # always adjust the icon to the right size stream = BytesIO(icon_data) stream.seek(0) img = None try: img = Image.open(stream) except Exception as e: cpt.add_hint("icon-open-failed", {'icon_fname': icon_name, 'error': str(e)}) return False newimg = img.resize((int(size), int(size)), Image.ANTIALIAS) newimg.save(icon_store_location) return True return False
ximion/appstream-dep11
dep11/iconhandler.py
Python
lgpl-3.0
16,459
#coding=utf-8 import math import File_Interface as FI from operator import itemgetter as _itemgetter import numpy as np import jieba from sklearn import preprocessing from collections import Counter import numpy as np class Word2Vec(): def __init__(self, vec_len=15000, learn_rate=0.025, win_len=5, model='cbow'): self.cutted_text_list = None self.vec_len = vec_len self.learn_rate = learn_rate self.win_len = win_len self.model = model self.word_dict = None # each element is a dict, including: word,possibility,vector,huffmancode self.huffman = None # the object of HuffmanTree def Load_Word_Freq(self,word_freq_path): # load the info of word frequence # will generate a word dict if self.word_dict is not None: raise RuntimeError('the word dict is not empty') word_freq = FI.load_pickle(word_freq_path) self.__Gnerate_Word_Dict(word_freq) def __Gnerate_Word_Dict(self,word_freq): # generate a word dict # which containing the word, freq, possibility, a random initial vector and Huffman value if not isinstance(word_freq,dict) and not isinstance(word_freq,list): raise ValueError('the word freq info should be a dict or list') word_dict = {} if isinstance(word_freq,dict): # if word_freq is in type of dictionary sum_count = sum(word_freq.values()) for word in word_freq: temp_dict = dict( word = word, freq = word_freq[word], possibility = word_freq[word]/sum_count, vector = np.random.random([1,self.vec_len]), Huffman = None ) word_dict[word] = temp_dict else: # if word_freq is in type of list freq_list = [x[1] for x in word_freq] sum_count = sum(freq_list) for item in word_freq: temp_dict = dict( word = item[0], freq = item[1], possibility = item[1]/sum_count, vector = np.random.random([1,self.vec_len]), Huffman = None ) word_dict[item[0]] = temp_dict self.word_dict = word_dict def Import_Model(self,model_path): model = FI.load_pickle(model_path) # a dict, {'word_dict','huffman','vec_len'} self.word_dict = model.word_dict self.huffman = model.huffman self.vec_len = model.vec_len self.learn_rate = model.learn_rate self.win_len = model.win_len self.model = model.model def Export_Model(self,model_path): data=dict( word_dict = self.word_dict, huffman = self.huffman, vec_len = self.vec_len, learn_rate = self.learn_rate, win_len = self.win_len, model = self.model ) FI.save_pickle(data,model_path) def Train_Model(self,text_list): # generate the word_dict and huffman tree if self.huffman==None: # if the dict is not loaded, it will generate a new dict if self.word_dict==None : wc = WordCounter(text_list) self.__Gnerate_Word_Dict(wc.count_res.larger_than(5)) self.cutted_text_list = wc.text_list # generate a huffman tree according to the possibility of words self.huffman = HuffmanTree(self.word_dict,vec_len=self.vec_len) print('word_dict and huffman tree already generated, ready to train vector') # start to train word vector before = (self.win_len-1) >> 1 after = self.win_len-1-before if self.model=='cbow': method = self.__Deal_Gram_CBOW else: method = self.__Deal_Gram_SkipGram if self.cutted_text_list: # if the text has been cutted total = self.cutted_text_list.__len__() count = 0 for line in self.cutted_text_list: line_len = line.__len__() for i in range(line_len): method(line[i],line[max(0,i-before):i]+line[i+1:min(line_len,i+after+1)]) count += 1 print('{c} of {d}'.format(c=count,d=total)) else: # if the text has note been cutted for line in text_list: line = list(jieba.cut(line,cut_all=False)) line_len = line.__len__() for i in range(line_len): method(line[i],line[max(0,i-before):i]+line[i+1:min(line_len,i+after+1)]) print('word vector has been generated') def __Deal_Gram_CBOW(self,word,gram_word_list): if not self.word_dict.__contains__(word): return word_huffman = self.word_dict[word]['Huffman'] gram_vector_sum = np.zeros([1,self.vec_len]) for i in range(gram_word_list.__len__())[::-1]: item = gram_word_list[i] if self.word_dict.__contains__(item): gram_vector_sum += self.word_dict[item]['vector'] else: gram_word_list.pop(i) if gram_word_list.__len__()==0: return e = self.__GoAlong_Huffman(word_huffman,gram_vector_sum,self.huffman.root) for item in gram_word_list: self.word_dict[item]['vector'] += e self.word_dict[item]['vector'] = preprocessing.normalize(self.word_dict[item]['vector']) def __Deal_Gram_SkipGram(self,word,gram_word_list): if not self.word_dict.__contains__(word): return word_vector = self.word_dict[word]['vector'] for i in range(gram_word_list.__len__())[::-1]: if not self.word_dict.__contains__(gram_word_list[i]): gram_word_list.pop(i) if gram_word_list.__len__()==0: return for u in gram_word_list: u_huffman = self.word_dict[u]['Huffman'] e = self.__GoAlong_Huffman(u_huffman,word_vector,self.huffman.root) self.word_dict[word]['vector'] += e self.word_dict[word]['vector'] = preprocessing.normalize(self.word_dict[word]['vector']) def __GoAlong_Huffman(self,word_huffman,input_vector,root): node = root e = np.zeros([1,self.vec_len]) for level in range(word_huffman.__len__()): huffman_charat = word_huffman[level] q = self.__Sigmoid(input_vector.dot(node.value.T)) grad = self.learn_rate * (1-int(huffman_charat)-q) e += grad * node.value node.value += grad * input_vector node.value = preprocessing.normalize(node.value) if huffman_charat=='0': node = node.right else: node = node.left return e def __Sigmoid(self,value): return 1/(1+math.exp(-value)) class HuffmanTreeNode(): def __init__(self,value,possibility): # common part of leaf node and tree node self.possibility = possibility self.left = None self.right = None # value of leaf node will be the word, and be # mid vector in tree node self.value = value # the value of word self.Huffman = "" # store the huffman code def __str__(self): return 'HuffmanTreeNode object, value: {v}, possibility: {p}, Huffman: {h}' \ .format(v=self.value,p=self.possibility,h=self.Huffman) class HuffmanTree(): def __init__(self, word_dict, vec_len=15000): self.vec_len = vec_len # the length of word vector self.root = None word_dict_list = list(word_dict.values()) node_list = [HuffmanTreeNode(x['word'],x['possibility']) for x in word_dict_list] self.build_tree(node_list) # self.build_CBT(node_list) self.generate_huffman_code(self.root, word_dict) def build_tree(self,node_list): # node_list.sort(key=lambda x:x.possibility,reverse=True) # for i in range(node_list.__len__()-1)[::-1]: # top_node = self.merge(node_list[i],node_list[i+1]) # node_list.insert(i,top_node) # self.root = node_list[0] while node_list.__len__()>1: i1 = 0 # i1表示概率最小的节点 i2 = 1 # i2 概率第二小的节点 if node_list[i2].possibility < node_list[i1].possibility : [i1,i2] = [i2,i1] for i in range(2,node_list.__len__()): # 找到最小的两个节点 if node_list[i].possibility<node_list[i2].possibility : i2 = i if node_list[i2].possibility < node_list[i1].possibility : [i1,i2] = [i2,i1] top_node = self.merge(node_list[i1],node_list[i2]) if i1<i2: node_list.pop(i2) node_list.pop(i1) elif i1>i2: node_list.pop(i1) node_list.pop(i2) else: raise RuntimeError('i1 should not be equal to i2') node_list.insert(0,top_node) self.root = node_list[0] def build_CBT(self,node_list): # build a complete binary tree node_list.sort(key=lambda x:x.possibility,reverse=True) node_num = node_list.__len__() before_start = 0 while node_num>1 : for i in range(node_num>>1): top_node = self.merge(node_list[before_start+i*2],node_list[before_start+i*2+1]) node_list.append(top_node) if node_num%2==1: top_node = self.merge(node_list[before_start+i*2+2],node_list[-1]) node_list[-1] = top_node before_start = before_start + node_num node_num = node_num>>1 self.root = node_list[-1] def generate_huffman_code(self, node, word_dict): # # use recursion in this edition # if node.left==None and node.right==None : # word = node.value # code = node.Huffman # print(word,code) # word_dict[word]['Huffman'] = code # return -1 # # code = node.Huffman # if code==None: # code = "" # node.left.Huffman = code + "1" # node.right.Huffman = code + "0" # self.generate_huffman_code(node.left, word_dict) # self.generate_huffman_code(node.right, word_dict) # use stack butnot recursion in this edition stack = [self.root] while (stack.__len__()>0): node = stack.pop() # go along left tree while node.left or node.right : code = node.Huffman node.left.Huffman = code + "1" node.right.Huffman = code + "0" stack.append(node.right) node = node.left word = node.value code = node.Huffman # print(word,'\t',code.__len__(),'\t',node.possibility) word_dict[word]['Huffman'] = code def merge(self,node1,node2): top_pos = node1.possibility + node2.possibility top_node = HuffmanTreeNode(np.zeros([1,self.vec_len]), top_pos) if node1.possibility >= node2.possibility : top_node.left = node1 top_node.right = node2 else: top_node.left = node2 top_node.right = node1 return top_node class WordCounter(): # can calculate the freq of words in a text list # for example # >>> data = ['Merge multiple sorted inputs into a single sorted output', # 'The API below differs from textbook heap algorithms in two aspects'] # >>> wc = WordCounter(data) # >>> print(wc.count_res) # >>> MulCounter({' ': 18, 'sorted': 2, 'single': 1, 'below': 1, 'inputs': 1, 'The': 1, 'into': 1, 'textbook': 1, # 'API': 1, 'algorithms': 1, 'in': 1, 'output': 1, 'heap': 1, 'differs': 1, 'two': 1, 'from': 1, # 'aspects': 1, 'multiple': 1, 'a': 1, 'Merge': 1}) def __init__(self, text_list): self.text_list = text_list self.stop_word = self.Get_Stop_Words() self.count_res = None self.Word_Count(self.text_list) def Get_Stop_Words(self): ret = [] ret = FI.load_pickle('./static/stop_words.pkl') return ret def Word_Count(self,text_list,cut_all=False): filtered_word_list = [] count = 0 for line in text_list: res = jieba.cut(line,cut_all=cut_all) res = list(res) text_list[count] = res count += 1 filtered_word_list += res self.count_res = MulCounter(filtered_word_list) for word in self.stop_word: try: self.count_res.pop(word) except: pass class MulCounter(Counter): # a class extends from collections.Counter # add some methods, larger_than and less_than """ def __init__(self,element_list): super().__init__(element_list) """ def larger_than(self,minvalue,ret='list'): temp = sorted(self.items(),key=_itemgetter(1),reverse=True) low = 0 high = temp.__len__() while(high - low > 1): mid = (low+high) >> 1 if temp[mid][1] >= minvalue: low = mid else: high = mid if temp[low][1]<minvalue: if ret=='dict': return {} else: return [] if ret=='dict': ret_data = {} for ele,count in temp[:high]: ret_data[ele]=count return ret_data else: return temp[:high] def less_than(self,maxvalue,ret='list'): temp = sorted(self.items(),key=_itemgetter(1)) low = 0 high = temp.__len__() while ((high-low) > 1): mid = (low+high) >> 1 if temp[mid][1] <= maxvalue: low = mid else: high = mid if temp[low][1]>maxvalue: if ret=='dict': return {} else: return [] if ret=='dict': ret_data = {} for ele,count in temp[:high]: ret_data[ele]=count return ret_data else: return temp[:high] if __name__ == '__main__': # text = FI.load_pickle('./static/demo.pkl') # text =[ x['dealed_text']['left_content'][0] for x in text] data = ['Merge multiple sorted inputs into a single sorted output','The API below differs from textbook heap algorithms in two aspects'] wv = Word2Vec(vec_len=500) wv.Train_Model(data) # FI.save_pickle(wv.word_dict,'./static/wv.pkl') # # data = FI.load_pickle('./static/wv.pkl') # x = {} # for key in data: # temp = data[key]['vector'] # temp = preprocessing.normalize(temp) # x[key] = temp # FI.save_pickle(x,'./static/normal_wv.pkl') # x = FI.load_pickle('./static/normal_wv.pkl') # def cal_simi(data,key1,key2): # return data[key1].dot(data[key2].T)[0][0] # keys=list(x.keys()) # for key in keys: # print(key,'\t',cal_simi(x,'姚明',key))
yuanlaihenjiandan/word2vec
word2vec_v2.0.py
Python
mit
15,850
# # Copyright (c) 2008 Red Hat, Inc. # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with this software; if not, see # http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. # # Red Hat trademarks are not licensed under GPLv2. No permission is # granted to use or replicate Red Hat trademarks that are incorporated # in this software or its documentation. # # # rhn-ssl-tool command line option module # # $Id$ ## FIXME: the logic here is *WAY* too complicated. Need to simplify -taw ## language imports import os import sys ## utitily imports from optparse import Option, OptionParser, make_option ## local imports from sslToolLib import daysTil18Jan2038, yearsTil18Jan2038, \ RhnSslToolException, errnoGeneralError from sslToolConfig import figureDEFS_dirs, figureDEFS_CA, figureDEFS_server from sslToolConfig import figureDEFS_distinguishing from sslToolConfig import DEFS, getOption, reInitDEFS # # option lists. # stitched together later to give a known list of commands. # def _getOptionsTree(defs): """ passing in the defaults dictionary (which is not static) build the options tree dependent on whats on the commandline """ _optCAKeyPassword = make_option('-p', '--password', action='store', type="string", help='CA password') _optCaKey = make_option('--ca-key', action='store', type="string", help='CA private key filename (default: %s)' % defs['--ca-key']) _optCaCert = make_option('--ca-cert', action='store', type="string", help='CA certificate filename (default: %s)' % defs['--ca-cert']) #_optServerKeyPassword = make_option('-p', '--password', action='store', type="string", help='password to generate the web server's SSL private key') _optCertExp = make_option('--cert-expiration', action='store', type="int", help='expiration of certificate (default: %s days)' % (int(defs['--cert-expiration']))) _optServerKey = make_option('--server-key', action='store', type="string", help="the web server's SSL private key filename (default: %s)" % defs['--server-key']) _optServerCertReq = make_option('--server-cert-req', action='store', type="string", help="location of the web server's SSL certificate request filename (default: %s)" % defs['--server-cert-req']) _optServerCert = make_option('--server-cert', action='store', type="string", help='the web server SSL certificate filename (default: %s)' % defs['--server-cert']) _optCaForce = make_option('-f', '--force', action='store_true', help='forcibly create a new CA SSL private key and/or public certificate') _optCaKeyOnly = make_option('--key-only', action='store_true', help='(rarely used) only generate a CA SSL private key. Review "--gen-ca --key-only --help" for more information.') _optCaCertOnly = make_option('--cert-only', action='store_true', help='(rarely used) only generate a CA SSL public certificate. Review "--gen-ca --cert-only --help" for more information.') _optServerKeyOnly = make_option('--key-only', action='store_true', help="""(rarely used) only generate the web server's SSL private key. Review "--gen-server --key-only --help" for more information.""") _optServerCertReqOnly = make_option('--cert-req-only', action='store_true', help="""(rarely used) only generate the web server's SSL certificate request. Review "--gen-server --cert-req-only --help" for more information.""") _optServerCertOnly = make_option('--cert-only', action='store_true', help="""(rarely used) only generate the web server's SSL certificate. Review "--gen-server --cert-only --help" for more information.""") _optCaCertRpm = make_option('--ca-cert-rpm', action='store', type="string", help='(rarely changed) RPM name that houses the CA SSL public certificate (the base filename, not filename-version-release.noarch.rpm).') _optServerRpm = make_option('--server-rpm', action='store', type="string", help="(rarely changed) RPM name that houses the web server's SSL key set (the base filename, not filename-version-release.noarch.rpm).") _optServerTar = make_option('--server-tar', action='store', type="string", help="(rarely changed) name of tar archive of the web server's SSL key set and CA SSL public certificate that is used solely by the hosted RHN Proxy installation routines (the base filename, not filename-version-release.tar).") _optRpmPackager = make_option('--rpm-packager', action='store', type="string", help='(rarely used) packager of the generated RPM, such as "RHN Admin <rhn-admin@example.com>".') _optRpmVender = make_option('--rpm-vendor', action='store', type="string", help='(rarely used) vendor of the generated RPM, such as "IS/IT Example Corp.".') _optRpmOnly = make_option('--rpm-only', action='store_true', help='(rarely used) only generate a deployable RPM. (and tar archive if used during the --gen-server step) Review "<baseoption> --rpm-only --help" for more information.') _optNoRpm = make_option('--no-rpm', action='store_true', help='(rarely used) do everything *except* generate an RPM.') _optSetHostname = make_option('--set-hostname', action='store', type="string", help='hostname of the web server you are installing the key set on (default: %s)' % repr(defs['--set-hostname'])) _buildRpmOptions = [_optRpmPackager, _optRpmVender, _optRpmOnly] _genOptions = [ make_option('-v','--verbose', action='count', help='be verbose. Accumulative: -vvv means "be *really* verbose".'), make_option('-d','--dir', action='store', help="build directory (default: %s)" % defs['--dir']), make_option('-q','--quiet', action='store_true', help="be quiet. No output."), ] _genConfOptions = [ make_option('--set-country', action='store', type="string", help='2 letter country code (default: %s)' % repr(defs['--set-country'])), make_option('--set-state', action='store', type="string", help='state or province (default: %s)' % repr(defs['--set-state'])), make_option('--set-city', action='store', type="string", help='city or locality (default: %s)' % repr(defs['--set-city'])), make_option('--set-org', action='store', type="string", help='organization or company name, such as "Red Hat Inc." (default: %s)' % repr(defs['--set-org'])), make_option('--set-org-unit', action='store', type="string", help='organizational unit, such as "RHN" (default: %s)' % repr(defs['--set-org-unit'])), make_option('--set-email', action='store', type="string", help='email address (default: %s)' % repr(defs['--set-email'])), ] _caConfOptions = [ make_option('--set-common-name', action='store', type="string", help='common name (default: %s)' % repr(defs['--set-common-name'])), ] + _genConfOptions _serverConfOptions = [ _optSetHostname ] + _genConfOptions # CA generation options _caOptions = [ _optCaForce, _optCAKeyPassword, _optCaKey, ] # CA cert generation options _caCertOptions = [ _optCaForce, _optCAKeyPassword, _optCaKey, _optCaCert, _optCertExp, ] + _caConfOptions # server key generation options _serverKeyOptions = [ #_optServerKeyPassword, _optServerKey, ] # server cert req generation options _serverCertReqOptions = [ #_optServerKeyPassword, _optServerKey, _optServerCertReq, ] # server cert generation options _serverCertOptions = [ _optCAKeyPassword, _optCaCert, _optCaKey, _optServerCertReq, Option('--startdate', action='store', type="string", default=defs['--startdate'], help="start date for the web server's SSL certificate validity (format: YYMMDDHHMMSSZ - where Z is a letter; default is 1 week ago: %s)" % defs['--startdate']), _optServerCert, _optCertExp, ] # the base options _optGenCa = make_option('--gen-ca', action='store_true', help='generate a Certificate Authority (CA) key pair and public RPM. Review "--gen-ca --help" for more information.') _optGenServer = make_option("--gen-server", action='store_true', help="""generate the web server's SSL key set, RPM and tar archive. Review "--gen-server --help" for more information.""") # CA build option tree set possibilities _caSet = [_optGenCa] + _caOptions + _caCertOptions \ + _genOptions + [_optCaKeyOnly, _optCaCertOnly] + _buildRpmOptions \ + [_optCaCertRpm, _optNoRpm] _caKeyOnlySet = [_optGenCa] + _caOptions + _genOptions \ + [_optCaKeyOnly] _caCertOnlySet = [_optGenCa] + _caOptions + _caCertOptions \ + _genOptions + [_optCaCertOnly] _caRpmOnlySet = [_optGenCa, _optCaKey, _optCaCert] \ + _buildRpmOptions + [_optCaCertRpm] + _genOptions # server build option tree set possibilities _serverSet = [_optGenServer] + _serverKeyOptions + _serverCertReqOptions \ + _serverCertOptions + _serverConfOptions + _genOptions \ + [_optServerKeyOnly, _optServerCertReqOnly, _optServerCertOnly] \ + _buildRpmOptions + [_optServerRpm, _optServerTar, _optNoRpm] _serverKeyOnlySet = [_optGenServer] + _serverKeyOptions \ + _genOptions + [_optServerKeyOnly] _serverCertReqOnlySet = [_optGenServer] + _serverKeyOptions \ + _serverCertReqOptions + _serverConfOptions \ + _genOptions + [_optServerCertReqOnly] _serverCertOnlySet = [_optGenServer] + _serverCertOptions \ + _genOptions + [_optServerCertOnly] _serverRpmOnlySet = [_optGenServer, _optServerKey, _optServerCertReq, _optServerCert, _optSetHostname ] \ + _buildRpmOptions + [_optServerRpm, _optServerTar] + _genOptions optionsTree = { '--gen-ca' : _caSet, '--gen-server' : _serverSet, } # quick check about the --*-only options _onlyOpts = ['--key-only', '--cert-req-only', '--cert-only', '--rpm-only'] _onlyIntersection = setIntersection(sys.argv, _onlyOpts) if len(_onlyIntersection) > 1: sys.stderr.write("""\ ERROR: cannot use these options in combination: %s\n""" % repr(_onlyIntersection)) sys.exit(errnoGeneralError) _onlyIntersection = setIntersection(sys.argv, ['--rpm-only', '--no-rpm']) if len(_onlyIntersection) > 1: sys.stderr.write("""\ ERROR: cannot use these options in combination: %s\n""" % repr(_onlyIntersection)) sys.exit(errnoGeneralError) if '--key-only' in sys.argv: optionsTree['--gen-ca'] = _caKeyOnlySet optionsTree['--gen-server'] = _serverKeyOnlySet elif '--cert-only' in sys.argv: optionsTree['--gen-ca'] = _caCertOnlySet optionsTree['--gen-server'] = _serverCertOnlySet elif '--cert-req-key-only' in sys.argv: optionsTree['--gen-server'] = _serverCertReqOnlySet elif '--rpm-only' in sys.argv: optionsTree['--gen-ca'] = _caRpmOnlySet optionsTree['--gen-server'] = _serverRpmOnlySet baseOptions = [_optGenCa, _optGenServer] return optionsTree, baseOptions def unique(s): """ make sure a sequence is unique. Using dead simple method (other faster methods assume too much). Returns a list. """ assert type(s) in (type([]), type(()), type("")) n = len(s) if not n: return [] l = [] for item in s: if item not in l: l.append(item) return l def setIntersection(*sets): """ return the intersection of 0 or more sequences. a teeny bit recursive. """ n = len(sets) if n <= 1: return unique(sets[0]) setA = unique(sets[0]) #setB = setIntersection(*sets[1:]) # a python 2.* -ism setB = apply(setIntersection, sets[1:], {}) inter = [] for item in setA: if item in setB: inter.append(item) return inter ## custom usage text _progName = os.path.basename(sys.argv[0]) BASE_USAGE = """\ %s [options] step 1 %s --gen-ca [sub-options] step 2 %s --gen-server [sub-options] The two options listed above are "base options". For more help about a particular option, just add --help to either one, such as: %s --gen-ca --help If confused, please refer to the man page or other documentation for sample usage.\ """ % tuple([_progName]*4) OTHER_USAGE = """\ %s [options] If confused, please refer to the man page or other documentation for sample usage.\ """ % _progName def _getOptionList(defs): """ stitch together the commandline given rules set in optionsTree and the grouping logic. """ optionsTree, baseOptions = _getOptionsTree(defs) optionsList = [] usage = OTHER_USAGE argIntersection = setIntersection(sys.argv, optionsTree.keys()) if len(argIntersection) == 1: optionsList = optionsTree[argIntersection[0]] optionsList = unique(optionsList) elif len(argIntersection) > 1: # disallow multiple base options on the same commandline sys.stderr.write("""\ ERROR: cannot use these options in combination: %s (%s --help)\n""" % (argIntersection, _progName)) sys.exit(errnoGeneralError) else: # if *no* base options on he commandline, clear on the list # and tag on a --help optionsList = baseOptions usage = BASE_USAGE if '--help' not in sys.argv: sys.argv.append('--help') return optionsList, usage def optionParse(): """ We parse in 3 steps: (1) parse options (2) set the defaults based on any options we override on the commandline - this is nice for things like (what dir we are working in etc). (3) reparse the options with defaults set Reset the default values DEFS given the options found. """ # force certain "first options". Not beautiful but it works. if len(sys.argv) > 1: if sys.argv[1] not in ('-h', '--help', '--gen-ca', '--gen-server'): # first option was not something we understand. Force a base --help del(sys.argv[1:]) sys.argv.append('--help') if '--gen-ca' in sys.argv: reInitDEFS(1) else: reInitDEFS(0) ## ## STEP 1: preliminarily parse options ## #print 'XXX STEP1' optionList, usage = _getOptionList(DEFS) optionListNoHelp = optionList[:] fake_help = Option("-h", "--help", action="count", help='') optionListNoHelp.append(fake_help) options, args = OptionParser(option_list=optionListNoHelp, add_help_option=0).parse_args() ## ## STEP 2: repopulate DEFS dict based on commandline ## and the *-openssl.cnf files ## #print 'XXX STEP2' figureDEFS_dirs(options) # build directory structure figureDEFS_CA(options) # CA key set stuff figureDEFS_server(options) # server key set stuff figureDEFS_distinguishing(options) # distinguishing name stuff ## ## STEP 3: reparse options again only if --help is in the commandline ## so that we can give a --help with correct defaults set. ## #print 'XXX STEP3' if '-h' in sys.argv or '--help' in sys.argv: # DEFS should be mapped with new values now... let's reparse the options. # The correct help text should be presented and all defaults # should be mapped as expected. optionList, usage = _getOptionList(DEFS) options, args = OptionParser(option_list=optionList, usage=usage).parse_args() # we take no extra commandline arguments that are not linked to an option if args: sys.stderr.write("\nERROR: these arguments make no sense in this " "context (try --help): %s\n" % repr(args)) sys.exit(errnoGeneralError) return options class CertExpTooShortException(RhnSslToolException): "certificate expiration must be at least 1 day" class CertExpTooLongException(RhnSslToolException): "cert expiration cannot be > 1 year before the 32-bit overflow (in days)" class InvalidCountryCodeException(RhnSslToolException): "invalid country code. Probably != 2 characters in length." def processCommandline(): options = optionParse() _maxDays = daysTil18Jan2038() cert_expiration = getOption(options, 'cert_expiration') if cert_expiration: if cert_expiration < 1: raise CertExpTooShortException( "certificate expiration must be at least 1 day") if cert_expiration > _maxDays: raise CertExpTooLongException( "certificate expiration cannot exceed %s days " "(~%.2f years)\n" % (int(_maxDays), yearsTil18Jan2038())) country = getOption(options, 'set_country') if country is not None and (country == '' or len(country) != 2): raise InvalidCountryCodeException( "country code must be exactly two characters, such as 'US'") if options.quiet: options.verbose = -1 if not options.verbose: options.verbose = 0 return options #===============================================================================
colloquium/spacewalk
spacewalk/certs-tools/sslToolCli.py
Python
gpl-2.0
17,416
from keras.models import Model, clone_model import keras.layers as layers import numpy as np from keras import backend as K def build_double_inp(compile=False): inp_1 = layers.Input((1,), name="inp_0") inp_2 = layers.Input((1,), name="inp_1") x = layers.Concatenate()([inp_1, inp_2]) x = layers.Dense(3)(x) output_1 = layers.Dense(1, name="out_0")(x) output_2 = layers.Dense(2, name="out_1")(x) test_model = Model((inp_1, inp_2), (output_1, output_2)) if compile: test_model.compile("adam", loss={"out_0": "mse", "out_1": "mse"}, metrics={"out_0": "mae", "out_1": "mae"}) return test_model def get_xys(): x = {"inp_0": np.array([9, 3]), "inp_1": np.array([81, 18])} y = {"out_0": np.array([1, 1]), "out_1": np.array([[0,0], [0,0]])} return x, y def build_single_inp(): inp = layers.Input((2,), name="inp") x = layers.Dense(3)(inp) output_1 = layers.Dense(1, name="out_0")(x) output_2 = layers.Dense(2, name="out_1")(x) test_model = Model(inp, (output_1, output_2)) return test_model def get_xs(model, batchsize=1): """ Get dummy data fitting a model. """ shapes = model.input_shape if len(model.input_names) == 1: shapes = [shapes, ] xs = {model.input_names[i]: np.ones([batchsize, ] + list(shapes[i][1:])) for i in range(len(model.input_names))} return xs def dropout_test(): def dropout_model(rate=0.): inp = layers.Input((10,)) out = layers.Dropout(rate)(inp) model = Model(inp, out) return model def get_layer_output(model, xs, which=-1): l_out = K.function([model.layers[0].input, K.learning_phase()], [model.layers[which].output]) # output in train mode = 1 layer_output = l_out([xs, 1])[0] return layer_output model0 = dropout_model(0.) model1 = dropout_model(0.99) xs = np.ones((3, 10)) print("no drop\n", get_layer_output(model0, xs)) print("\nmax drop\n", get_layer_output(model1, xs)) model1.layers[-1].rate = 0. print("\nchanged max drop to zero\n", model1.layers[-1].get_config()) print(get_layer_output(model1, xs)) model1_clone = clone_model(model1) print("\n clone changed model\n", get_layer_output(model1_clone, xs)) def get_structured_array(): x = np.array([(9, 81.0), (3, 18), (3, 18), (3, 18)], dtype=[('inp_0', 'f4'), ('inp_1', 'f4')]) return x def get_dict(): x = {"inp_0": np.array([9, 3]), "inp_1": np.array([81, 18])} return x def transf_arr(x): xd = {name: x[name] for name in x.dtype.names} return xd
ViaFerrata/DL_pipeline_TauAppearance
scraps/test_model.py
Python
agpl-3.0
2,683
# -*- coding: utf-8 -*- class IS_CUIT(object): def __init__(self, error_message='debe ser un CUIT válido en formato XX-YYYYYYYY-Z'): self.error_message = error_message def __call__(self, value): # validaciones mínimas if len(value) == 13 and value[2] == "-" and value[11] == "-": base = [5,4,3,2,7,6,5,4,3,2] cuit = value.replace("-","") # remuevo las barras # calculo el dígito verificador: aux = 0 for i in xrange(10): aux += int(cuit[i])*base[i] aux = 11-(aux-(int(aux / 11)*11)) if aux==11: aux = 0 if aux==10: aux = 9 if aux == int(cuit[10]): return (value, None) return (value, self.error_message) def formatter(self, value): return value
InstitutoPascal/Staff
models/cuit.py
Python
gpl-3.0
873
import click @click.group(help="Command line interface for trefoil") def cli(): pass
consbio/clover
trefoil/cli/__init__.py
Python
bsd-3-clause
90
#!/usr/bin/env python """ dgit default configuration manager [User] section: * user.name: Name of the user * user.email: Email address (to be used when needed) * user.fullname: Full name of the user """ import os, sys, json, re, traceback, getpass try: from urllib.parse import urlparse except: from urlparse import urlparse import configparser from .plugins.common import plugins_get_mgr config = None ################################### # Input validators ################################### class ChoiceValidator(object): def __init__(self, choices): self.choices = choices message = "Supported options include: {}" self.message = message.format(",".join(self.choices)) def is_valid(self, value): if value in self.choices: return True return False class NonEmptyValidator(object): def __init__(self): self.message = "Value cannot be an empty string" def is_valid(self, value): if value is None or len(value) == 0: return False return True class EmailValidator(object): def __init__(self): self.message = "Value has to be an email address" self.pattern = r"[^@]+@[^@]+\.[^@]+" def is_valid(self, value): if not re.match(self.pattern, value): return False return True class URLValidator(object): def __init__(self): self.message = "Value should be a valid URL" def is_valid(self, value): o = urlparse(value) return o.scheme in ['http', 'https'] ################################### # Main helper functions... ################################### def getprofileini(): if 'DGIT_INI' in os.environ: profileini = os.environ['DGIT_INI'] else: homedir = os.path.abspath(os.environ['HOME']) profileini = os.path.join(homedir,'.dgit.ini') return profileini def init(globalvars=None, show=False): """ Load profile INI """ global config profileini = getprofileini() if os.path.exists(profileini): config = configparser.ConfigParser() config.read(profileini) mgr = plugins_get_mgr() mgr.update_configs(config) if show: for source in config: print("[%s] :" %(source)) for k in config[source]: print(" %s : %s" % (k, config[source][k])) else: print("Profile does not exist. So creating one") if not show: update(globalvars) print("Complete init") def input_with_default(message, default): res = input("%s [%s]: " %(message, default)) return res or default def update(globalvars): """ Update the profile """ global config profileini = getprofileini() config = configparser.ConfigParser() config.read(profileini) defaults = {} if globalvars is not None: defaults = {a[0]: a[1] for a in globalvars } # Generic variables to be captured... generic_configs = [{ 'name': 'User', 'nature': 'generic', 'description': "General information", 'variables': ['user.email', 'user.name', 'user.fullname'], 'defaults': { 'user.email': { 'value': defaults.get('user.email',''), 'description': "Email address", 'validator': EmailValidator() }, 'user.fullname': { 'value': defaults.get('user.fullname',''), 'description': "Full Name", 'validator': NonEmptyValidator() }, 'user.name': { 'value': defaults.get('user.name', getpass.getuser()), 'description': "Name", 'validator': NonEmptyValidator() }, } }] # Gather configuration requirements from all plugins mgr = plugins_get_mgr() extra_configs = mgr.gather_configs() allconfigs = generic_configs + extra_configs # Read the existing config and update the defaults for c in allconfigs: name = c['name'] for v in c['variables']: try: c['defaults'][v]['value'] = config[name][v] except: continue for c in allconfigs: print("") print(c['description']) print("==================") if len(c['variables']) == 0: print("Nothing to do. Enabled by default") continue name = c['name'] config[name] = {} config[name]['nature'] = c['nature'] for v in c['variables']: # defaults value = '' description = v + " " helptext = "" validator = None # Look up pre-set values if v in c['defaults']: value = c['defaults'][v].get('value','') helptext = c['defaults'][v].get("description","") validator = c['defaults'][v].get('validator',None) if helptext != "": description += "(" + helptext + ")" # Get user input.. while True: choice = input_with_default(description, value) if validator is not None: if validator.is_valid(choice): break else: print("Invalid input. Expected input is {}".format(validator.message)) else: break config[name][v] = choice if v == 'enable' and choice == 'n': break with open(profileini, 'w') as fd: config.write(fd) print("Updated profile file:", config) def get_config(): if config is None: init() return config
pingali/dgit
dgitcore/config.py
Python
isc
5,839
#!/usr/bin/python3 import sys import pickle codons_dict = pickle.load(open("codons_dict.pickle", "rb")) def rna_to_amino(string, codict=codons_dict): """Returns the amino acid sequence of an exact RNA sequence.""" assert len(string) % 3 == 0, "RNA sequence malformed (string length not divisible by 3)" if len(string) == 0: return "" else: if codict[string[0:3]] != "Stop": return codict[string[0:3]] + rna_to_amino(string[3:], codict) else: return "" # A stop codon means the string is done, obv. def split_nth(seq, n=300): """Split a string into a list of strings n characters long.""" while seq: yield seq[:n] seq = seq[n:] if __name__=="__main__": for line in sys.stdin: for chunk in split_nth(line.strip()): print(rna_to_amino(chunk), end="") print("") # newline # Alright, this works well enough for small inputs, but Python # isn't optimized for recursion and I'll need to figure out a way # for this to scale better. Gah, my elegance will be lost!!
andrew-quinn/rosalind-exercises
problems/prot/prot.py
Python
mit
1,083
from __future__ import unicode_literals class AppSettings(object): def __init__(self): pass def _setting(self, name, dflt): from django.conf import settings getter = getattr(settings, 'SPONSOR_SETTING_GETTER', lambda name, dflt: getattr(settings, name, dflt)) return getter(name, dflt) @property def SPONSOR_EXPIRATES(self): """ Do sponsorships expire? True or False. """ return self._setting('SPONSOR_EXPIRATES', False) @property def SPONSOR_EXPIRE_ON_MONTHS(self): """ Default number of months that a sponsor's expiration date is set from now. """ return self._setting('SPONSOR_EXPIRE_ON_MONTHS', 12) @property def SPONSOR_LOGO_WIDTH(self): """ Default logo width used when creating a sponsor object, then image will be dinamically resized using this property. Also you can change it for any sponsor in the admin. """ return self._setting('settings.SPONSOR_LOGO_WIDTH', 200) @property def SPONSOR_LOGO_HEIGHT(self): """ Default logo height used when creating a sponsor object, then image will be dinamically resized using this property. Also you can change it for any sponsor in the admin. Better set it to None, and in case a special logo needs to be resized vertically, do it in the admin independently to it. """ return self._setting('settings.SPONSOR_LOGO_WIDTH', None) # Ugly? Guido recommends this himself ... # http://mail.python.org/pipermail/python-ideas/2012-May/014969.html import sys app_settings = AppSettings() app_settings.__name__ = __name__ sys.modules[__name__] = app_settings
miguelfg/django-sponsors
sponsors/app_settings.py
Python
mit
1,790
from mpi4py import MPI import helloworld as hw null = MPI.COMM_NULL fnull = null.py2f() hw.sayhello(fnull) comm = MPI.COMM_WORLD fcomm = comm.py2f() hw.sayhello(fcomm) try: hw.sayhello(list()) except: pass else: assert 0, "exception not raised"
pressel/mpi4py
demo/wrap-f2py/test.py
Python
bsd-2-clause
260
import numpy as np import pickle import ray from ray.rllib.models.modelv2 import ModelV2 from ray.rllib.models.tf.misc import normc_initializer from ray.rllib.models.tf.recurrent_net import RecurrentNetwork from ray.rllib.utils.annotations import override from ray.rllib.utils.framework import try_import_tf tf1, tf, tfv = try_import_tf() class SpyLayer(tf.keras.layers.Layer): """A keras Layer, which intercepts its inputs and stored them as pickled. """ output = np.array(0, dtype=np.int64) def __init__(self, num_outputs, **kwargs): super().__init__(**kwargs) self.dense = tf.keras.layers.Dense( units=num_outputs, kernel_initializer=normc_initializer(0.01)) def call(self, inputs, **kwargs): """Does a forward pass through our Dense, but also intercepts inputs. """ del kwargs spy_fn = tf1.py_func( self.spy, [ inputs[0], # observations inputs[2], # seq_lens inputs[3], # h_in inputs[4], # c_in inputs[5], # h_out inputs[6], # c_out ], tf.int64, # Must match SpyLayer.output's type. stateful=True) # Compute outputs with tf1.control_dependencies([spy_fn]): return self.dense(inputs[1]) @staticmethod def spy(inputs, seq_lens, h_in, c_in, h_out, c_out): """The actual spy operation: Store inputs in internal_kv.""" if len(inputs) == 1: # don't capture inference inputs return SpyLayer.output # TF runs this function in an isolated context, so we have to use # redis to communicate back to our suite ray.experimental.internal_kv._internal_kv_put( "rnn_spy_in_{}".format(RNNSpyModel.capture_index), pickle.dumps({ "sequences": inputs, "seq_lens": seq_lens, "state_in": [h_in, c_in], "state_out": [h_out, c_out] }), overwrite=True) RNNSpyModel.capture_index += 1 return SpyLayer.output class RNNSpyModel(RecurrentNetwork): capture_index = 0 cell_size = 3 def __init__(self, obs_space, action_space, num_outputs, model_config, name): super().__init__(obs_space, action_space, num_outputs, model_config, name) self.cell_size = RNNSpyModel.cell_size # Create a keras LSTM model. inputs = tf.keras.layers.Input( shape=(None, ) + obs_space.shape, name="input") state_in_h = tf.keras.layers.Input(shape=(self.cell_size, ), name="h") state_in_c = tf.keras.layers.Input(shape=(self.cell_size, ), name="c") seq_lens = tf.keras.layers.Input( shape=(), name="seq_lens", dtype=tf.int32) lstm_out, state_out_h, state_out_c = tf.keras.layers.LSTM( self.cell_size, return_sequences=True, return_state=True, name="lstm")( inputs=inputs, mask=tf.sequence_mask(seq_lens), initial_state=[state_in_h, state_in_c]) logits = SpyLayer(num_outputs=self.num_outputs)([ inputs, lstm_out, seq_lens, state_in_h, state_in_c, state_out_h, state_out_c ]) # Value branch. value_out = tf.keras.layers.Dense( units=1, kernel_initializer=normc_initializer(1.0))(lstm_out) self.base_model = tf.keras.Model( [inputs, seq_lens, state_in_h, state_in_c], [logits, value_out, state_out_h, state_out_c]) self.base_model.summary() @override(RecurrentNetwork) def forward_rnn(self, inputs, state, seq_lens): # Previously, a new class object was created during # deserialization and this `capture_index` # variable would be refreshed between class instantiations. # This behavior is no longer the case, so we manually refresh # the variable. RNNSpyModel.capture_index = 0 model_out, value_out, h, c = self.base_model( [inputs, seq_lens, state[0], state[1]]) self._value_out = value_out return model_out, [h, c] @override(ModelV2) def value_function(self): return tf.reshape(self._value_out, [-1]) @override(ModelV2) def get_initial_state(self): return [ np.zeros(self.cell_size, np.float32), np.zeros(self.cell_size, np.float32) ]
pcmoritz/ray-1
rllib/examples/models/rnn_spy_model.py
Python
apache-2.0
4,582
from collections import namedtuple from model.flyweight import Flyweight from model.static.database import database from model.dynamic.inventory.item import Item class TypeRequirements(Flyweight): #IGNORE:R0903 def __init__(self, type_id): #prevents reinitializing if "_inited" in self.__dict__: return self._inited = None #prevents reinitializing self.type_id = type_id """Remember: the key is the activity type 0 = None 1 = Manufacturing 2 = Research Technology 3 = Research Time Productivity 4 = Research Material Productivity 5 = Copying 6 = Duplicating 7 = Reverse Engineering 8 = Invention""" self._requirements = dict() cursor = database.get_cursor( "select * from ramTypeRequirements where typeID={};".format( self.type_id)) requirement = namedtuple("requirement", "item, damage, recycle") for row in cursor: if row["activityID"] not in self._requirements: self._requirements[row["activityID"]] = list() self._requirements[row["activityID"]].append(requirement( item=Item(row["requiredTypeID"], quantity=row["quantity"]), damage=row["damagePerJob"], recycle=True if row["recycle"] == 1 else False)) cursor.close() def __getitem__(self, k): """Allows TypeRequirements[k]""" return self._requirements[k]
Iconik/eve-suite
src/model/static/ram/type_requirements.py
Python
gpl-3.0
1,578
#!/usr/bin/python """ Context manager for temporarily suppressing logging """ from __future__ import unicode_literals from __future__ import absolute_import, division, print_function __author__ = "Graham Klyne (GK@ACM.ORG)" __copyright__ = "Copyright 2011-2014, University of Oxford" __license__ = "MIT (http://opensource.org/licenses/MIT)" import logging log = logging.getLogger(__name__) class SuppressLogging: """ Context handler class that suppresses logging for some controlled code. """ def __init__(self, loglevel): logging.disable(loglevel) return def __enter__(self): return def __exit__(self, exctype, excval, exctraceback): logging.disable(logging.NOTSET) return False if __name__ == "__main__": logging.basicConfig(level=logging.INFO) log.info("log this") with SuppressLogging(logging.WARNING): log.info("don't log this") log.warning("don't log this warning") log.error("log this error while up to WARNING suppressed") log.info("log this again") # End.
gklyne/annalist
src/annalist_root/utils/SuppressLoggingContext.py
Python
mit
1,098
import time from emotion import Controller from emotion import log as elog from emotion.controller import add_axis_method from emotion.axis import AxisState from emotion.comm import tcp """ - Emotion controller for PiezoMotor PMD206 piezo motor controller. - Ethernet - Cyril Guilloud ESRF BLISS - Thu 10 Apr 2014 09:18:51 """ def int_to_hex(dec_val): """ Conversion function to code PMD206 messages. - ex : hex(1050)[2:] = "41a" - ex : hex(-3 + pow(2, 32))[2:] = "fffffffd" """ if dec_val < 0: return hex(dec_val + pow(2, 32))[2:] else: return hex(dec_val)[2:] def hex_to_int(hex_val): """ Conversion function to decode PMD206 messages. - ex : int("41a", 16)- pow(2, 32) = 1050 - ex : int("ffffffff", 16) - pow(2, 32) = -1 """ if int(hex_val, 16) > pow(2, 31): return int(hex_val, 16) - pow(2, 32) else: return int(hex_val, 16) class PMD206(Controller): """ - Emotion controller for PiezoMotor PMD206 piezo motor controller. - Ethernet - Cyril Guilloud ESRF BLISS - Thu 10 Apr 2014 09:18:51 """ def __init__(self, name, config, axes, encoders): Controller.__init__(self, name, config, axes, encoders) self._controller_error_codes = [ (0x8000, "Abnormal reset detected."), (0x4000, "ComPic cannot communicate internally with MotorPic1 or MotorPic2"), (0x2000, "MotorPic2 has sent an unexpected response (internal error)"), (0x1000, "MotorPic1 has sent an unexpected response (internal error)"), (0x800, "Error reading ADC. A voltage could not be read"), (0x400, "48V level low or high current draw detected"), (0x200, "5V level on driver board outside limits"), (0x100, "3V3 level on driver board outside limits"), (0x80, "Sensor board communication error detected"), (0x40, "Parity or frame error RS422 sensor UART. Check cable/termination"), (0x20, "Wrong data format on external sensor (RS422 or TCP/IP)"), (0x10, "External sensor not detected (RS422 and TCP/IP)"), (0x08, "Problem with UART on host. Check cable and termination"), (0x04, "Host command error - driver board (e.g. buffer overrun)"), (0x02, "300 ms command timeout ocurred"), (0x01, "Command execution gave a warning"), ] self._motor_error_codes = [ (0x80, "48V low or other critical error, motor is stopped"), (0x40, "Temperature limit reached, motor is stopped"), (0x20, "Motor is parked"), (0x10, "Max or min encoder limit was reached in target mode, \ or motor was stopped due to external limit signal "), (0x8, "Target mode is active"), (0x4, "Target position was reached (if target mode is active). \ Also set during parking/unparking. "), (0x2, "Motor direction"), (0x1, "Motor is running"), ] self.host = self.config.get("host") def initialize(self): """ Opens a single communication socket to the controller for all 1..6 axes. """ self.sock = tcp.Socket(self.host, 9760) print "socket open", self.sock def finalize(self): """ Closes the controller socket. """ self.sock.close() print "socket close", self.sock def initialize_axis(self, axis): """ Args: - <axis> Returns: - None """ axis.channel = axis.config.get("channel", int) # Stores one axis to talk to the controller. if axis.channel == 1: self.ctrl_axis = axis elog.debug("AX CH =%r" % axis.channel) # Adds new axis oject methods. add_axis_method(axis, self.park_motor, types_info=("None", "None")) add_axis_method(axis, self.unpark_motor, types_info=("None", "None")) add_axis_method(axis, self.raw_write_read_axis, types_info=(str, str)) def initialize_encoder(self, encoder): encoder.channel = encoder.config.get("channel", int) def set_on(self, axis): pass def set_off(self, axis): pass def read_position(self, axis): """ Returns position's setpoint (in encoder counts). Args: - <axis> : emotion axis. Returns: - <position> : float : """ # 1234567812345678 # example of answer : 'PM11MP?:fffffff6' _ans = self.send(axis, "TP?") _pos = hex_to_int(_ans[8:]) elog.debug( "PMD206 position setpoint (encoder counts) read : %d (_ans=%s)" % (_pos, _ans)) return _pos def read_encoder(self, encoder): _ans = self.send(encoder, "MP?") _pos = hex_to_int(_ans[8:]) elog.debug( "PMD206 position measured (encoder counts) read : %d (_ans=%s)" % (_pos, _ans)) return _pos def read_velocity(self, axis): """ Args: - <axis> : Emotion axis object. Returns: - <velocity> : float : velocity in motor-units """ _velocity = 1 elog.debug("read_velocity : %d" % _velocity) return _velocity def set_velocity(self, axis, new_velocity): """ <new_velocity> is in motor units. (encoder steps) Returns velocity in motor units. """ _nv = new_velocity elog.debug("velocity NOT wrotten : %d " % _nv) return self.read_velocity(axis) def read_acctime(self, axis): """ Returns acceleration time in seconds. """ # _ans = self.send(axis, "CP?9") # 123456789 # _ans should looks like : 'PM11CP?9:00000030' # Removes 9 firsts characters. # _acceleration = hex_to_int(_ans[9:]) return float(axis.settings.get('acctime')) def set_acctime(self, axis, new_acctime): # !!!! must be converted ? # _nacc = int_to_hex(new_acctime) # _nacc = 30 # self.send(axis, "CP=9,%d" % _nacc) axis.settings.set('acctime', new_acctime) return new_acctime """ STATUS """ def pmd206_get_status(self, axis): """ Sends status command (CS?) and puts results (hexa strings) in : - self._ctrl_status - self._axes_status[1..6] Must be called before get_controller_status and get_motor_status. """ # broadcast command -> returns status of all 6 axis # _ans should looks like : 'PM11CS?:0100,20,20,20,20,20,20' # ~ 1.6ms _ans = self.send(axis, "CS?") self._axes_status = dict() (self._ctrl_status, self._axes_status[1], self._axes_status[2], self._axes_status[3], self._axes_status[4], self._axes_status[5], self._axes_status[6]) = _ans.split(':')[1].split(',') elog.debug("ctrl status : %s" % self._ctrl_status) elog.debug("mot1 status : %s" % self._axes_status[1]) elog.debug("mot2 status : %s" % self._axes_status[2]) elog.debug("mot3 status : %s" % self._axes_status[3]) elog.debug("mot4 status : %s" % self._axes_status[4]) elog.debug("mot5 status : %s" % self._axes_status[5]) elog.debug("mot6 status : %s" % self._axes_status[6]) def get_controller_status(self): """ Returns a string build with all status of controller. """ _s = hex_to_int(self._ctrl_status) _status = "" for _c in self._controller_error_codes: if _s & _c[0]: # print _c[1] _status = _status + (_c[1] + "\n") return _status def get_motor_status(self, axis): """ Returns a string build with all status of motor <axis>. """ _s = hex_to_int(self._axes_status[axis.channel]) _status = "" for _c in self._motor_error_codes: if _s & _c[0]: # print _c[1] _status = _status + (_c[1] + "\n") return _status def motor_state(self, axis): _s = hex_to_int(self._axes_status[axis.channel]) elog.debug( "axis %d status : %s" % (axis.channel, self._axes_status[axis.channel])) if self.s_is_parked(_s): return AxisState("OFF") # running means position is corrected, related to closed loop # we just check if target position was reached if self.s_is_closed_loop(_s): if self.s_is_position_reached(_s): return AxisState("READY") else: return AxisState("MOVING") else: if self.s_is_moving(_s): return AxisState("MOVING") else: return AxisState("READY") def s_is_moving(self, status): return status & 0x1 def s_is_closed_loop(self, status): return status & 0x08 def s_is_position_reached(self, status): return status & 0x04 def s_is_parked(self, status): return status & 0x20 def state(self, axis): """ Read status from controller. No way to read only single axis. """ self.pmd206_get_status(axis) return self.motor_state(axis) def status(self, axis): """ Returns a string composed by controller and motor status string. """ return self.get_controller_status() + "\n\n" + self.get_motor_status(axis) """ Movements """ def prepare_move(self, motion): """ - TODO for multiple move... """ pass def start_one(self, motion): """ - Sends Args: - <motion> : Emotion motion object. Returns: - None """ # unpark only on demand ! # # unpark the axis motor if needed # # status bit 0x20 : "Motor is parked" # self.pmd206_get_status(motion.axis) # _hex_status_string = self._axes_status[motion.axis.channel] # _status = hex_to_int(_hex_status_string) # if _status & 0x20: # elog.info("Motor is parked. I unpark it") # self.unpark_motor(motion.axis) # print "targetpos=", motion.target_pos _enc_target = int_to_hex(int(motion.target_pos)) # print "_enc_target=", _enc_target self.send(motion.axis, "TP=%s" % _enc_target) def stop(self, axis): """ Stops all axis motions sending CS=0 command. Args: - <axis> : Emotion axis object. """ self.send(axis, "CS=0") """ PMD206 specific communication """ def send(self, axis, cmd): """ - Adds 'CP<x><y>' prefix - Adds the 'carriage return' terminator character : "\\\\r" - Sends command <cmd> to the PMD206 controller. - Channel is defined in <cmd>. - <axis> is passed for debugging purposes. - if <axis> is 0 : sends a broadcast message. Args: - <axis> : passed for debugging purposes. - <cmd> : command to send to controller (Channel is already mentionned in <cmd>). Returns: - Answer from controller for get commands. - True if for successful set commands. Raises: ? """ # PC: don't know how to send a broadcast command to controller, not axis # intercept it here ... # put 0 instead of channel elog.debug("in send(%r)" % cmd) broadcast_command = cmd[:4] in ["CC=4", "CC=5"] if broadcast_command: elog.debug("BROADCAST COMMAND ") _prefix = "PM%d%d" % (1, 0) else: _prefix = "PM%d%d" % (1, axis.channel) _cmd = _prefix + cmd + "\r" _t0 = time.time() _ans = self.sock.write_readline(_cmd, eol='\r') elog.debug("send(%s) returns : %s " % (_cmd, _ans)) set_command = cmd[:3] in ["DR=", "CS=", "TP=", "TR=", "RS="] if set_command: elog.debug("SET COMMAND ") if _ans != _cmd: pass # print "oh oh set command not answered correctly ?" # print "_ans=" ,_ans _duration = time.time() - _t0 if _duration > 0.006: print "PMD206 Received %s from Send %s (duration : %g ms) " % \ (repr(_ans), repr(_cmd), _duration * 1000) return _ans def get_error(self, axis): pass def do_homing(self, axis, freq, max_steps, max_counts, first_dir): """ Sends HO command. """ self.send("HO=%d,%d,%d,%d,%d,%d" % (freq, max_steps, max_counts, first_dir, max_steps, max_counts)) def homing_sequence_status_string(self, status): _home_status_table = [ ('0c', "initiating"), ('0b', "starting index mode 3"), ('0a', "starting direction 1"), ('09', "running direction 1"), ('08', "starting direction 2"), ('07', "running direction 2"), ('06', "is encoder counting ?"), ('05', "running direction 2"), ('04', "end direction 2"), ('03', "stopped with error"), ('02', "index not found"), ('01', "index was found"), ('00', "not started") ] print _home_status_table def park_motor(self, axis): """ Parks axis motor. """ self.send(axis, "CC=1") def unpark_motor(self, axis): """ Unpark axis motor (mandatory before moving). """ self.send(axis, "CC=0") def get_info(self, axis): """ Returns a set of usefull information about controller. Helpful to tune the device. Args: <axis> : emotion axis Returns: None Raises: ? """ _infos = [ ("Firmware version ", "SV?"), ("Extended Version Information ", "XV?"), ("Controller status ", "CS?"), ("Extended Controller status ", "XS?"), ("Closed loop status ", "CM?"), ("Mot. Pos. Encoder Value (hex) ", "MP?"), ("Last target Position (hex) ", "TP?"), ("Status of Homing Sequence ", "HO?"), ("Cycle counter ", "CP?0"), ("Parking and initialization ", "CP?1"), ("External limits ", "CP?2"), ("Position limit high ", "CP?3"), ("Position limit low ", "CP?4"), ("Stop range (dead band) ", "CP?5"), ("Encoder direction ", "CP?6"), ("Minimum speed in target mode ", "CP?7"), ("Maximum speed in target mode ", "CP?8"), ("Speed ramp up in target mode ", "CP?9"), ("Speed ramp down in target mode ", "CP?a"), ("StepsPerCount ", "CP?b"), ("Driver board temperature ", "CP?10"), ("Driver board 48 V level ", "CP?12"), ("Position ", "CP?14"), ("Wfm point and voltages ", "CP?1d"), ("Target mode parameters ", "CP?1e"), ] _txt = "" self.pmd206_get_status(axis) _ctrl_status = self.get_controller_status() _axis_status = self.get_motor_status(axis) for i in _infos: _txt = _txt + " %s %s\n" % \ (i[0], self.send(axis, i[1])) _txt = _txt + " ctrl status : %s" % _ctrl_status _txt = _txt + " axis status : %s" % _axis_status _txt = _txt + " IP address : %s" % self.get_ip(axis) return _txt def get_ip(self, axis): """ Returns IP address as a 4 decimal numbers string. """ _ans = self.send(axis, "IP?") return ".".join( map(str, map(hex_to_int, _ans.split(':')[1].split(',')[0: 4]))) def raw_write(self, cmd): # no send_no_ans? # self.send_no_ans(self.ctrl_axis, cmd) pass def raw_write_read(self, cmd): return self.send(self.ctrl_axis, cmd) def raw_write_read_axis(self, axis, cmd): return self.send(axis, cmd)
esrf-emotion/emotion
emotion/controllers/PMD206.py
Python
gpl-2.0
16,601
#!/usr/bin/env python """ Image processing support functions This file is part of mrgaze. mrgaze 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. mrgaze 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 mrgaze. If not, see <http://www.gnu.org/licenses/>. Copyright 2014 California Institute of Technology. """ import cv2 import pywt import numpy as np from skimage import exposure from mrgaze import utils def EstimateBias(fr): ''' Estimate illumination bias field Arguments ---- fr : 2D numpy uint8 array Uncorrected image with biased illumination Returns ---- bias_field : 2D numpy float array Estimated bias multiplier field ''' # Target downsampled matrix size nd = 32; # Get image dimensions ny, nx = fr.shape # Target maximum dimension is 32 # Apect ratio preserved approximately if nx > ny: nxd = nd nyd = int(nx/32.0 * ny) else: nxd = int(ny/32.0 * nx) nyd = nd # Downsample frame fr_d = cv2.resize(fr, (nxd, nyd)) # 2D baseline estimation # Use large kernel relative to image size k = utils._forceodd(nd/2) bias_field_d = cv2.medianBlur(fr_d, k) # Bias correction bias_corr_d = 1 - (bias_field_d - np.mean(fr_d)) / fr_d # Upsample biasfield to same size as original frame bias_corr = cv2.resize(bias_corr_d, (nx, ny)) # DEBUG: Flat bias correction bias_corr = np.ones_like(fr) return bias_corr def Unbias(fr, bias_corr): # Cast frame to floats frf = fr.astype(float) # Apply bias correction multiplier fr_unbias = np.uint8(frf * bias_corr) return fr_unbias def RobustRescale(gray, perc_range=(5, 95)): """ Robust image intensity rescaling Arguments ---- gray : numpy uint8 array Original grayscale image. perc_range : two element tuple of floats in range [0,100] Percentile scaling range Returns ---- gray_rescale : numpy uint8 array Percentile rescaled image. """ # Calculate intensity percentile range pA, pB = np.percentile(gray, perc_range) # Only rescale if limits are different if pB == pA: gray_rescale = gray else: gray_rescale = exposure.rescale_intensity(gray, in_range=(pA, pB)) return gray_rescale def NoiseSD(x): ''' Robust background noise SD estimation ''' return np.median(np.abs(x.flatten())) * 1.48 def WaveletNoiseSD(x): ''' Estimate noise SD from wavelet detail coefficients ''' # Wavelet decomposition cA, cD = pywt.dwt(x.flatten(), 'db1') # Estimate sd_n from MAD of detail coefficients sd_n = np.median(np.abs(cD)) * 1.48 return sd_n def ResizeImage(img, w_max=128, h_max=128): ''' Resize image to a given maximum width and/or height with letterboxing ''' # Size of original image ny,nx = img.shape # Nearest neighbour interpolation img_new = cv2.resize(img, dsize=(128,128), interpolation=cv2.INTER_NEAREST) return img_new
jmtyszka/mrgaze
mrgaze/improc.py
Python
mit
3,537
""" Input Class (TODO DOC) """ from c_sharp_vuln_test_suite_gen.sample import Sample class InputSample(Sample): # Initialize the type of input and the code parameters of the class """FiletringSample class Args : **sample** (xml.etree.ElementTree.Element): The XML element containing the input tag in the \ file "input.xml". Attributes : **_input_type** (str): Type of input variable (private member, please use getter and setter). **_output_type** (str): Type of output variable (private member, please use getter and setter). **_flaws** (dict str->(dict str->bool): Collection of flaws for this filtering with safety \ (private member, please use getter and setter). """ # compatible with new structure def __init__(self, sample): # XML tree in parameter Sample.__init__(self, sample) self._input_type = sample.find("input_type").text.lower() self._output_type = sample.find("output_type").text.lower() self._flaws = {} for flaw in sample.find("flaws").findall("flaw"): flaw_type = flaw.get("flaw_type").lower() self._flaws[flaw_type] = {} self._flaws[flaw_type]["safe"] = (flaw.get("safe") == "1") self._flaws[flaw_type]["unsafe"] = (flaw.get("unsafe") == "1") def __str__(self): return "*** Input ***\n{}\n\tinput type : {}\n\toutput type : {}\n\tflaws : {}\n\tcode : {}\n\ \n".format(super(InputSample, self).__str__(), self.input_type, self.output_type, self.flaws) def is_safe(self, flaw_type): """ Check if current input is safe for a flaw type """ if flaw_type in self.get_flaws_types(): return self.flaws[flaw_type]["safe"] if "default" in self.get_flaws_types(): return self.flaws["default"]["safe"] return None def is_unsafe(self, flaw_type): """ Check if current input is unsafe for a flaw type """ if flaw_type in self.get_flaws_types(): return self.flaws[flaw_type]["unsafe"] if "default" in self.get_flaws_types(): return self.flaws["default"]["unsafe"] return None @property def input_type(self): """ Type of input variable. :getter: Returns this input type. :type: str """ return self._input_type @property def output_type(self): """ Type of output variable. :getter: Returns this output type. :type: str """ return self._output_type def compatible_with_filtering_sink(self, filtering, sink): """ Return True if current input is compatible with filtering and sink, False otherwise. Args: **sink** (SinkSample) **filtering** (FilteringSample) """ if filtering.input_type != "nofilter": return self.output_type == filtering.input_type else: return self.output_type == sink.input_type @property def flaws(self): """ Collection of flaws for this input with safety. :getter: Returns this collection. :type: str """ return self._flaws def get_flaws_types(self): """ Collection of flaws for this input with safety. :getter: Returns the keys of this collection. :type: list of str """ return self.flaws.keys()
stivalet/C-Sharp-Vuln-test-suite-gen
c_sharp_vuln_test_suite_gen/input_sample.py
Python
mit
3,654
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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. # # ##### END GPL LICENSE BLOCK ##### """ Blender exporter for Three.js (ASCII JSON format). TODO - binary format """ import bpy import mathutils import shutil import os import os.path import math import operator import random # ##################################################### # Configuration # ##################################################### DEFAULTS = { "bgcolor" : [0, 0, 0], "bgalpha" : 1.0, "position" : [0, 0, 0], "rotation" : [-math.pi/2, 0, 0], "scale" : [1, 1, 1], "camera" : { "name" : "default_camera", "type" : "perspective", "near" : 1, "far" : 10000, "fov" : 60, "aspect": 1.333, "position" : [0, 0, 10], "target" : [0, 0, 0] }, "light" : { "name" : "default_light", "type" : "directional", "direction" : [0, 1, 1], "color" : [1, 1, 1], "intensity" : 0.8 } } # default colors for debugging (each material gets one distinct color): # white, red, green, blue, yellow, cyan, magenta COLORS = [0xeeeeee, 0xee0000, 0x00ee00, 0x0000ee, 0xeeee00, 0x00eeee, 0xee00ee] # ##################################################### # Templates - scene # ##################################################### TEMPLATE_SCENE_ASCII = """\ { "metadata" : { "formatVersion" : 3, "sourceFile" : "%(fname)s", "generatedBy" : "Blender 2.63 Exporter", "objects" : %(nobjects)s, "geometries" : %(ngeometries)s, "materials" : %(nmaterials)s, "textures" : %(ntextures)s }, "type" : "scene", "urlBaseType" : %(basetype)s, %(sections)s "transform" : { "position" : %(position)s, "rotation" : %(rotation)s, "scale" : %(scale)s }, "defaults" : { "bgcolor" : %(bgcolor)s, "bgalpha" : %(bgalpha)f, "camera" : %(defcamera)s } } """ TEMPLATE_SECTION = """ "%s" : { %s }, """ TEMPLATE_OBJECT = """\ %(object_id)s : { "geometry" : %(geometry_id)s, "groups" : [ %(group_id)s ], "materials" : [ %(material_id)s ], "position" : %(position)s, "rotation" : %(rotation)s, "quaternion": %(quaternion)s, "scale" : %(scale)s, "visible" : %(visible)s, "castShadow" : %(castShadow)s, "receiveShadow" : %(receiveShadow)s, "doubleSided" : %(doubleSided)s }""" TEMPLATE_EMPTY = """\ %(object_id)s : { "groups" : [ %(group_id)s ], "position" : %(position)s, "rotation" : %(rotation)s, "quaternion": %(quaternion)s, "scale" : %(scale)s }""" TEMPLATE_GEOMETRY_LINK = """\ %(geometry_id)s : { "type" : "ascii_mesh", "url" : %(model_file)s }""" TEMPLATE_GEOMETRY_EMBED = """\ %(geometry_id)s : { "type" : "embedded_mesh", "id" : %(embed_id)s }""" TEMPLATE_TEXTURE = """\ %(texture_id)s : { "url": %(texture_file)s%(extras)s }""" TEMPLATE_MATERIAL_SCENE = """\ %(material_id)s : { "type": %(type)s, "parameters": { %(parameters)s } }""" TEMPLATE_CAMERA_PERSPECTIVE = """\ %(camera_id)s : { "type" : "perspective", "fov" : %(fov)f, "aspect": %(aspect)f, "near" : %(near)f, "far" : %(far)f, "position": %(position)s, "target" : %(target)s }""" TEMPLATE_CAMERA_ORTHO = """\ %(camera_id)s: { "type" : "ortho", "left" : %(left)f, "right" : %(right)f, "top" : %(top)f, "bottom": %(bottom)f, "near" : %(near)f, "far" : %(far)f, "position": %(position)s, "target" : %(target)s }""" TEMPLATE_LIGHT_DIRECTIONAL = """\ %(light_id)s: { "type" : "directional", "direction" : %(direction)s, "color" : %(color)d, "intensity" : %(intensity).2f }""" TEMPLATE_LIGHT_POINT = """\ %(light_id)s: { "type" : "point", "position" : %(position)s, "color" : %(color)d, "intensity" : %(intensity).3f }""" TEMPLATE_VEC4 = '[ %f, %f, %f, %f ]' TEMPLATE_VEC3 = '[ %f, %f, %f ]' TEMPLATE_VEC2 = '[ %f, %f ]' TEMPLATE_STRING = '"%s"' TEMPLATE_HEX = "0x%06x" # ##################################################### # Templates - model # ##################################################### TEMPLATE_FILE_ASCII = """\ { "metadata" : { "formatVersion" : 3, "generatedBy" : "Blender 2.63 Exporter", "vertices" : %(nvertex)d, "faces" : %(nface)d, "normals" : %(nnormal)d, "colors" : %(ncolor)d, "uvs" : %(nuv)d, "materials" : %(nmaterial)d, "morphTargets" : %(nmorphTarget)d }, %(model)s } """ TEMPLATE_MODEL_ASCII = """\ "scale" : %(scale)f, "materials": [%(materials)s], "vertices": [%(vertices)s], "morphTargets": [%(morphTargets)s], "normals": [%(normals)s], "colors": [%(colors)s], "uvs": [[%(uvs)s]], "faces": [%(faces)s] """ TEMPLATE_VERTEX = "%f,%f,%f" TEMPLATE_VERTEX_TRUNCATE = "%d,%d,%d" TEMPLATE_N = "%f,%f,%f" TEMPLATE_UV = "%f,%f" TEMPLATE_C = "%d" # ##################################################### # Utils # ##################################################### def veckey3(x,y,z): return round(x, 6), round(y, 6), round(z, 6) def veckey3d(v): return veckey3(v.x, v.y, v.z) def veckey2d(v): return round(v[0], 6), round(v[1], 6) def get_faces(obj): if hasattr(obj, "tessfaces"): return obj.tessfaces else: return obj.faces def get_normal_indices(v, normals, mesh): n = [] mv = mesh.vertices for i in v: normal = mv[i].normal key = veckey3d(normal) n.append( normals[key] ) return n def get_uv_indices(face_index, uvs, mesh): uv = [] uv_layer = mesh.tessface_uv_textures.active.data for i in uv_layer[face_index].uv: uv.append( uvs[veckey2d(i)] ) return uv def get_color_indices(face_index, colors, mesh): c = [] color_layer = mesh.tessface_vertex_colors.active.data face_colors = color_layer[face_index] face_colors = face_colors.color1, face_colors.color2, face_colors.color3, face_colors.color4 for i in face_colors: c.append( colors[hexcolor(i)] ) return c def rgb2int(rgb): color = (int(rgb[0]*255) << 16) + (int(rgb[1]*255) << 8) + int(rgb[2]*255); return color # ##################################################### # Utils - files # ##################################################### def write_file(fname, content): out = open(fname, "w") out.write(content) out.close() def ensure_folder_exist(foldername): """Create folder (with whole path) if it doesn't exist yet.""" if not os.access(foldername, os.R_OK|os.W_OK|os.X_OK): os.makedirs(foldername) def ensure_extension(filepath, extension): if not filepath.lower().endswith(extension): filepath += extension return filepath def generate_mesh_filename(meshname, filepath): normpath = os.path.normpath(filepath) path, ext = os.path.splitext(normpath) return "%s.%s%s" % (path, meshname, ext) # ##################################################### # Utils - alignment # ##################################################### def bbox(vertices): """Compute bounding box of vertex array. """ if len(vertices)>0: minx = maxx = vertices[0].co.x miny = maxy = vertices[0].co.y minz = maxz = vertices[0].co.z for v in vertices[1:]: if v.co.x < minx: minx = v.co.x elif v.co.x > maxx: maxx = v.co.x if v.co.y < miny: miny = v.co.y elif v.co.y > maxy: maxy = v.co.y if v.co.z < minz: minz = v.co.z elif v.co.z > maxz: maxz = v.co.z return { 'x':[minx,maxx], 'y':[miny,maxy], 'z':[minz,maxz] } else: return { 'x':[0,0], 'y':[0,0], 'z':[0,0] } def translate(vertices, t): """Translate array of vertices by vector t. """ for i in range(len(vertices)): vertices[i].co.x += t[0] vertices[i].co.y += t[1] vertices[i].co.z += t[2] def center(vertices): """Center model (middle of bounding box). """ bb = bbox(vertices) cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0 cy = bb['y'][0] + (bb['y'][1] - bb['y'][0])/2.0 cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0 translate(vertices, [-cx,-cy,-cz]) def top(vertices): """Align top of the model with the floor (Y-axis) and center it around X and Z. """ bb = bbox(vertices) cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0 cy = bb['y'][1] cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0 translate(vertices, [-cx,-cy,-cz]) def bottom(vertices): """Align bottom of the model with the floor (Y-axis) and center it around X and Z. """ bb = bbox(vertices) cx = bb['x'][0] + (bb['x'][1] - bb['x'][0])/2.0 cy = bb['y'][0] cz = bb['z'][0] + (bb['z'][1] - bb['z'][0])/2.0 translate(vertices, [-cx,-cy,-cz]) # ##################################################### # Elements rendering # ##################################################### def hexcolor(c): return ( int(c[0] * 255) << 16 ) + ( int(c[1] * 255) << 8 ) + int(c[2] * 255) def generate_vertices(vertices, option_vertices_truncate, option_vertices): if not option_vertices: return "" return ",".join(generate_vertex(v, option_vertices_truncate) for v in vertices) def generate_vertex(v, option_vertices_truncate): if not option_vertices_truncate: return TEMPLATE_VERTEX % (v.co.x, v.co.y, v.co.z) else: return TEMPLATE_VERTEX_TRUNCATE % (v.co.x, v.co.y, v.co.z) def generate_normal(n): return TEMPLATE_N % (n[0], n[1], n[2]) def generate_vertex_color(c): return TEMPLATE_C % c def generate_uv(uv): return TEMPLATE_UV % (uv[0], 1.0 - uv[1]) # ##################################################### # Model exporter - faces # ##################################################### def setBit(value, position, on): if on: mask = 1 << position return (value | mask) else: mask = ~(1 << position) return (value & mask) def generate_faces(normals, uvs, colors, meshes, option_normals, option_colors, option_uv_coords, option_materials, option_faces): if not option_faces: return "", 0 vertex_offset = 0 material_offset = 0 chunks = [] for mesh, object in meshes: faceUV = (len(mesh.uv_textures) > 0) vertexUV = (len(mesh.sticky) > 0) vertexColors = len(mesh.vertex_colors) > 0 mesh_colors = option_colors and vertexColors mesh_uvs = option_uv_coords and (faceUV or vertexUV) if faceUV or vertexUV: active_uv_layer = mesh.uv_textures.active if not active_uv_layer: mesh_extract_uvs = False if vertexColors: active_col_layer = mesh.vertex_colors.active if not active_col_layer: mesh_extract_colors = False for i, f in enumerate(get_faces(mesh)): face = generate_face(f, i, normals, uvs, colors, mesh, option_normals, mesh_colors, mesh_uvs, option_materials, vertex_offset, material_offset) chunks.append(face) vertex_offset += len(mesh.vertices) material_count = len(mesh.materials) if material_count == 0: material_count = 1 material_offset += material_count return ",".join(chunks), len(chunks) def generate_face(f, faceIndex, normals, uvs, colors, mesh, option_normals, option_colors, option_uv_coords, option_materials, vertex_offset, material_offset): isTriangle = ( len(f.vertices) == 3 ) if isTriangle: nVertices = 3 else: nVertices = 4 hasMaterial = option_materials hasFaceUvs = False # not supported in Blender hasFaceVertexUvs = option_uv_coords hasFaceNormals = False # don't export any face normals (as they are computed in engine) hasFaceVertexNormals = option_normals hasFaceColors = False # not supported in Blender hasFaceVertexColors = option_colors faceType = 0 faceType = setBit(faceType, 0, not isTriangle) faceType = setBit(faceType, 1, hasMaterial) faceType = setBit(faceType, 2, hasFaceUvs) faceType = setBit(faceType, 3, hasFaceVertexUvs) faceType = setBit(faceType, 4, hasFaceNormals) faceType = setBit(faceType, 5, hasFaceVertexNormals) faceType = setBit(faceType, 6, hasFaceColors) faceType = setBit(faceType, 7, hasFaceVertexColors) faceData = [] # order is important, must match order in JSONLoader # face type # vertex indices # material index # face uvs index # face vertex uvs indices # face color index # face vertex colors indices faceData.append(faceType) # must clamp in case on polygons bigger than quads for i in range(nVertices): index = f.vertices[i] + vertex_offset faceData.append(index) if hasMaterial: index = f.material_index + material_offset faceData.append( index ) if hasFaceVertexUvs: uv = get_uv_indices(faceIndex, uvs, mesh) for i in range(nVertices): index = uv[i] faceData.append(index) if hasFaceVertexNormals: n = get_normal_indices(f.vertices, normals, mesh) for i in range(nVertices): index = n[i] faceData.append(index) if hasFaceVertexColors: c = get_color_indices(faceIndex, colors, mesh) for i in range(nVertices): index = c[i] faceData.append(index) return ",".join( map(str, faceData) ) # ##################################################### # Model exporter - normals # ##################################################### def extract_vertex_normals(mesh, normals, count): for f in get_faces(mesh): for v in f.vertices: normal = mesh.vertices[v].normal key = veckey3d(normal) if key not in normals: normals[key] = count count += 1 return count def generate_normals(normals, option_normals): if not option_normals: return "" chunks = [] for key, index in sorted(normals.items(), key = operator.itemgetter(1)): chunks.append(key) return ",".join(generate_normal(n) for n in chunks) # ##################################################### # Model exporter - vertex colors # ##################################################### def extract_vertex_colors(mesh, colors, count): color_layer = mesh.tessface_vertex_colors.active.data for face_index, face in enumerate(get_faces(mesh)): face_colors = color_layer[face_index] face_colors = face_colors.color1, face_colors.color2, face_colors.color3, face_colors.color4 for c in face_colors: key = hexcolor(c) if key not in colors: colors[key] = count count += 1 return count def generate_vertex_colors(colors, option_colors): if not option_colors: return "" chunks = [] for key, index in sorted(colors.items(), key=operator.itemgetter(1)): chunks.append(key) return ",".join(generate_vertex_color(c) for c in chunks) # ##################################################### # Model exporter - UVs # ##################################################### def extract_uvs(mesh, uvs, count): uv_layer = mesh.tessface_uv_textures.active.data for face_index, face in enumerate(get_faces(mesh)): for uv_index, uv in enumerate(uv_layer[face_index].uv): key = veckey2d(uv) if key not in uvs: uvs[key] = count count += 1 return count def generate_uvs(uvs, option_uv_coords): if not option_uv_coords: return "" chunks = [] for key, index in sorted(uvs.items(), key=operator.itemgetter(1)): chunks.append(key) return ",".join(generate_uv(n) for n in chunks) # ##################################################### # Model exporter - materials # ##################################################### def generate_color(i): """Generate hex color corresponding to integer. Colors should have well defined ordering. First N colors are hardcoded, then colors are random (must seed random number generator with deterministic value before getting colors). """ if i < len(COLORS): #return "0x%06x" % COLORS[i] return COLORS[i] else: #return "0x%06x" % int(0xffffff * random.random()) return int(0xffffff * random.random()) def generate_mtl(materials): """Generate dummy materials. """ mtl = {} for m in materials: index = materials[m] mtl[m] = { "DbgName": m, "DbgIndex": index, "DbgColor": generate_color(index), "vertexColors" : False } return mtl def value2string(v): if type(v) == str and v[0:2] != "0x": return '"%s"' % v elif type(v) == bool: return str(v).lower() elif type(v) == list: return "[%s]" % (", ".join(value2string(x) for x in v)) return str(v) def generate_materials(mtl, materials, draw_type): """Generate JS array of materials objects """ mtl_array = [] for m in mtl: index = materials[m] # add debug information # materials should be sorted according to how # they appeared in OBJ file (for the first time) # this index is identifier used in face definitions mtl[m]['DbgName'] = m mtl[m]['DbgIndex'] = index mtl[m]['DbgColor'] = generate_color(index) if draw_type in [ "BOUNDS", "WIRE" ]: mtl[m]['wireframe'] = True mtl[m]['DbgColor'] = 0xff0000 mtl_raw = ",\n".join(['\t"%s" : %s' % (n, value2string(v)) for n,v in sorted(mtl[m].items())]) mtl_string = "\t{\n%s\n\t}" % mtl_raw mtl_array.append([index, mtl_string]) return ",\n\n".join([m for i,m in sorted(mtl_array)]), len(mtl_array) def extract_materials(mesh, scene, option_colors, option_copy_textures, filepath): world = scene.world materials = {} for m in mesh.materials: if m: materials[m.name] = {} material = materials[m.name] material['colorDiffuse'] = [m.diffuse_intensity * m.diffuse_color[0], m.diffuse_intensity * m.diffuse_color[1], m.diffuse_intensity * m.diffuse_color[2]] material['colorSpecular'] = [m.specular_intensity * m.specular_color[0], m.specular_intensity * m.specular_color[1], m.specular_intensity * m.specular_color[2]] world_ambient_color = [0, 0, 0] if world: world_ambient_color = world.ambient_color material['colorAmbient'] = [m.ambient * world_ambient_color[0], m.ambient * world_ambient_color[1], m.ambient * world_ambient_color[2]] material['transparency'] = m.alpha # not sure about mapping values to Blinn-Phong shader # Blender uses INT from [1, 511] with default 0 # http://www.blender.org/documentation/blender_python_api_2_54_0/bpy.types.Material.html#bpy.types.Material.specular_hardness material["specularCoef"] = m.specular_hardness textures = guess_material_textures(m) handle_texture('diffuse', textures, material, filepath, option_copy_textures) handle_texture('light', textures, material, filepath, option_copy_textures) handle_texture('normal', textures, material, filepath, option_copy_textures) handle_texture('specular', textures, material, filepath, option_copy_textures) material["vertexColors"] = m.THREE_useVertexColors and option_colors # can't really use this reliably to tell apart Phong from Lambert # as Blender defaults to non-zero specular color #if m.specular_intensity > 0.0 and (m.specular_color[0] > 0 or m.specular_color[1] > 0 or m.specular_color[2] > 0): # material['shading'] = "Phong" #else: # material['shading'] = "Lambert" if textures['normal']: material['shading'] = "Phong" else: material['shading'] = m.THREE_materialType material['blending'] = m.THREE_blendingType material['depthWrite'] = m.THREE_depthWrite material['depthTest'] = m.THREE_depthTest material['transparent'] = m.use_transparency return materials def generate_materials_string(mesh, scene, option_colors, draw_type, option_copy_textures, filepath, offset): random.seed(42) # to get well defined color order for debug materials materials = {} if mesh.materials: for i, m in enumerate(mesh.materials): mat_id = i + offset if m: materials[m.name] = mat_id else: materials["undefined_dummy_%0d" % mat_id] = mat_id if not materials: materials = { 'default': 0 } # default dummy materials mtl = generate_mtl(materials) # extract real materials from the mesh mtl.update(extract_materials(mesh, scene, option_colors, option_copy_textures, filepath)) return generate_materials(mtl, materials, draw_type) def handle_texture(id, textures, material, filepath, option_copy_textures): if textures[id]: texName = 'map%s' % id.capitalize() repeatName = 'map%sRepeat' % id.capitalize() wrapName = 'map%sWrap' % id.capitalize() slot = textures[id]['slot'] texture = textures[id]['texture'] image = texture.image fname = extract_texture_filename(image) material[texName] = fname if option_copy_textures: save_image(image, fname, filepath) if texture.repeat_x != 1 or texture.repeat_y != 1: material[repeatName] = [texture.repeat_x, texture.repeat_y] if texture.extension == "REPEAT": wrap_x = "repeat" wrap_y = "repeat" if texture.use_mirror_x: wrap_x = "mirror" if texture.use_mirror_y: wrap_y = "mirror" material[wrapName] = [wrap_x, wrap_y] if slot.use_map_normal: if slot.normal_factor != 1.0: material['mapNormalFactor'] = slot.normal_factor # ##################################################### # ASCII model generator # ##################################################### def generate_ascii_model(meshes, morphs, scene, option_vertices, option_vertices_truncate, option_faces, option_normals, option_uv_coords, option_materials, option_colors, align_model, flipyz, option_scale, option_copy_textures, filepath, option_animation, option_frame_step): vertices = [] vertex_offset = 0 vertex_offsets = [] nnormal = 0 normals = {} ncolor = 0 colors = {} nuv = 0 uvs = {} nmaterial = 0 materials = [] for mesh, object in meshes: faceUV = (len(mesh.uv_textures) > 0) vertexUV = (len(mesh.sticky) > 0) vertexColors = len(mesh.vertex_colors) > 0 mesh_extract_colors = option_colors and vertexColors mesh_extract_uvs = option_uv_coords and (faceUV or vertexUV) if faceUV or vertexUV: active_uv_layer = mesh.uv_textures.active if not active_uv_layer: mesh_extract_uvs = False if vertexColors: active_col_layer = mesh.vertex_colors.active if not active_col_layer: mesh_extract_colors = False vertex_offsets.append(vertex_offset) vertex_offset += len(vertices) vertices.extend(mesh.vertices[:]) if option_normals: nnormal = extract_vertex_normals(mesh, normals, nnormal) if mesh_extract_colors: ncolor = extract_vertex_colors(mesh, colors, ncolor) if mesh_extract_uvs: nuv = extract_uvs(mesh, uvs, nuv) if option_materials: mesh_materials, nmaterial = generate_materials_string(mesh, scene, mesh_extract_colors, object.draw_type, option_copy_textures, filepath, nmaterial) materials.append(mesh_materials) morphTargets_string = "" nmorphTarget = 0 if option_animation: chunks = [] for i, morphVertices in enumerate(morphs): morphTarget = '{ "name": "%s_%06d", "vertices": [%s] }' % ("animation", i, morphVertices) chunks.append(morphTarget) morphTargets_string = ",\n\t".join(chunks) nmorphTarget = len(morphs) if align_model == 1: center(vertices) elif align_model == 2: bottom(vertices) elif align_model == 3: top(vertices) faces_string, nfaces = generate_faces(normals, uvs, colors, meshes, option_normals, option_colors, option_uv_coords, option_materials, option_faces) materials_string = ",\n\n".join(materials) model_string = TEMPLATE_MODEL_ASCII % { "scale" : option_scale, "uvs" : generate_uvs(uvs, option_uv_coords), "normals" : generate_normals(normals, option_normals), "colors" : generate_vertex_colors(colors, option_colors), "materials" : materials_string, "vertices" : generate_vertices(vertices, option_vertices_truncate, option_vertices), "faces" : faces_string, "morphTargets" : morphTargets_string } text = TEMPLATE_FILE_ASCII % { "nvertex" : len(vertices), "nface" : nfaces, "nuv" : nuv, "nnormal" : nnormal, "ncolor" : ncolor, "nmaterial" : nmaterial, "nmorphTarget": nmorphTarget, "model" : model_string } return text, model_string # ##################################################### # Model exporter - export single mesh # ##################################################### def extract_meshes(objects, scene, export_single_model, option_scale, flipyz): meshes = [] for object in objects: if object.type == "MESH" and object.THREE_exportGeometry: # collapse modifiers into mesh mesh = object.to_mesh(scene, True, 'RENDER') if not mesh: raise Exception("Error, could not get mesh data from object [%s]" % object.name) if export_single_model: if flipyz: # that's what Blender's native export_obj.py does # to flip YZ X_ROT = mathutils.Matrix.Rotation(-math.pi/2, 4, 'X') mesh.transform(X_ROT * object.matrix_world) else: mesh.transform(object.matrix_world) mesh.calc_normals() mesh.calc_tessface() mesh.transform(mathutils.Matrix.Scale(option_scale, 4)) meshes.append([mesh, object]) return meshes def generate_mesh_string(objects, scene, option_vertices, option_vertices_truncate, option_faces, option_normals, option_uv_coords, option_materials, option_colors, align_model, flipyz, option_scale, export_single_model, option_copy_textures, filepath, option_animation, option_frame_step): meshes = extract_meshes(objects, scene, export_single_model, option_scale, flipyz) morphs = [] if option_animation: original_frame = scene.frame_current # save animation state scene_frames = range(scene.frame_start, scene.frame_end + 1, option_frame_step) for frame in scene_frames: scene.frame_set(frame, 0.0) anim_meshes = extract_meshes(objects, scene, export_single_model, option_scale, flipyz) frame_vertices = [] for mesh, object in anim_meshes: frame_vertices.extend(mesh.vertices[:]) morphVertices = generate_vertices(frame_vertices, option_vertices_truncate, option_vertices) morphs.append(morphVertices) # remove temp meshes for mesh, object in anim_meshes: bpy.data.meshes.remove(mesh) scene.frame_set(original_frame, 0.0) # restore animation state text, model_string = generate_ascii_model(meshes, morphs, scene, option_vertices, option_vertices_truncate, option_faces, option_normals, option_uv_coords, option_materials, option_colors, align_model, flipyz, option_scale, option_copy_textures, filepath, option_animation, option_frame_step) # remove temp meshes for mesh, object in meshes: bpy.data.meshes.remove(mesh) return text, model_string def export_mesh(objects, scene, filepath, option_vertices, option_vertices_truncate, option_faces, option_normals, option_uv_coords, option_materials, option_colors, align_model, flipyz, option_scale, export_single_model, option_copy_textures, option_animation, option_frame_step): """Export single mesh""" text, model_string = generate_mesh_string(objects, scene, option_vertices, option_vertices_truncate, option_faces, option_normals, option_uv_coords, option_materials, option_colors, align_model, flipyz, option_scale, export_single_model, option_copy_textures, filepath, option_animation, option_frame_step) write_file(filepath, text) print("writing", filepath, "done") # ##################################################### # Scene exporter - render elements # ##################################################### def generate_vec4(vec): return TEMPLATE_VEC4 % (vec[0], vec[1], vec[2], vec[3]) def generate_vec3(vec): return TEMPLATE_VEC3 % (vec[0], vec[1], vec[2]) def generate_vec2(vec): return TEMPLATE_VEC2 % (vec[0], vec[1]) def generate_hex(number): return TEMPLATE_HEX % number def generate_string(s): return TEMPLATE_STRING % s def generate_string_list(src_list): return ", ".join(generate_string(item) for item in src_list) def generate_section(label, content): return TEMPLATE_SECTION % (label, content) def get_mesh_filename(mesh): object_id = mesh["data"]["name"] filename = "%s.js" % sanitize(object_id) return filename def generate_material_id_list(materials): chunks = [] for material in materials: chunks.append(material.name) return chunks def generate_group_id_list(obj): chunks = [] for group in bpy.data.groups: if obj.name in group.objects: chunks.append(group.name) return chunks def generate_bool_property(property): if property: return "true" return "false" # ##################################################### # Scene exporter - objects # ##################################################### def generate_objects(data): chunks = [] for obj in data["objects"]: if obj.type == "MESH" and obj.THREE_exportGeometry: object_id = obj.name if len(obj.modifiers) > 0: geo_name = obj.name else: geo_name = obj.data.name geometry_id = "geo_%s" % geo_name material_ids = generate_material_id_list(obj.material_slots) group_ids = generate_group_id_list(obj) position, quaternion, scale = obj.matrix_world.decompose() rotation = quaternion.to_euler("XYZ") material_string = "" if len(material_ids) > 0: material_string = generate_string_list(material_ids) group_string = "" if len(group_ids) > 0: group_string = generate_string_list(group_ids) castShadow = obj.THREE_castShadow receiveShadow = obj.THREE_receiveShadow doubleSided = obj.THREE_doubleSided visible = True geometry_string = generate_string(geometry_id) object_string = TEMPLATE_OBJECT % { "object_id" : generate_string(object_id), "geometry_id" : geometry_string, "group_id" : group_string, "material_id" : material_string, "position" : generate_vec3(position), "rotation" : generate_vec3(rotation), "quaternion" : generate_vec4(quaternion), "scale" : generate_vec3(scale), "castShadow" : generate_bool_property(castShadow), "receiveShadow" : generate_bool_property(receiveShadow), "doubleSided" : generate_bool_property(doubleSided), "visible" : generate_bool_property(visible) } chunks.append(object_string) elif obj.type == "EMPTY" or (obj.type == "MESH" and not obj.THREE_exportGeometry): object_id = obj.name group_ids = generate_group_id_list(obj) position, quaternion, scale = obj.matrix_world.decompose() rotation = quaternion.to_euler("XYZ") group_string = "" if len(group_ids) > 0: group_string = generate_string_list(group_ids) object_string = TEMPLATE_EMPTY % { "object_id" : generate_string(object_id), "group_id" : group_string, "position" : generate_vec3(position), "rotation" : generate_vec3(rotation), "quaternion" : generate_vec4(quaternion), "scale" : generate_vec3(scale) } chunks.append(object_string) return ",\n\n".join(chunks), len(chunks) # ##################################################### # Scene exporter - geometries # ##################################################### def generate_geometries(data): chunks = [] geo_set = set() for obj in data["objects"]: if obj.type == "MESH" and obj.THREE_exportGeometry: if len(obj.modifiers) > 0: name = obj.name else: name = obj.data.name if name not in geo_set: geometry_id = "geo_%s" % name if data["embed_meshes"]: embed_id = "emb_%s" % name geometry_string = TEMPLATE_GEOMETRY_EMBED % { "geometry_id" : generate_string(geometry_id), "embed_id" : generate_string(embed_id) } else: model_filename = os.path.basename(generate_mesh_filename(name, data["filepath"])) geometry_string = TEMPLATE_GEOMETRY_LINK % { "geometry_id" : generate_string(geometry_id), "model_file" : generate_string(model_filename) } chunks.append(geometry_string) geo_set.add(name) return ",\n\n".join(chunks), len(chunks) # ##################################################### # Scene exporter - textures # ##################################################### def generate_textures_scene(data): chunks = [] # TODO: extract just textures actually used by some objects in the scene for texture in bpy.data.textures: if texture.type == 'IMAGE' and texture.image: img = texture.image texture_id = img.name texture_file = extract_texture_filename(img) if data["copy_textures"]: save_image(img, texture_file, data["filepath"]) extras = "" if texture.repeat_x != 1 or texture.repeat_y != 1: extras += ',\n "repeat": [%f, %f]' % (texture.repeat_x, texture.repeat_y) if texture.extension == "REPEAT": wrap_x = "repeat" wrap_y = "repeat" if texture.use_mirror_x: wrap_x = "mirror" if texture.use_mirror_y: wrap_y = "mirror" extras += ',\n "wrap": ["%s", "%s"]' % (wrap_x, wrap_y) texture_string = TEMPLATE_TEXTURE % { "texture_id" : generate_string(texture_id), "texture_file" : generate_string(texture_file), "extras" : extras } chunks.append(texture_string) return ",\n\n".join(chunks), len(chunks) def extract_texture_filename(image): fn = bpy.path.abspath(image.filepath) fn = os.path.normpath(fn) fn_strip = os.path.basename(fn) return fn_strip def save_image(img, name, fpath): dst_dir = os.path.dirname(fpath) dst_path = os.path.join(dst_dir, name) ensure_folder_exist(dst_dir) if img.packed_file: img.save_render(dst_path) else: src_path = bpy.path.abspath(img.filepath) shutil.copy(src_path, dst_dir) # ##################################################### # Scene exporter - materials # ##################################################### def extract_material_data(m, option_colors): world = bpy.context.scene.world material = { 'name': m.name } material['colorDiffuse'] = [m.diffuse_intensity * m.diffuse_color[0], m.diffuse_intensity * m.diffuse_color[1], m.diffuse_intensity * m.diffuse_color[2]] material['colorSpecular'] = [m.specular_intensity * m.specular_color[0], m.specular_intensity * m.specular_color[1], m.specular_intensity * m.specular_color[2]] world_ambient_color = [0, 0, 0] if world: world_ambient_color = world.ambient_color material['colorAmbient'] = [m.ambient * world_ambient_color[0], m.ambient * world_ambient_color[1], m.ambient * world_ambient_color[2]] material['transparency'] = m.alpha # not sure about mapping values to Blinn-Phong shader # Blender uses INT from [1,511] with default 0 # http://www.blender.org/documentation/blender_python_api_2_54_0/bpy.types.Material.html#bpy.types.Material.specular_hardness material["specularCoef"] = m.specular_hardness material["vertexColors"] = m.THREE_useVertexColors and option_colors material['mapDiffuse'] = "" material['mapLight'] = "" material['mapSpecular'] = "" material['mapNormal'] = "" material['mapNormalFactor'] = 1.0 textures = guess_material_textures(m) if textures['diffuse']: material['mapDiffuse'] = textures['diffuse']['texture'].image.name if textures['light']: material['mapLight'] = textures['light']['texture'].image.name if textures['specular']: material['mapSpecular'] = textures['specular']['texture'].image.name if textures['normal']: material['mapNormal'] = textures['normal']['texture'].image.name if textures['normal']['slot'].use_map_normal: material['mapNormalFactor'] = textures['normal']['slot'].normal_factor material['shading'] = m.THREE_materialType material['blending'] = m.THREE_blendingType material['depthWrite'] = m.THREE_depthWrite material['depthTest'] = m.THREE_depthTest material['transparent'] = m.use_transparency return material def guess_material_textures(material): textures = { 'diffuse' : None, 'light' : None, 'normal' : None, 'specular': None } # just take first textures of each, for the moment three.js materials can't handle more # assume diffuse comes before lightmap, normalmap has checked flag for i in range(len(material.texture_slots)): slot = material.texture_slots[i] if slot: texture = slot.texture if slot.use and texture and texture.type == 'IMAGE': if texture.use_normal_map: textures['normal'] = { "texture": texture, "slot": slot } elif slot.use_map_specular or slot.use_map_hardness: textures['specular'] = { "texture": texture, "slot": slot } else: if not textures['diffuse']: textures['diffuse'] = { "texture": texture, "slot": slot } else: textures['light'] = { "texture": texture, "slot": slot } if textures['diffuse'] and textures['normal'] and textures['light'] and textures['specular']: break return textures def generate_material_string(material): material_id = material["name"] # default to Lambert shading = material.get("shading", "Lambert") # normal mapped materials must use Phong # to get all required parameters for normal shader if material['mapNormal']: shading = "Phong" type_map = { "Lambert" : "MeshLambertMaterial", "Phong" : "MeshPhongMaterial" } material_type = type_map.get(shading, "MeshBasicMaterial") parameters = '"color": %d' % rgb2int(material["colorDiffuse"]) parameters += ', "opacity": %.2g' % material["transparency"] if shading == "Phong": parameters += ', "ambient": %d' % rgb2int(material["colorAmbient"]) parameters += ', "specular": %d' % rgb2int(material["colorSpecular"]) parameters += ', "shininess": %.1g' % material["specularCoef"] colorMap = material['mapDiffuse'] lightMap = material['mapLight'] specularMap = material['mapSpecular'] normalMap = material['mapNormal'] normalMapFactor = material['mapNormalFactor'] if colorMap: parameters += ', "map": %s' % generate_string(colorMap) if lightMap: parameters += ', "lightMap": %s' % generate_string(lightMap) if specularMap: parameters += ', "specularMap": %s' % generate_string(specularMap) if normalMap: parameters += ', "normalMap": %s' % generate_string(normalMap) if normalMapFactor != 1.0: parameters += ', "normalMapFactor": %f' % normalMapFactor if material['vertexColors']: parameters += ', "vertexColors": "vertex"' if material['transparent']: parameters += ', "transparent": true' parameters += ', "blending": "%s"' % material['blending'] if not material['depthWrite']: parameters += ', "depthWrite": false' if not material['depthTest']: parameters += ', "depthTest": false' material_string = TEMPLATE_MATERIAL_SCENE % { "material_id" : generate_string(material_id), "type" : generate_string(material_type), "parameters" : parameters } return material_string def generate_materials_scene(data): chunks = [] # TODO: extract just materials actually used by some objects in the scene for m in bpy.data.materials: material = extract_material_data(m, data["use_colors"]) material_string = generate_material_string(material) chunks.append(material_string) return ",\n\n".join(chunks), len(chunks) # ##################################################### # Scene exporter - cameras # ##################################################### def generate_cameras(data): if data["use_cameras"]: cams = bpy.data.objects cams = [ob for ob in cams if (ob.type == 'CAMERA' and ob.select)] chunks = [] if not cams: camera = DEFAULTS["camera"] if camera["type"] == "perspective": camera_string = TEMPLATE_CAMERA_PERSPECTIVE % { "camera_id" : generate_string(camera["name"]), "fov" : camera["fov"], "aspect" : camera["aspect"], "near" : camera["near"], "far" : camera["far"], "position" : generate_vec3(camera["position"]), "target" : generate_vec3(camera["target"]) } elif camera["type"] == "ortho": camera_string = TEMPLATE_CAMERA_ORTHO % { "camera_id" : generate_string(camera["name"]), "left" : camera["left"], "right" : camera["right"], "top" : camera["top"], "bottom" : camera["bottom"], "near" : camera["near"], "far" : camera["far"], "position" : generate_vec3(camera["position"]), "target" : generate_vec3(camera["target"]) } chunks.append(camera_string) else: for cameraobj in cams: camera = bpy.data.cameras[cameraobj.name] # TODO: # Support more than perspective camera # Calculate a target/lookat # Get correct aspect ratio if camera.id_data.type == "PERSP": camera_string = TEMPLATE_CAMERA_PERSPECTIVE % { "camera_id" : generate_string(camera.name), "fov" : (camera.angle / 3.14) * 180.0, "aspect" : 1.333, "near" : camera.clip_start, "far" : camera.clip_end, "position" : generate_vec3([cameraobj.location[0], -cameraobj.location[1], cameraobj.location[2]]), "target" : generate_vec3([0, 0, 0]) } chunks.append(camera_string) return ",\n\n".join(chunks) return "" # ##################################################### # Scene exporter - lights # ##################################################### def generate_lights(data): if data["use_lights"]: lights = data.get("lights", []) if not lights: lights.append(DEFAULTS["light"]) chunks = [] for light in lights: if light["type"] == "directional": light_string = TEMPLATE_LIGHT_DIRECTIONAL % { "light_id" : generate_string(light["name"]), "direction" : generate_vec3(light["direction"]), "color" : rgb2int(light["color"]), "intensity" : light["intensity"] } elif light["type"] == "point": light_string = TEMPLATE_LIGHT_POINT % { "light_id" : generate_string(light["name"]), "position" : generate_vec3(light["position"]), "color" : rgb2int(light["color"]), "intensity" : light["intensity"] } chunks.append(light_string) return ",\n\n".join(chunks) return "" # ##################################################### # Scene exporter - embedded meshes # ##################################################### def generate_embeds(data): if data["embed_meshes"]: chunks = [] for e in data["embeds"]: embed = '"emb_%s": {%s}' % (e, data["embeds"][e]) chunks.append(embed) return ",\n\n".join(chunks) return "" # ##################################################### # Scene exporter - generate ASCII scene # ##################################################### def generate_ascii_scene(data): objects, nobjects = generate_objects(data) geometries, ngeometries = generate_geometries(data) textures, ntextures = generate_textures_scene(data) materials, nmaterials = generate_materials_scene(data) cameras = generate_cameras(data) lights = generate_lights(data) embeds = generate_embeds(data) basetype = "relativeTo" if data["base_html"]: basetype += "HTML" else: basetype += "Scene" sections = [ ["objects", objects], ["geometries", geometries], ["textures", textures], ["materials", materials], ["cameras", cameras], ["lights", lights], ["embeds", embeds] ] chunks = [] for label, content in sections: if content: chunks.append(generate_section(label, content)) sections_string = "\n".join(chunks) default_camera = "" if data["use_cameras"]: cams = [ob for ob in bpy.data.objects if (ob.type == 'CAMERA' and ob.select)] if not cams: default_camera = "default_camera" else: default_camera = cams[0].name parameters = { "fname" : data["source_file"], "sections" : sections_string, "bgcolor" : generate_vec3(DEFAULTS["bgcolor"]), "bgalpha" : DEFAULTS["bgalpha"], "defcamera" : generate_string(default_camera), "nobjects" : nobjects, "ngeometries" : ngeometries, "ntextures" : ntextures, "basetype" : generate_string(basetype), "nmaterials" : nmaterials, "position" : generate_vec3(DEFAULTS["position"]), "rotation" : generate_vec3(DEFAULTS["rotation"]), "scale" : generate_vec3(DEFAULTS["scale"]) } text = TEMPLATE_SCENE_ASCII % parameters return text def export_scene(scene, filepath, flipyz, option_colors, option_lights, option_cameras, option_embed_meshes, embeds, option_url_base_html, option_copy_textures): source_file = os.path.basename(bpy.data.filepath) # objects are contained in scene and linked groups objects = [] # get scene objects sceneobjects = scene.objects for obj in sceneobjects: objects.append(obj) # get linked group objcts for group in bpy.data.groups: for object in group.objects: objects.append(object) scene_text = "" data = { "scene" : scene, "objects" : objects, "embeds" : embeds, "source_file" : source_file, "filepath" : filepath, "flipyz" : flipyz, "use_colors" : option_colors, "use_lights" : option_lights, "use_cameras" : option_cameras, "embed_meshes" : option_embed_meshes, "base_html" : option_url_base_html, "copy_textures": option_copy_textures } scene_text += generate_ascii_scene(data) write_file(filepath, scene_text) # ##################################################### # Main # ##################################################### def save(operator, context, filepath = "", option_flip_yz = True, option_vertices = True, option_vertices_truncate = False, option_faces = True, option_normals = True, option_uv_coords = True, option_materials = True, option_colors = True, align_model = 0, option_export_scene = False, option_lights = False, option_cameras = False, option_scale = 1.0, option_embed_meshes = True, option_url_base_html = False, option_copy_textures = False, option_animation = False, option_frame_step = 1, option_all_meshes = True): #print("URL TYPE", option_url_base_html) filepath = ensure_extension(filepath, '.js') scene = context.scene if scene.objects.active: bpy.ops.object.mode_set(mode='OBJECT') if option_all_meshes: sceneobjects = scene.objects else: sceneobjects = context.selected_objects # objects are contained in scene and linked groups objects = [] # get scene objects for obj in sceneobjects: objects.append(obj) # get objects in linked groups for group in bpy.data.groups: for object in group.objects: objects.append(object) if option_export_scene: geo_set = set() embeds = {} for object in objects: if object.type == "MESH" and object.THREE_exportGeometry: # create extra copy of geometry with applied modifiers # (if they exist) if len(object.modifiers) > 0: name = object.name # otherwise can share geometry else: name = object.data.name if name not in geo_set: if option_embed_meshes: text, model_string = generate_mesh_string([object], scene, option_vertices, option_vertices_truncate, option_faces, option_normals, option_uv_coords, option_materials, option_colors, False, # align_model option_flip_yz, option_scale, False, # export_single_model False, # option_copy_textures filepath, option_animation, option_frame_step) embeds[name] = model_string else: fname = generate_mesh_filename(name, filepath) export_mesh([object], scene, fname, option_vertices, option_vertices_truncate, option_faces, option_normals, option_uv_coords, option_materials, option_colors, False, # align_model option_flip_yz, option_scale, False, # export_single_model option_copy_textures, option_animation, option_frame_step) geo_set.add(name) export_scene(scene, filepath, option_flip_yz, option_colors, option_lights, option_cameras, option_embed_meshes, embeds, option_url_base_html, option_copy_textures) else: export_mesh(objects, scene, filepath, option_vertices, option_vertices_truncate, option_faces, option_normals, option_uv_coords, option_materials, option_colors, align_model, option_flip_yz, option_scale, True, # export_single_model option_copy_textures, option_animation, option_frame_step) return {'FINISHED'}
box/three.js
utils/exporters/blender/2.63/scripts/addons/io_mesh_threejs/export_threejs.py
Python
mit
58,235
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Generated code. DO NOT EDIT! # # Snippet for ExportData # NOTE: This snippet has been automatically generated for illustrative purposes only. # It may require modifications to work in your environment. # To install the latest published package dependency, execute the following: # python3 -m pip install google-cloud-datalabeling # [START datalabeling_v1beta1_generated_DataLabelingService_ExportData_sync] from google.cloud import datalabeling_v1beta1 def sample_export_data(): # Create a client client = datalabeling_v1beta1.DataLabelingServiceClient() # Initialize request argument(s) request = datalabeling_v1beta1.ExportDataRequest( name="name_value", annotated_dataset="annotated_dataset_value", ) # Make the request operation = client.export_data(request=request) print("Waiting for operation to complete...") response = operation.result() # Handle the response print(response) # [END datalabeling_v1beta1_generated_DataLabelingService_ExportData_sync]
googleapis/python-datalabeling
samples/generated_samples/datalabeling_v1beta1_generated_data_labeling_service_export_data_sync.py
Python
apache-2.0
1,635
#!/usr/bin/env python # ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero Public License version 3 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 Affero Public License for more details. # # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/ # ---------------------------------------------------------------------- import copy import numpy from collections import deque from nupic.bindings.regions.PyRegion import PyRegion class LanguageSensor(PyRegion): """ LanguageSensor (LS) is an extensible sensor for text data. The LS obtains info from a file, csv or txt (not yet implemented). An LS is essentially a shell containing two objects: 1. A DataSource object gets one record at a time. This record is returned as a dict object by getNextRecordDict(). For example, a DataSource might return: {sample="Hello world!", labels=["Python"]} 2. An encoder from nupic.fluent/encoders The DataSource and LanguageEncoder are supplied after the node is created, not in the node itself. """ def __init__(self, verbosity=0, numCategories=1): """Create a node without an encoder or datasource.""" self.numCategories = numCategories self.verbosity = verbosity # These fields are set outside when building the region. self.encoder = None self.dataSource = None self._outputValues = {} self._iterNum = 0 self.queue = deque() @classmethod def getSpec(cls): """Return base spec for this region. See base class method for more info.""" spec = { "description":"Sensor that reads text data records and encodes them for " "an HTM network.", "singleNodeOnly":True, "outputs":{ "dataOut":{ "description":"Encoded text", "dataType":"Real32", "count":0, "regionLevel":True, "isDefaultOutput":True, }, "categoryOut":{ "description":"Index of the current word's category.", "dataType":"Real32", "count":0, "regionLevel":True, "isDefaultOutput":False, }, "resetOut":{ "description":"Boolean reset output.", "dataType":"Real32", "count":1, "regionLevel":True, "isDefaultOutput":False, }, "sequenceIdOut":{ "description":"Sequence ID", "dataType":'Real32', "count":1, "regionLevel":True, "isDefaultOutput":False, }, }, "inputs":{}, "parameters":{ "verbosity":{ "description":"Verbosity level", "dataType":"UInt32", "accessMode":"ReadWrite", "count":1, "constraints":"", }, "numCategories":{ "description":("Total number of categories to expect from the " "FileRecordStream"), "dataType":"UInt32", "accessMode":"ReadWrite", "count":1, "constraints":""}, }, "commands":{}, } return spec def initialize(self): """Initialize the node after the network is fully linked.""" if self.encoder is None: raise Exception("Unable to initialize LanguageSensor -- " "encoder has not been set") def rewind(self): """Reset the sensor to the beginning of the data file.""" self._iterNum = 0 if self.dataSource is not None: self.dataSource.rewind() def populateCategoriesOut(self, categories, output): """ Populate the output array with the category indices. Note: non-categories are represented with -1. """ if categories[0] is None: # The record has no entry in category field. output[:] = -1 else: # Populate category output array by looping over the smaller of the # output array (size specified by numCategories) and the record's number # of categories. [numpy.put(output, [i], cat) for i, (_, cat) in enumerate(zip(output, categories))] output[len(categories):] = -1 def compute(self, inputs, outputs): """ Get a record from the dataSource and encode it. The fields for inputs and outputs are as defined in the spec above. Expects the text data to be in under header "token" from the dataSource. """ if len(self.queue) > 0: # Data has been added to the queue, so use it data = self.queue.pop() elif self.dataSource is None: raise Exception("LanguageSensor: No data to encode: queue is empty " "and the dataSource is None.") else: data = self.dataSource.getNextRecordDict() # Keys in data that are not column headers from the data source are # standard of RecordStreamIface objects # Copy important data input fields over to outputs dict. outputs["resetOut"][0] = data["_reset"] outputs["sequenceIdOut"][0] = data["_sequenceId"] self.populateCategoriesOut(data["_category"], outputs["categoryOut"]) self.encoder.encodeIntoArray(data["_token"], outputs["dataOut"]) if self.verbosity > 0: print "LanguageSensor outputs:" print "SeqID: ", outputs["sequenceIdOut"] print "Categories out: ", outputs['categoryOut'] print "dataOut: ", outputs["dataOut"].nonzero()[0] # Deep copy the outputs so self._outputValues doesn't point to the values # used within the Network API self._outputValues = { field: copy.deepcopy(value) for field, value in outputs.iteritems() } self._outputValues["sourceOut"] = data["_token"] self._iterNum += 1 def addDataToQueue(self, token, categoryList, sequenceId, reset=0): """ Add the given data item to the sensor's internal queue. Calls to compute will cause items in the queue to be dequeued in FIFO order. @param token (str) The text token @param categoryList (list) A list of one or more integer labels associated with this token. If the list is [None], no categories will be associated with this item. @param sequenceId (int) An integer ID associated with this token and its sequence (document). @param reset (int) Should be 0 or 1. resetOut will be set to this value when this item is computed. """ self.queue.appendleft ({ "_token": token, "_category": categoryList, "_sequenceId": sequenceId, "_reset": reset }) def getOutputValues(self, outputName): """Return the region's values for outputName. """ return self._outputValues[outputName] def getOutputElementCount(self, name): """Returns the width of dataOut.""" if name == "resetOut" or name == "sequenceIdOut": print ("WARNING: getOutputElementCount should not have been called with " "{}.".format(name)) return 1 elif name == "dataOut": if self.encoder == None: raise Exception("Network requested output element count for {} on a " "LanguageSensor node, but the encoder has not been set." .format(name)) return self.encoder.getWidth() elif name == "categoryOut": return self.numCategories else: raise Exception("Unknown output {}.".format(name))
ywcui1990/nupic.research
htmresearch/regions/LanguageSensor.py
Python
agpl-3.0
8,091
def run(whatweb, pluginname): whatweb.recog_from_file(pluginname, "Public/Script/VertifyForm.js", "zzs20100721")
cflq3/getcms
plugins/strongsoft_cms.py
Python
mit
118
from .ucuenca import Ucuenca from .ucuenca import UcuencaException
stsewd/ucuenca.py
ucuenca/__init__.py
Python
mit
68
""" Data iterator""" import mxnet as mx import numpy as np import sys, os import cv2 import time import multiprocessing import itertools from scipy import ndimage from sklearn import neighbors sys.path.append('../') from utils import get_rgb_data from utils import get_spectral_data from utils import get_polygons from utils import rasterize_polgygon from utils import get_raster from utils import colorize_raster from utils import get_rgb_image from utils import unsoft, get_scale_factor, rasterize_polgygon import tifffile as tiff import cv2 import numpy as np import pandas as pd from shapely import wkt from shapely import affinity from rasterio.features import rasterize from rasterio import features from shapely import geometry from collections import defaultdict from shapely.geometry import MultiPolygon, Polygon from skimage import measure, exposure A_data = [] M_data = [] P_data = [] y_mask = [] sf = 24 a_size = 16 m_size = 64 p_size = 128 l_size = 128 n_out = 10 print('sf: {}'.format(sf)) class CropSampler(object): ''' Draw a class_i from the class probability distribution; Draw a random ImageId with given class_i, from the prev step; Sample a crop position from ImageId based on the kde of labels ''' def __init__(self, masks): n_class = 10 self.maps_with_class = [[], [], [], [], [], [], [], [], [], []] self.kde_samplers = [] self.class_probs = np.ones(n_class) / n_class # self.class_probs = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0.5, 0.5]) self.mask_size = None ts = time.time() for mask_i, mask in enumerate(masks): assert mask.shape[2] == n_class if not self.mask_size: self.mask_size = mask.shape[1] samplers = [] for class_i in range(n_class): X = np.nonzero(mask[:, :, class_i]) X = np.stack(X, axis=1) # np.random.shuffle(X) # X = X[:50000] if not X.size: samplers.append(None) else: self.maps_with_class[class_i].append(mask_i) sampler = neighbors.KernelDensity(self.mask_size * 0.02).fit(X) samplers.append(sampler) assert len(samplers) == n_class self.kde_samplers.append(samplers) print('sampler init time: {}'.format(time.time() - ts)) def update(self, probs): assert self.class_probs.size == probs.size self.class_probs = np.copy(probs) def sample_crop(self, n): kx = np.array([len(x) for x in self.maps_with_class]) class_hist = np.random.multinomial(n, self.class_probs * (kx != 0)) class_ids = np.repeat(np.arange(class_hist.shape[0]), class_hist) X = [] for class_id in class_ids: for i in range(20): random_image_idx = np.random.choice(self.maps_with_class[class_id]) if random_image_idx < 25: break x = self.kde_samplers[random_image_idx][class_id].sample()[0] x /= self.mask_size x = np.clip(x, 0., 1.) return x, class_id, random_image_idx X.append(x) return X sampler = None def flip_mat(mat): n_mat = np.zeros(mat.shape, dtype=np.float32) for i in range(mat.shape[2]): n_mat[:, :, i] = np.fliplr(mat[:, :, i]) return n_mat def rot90_mat(mat, k): n_mat = np.zeros(mat.shape, dtype=np.float32) for i in range(mat.shape[2]): n_mat[:, :, i] = np.rot90(mat[:, :, i], k) return n_mat def get_data(image_id, a_size, m_size, p_size, sf): rgb_data = get_rgb_data(image_id) rgb_data = cv2.resize(rgb_data, (p_size*sf, p_size*sf), interpolation=cv2.INTER_LANCZOS4) # rgb_data = rgb_data.astype(np.float) / 2500. # print(np.max(rgb_data), np.mean(rgb_data)) # rgb_data[:, :, 0] = exposure.equalize_adapthist(rgb_data[:, :, 0], clip_limit=0.04) # rgb_data[:, :, 1] = exposure.equalize_adapthist(rgb_data[:, :, 1], clip_limit=0.04) # rgb_data[:, :, 2] = exposure.equalize_adapthist(rgb_data[:, :, 2], clip_limit=0.04) A_data = get_spectral_data(image_id, a_size*sf, a_size*sf, bands=['A']) M_data = get_spectral_data(image_id, m_size*sf, m_size*sf, bands=['M']) P_data = get_spectral_data(image_id, p_size*sf, p_size*sf, bands=['P']) # lab_data = cv2.cvtColor(rgb_data, cv2.COLOR_BGR2LAB) P_data = np.concatenate([rgb_data, P_data], axis=2) return A_data, M_data, P_data def crop_maps(maps, rel_x, rel_y, rel_size): ''' Crop with relative coords ''' # assert all([0. <= rel_x, rel_y, rel_size <= 1.]) assert rel_x + rel_size <= 1 res = [] for m in maps: abs_x = int(rel_x * m.shape[1]) abs_y = int(rel_y * m.shape[1]) abs_size = int(rel_size * m.shape[1]) res.append(m[abs_x: abs_x + abs_size, abs_y: abs_y + abs_size]) return res def get_crop_position(rel_cx, rel_cy, crop_size, map_size): abs_cx = rel_cx * map_size - crop_size / 2. abs_cy = rel_cy * map_size - crop_size / 2. abs_cx = int(min(max(abs_cx, 0), map_size - crop_size)) # out of border abs_cy = int(min(max(abs_cy, 0), map_size - crop_size)) return abs_cx, abs_cy def rel_crop(im, rel_cx, rel_cy, crop_size): map_size = im.shape[1] r = crop_size / 2 abs_cx = rel_cx * map_size abs_cy = rel_cy * map_size na = np.floor([abs_cy-r, abs_cy+r, abs_cx-r, abs_cx+r]).astype(np.int32) a = np.clip(na, 0, map_size) px0 = a[2] - na[2] px1 = na[3] - a[3] py0 = a[0] - na[0] py1 = na[1] - a[1] crop = im[a[0]:a[1], a[2]:a[3]] crop = np.pad(crop, ((py0, py1), (px0, px1), (0, 0)), mode='reflect') assert crop.shape == (crop_size, crop_size, im.shape[2]) return crop def get_random_data(): (y, x), class_id, im_idx = sampler.sample_crop(1) a_data_glob = A_data[im_idx] m_data_glob = M_data[im_idx] p_data_glob = P_data[im_idx] label_glob = y_mask[im_idx] a_x, a_y = get_crop_position(x, y, a_size, a_data_glob.shape[1]) m_x, m_y = get_crop_position(x, y, m_size, m_data_glob.shape[1]) p_x, p_y = get_crop_position(x, y, p_size, p_data_glob.shape[1]) l_x, l_y = get_crop_position(x, y, l_size, label_glob.shape[1]) a_data = a_data_glob[a_y: a_y + a_size, a_x: a_x + a_size] m_data = m_data_glob[m_y: m_y + m_size, m_x: m_x + m_size] p_data = p_data_glob[p_y: p_y + p_size, p_x: p_x + p_size] label = label_glob[l_y: l_y + l_size, l_x: l_x + l_size] # a_data = rel_crop(a_data_glob, x, y, a_size) # m_data = rel_crop(m_data_glob, x, y, m_size) # p_data = rel_crop(p_data_glob, x, y, p_size) # label = rel_crop(label_glob, x, y, l_size) # rgb = colorize_raster(label) # cv2.circle(rgb, (int(x * label_glob.shape[1]), int(y * label_glob.shape[1])), 30, (0, 0, 255)) # cv2.imshow('label', rgb) # # def get_rgb_image1(image, h=None, w=None): # image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # for c in range(3): # min_val, max_val = np.percentile(image[:, :, c], [2, 98]) # image[:, :, c] = 255*(image[:, :, c] - min_val) / (max_val - min_val) # image[:, :, c] = np.clip(image[:, :, c], 0, 255) # image = (image).astype(np.uint8) # return image # # rgb_data = get_rgb_image1(p_data[:, :, 0:3]) # cv2.imshow('rgb_data', rgb_data) # cv2.waitKey() if np.random.randint(0, 2): a_data = flip_mat(a_data) m_data = flip_mat(m_data) p_data = flip_mat(p_data) label = flip_mat(label) if np.random.randint(0, 2): k = np.random.randint(0, 4) a_data = rot90_mat(a_data, k) m_data = rot90_mat(m_data, k) p_data = rot90_mat(p_data, k) label = rot90_mat(label, k) # if np.random.randint(0, 2): # angle = np.random.randint(0, 180) # data = ndimage.interpolation.rotate(data, angle, reshape=False) # label = ndimage.interpolation.rotate(label, angle, reshape=False) # assert label.shape[:2] == p_data.shape[:2] a_data = np.transpose(a_data, (2, 0, 1)) m_data = np.transpose(m_data, (2, 0, 1)) p_data = np.transpose(p_data, (2, 0, 1)) label = np.transpose(label, (2, 0, 1)) if n_out == 11: label = np.argmax(label, axis=0) + (np.max(label, axis=0) != 0) # 0 label.shape = (1,) + label.shape return a_data, m_data, p_data, label class Batch(mx.io.DataBatch): def __init__(self, data_names, data, label_names, label): self.data = data self.label = label self.data_names = data_names self.label_names = label_names self.pad = 0 self.index = 0 @property def provide_data(self): return [(n, x.shape) for n, x in zip(self.data_names, self.data)] @property def provide_label(self): return [(n, x.shape) for n, x in zip(self.label_names, self.label)] #polygons_test = pd.read_csv('blend.csv') #def get_test_polygons(img_id, h, w): # y_sf, x_sf = get_scale_factor(img_id, w, h) # polygons = [] # image = polygons_test[polygons_test.ImageId == img_id] # for cType in image.ClassType.unique(): # wkt_str = image[image.ClassType == cType].MultipolygonWKT.values[0] # sh = wkt.loads(wkt_str) # sh = affinity.scale(sh, xfact=x_sf, yfact=y_sf, origin=(0, 0, 0)) # polygons.append(sh) # return polygons class MultiInputSegDataIter(mx.io.DataIter): def __init__(self, image_list, batch_size, epoch_size, data_name="data", label_name="softmax_label", start_aug=True, test_list=[]): super(MultiInputSegDataIter, self).__init__() print('Data iterator initialization..') self.data_name = data_name self.label_name = label_name global y_mask, A_data, M_data, P_data, a_size, p_size, m_size, l_size self.batch_size = batch_size self.epoch_size = epoch_size self.cursor = -1 self.image_data = [] self.true_raster = [] for image_id in image_list: a, m, p = get_data(image_id, a_size, m_size, p_size, sf) A_data.append(a) M_data.append(m) P_data.append(p) mask = get_raster(image_id, l_size*sf, l_size*sf) y_mask.append(mask) # test to train # for image_id in test_list: # a, m, p = get_data(image_id, a_size, m_size, p_size, sf) # A_data.append(a) # M_data.append(m) # P_data.append(p) # polygons = get_test_polygons(image_id, p_size*sf, p_size*sf) # y_mask.append(rasterize_polgygon(polygons, p_size*sf, p_size*sf)) print('number of maps(train + test): {}'.format(len(y_mask))) global sampler sampler = CropSampler(y_mask) print('Sampler is ready.') self.a_data_depth = A_data[0].shape[2] self.m_data_depth = M_data[0].shape[2] self.p_data_depth = P_data[0].shape[2] self.label_depth = y_mask[0].shape[2] self.thread_number = 4 self.prefetch_threads = [] if not start_aug: return print('Data loaded.') self.manager = multiprocessing.Manager() self.q = self.manager.Queue(1024) for i in range(self.thread_number): pt = multiprocessing.Process(target=self.gen, args=[self.q]) pt.daemon = True pt.start() self.prefetch_threads.append(pt) print('Daemon prefetcher threads started.') def gen(self, q): while True: a, m, p, label = zip(*[get_random_data() for _ in range(self.batch_size)]) q.put((a, m, p, label)) def update_sampler(self, class_weights): # print(class_weights) class_weights = 1. / (0.02 + class_weights) # class_weights /= np.sum(class_weights) # class_weights = np.clip(class_weights, 0.1, 0.9) class_weights /= np.sum(class_weights) sampler.update(class_weights) # print(class_weights) @property def provide_data(self): return [('a_data', (self.batch_size, self.a_data_depth, a_size, a_size)), ('m_data', (self.batch_size, self.m_data_depth, m_size, m_size)), ('p_data', (self.batch_size, self.p_data_depth, p_size, p_size))] @property def provide_label(self): return [('softmax_label', (self.batch_size, 1 if n_out == 11 else 10, l_size, l_size))] def get_batch_size(self): return self.batch_size def reset(self): self.cursor = -1 def iter_next(self): self.cursor += 1 if(self.cursor < self.epoch_size): return True else: return False def next(self): if self.iter_next(): a, m, p, label = self.q.get(True) data_all = [mx.nd.array(a), mx.nd.array(m), mx.nd.array(p)] label_all = [mx.nd.array(label)] data_names = ['a_data', 'm_data', 'p_data'] label_names = ['softmax_label'] return Batch(data_names, data_all, label_names, label_all) else: raise StopIteration def close(self): for t in self.prefetch_threads: t.terminate() self.manager.shutdown() #train_iter = SegDataIter(['6040_2_2'], 8, 128) #train_iter = mx.io.PrefetchingIter(train_iter) # #n_epoch = 100 #ts = time.time() #for epoch in range(n_epoch): # for i, batch in enumerate(train_iter): # data = batch.data # print('epoch time: {}'.format(time.time() - ts)) # train_iter.reset() # ts = time.time() #train_iter.close()
u1234x1234/kaggle-dstl-satellite-imagery-feature-detection
b3_data_iter.py
Python
apache-2.0
13,936
# encoding=utf-8 import jieba.posseg as pseg import jieba import sys import os import urllib2 import json import re import copy import datetime import time import calendar from parsedate import parseDate from getdata import* from showAll import* cwd_url = os.getcwd() jieba.load_userdict(cwd + '/wendata/dict/dict1.txt') jieba.load_userdict(cwd + '/wendata/dict/dict_manual.txt') jieba.load_userdict(cwd + '/wendata/dict/dict_date.txt') jieba.load_userdict(cwd + '/wendata/dict/dict2.txt') reload(sys) sys.setdefaultencoding('utf-8') def merge_positions(l): positions = {} for x in l: for y in x: positions[y] = 'position' return positions def divide(str): words = pseg.cut(str) li = [] for w in words: li.append([w.word.encode('utf-8'), w.flag.encode('utf-8')]) return li def filt(li, type): # get the specific words depending on the type you want rli = [] for w in li: if w[1] == type: rli.append(w[0]) return rli def paraFilter(store): # check parameters in store dictionary = {} for x in store.keys(): dictionary[x] = [] for y in x.split(" "): j = [] j = re.findall(r'\w+', y) if j != []: dictionary[x].append(j) print "dictionary", dictionary return dictionary def get_platform(): pass # sentence_result = getQueryTypeSet(divide_result, dict2, para, pro, paraCategory) def getQueryTypeSet(li, dictionary, para, pro, paraCategory): # calculate the types of the query words # showp() qType = [] Nkey = 0 hasPosition = 0 hasName = 0 paradic = {} for w in li: word = w[0] if word in dictionary.keys(): qType.append(dictionary[word]) if word in pro: Nkey += 1 if word in paraCategory.keys(): paradic[paraCategory[word]] = word # print "qType", qType # print "para", para for x in paradic.values(): para.append(x) if Nkey == 0: return 0 return qType def pointquery(li, points, devices, stations, para): # "获取某个监测点的数据" point = "" device = "" station = "" for w in li: word = w[0] # print 1 if points.has_key(word): point = word elif devices.has_key(word): device=word elif stations.has_key(word): station=word if point!="" and station!="" and device!="": url = "/data/point_info_with_real_time?station_name="+station+"&device_name="+device+"&point_name="+point return getResult(url) else: return 0 def getPrefixHit(qType, store): # calculate the hit times of each prefix sentences in store count = {} setType = set(qType) for i in range(len(store.keys())): setStore = set(store.keys()[i].split(' ')) count[store.keys()[i]] = len(setStore & setType) return count def ranking(count, qType): # calculate the probability setType = set(qType) N = len(setType) p = {} for x in count.keys(): p[x] = float(count[x] / float(N)) p = sort(p) return p def sort(p): #对命中率进行排序 dicts = sorted(p.iteritems(), key=lambda d: d[1], reverse=True) return dicts # print dicts def revranking(count): # showDict(count) p = {} for x in count.keys(): p[x] = float(count[x] / float(len(x.split(" ")))) # showDict(p) p = sort(p) # print p return p def excuteREST(p, rp, st, para, paraDict, qType, remember): # 执行查询 # p: 正排序后的store匹配度列表 # rp: 反排序后的store匹配度列表 # st: store字典 # para: 输入语句中的参数列表 # paraDict: store中参数列表 # print showList() # p[[[],[]],[]] # st{:} p = resort(p, rp) # print p writeData(p) url = "" # print "para", para if len(para) == 0: for x in p: if len(paraDict[x[0]]) == 0: url = st[x[0]] remember.append(x) break elif len(para) == 1: for x in p: if len(paraDict[x[0]]) == 1: # print paraDict[x[0]][0][0] if qType.count(paraDict[x[0]][0][0]) == 1: url = st[x[0]] + para[0] remember.append(x) break if url == "": return 0 elif len(para) == 2: for x in p: if len(paraDict[x[0]]) == 2: url = st[x[0]][0] + para[0] + st[x[0]][1] + para[1][0]+st[x[0]][2]+para[1][1] remember.append(x) break if url == "": return 0 # url=st[p[0][0]] # if len(para)!=0: # url+=para[0] return getResult(url) def getResult(url): # 与服务器建立连接,获取json数据并返回 # 有一条通服务期跳转的例子需要解决,如下 # //{"查询 全部 工具包":"http://122.224.116.44:5005/toolkit/toolkits/public"} # turl = '/root/INTELLI-City/docs/refer_project/wx/wendata/token' turl = cwd_url + '/wendata/token' fin1 = open(turl, 'r+') token = fin1.read() web_flag = 0 print "url", url if url[:4] != "http": url = 'http://www.intellense.com:3080' + url web_flag = 1 print "url", url elif url == "http://122.227.52.114:53306/django_cas/": return ("请先完成注册!\n点击如下网址: " + url, 1) elif url == "http://60.190.248.2:9990/videos/play/IMG_8056.MOV": return ("监控视频请打开如下网址:\n " + url, 1) elif url == "http://fake data": return ("探测到用户所在位置: 杭州\n——实时气象信息——\n温度: 24摄氏度、\n相对湿度: 68%、\n降水量: 0mm、\n风力风向: 东风3级、\n空气质量: 49 优", 1) req = urllib2.Request(url) req.add_header('authorization', token) if web_flag else None response = urllib2.urlopen(req) # req = urllib2.Request(url) # print "req", req # req.add_header('authorization', token) if web_flag else None # response = urllib2.urlopen(req) # print "response", response # else: # return "请打开网址" + url fin1.close() # try: # response = urllib2.urlopen(req)["message"] # print "response", response # except Exception as e: # return 0 return response.read(), 0 def resort(l1, l2): # 反向检查匹配度 # print l2 l1 = copy.deepcopy(l1) l2 = copy.deepcopy(l2) nl = [] g = -1 group = -1 gdict = {} newlist = [] for x in l1: if g != x[1]: group += 1 g = x[1] nl.append([]) nl[group].append(x) else: nl[group].append(x) for g in nl: for x in g: for y in range(len(l2)): if x[0] == l1[y][0]: gdict[x] = y break sublist = sort(gdict) for x in sublist: newlist.append(x[0]) return newlist def writeData(list): url = 'test.txt' fout = open(url, 'w+') for item in list: fout.write(item[0] + " " + str(item[1]) + '\n') fout.close() def connectTuring(a): #在没有匹配的时候调用外部问答 kurl = '/root/INTELLI-City/docs/refer_project/wx/wendata/turkey' fin = open(kurl, 'r+') key = fin.read() url = r'http://www.tuling123.com/openapi/api?key=' + key + '&loc=杭州市' + '&info=' + a print 'turing url', url reson = urllib2.urlopen(url) reson = json.loads(reson.read()) fin.close() return reson['text'] # def toUTF8(origin): # # change unicode type dict to UTF-8 # result = {} # for x in origin.keys(): # val = origin[x].encode('utf-8') # x = x.encode('utf-8') # result[x] = val # return result # def showDict(l): # for x in l.keys(): # print x + ' ' + str(l[x]) # def showList(l): # for x in l: # print x def test(sentence): sentence = sentence.replace(' ', '') people = getPeople() cities = getPosition('cities') towns = getPosition('towns') stations = getPosition('stations') devices = getPosition('devices') positions = merge_positions([cities, towns, stations, devices]) pro = getPros() general = getGenerals() paraCategory = dict(positions, **people) dict1 = dict(general, **pro) dict2 = dict(dict1, **paraCategory) points = getPoints() st = getStore() # store dict para = [] # keyphrase = pro.keys() paraDict = paraFilter(st) date = parseDate(sentence) ftype=0 remember=[] print "prepare data ready" divide_result = divide(sentence) # list print "devide_result", divide_result sentence_result = getQueryTypeSet( divide_result, dict2, para, pro, paraCategory) # set # for el in sentence_result: # print "sentence_result", unicode(el, "utf8", errors="ignore") point_result = pointquery(divide_result, points, devices, stations, para) if point_result != 0: # print get_point_info_with_real_time(json.loads(point_result)) return get_point_info_with_real_time(json.loads(point_result)) elif sentence_result == 0: return connectTuring(sentence) else: if date != 0: sentence_result.append('time') hit_result = getPrefixHit(sentence_result, st) # dict # print "hit_result", hit_result rank_result = ranking(hit_result, sentence_result) # dict # print "rank_result", rank_result reranking_result = revranking(hit_result) # print "reranking_result", reranking_result[0] if date != 0: para.append(date) excute_result, str_flg = excuteREST( rank_result, reranking_result, st, para, paraDict, sentence_result, remember) print "excute_result", excute_result[:100], type(excute_result) if excute_result == 0: return connectTuring(sentence) else: re_info = showResult(json.loads(excute_result), remember[0]) if not str_flg else excute_result # try: # json.loads(excute_result) # print "done" # re_info = showResult(json.loads(excute_result), remember[0]) # except: # return re_info print "re_info", type(re_info), re_info[:100] if re_info == "": return '没有相关数据信息' else: return re_info # test() def showReply(sentence): sentence = str(sentence) # try: # return test(sentence) # except Exception as e: # return '我好像不太明白·_·' return test(sentence) # print showReply("查询工单")
xiaotianyi/INTELLI-City
docs/refer_project/wx/wenpl/divide.py
Python
mit
11,082
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/spack/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 RColorspace(RPackage): """Carries out mapping between assorted color spaces including RGB, HSV, HLS, CIEXYZ, CIELUV, HCL (polar CIELUV), CIELAB and polar CIELAB. Qualitative, sequential, and diverging color palettes based on HCL colors are provided.""" homepage = "https://cran.r-project.org/web/packages/colorspace/index.html" url = "https://cran.r-project.org/src/contrib/colorspace_1.3-2.tar.gz" list_url = "https://cran.r-project.org/src/contrib/Archive/colorspace" version('1.3-2', '63000bab81d995ff167df76fb97b2984') version('1.2-6', 'a30191e9caf66f77ff4e99c062e9dce1')
krafczyk/spack
var/spack/repos/builtin/packages/r-colorspace/package.py
Python
lgpl-2.1
1,882
# Copyright (c) 2008-2009 Aryeh Leib Taurog, all rights reserved. # Released under the New BSD license. """ This module contains a base type which provides list-style mutations without specific data storage methods. See also http://www.aryehleib.com/MutableLists.html Author: Aryeh Leib Taurog. """ from django.utils.functional import total_ordering @total_ordering class ListMixin(object): """ A base class which provides complete list interface. Derived classes must call ListMixin's __init__() function and implement the following: function _get_single_external(self, i): Return single item with index i for general use. The index i will always satisfy 0 <= i < len(self). function _get_single_internal(self, i): Same as above, but for use within the class [Optional] Note that if _get_single_internal and _get_single_internal return different types of objects, _set_list must distinguish between the two and handle each appropriately. function _set_list(self, length, items): Recreate the entire object. NOTE: items may be a generator which calls _get_single_internal. Therefore, it is necessary to cache the values in a temporary: temp = list(items) before clobbering the original storage. function _set_single(self, i, value): Set the single item at index i to value [Optional] If left undefined, all mutations will result in rebuilding the object using _set_list. function __len__(self): Return the length int _minlength: The minimum legal length [Optional] int _maxlength: The maximum legal length [Optional] type or tuple _allowed: A type or tuple of allowed item types [Optional] class _IndexError: The type of exception to be raise on invalid index [Optional] """ _minlength = 0 _maxlength = None _IndexError = IndexError ### Python initialization and special list interface methods ### def __init__(self, *args, **kwargs): if not hasattr(self, '_get_single_internal'): self._get_single_internal = self._get_single_external if not hasattr(self, '_set_single'): self._set_single = self._set_single_rebuild self._assign_extended_slice = self._assign_extended_slice_rebuild super(ListMixin, self).__init__(*args, **kwargs) def __getitem__(self, index): "Get the item(s) at the specified index/slice." if isinstance(index, slice): return [self._get_single_external(i) for i in xrange(*index.indices(len(self)))] else: index = self._checkindex(index) return self._get_single_external(index) def __delitem__(self, index): "Delete the item(s) at the specified index/slice." if not isinstance(index, (int, long, slice)): raise TypeError("%s is not a legal index" % index) # calculate new length and dimensions origLen = len(self) if isinstance(index, (int, long)): index = self._checkindex(index) indexRange = [index] else: indexRange = range(*index.indices(origLen)) newLen = origLen - len(indexRange) newItems = ( self._get_single_internal(i) for i in xrange(origLen) if i not in indexRange ) self._rebuild(newLen, newItems) def __setitem__(self, index, val): "Set the item(s) at the specified index/slice." if isinstance(index, slice): self._set_slice(index, val) else: index = self._checkindex(index) self._check_allowed((val,)) self._set_single(index, val) def __iter__(self): "Iterate over the items in the list" for i in xrange(len(self)): yield self[i] ### Special methods for arithmetic operations ### def __add__(self, other): 'add another list-like object' return self.__class__(list(self) + list(other)) def __radd__(self, other): 'add to another list-like object' return other.__class__(list(other) + list(self)) def __iadd__(self, other): 'add another list-like object to self' self.extend(list(other)) return self def __mul__(self, n): 'multiply' return self.__class__(list(self) * n) def __rmul__(self, n): 'multiply' return self.__class__(list(self) * n) def __imul__(self, n): 'multiply' if n <= 0: del self[:] else: cache = list(self) for i in range(n-1): self.extend(cache) return self def __eq__(self, other): for i in range(len(self)): try: c = self[i] == other[i] except IndexError: # must be other is shorter return False if not c: return False return True def __lt__(self, other): slen = len(self) for i in range(slen): try: c = self[i] < other[i] except IndexError: # must be other is shorter return False if c: return c return slen < len(other) ### Public list interface Methods ### ## Non-mutating ## def count(self, val): "Standard list count method" count = 0 for i in self: if val == i: count += 1 return count def index(self, val): "Standard list index method" for i in xrange(0, len(self)): if self[i] == val: return i raise ValueError('%s not found in object' % str(val)) ## Mutating ## def append(self, val): "Standard list append method" self[len(self):] = [val] def extend(self, vals): "Standard list extend method" self[len(self):] = vals def insert(self, index, val): "Standard list insert method" if not isinstance(index, (int, long)): raise TypeError("%s is not a legal index" % index) self[index:index] = [val] def pop(self, index=-1): "Standard list pop method" result = self[index] del self[index] return result def remove(self, val): "Standard list remove method" del self[self.index(val)] def reverse(self): "Standard list reverse method" self[:] = self[-1::-1] def sort(self, cmp=cmp, key=None, reverse=False): "Standard list sort method" if key: temp = [(key(v),v) for v in self] temp.sort(cmp=cmp, key=lambda x: x[0], reverse=reverse) self[:] = [v[1] for v in temp] else: temp = list(self) temp.sort(cmp=cmp, reverse=reverse) self[:] = temp ### Private routines ### def _rebuild(self, newLen, newItems): if newLen < self._minlength: raise ValueError('Must have at least %d items' % self._minlength) if self._maxlength is not None and newLen > self._maxlength: raise ValueError('Cannot have more than %d items' % self._maxlength) self._set_list(newLen, newItems) def _set_single_rebuild(self, index, value): self._set_slice(slice(index, index + 1, 1), [value]) def _checkindex(self, index, correct=True): length = len(self) if 0 <= index < length: return index if correct and -length <= index < 0: return index + length raise self._IndexError('invalid index: %s' % str(index)) def _check_allowed(self, items): if hasattr(self, '_allowed'): if False in [isinstance(val, self._allowed) for val in items]: raise TypeError('Invalid type encountered in the arguments.') def _set_slice(self, index, values): "Assign values to a slice of the object" try: iter(values) except TypeError: raise TypeError('can only assign an iterable to a slice') self._check_allowed(values) origLen = len(self) valueList = list(values) start, stop, step = index.indices(origLen) # CAREFUL: index.step and step are not the same! # step will never be None if index.step is None: self._assign_simple_slice(start, stop, valueList) else: self._assign_extended_slice(start, stop, step, valueList) def _assign_extended_slice_rebuild(self, start, stop, step, valueList): 'Assign an extended slice by rebuilding entire list' indexList = range(start, stop, step) # extended slice, only allow assigning slice of same size if len(valueList) != len(indexList): raise ValueError('attempt to assign sequence of size %d ' 'to extended slice of size %d' % (len(valueList), len(indexList))) # we're not changing the length of the sequence newLen = len(self) newVals = dict(zip(indexList, valueList)) def newItems(): for i in xrange(newLen): if i in newVals: yield newVals[i] else: yield self._get_single_internal(i) self._rebuild(newLen, newItems()) def _assign_extended_slice(self, start, stop, step, valueList): 'Assign an extended slice by re-assigning individual items' indexList = range(start, stop, step) # extended slice, only allow assigning slice of same size if len(valueList) != len(indexList): raise ValueError('attempt to assign sequence of size %d ' 'to extended slice of size %d' % (len(valueList), len(indexList))) for i, val in zip(indexList, valueList): self._set_single(i, val) def _assign_simple_slice(self, start, stop, valueList): 'Assign a simple slice; Can assign slice of any length' origLen = len(self) stop = max(start, stop) newLen = origLen - stop + start + len(valueList) def newItems(): for i in xrange(origLen + 1): if i == start: for val in valueList: yield val if i < origLen: if i < start or i >= stop: yield self._get_single_internal(i) self._rebuild(newLen, newItems())
rebost/django
django/contrib/gis/geos/mutable_list.py
Python
bsd-3-clause
10,687
import unittest from calc.interpreter import INTEGER, PLUS, Token, Interpreter, ParserError class TestInterpreter(unittest.TestCase): def test_addition(self): interpreter = Interpreter('4 + 3') result = interpreter.parse() self.assertEqual(result, 7) def test_subtraction(self): interpreter = Interpreter('4 - 3') result = interpreter.parse() self.assertEqual(result, 1) def test_multiple_operations(self): interpreter = Interpreter('4 + 3 - 3') result = interpreter.parse() self.assertEqual(result, 4) def test_raises_parser_error_on_invalid_input(self): interpreter = Interpreter('a') self.assertRaises(ParserError, interpreter._get_next_token) def test_raises_parser_error_on_unexpected_token(self): # Instantiate an "empty" ``Interpreter`` and manually set its token. interpreter = Interpreter('') interpreter.current_token = Token(INTEGER, 0) # Assert a ``ParserError`` is raised if the wrong token is consumed. self.assertRaises(ParserError, interpreter._consume, PLUS)
reillysiemens/calc
tests/test_interpreter.py
Python
isc
1,132
#################################################################################################### # # PySpice - A Spice Package for Python # Copyright (C) 2014 Fabrice Salvaire # # 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/>. # #################################################################################################### # Used by Spice/Library.py #################################################################################################### import os import subprocess #################################################################################################### def file_name_has_extension(file_name, extension): return file_name.endswith(extension) #################################################################################################### def file_extension(filename): # index = filename.rfind(os.path.extsep) # if index == -1: # return None # else: # return filename[index:] return os.path.splitext(filename)[1] #################################################################################################### def run_shasum(filename, algorithm=1, text=False, binary=False, portable=False): if algorithm not in (1, 224, 256, 384, 512, 512224, 512256): raise ValueError args = ['shasum', '--algorithm=' + str(algorithm)] if text: args.append('--text') elif binary: args.append('--binary') elif portable: args.append('--portable') args.append(filename) output = subprocess.check_output(args) shasum = output[:output.find(' ')] return shasum #################################################################################################### class Path: ############################################## def __init__(self, path): self._path = str(path) ############################################## def __bool__(self): return os.path.exists(self._path) ############################################## def __str__(self): return self._path ############################################## @property def path(self): return self._path ############################################## def is_absolut(self): return os.path.isabs(self._path) ############################################## def absolut(self): return self.clone_for_path(os.path.abspath(self._path)) ############################################## def normalise(self): return self.clone_for_path(os.path.normpath(self._path)) ############################################## def normalise_case(self): return self.clone_for_path(os.path.normcase(self._path)) ############################################## def expand_vars_and_user(self): return self.clone_for_path(os.path.expandvars(os.path.expanduser(self._path))) ############################################## def real_path(self): return self.clone_for_path(os.path.realpath(self._path)) ############################################## def relative_to(self, directory): return self.clone_for_path(os.path.relpath(self._path, str(directory))) ############################################## def clone_for_path(self, path): return self.__class__(path) ############################################## def split(self): return self._path.split(os.path.sep) ############################################## def directory_part(self): return Directory(os.path.dirname(self._path)) ############################################## def filename_part(self): return os.path.basename(self._path) ############################################## def is_directory(self): return os.path.isdir(self._path) ############################################## def is_file(self): return os.path.isfile(self._path) ############################################## @property def inode(self): return os.stat(self._path).st_ino ############################################## @property def creation_time(self): return os.stat(self._path).st_ctime #################################################################################################### class Directory(Path): ############################################## def __bool__(self): return super().__nonzero__() and self.is_directory() ############################################## def join_directory(self, directory): return self.__class__(os.path.join(self._path, str(directory))) ############################################## def join_filename(self, filename): return File(filename, self._path) ############################################## def iter_file(self, followlinks=False): if self.is_file(): yield File(self.filename_part(), self.directory_part()) else: for root, directories, files in os.walk(self._path, followlinks=followlinks): for filename in files: yield File(filename, root) ############################################## def iter_directories(self, followlinks=False): for root, directories, files in os.walk(self._path, followlinks=followlinks): for directory in directories: yield Path(os.path.join(root, directory)) #################################################################################################### class File(Path): default_shasum_algorithm = 256 ############################################## def __init__(self, filename, path=''): super().__init__(os.path.join(str(path), str(filename))) self._filename = self.filename_part() if not self._filename: raise ValueError self._directory = self.directory_part() self._shasum = None # lazy computation ############################################## def __bool__(self): return super().__nonzero__() and os.path.isfile(self._path) ############################################## @property def directory(self): return self._directory ############################################## @property def filename(self): return self._filename ############################################## @property def extension(self): return file_extension(self._filename) ############################################## @property def shasum(self): if self._shasum is None: return self.compute_shasum() else: return self._shasum ############################################## def compute_shasum(self, algorithm=None): if algorithm is None: algorithm = self.default_shasum_algorithm self._shasum = run_shasum(self._path, algorithm, portable=True) return self._shasum
FabriceSalvaire/PySpice
PySpice/Tools/File.py
Python
gpl-3.0
7,617
""" (c) Copyright Ascensio System SIA 2021 * The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from urllib.parse import unquote class User: def __init__(self, id, name, email, group, reviewGroups, commentGroups, favorite, deniedPermissions, descriptions, templates): self.id = id self.name = name self.email = email self.group = group self.reviewGroups = reviewGroups self.commentGroups = commentGroups self.favorite = favorite self.deniedPermissions = deniedPermissions self.descriptions = descriptions self.templates = templates descr_user_1 = [ "File author by default", "Doesn’t belong to any group", "Can review all the changes", "Can perform all actions with comments", "The file favorite state is undefined", "Can create files from templates using data from the editor" ] descr_user_2 = [ "Belongs to Group2", "Can review only his own changes or changes made by users with no group", "Can view comments, edit his own comments and comments left by users with no group. Can remove his own comments only", "This file is marked as favorite", "Can create new files from the editor" ] descr_user_3 = [ "Belongs to Group3", "Can review changes made by Group2 users", "Can view comments left by Group2 and Group3 users. Can edit comments left by the Group2 users", "This file isn’t marked as favorite", "Can’t copy data from the file to clipboard", "Can’t download the file", "Can’t print the file", "Can create new files from the editor" ] descr_user_0 = [ "The name is requested when the editor is opened", "Doesn’t belong to any group", "Can review all the changes", "Can perform all actions with comments", "The file favorite state is undefined", "Can't mention others in comments", "Can't create new files from the editor" ] USERS = [ User('uid-1', 'John Smith', 'smith@example.com', None, None, {}, None, [], descr_user_1, True), User('uid-2', 'Mark Pottato', 'pottato@example.com', 'group-2', ['group-2', ''], { 'view': "", 'edit': ["group-2", ""], 'remove': ["group-2"] }, True, [], descr_user_2, False), User('uid-3', 'Hamish Mitchell', 'mitchell@example.com', 'group-3', ['group-2'], { 'view': ["group-3", "group-2"], 'edit': ["group-2"], 'remove': [] }, False, ["copy", "download", "print"], descr_user_3, False), User('uid-0', None, None, None, None, {}, None, [], descr_user_0, False) ] DEFAULT_USER = USERS[0] # get all users def getAllUsers(): return USERS # get user information from the request def getUserFromReq(req): uid = req.COOKIES.get('uid') for user in USERS: if (user.id == uid): return user return DEFAULT_USER # get users data for mentions def getUsersForMentions(uid): usersData = [] for user in USERS: if(user.id != uid and user.name != None and user.email != None): usersData.append({'name':user.name, 'email':user.email}) return usersData
ONLYOFFICE/document-server-integration
web/documentserver-example/python/src/utils/users.py
Python
apache-2.0
4,239
""" :mod: RegisterReplica ================== .. module: RegisterReplica :synopsis: register replica handler RegisterReplica operation handler """ __RCSID__ = "$Id $" from DIRAC import S_OK, S_ERROR from DIRAC.FrameworkSystem.Client.MonitoringClient import gMonitor from DIRAC.DataManagementSystem.Agent.RequestOperations.DMSRequestOperationsBase import DMSRequestOperationsBase ######################################################################## class RegisterReplica( DMSRequestOperationsBase ): """ .. class:: RegisterReplica RegisterReplica operation handler """ def __init__( self, operation = None, csPath = None ): """c'tor :param self: self reference :param Operation operation: Operation instance :param str csPath: CS path for this handler """ DMSRequestOperationsBase.__init__( self, operation, csPath ) # # RegisterReplica specific monitor info gMonitor.registerActivity( "RegisterReplicaAtt", "Attempted replicas registrations", "RequestExecutingAgent", "Replicas/min", gMonitor.OP_SUM ) gMonitor.registerActivity( "RegisterReplicaOK", "Successful replicas registrations", "RequestExecutingAgent", "Replicas/min", gMonitor.OP_SUM ) gMonitor.registerActivity( "RegisterReplicaFail", "Failed replicas registrations", "RequestExecutingAgent", "Replicas/min", gMonitor.OP_SUM ) def __call__( self ): """ call me maybe """ # # counter for failed replicas failedReplicas = 0 # # catalog to use catalogs = self.operation.Catalog if catalogs: catalogs = [ cat.strip() for cat in catalogs.split( ',' ) ] # # get waiting files waitingFiles = self.getWaitingFilesList() # # loop over files registerOperations = {} for opFile in waitingFiles: gMonitor.addMark( "RegisterReplicaAtt", 1 ) # # get LFN lfn = opFile.LFN # # and others targetSE = self.operation.targetSEList[0] replicaTuple = ( lfn , opFile.PFN, targetSE ) # # call ReplicaManager registerReplica = self.dm.registerReplica( replicaTuple, catalogs ) # # check results if not registerReplica["OK"] or lfn in registerReplica["Value"]["Failed"]: # There have been some errors gMonitor.addMark( "RegisterReplicaFail", 1 ) self.dataLoggingClient().addFileRecord( lfn, "RegisterReplicaFail", ','.join( catalogs ) if catalogs else "all catalogs", "", "RegisterReplica" ) reason = registerReplica.get( "Message", registerReplica.get( "Value", {} ).get( "Failed", {} ).get( lfn, 'Unknown' ) ) errorStr = "failed to register LFN %s: %s" % ( lfn, str( reason ) ) # FIXME: this is incompatible with the change made in the DM that we ignore failures if successful in at least one catalog if lfn in registerReplica["Value"].get( "Successful", {} ) and type( reason ) == type( {} ): # As we managed, let's create a new operation for just the remaining registration errorStr += ' - adding registerReplica operations to request' for failedCatalog in reason: key = '%s/%s' % ( targetSE, failedCatalog ) newOperation = self.getRegisterOperation( opFile, targetSE, type = 'RegisterReplica', catalog = failedCatalog ) if key not in registerOperations: registerOperations[key] = newOperation else: registerOperations[key].addFile( newOperation[0] ) opFile.Status = 'Done' else: opFile.Error = errorStr catMaster = True if type( reason ) == type( {} ): from DIRAC.Resources.Catalog.FileCatalog import FileCatalog for failedCatalog in reason: catMaster = catMaster and FileCatalog()._getCatalogConfigDetails( failedCatalog ).get( 'Value', {} ).get( 'Master', False ) # If one targets explicitly a catalog and it fails or if it fails on the master catalog if ( catalogs or catMaster ) and ( 'file does not exist' in opFile.Error.lower() or 'no such file' in opFile.Error.lower() ) : opFile.Status = 'Failed' failedReplicas += 1 self.log.warn( errorStr ) else: # All is OK gMonitor.addMark( "RegisterReplicaOK", 1 ) self.dataLoggingClient().addFileRecord( lfn, "RegisterReplicaOK", ','.join( catalogs ) if catalogs else "all catalogs", "", "RegisterReplica" ) self.log.info( "Replica %s has been registered at %s" % ( lfn, ','.join( catalogs ) if catalogs else "all catalogs" ) ) opFile.Status = "Done" # # if we have new replications to take place, put them at the end if registerOperations: self.log.info( "adding %d operations to the request" % len( registerOperations ) ) for operation in registerOperations.values(): self.operation._parent.addOperation( operation ) # # final check if failedReplicas: self.log.info( "all replicas processed, %s replicas failed to register" % failedReplicas ) self.operation.Error = "some replicas failed to register" return S_ERROR( self.operation.Error ) return S_OK()
calancha/DIRAC
DataManagementSystem/Agent/RequestOperations/RegisterReplica.py
Python
gpl-3.0
5,236
# -*- coding: utf-8 -*- # © Didotech srl (www.didotech.com) from osv import fields, orm from tools.translate import _ class mrp_production_product_line(orm.Model): _inherit = "mrp.production.product.line" def onchange_product_id(self, cr, uid, ids, product_id, product_qty=1, context=None): context = context or self.pool['res.users'].context_get(cr, uid) result_dict = {} if product_id: product = self.pool['product.product'].browse(cr, uid, product_id, context) result_dict.update({ 'name': product.name, 'product_uom': product.uom_id and product.uom_id.id or False, 'product_qty': product_qty }) return {'value': result_dict}
iw3hxn/LibrERP
sale_order_requirement/models/mrp_production_product_line.py
Python
agpl-3.0
762
import numpy as np from week3 import lnn, tools import os def f(x): if 0 <= x < 0.25: return float(0) elif 0.25 <= x < 0.5: return 16.0 * (x - 0.25) elif 0.5 <= x < 0.75: return -16.0 * (x - 0.75) elif 0.75 < x <= 1: return float(0) else: raise ValueError('value should in [0, 1], now is {0}'.format(x)) def MCMC_SD(size=100): """ Assume X~U(0, 1) with only 1 dimension, then generate lots of that X, if acceptable, add it to the result set, if not, add last X. """ result = [] current = 0.5 for i in range(0, size): next_ = np.random.rand() u = np.random.rand() if f(current) == float(0): condition = 0 else: condition = min(f(next_) / f(current), 1) if u < condition: # accept result.append(next_) current = next_ else: # refuse result.append(current) return result def main(): # change the size of samples size = 100000 data = MCMC_SD(size) data = [[data[i]] for i in range(size)] data = np.array(data) true = -1.276263936 # for k in (24): k = 27 result = [] for tr in range(k, 40, 5): try: entropy = lnn.LNN_2_entropy(data, k=k, tr=tr, bw=0) print entropy result.append(entropy) # print 'k={0} tr={1} error={2}'.format(k, tr, error) except ValueError, e: print 'k={0} tr={1} error={2}'.format(k, tr, e) except IndexError, e: print 'k={0} tr={1} error={2}'.format(k, tr, e) result = np.array(result) with open('w3_klnn-estimate-result', 'a') as f: print result-true RMSE = tools.getRootMeanSquaredError(result, true) f.write(':'.join([str(size), str(k), str(RMSE)])) f.write('\n') f.close() print 'write for k={0} done'.format(k) return tools.getRootMeanSquaredError(result, true) if __name__ == '__main__': # if os.path.exists('w3_klnn-estimate-result'): # os.remove('w3_klnn-estimate-result') results = [] # repeat for 50 times for i in range(0, 50): results.append(main()) print tools.getMean(results)
cyruscyliu/diffentropy
week3/w3_lnn.py
Python
mit
2,275
# -*- coding: utf-8 -*- #!/usr/bin/env python import webapp2,jinja2,os import logging import wowapi from datetime import datetime from google.appengine.ext import ndb from google.appengine.api.memcache import Client from google.appengine.api import taskqueue from google.appengine.api.taskqueue import Queue from google.appengine.api.taskqueue import QueueStatistics JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape']) class Progression(ndb.Model): raidname = ndb.StringProperty(indexed = True, required = True) numbosses = ndb.IntegerProperty(default = 0, required = True) normal = ndb.IntegerProperty(default = 0, required = True) heroic = ndb.IntegerProperty(default = 0, required = True) mythic = ndb.IntegerProperty(default = 0, required = True) class Group(ndb.Model): name = ndb.StringProperty(indexed=True, required = True) toons = ndb.StringProperty(repeated=True) brf = ndb.StructuredProperty(Progression, required = True) hm = ndb.StructuredProperty(Progression, required = True) lastupdated = ndb.DateTimeProperty(auto_now=True) avgilvl = ndb.IntegerProperty(default = 0) class Global(ndb.Model): lastupdated = ndb.DateTimeProperty(auto_now=True) class ProgressBuilder(webapp2.RequestHandler): difficulties = ['normal','heroic','mythic'] hmbosses = ['Kargath Bladefist','The Butcher','Brackenspore','Tectus','Twin Ogron','Ko\'ragh','Imperator Mar\'gok'] brfbosses = ['Oregorger','Gruul','The Blast Furnace','Hans\'gar and Franzok','Flamebender Ka\'graz','Kromog','Beastlord Darmac','Operator Thogar','The Iron Maidens','Blackhand'] def post(self): start = self.request.get('start') end = self.request.get('end') logging.info('%s %s' % (start,end)) importer = wowapi.Importer() q = Group.query() groups = q.fetch() logging.info('Builder task for range %s to %s started' % (start, end)) for group in groups: firstchar = group.name[0] if firstchar < start or firstchar > end: continue data = list() importer.load(group.toons, data) progress = dict() self.parse(ProgressBuilder.difficulties, ProgressBuilder.hmbosses, data, 'Highmaul', progress) self.parse(ProgressBuilder.difficulties, ProgressBuilder.brfbosses, data, 'Blackrock Foundry', progress) # calculate the avg ilvl values from the toon data group.avgilvl = 0 numtoons = 0 for toon in data: if 'items' in toon: numtoons += 1 group.avgilvl += toon['items']['averageItemLevel'] if numtoons != 0: group.avgilvl /= numtoons self.response.write(group.name + " data generated<br/>") # update the entry in ndb with the new progression data for this # group. this also checks to make sure that the progress only ever # increases, in case of wierdness with the data. group.brf.normal = max(group.brf.normal, progress['Blackrock Foundry']['normal']) group.brf.heroic = max(group.brf.heroic, progress['Blackrock Foundry']['heroic']) group.brf.mythic = max(group.brf.mythic, progress['Blackrock Foundry']['mythic']) group.hm.normal = max(group.hm.normal, progress['Highmaul']['normal']) group.hm.heroic = max(group.hm.heroic, progress['Highmaul']['heroic']) group.hm.mythic = max(group.hm.mythic, progress['Highmaul']['mythic']) group.put() logging.info('Finished building group %s' % group.name) logging.info('Builder task for range %s to %s completed' % (start, end)) # update the last updated for the whole dataset. don't actually # have to set the time here, the auto_now flag on the property does # it for us. q = Global.query() r = q.fetch() if (len(r) == 0): g = Global() else: g = r[0] g.put() def parse(self, difficulties, bosses, toondata, raidname, progress): progress[raidname] = dict() bossdata = dict() for boss in bosses: bossdata[boss] = dict() for d in difficulties: bossdata[boss][d] = dict() bossdata[boss][d]['times'] = list() bossdata[boss][d]['timeset'] = set() bossdata[boss][d]['killed'] = True bossdata[boss][d]['killtime'] = 0 bossdata[boss][d]['killinv'] = 0 # loop through each toon in the data from the blizzard API for toon in toondata: if 'progression' not in toon: continue # get just the raid data for this toon raids = toon['progression']['raids'] # this filters the raid data down to just the raid we're looking # at this pass raid = [d for d in raids if d['name'] == raidname][0] # loop through the individual bosses and get the timestamp for # the last kill for this toon for each boss for boss in bosses: # this filters the raid data down to just a single boss b = [d for d in raid['bosses'] if d['name'] == boss][0] # loop through each difficulty level and grab each timestamp. # skip any timestamps of zero. that means the toon never # killed the boss. for d in difficulties: if b[d+'Timestamp'] != 0: bossdata[boss][d]['times'].append(b[d+'Timestamp']) bossdata[boss][d]['timeset'].add(b[d+'Timestamp']) # loop back through the difficulties and bosses and build up the # progress data for d in difficulties: progress[raidname][d] = 0 for boss in bosses: # for each boss, grab the set of unique timestamps and sort it # with the last kill first timelist = list(bossdata[boss][d]['timeset']) timelist.sort(reverse=True) # now loop through that time list. a kill involving 5 or more # players from the group is considered a kill for the whole # group and counts towards progress. for t in timelist: count = bossdata[boss][d]['times'].count(t) if count >= 5: bossdata[boss][d]['killed'] = True bossdata[boss][d]['killtime'] = t bossdata[boss][d]['killinv'] = count progress[raidname][d] += 1 ts = datetime.fromtimestamp(t/1000) # logging.info('count for %s %s at time %s (involved %d members)' % (boss, d, ts.strftime("%Y-%m-%d %H:%M:%S"), count)) break class Ranker(webapp2.RequestHandler): def get(self): queue = Queue() stats = queue.fetch_statistics() template_values={ 'tasks': stats.tasks, 'in_flight': stats.in_flight, } template = JINJA_ENVIRONMENT.get_template('templates/ranker.html') self.response.write(template.render(template_values)) def post(self): # refuse to start the tasks if there are some already running queue = Queue() stats = queue.fetch_statistics() if stats.tasks == 0: print 'nop' taskqueue.add(url='/builder', params={'start':'A', 'end':'B'}) taskqueue.add(url='/builder', params={'start':'C', 'end':'E'}) taskqueue.add(url='/builder', params={'start':'F', 'end':'G'}) taskqueue.add(url='/builder', params={'start':'H', 'end':'H'}) taskqueue.add(url='/builder', params={'start':'I', 'end':'M'}) taskqueue.add(url='/builder', params={'start':'N', 'end':'O'}) taskqueue.add(url='/builder', params={'start':'P', 'end':'R'}) taskqueue.add(url='/builder', params={'start':'S', 'end':'S'}) taskqueue.add(url='/builder', params={'start':'T', 'end':'T'}) taskqueue.add(url='/builder', params={'start':'U', 'end':'Z'}) self.redirect('/rank') class Display(webapp2.RequestHandler): def get(self): q = Global.query() r = q.fetch() template_values = { 'last_updated': r[0].lastupdated } template = JINJA_ENVIRONMENT.get_template('templates/header.html') self.response.write(template.render(template_values)) # get the group data from the datastore, and order it in decreasing order # so that further progressed teams show up first. break ties by # alphabetical order of group names q = Group.query().order(-Group.brf.mythic, -Group.brf.heroic, -Group.brf.normal).order(-Group.hm.mythic, -Group.hm.heroic, -Group.hm.normal).order(Group.name) groups = q.fetch() for group in groups: template_values = {'group' : group} template = JINJA_ENVIRONMENT.get_template('templates/group.html') self.response.write(template.render(template_values)) self.response.write(" <div style='clear: both;font-size: 12px;text-align:center'>Site code by Tamen - Aerie Peak(US) &#149; <a href='http://github.com/timwoj/ctrprogress'>http://github.com/timwoj/ctrprogress<a/></div>") self.response.write('</body></html>') class DisplayText(webapp2.RequestHandler): def get(self): q = Global.query() r = q.fetch() if (len(r)): print r[0] template_values = { 'last_updated': r[0].lastupdated } template = JINJA_ENVIRONMENT.get_template('templates/header.html') self.response.write(template.render(template_values)) # get the group data from the datastore, and order it in decreasing order # so that further progressed teams show up first. break ties by # alphabetical order of group names q = Group.query().order(-Group.brf.mythic, -Group.brf.heroic, -Group.brf.normal).order(-Group.hm.mythic, -Group.hm.heroic, -Group.hm.normal).order(Group.name) groups = q.fetch() for group in groups: self.response.write('%s (Avg ilvl: %d)<br/>' % (group.name,group.avgilvl)) self.writeProgress(group.brf) self.writeProgress(group.hm) self.response.write('<br/>') self.response.write('</body></html>') def writeProgress(self, raid): self.response.write("%s: %d/%dN %d/%dH %d/%dM<br/>" % (raid.raidname, raid.normal, raid.numbosses, raid.heroic, raid.numbosses, raid.mythic, raid.numbosses))
AndyHannon/ctrprogress
ranker.py
Python
mit
11,305
import boto3 import datetime import json import logging import os import pytz import requests import structlog import transaction import urllib.parse from botocore.exceptions import ClientError from copy import deepcopy from pyramid.httpexceptions import ( HTTPForbidden, HTTPTemporaryRedirect, HTTPNotFound, # HTTPBadRequest ) from pyramid.response import Response from pyramid.settings import asbool from pyramid.threadlocal import get_current_request from pyramid.traversal import resource_path from pyramid.view import view_config from snovault import ( AfterModified, BeforeModified, CONNECTION, calculated_property, collection, load_schema, abstract_collection, ) from snovault.attachment import ItemWithAttachment from snovault.crud_views import ( collection_add, item_edit, ) from snovault.elasticsearch import ELASTIC_SEARCH from snovault.invalidation import add_to_indexing_queue from snovault.schema_utils import schema_validator from snovault.util import debug_log from snovault.validators import ( validate_item_content_post, validate_item_content_put, validate_item_content_patch, validate_item_content_in_place, no_validate_item_content_post, no_validate_item_content_put, no_validate_item_content_patch ) from urllib.parse import ( parse_qs, urlparse, ) from uuid import uuid4 from ..authentication import session_properties from ..search import make_search_subreq # from . import TrackingItem from .base import ( Item, ALLOW_SUBMITTER_ADD, get_item_or_none, lab_award_attribution_embed_list ) from .dependencies import DependencyEmbedder from ..util import check_user_is_logged_in logging.getLogger('boto3').setLevel(logging.CRITICAL) log = structlog.getLogger(__name__) # XXX: Need expanding to cover display_title file_workflow_run_embeds = [ 'workflow_run_inputs.workflow.title', 'workflow_run_inputs.input_files.workflow_argument_name', 'workflow_run_inputs.input_files.value.filename', 'workflow_run_inputs.input_files.value.display_title', 'workflow_run_inputs.input_files.value.file_format', 'workflow_run_inputs.input_files.value.uuid', 'workflow_run_inputs.input_files.value.accession', 'workflow_run_inputs.output_files.workflow_argument_name', 'workflow_run_inputs.output_files.value.display_title', 'workflow_run_inputs.output_files.value.file_format', 'workflow_run_inputs.output_files.value.uuid', 'workflow_run_inputs.output_files.value.accession', 'workflow_run_inputs.output_files.value_qc.url', 'workflow_run_inputs.output_files.value_qc.overall_quality_status' ] file_workflow_run_embeds_processed = file_workflow_run_embeds + [e.replace('workflow_run_inputs.', 'workflow_run_outputs.') for e in file_workflow_run_embeds] def show_upload_credentials(request=None, context=None, status=None): if request is None or status not in ('uploading', 'to be uploaded by workflow', 'upload failed'): return False return request.has_permission('edit', context) def external_creds(bucket, key, name=None, profile_name=None): """ if name is None, we want the link to s3 but no need to generate an access token. This is useful for linking metadata to files that already exist on s3. """ logging.getLogger('boto3').setLevel(logging.CRITICAL) credentials = {} if name is not None: policy = { 'Version': '2012-10-17', 'Statement': [ { 'Effect': 'Allow', 'Action': 's3:PutObject', 'Resource': 'arn:aws:s3:::{bucket}/{key}'.format(bucket=bucket, key=key), } ] } # boto.set_stream_logger('boto3') conn = boto3.client('sts') token = conn.get_federation_token(Name=name, Policy=json.dumps(policy)) # 'access_key' 'secret_key' 'expiration' 'session_token' credentials = token.get('Credentials') credentials.update({ 'upload_url': 's3://{bucket}/{key}'.format(bucket=bucket, key=key), 'federated_user_arn': token.get('FederatedUser').get('Arn'), 'federated_user_id': token.get('FederatedUser').get('FederatedUserId'), 'request_id': token.get('ResponseMetadata').get('RequestId'), 'key': key }) return { 'service': 's3', 'bucket': bucket, 'key': key, 'upload_credentials': credentials, } def property_closure(request, propname, root_uuid): # Must avoid cycles conn = request.registry[CONNECTION] seen = set() remaining = {str(root_uuid)} while remaining: seen.update(remaining) next_remaining = set() for uuid in remaining: obj = conn.get_by_uuid(uuid) next_remaining.update(obj.__json__(request).get(propname, ())) remaining = next_remaining - seen return seen @collection( name='file-sets', unique_key='accession', properties={ 'title': 'File Sets', 'description': 'Listing of File Sets', }) class FileSet(Item): """Collection of files stored under fileset.""" item_type = 'file_set' schema = load_schema('encoded:schemas/file_set.json') name_key = 'accession' @collection( name='file-set-calibrations', unique_key='accession', properties={ 'title': 'Calibration File Sets', 'description': 'Listing of File Sets', }) class FileSetCalibration(FileSet): """Collection of files stored under fileset.""" base_types = ['FileSet'] + Item.base_types item_type = 'file_set_calibration' schema = load_schema('encoded:schemas/file_set_calibration.json') name_key = 'accession' embedded_list = Item.embedded_list + [ # User linkTo 'files_in_set.submitted_by.first_name', 'files_in_set.submitted_by.last_name', 'files_in_set.submitted_by.job_title', # Lab linkTo 'files_in_set.lab.title', 'files_in_set.lab.name', # File linkTo 'files_in_set.accession', 'files_in_set.href', 'files_in_set.file_size', 'files_in_set.upload_key', 'files_in_set.file_classification', # FileFormat linkTo 'files_in_set.file_format.file_format', ] @collection( name='file-set-microscope-qcs', unique_key='accession', properties={ 'title': 'Microscope QC File Sets', 'description': 'Listing of File Sets', }) class FileSetMicroscopeQc(ItemWithAttachment, FileSet): """Collection of files stored under fileset.""" base_types = ['FileSet'] + Item.base_types item_type = 'file_set_microscope_qc' schema = load_schema('encoded:schemas/file_set_microscope_qc.json') name_key = 'accession' embedded_list = Item.embedded_list + [ # User linkTo 'files_in_set.submitted_by.first_name', 'files_in_set.submitted_by.last_name', 'files_in_set.submitted_by.job_title', # Lab linkTo 'files_in_set.lab.title', 'files_in_set.lab.name', # File linkTo 'files_in_set.accession', 'files_in_set.href', 'files_in_set.file_size', 'files_in_set.upload_key', 'files_in_set.file_classification', # FileFormat linkTo 'files_in_set.file_format.file_format', ] @abstract_collection( name='files', unique_key='accession', acl=ALLOW_SUBMITTER_ADD, properties={ 'title': 'Files', 'description': 'Listing of Files', }) class File(Item): """Collection for individual files.""" item_type = 'file' base_types = ['File'] + Item.base_types schema = load_schema('encoded:schemas/file.json') # TODO: embed file_format embedded_list = Item.embedded_list + lab_award_attribution_embed_list + [ # XXX: Experiment linkTo 'experiments.accession', # ExperimentType linkTo 'experiments.experiment_type.title', # ExperimentSet linkTo 'experiments.experiment_sets.accession', 'experiments.experiment_sets.experimentset_type', 'experiments.experiment_sets.@type', # Enzyme linkTo 'experiments.digestion_enzyme.name', # Standard embed 'experiments.last_modified.date_modified', # Biosample linkTo 'experiments.biosample.accession', 'experiments.biosample.biosource_summary', # REQUIRES additional embeds #1 'experiments.biosample.modifications_summary', 'experiments.biosample.treatments_summary', # Biosource linkTo 'experiments.biosample.biosource.biosource_type', 'experiments.biosample.biosource.cell_line_tier', 'experiments.biosample.biosource.override_biosource_name', 'experiments.biosample.cell_culture_details.in_vitro_differentiated', # needed for calc prop #1 # OntologyTerm linkTo 'experiments.biosample.biosource.cell_line.preferred_name', 'experiments.biosample.biosource.cell_line.term_name', 'experiments.biosample.biosource.cell_line.term_id', # OntologyTerm linkTo 'experiments.biosample.biosource.tissue.preferred_name', 'experiments.biosample.biosource.tissue.term_name', 'experiments.biosample.biosource.tissue.term_id', # Modification linkTo 'experiments.biosample.biosource.modifications.modification_type', 'experiments.biosample.biosource.modifications.genomic_change', 'experiments.biosample.biosource.modifications.override_modification_name', # BioFeature linkTo 'experiments.biosample.biosource.modifications.target_of_mod.feature_type', 'experiments.biosample.biosource.modifications.target_of_mod.preferred_label', 'experiments.biosample.biosource.modifications.target_of_mod.cellular_structure', 'experiments.biosample.biosource.modifications.target_of_mod.organism_name', 'experiments.biosample.biosource.modifications.target_of_mod.relevant_genes', 'experiments.biosample.biosource.modifications.target_of_mod.feature_mods', 'experiments.biosample.biosource.modifications.target_of_mod.genome_location', # Organism linkTo 'experiments.biosample.biosource.individual.organism.name', 'experiments.biosample.biosource.individual.organism.scientific_name', # FileFormat linkTo 'file_format.file_format', # File linkTo 'related_files.relationship_type', 'related_files.file.accession', # QualityMetric linkTo 'quality_metric.url', 'quality_metric.@type', 'quality_metric.Total reads', # Calc prop depends on qc_list 'quality_metric.quality_metric_summary.*', # QualityMetric linkTo 'quality_metric.qc_list.qc_type', 'quality_metric.qc_list.value.url', 'quality_metric.qc_list.value.@type', 'quality_metric.qc_list.value.Total reads' ] name_key = 'accession' rev = { 'experiments': ('Experiment', 'files'), } @calculated_property(schema={ "title": "Experiments", "description": "Experiments that this file is associated with", "type": "array", "items": { "title": "Experiments", "type": ["string", "object"], "linkTo": "Experiment" } }) def experiments(self, request): return self.rev_link_atids(request, "experiments") @calculated_property(schema={ "title": "Display Title", "description": "Name of this File", "type": "string" }) def display_title(self, request, file_format, accession=None, external_accession=None): # TODO: refactor to use file_format embed accession = accession or external_accession file_format_item = get_item_or_none(request, file_format, 'file-formats') try: file_extension = '.' + file_format_item.get('standard_file_extension') except AttributeError: file_extension = '' return '{}{}'.format(accession, file_extension) @calculated_property(schema={ "title": "File Type", "description": "Type of File", "type": "string" }) def file_type_detailed(self, request, file_format, file_type=None): outString = (file_type or 'other') file_format_item = get_item_or_none(request, file_format, 'file-formats') try: fformat = file_format_item.get('file_format') outString = outString + ' (' + fformat + ')' except AttributeError: pass return outString def generate_track_title(self, track_info, props): if not props.get('higlass_uid'): return None exp_type = track_info.get('experiment_type', None) if exp_type is None: return None bname = track_info.get('biosource_name', 'unknown sample') ftype = props.get('file_type', 'unspecified type') assay = track_info.get('assay_info', '') title = '{ft} for {bs} {et} {ai}'.format( ft=ftype, ai=assay, et=exp_type, bs=bname ) return title.replace(' ', ' ').rstrip() def _get_file_expt_bucket(self, request, item2check): fatid = self.jsonld_id(request) if 'files' in item2check: if fatid in item2check.get('files'): return 'raw file' if 'processed_files' in item2check: if fatid in item2check.get('processed_files'): return 'processed file' of_info = item2check.get('other_processed_files', []) for obucket in of_info: ofiles = obucket.get('files') if [of for of in ofiles if of == fatid]: return obucket.get('title') return None def _get_ds_cond_lab_from_repset(self, request, repset): elab = get_item_or_none(request, repset.get('lab')) if elab: elab = elab.get('display_title') return (repset.get('dataset_label', None), repset.get('condition', None), elab) def _get_file_experiment_info(self, request, currinfo): """ Get info about an experiment that a file belongs given a File. A file may also be linked to an experiment set only Checks the rev_linked experiments and experiment_sets """ info = {} expid = None repsetid = None rev_exps = self.experiments(request) if rev_exps: if len(rev_exps) != 1: # most files with experiments revlinks linked to only one # edge case eg. sci-Hi-C -- punt and add info 'manually' return info expid = rev_exps[0] elif hasattr(self, 'experiment_sets'): # FileProcessed only rev_exp_sets = self.experiment_sets(request) if rev_exp_sets: repset = [rs for rs in rev_exp_sets if 'replicate' in rs] if len(repset) != 1: # some microscopy files linked to multiple repsets # for these edge cases add info 'manually' return info repsetid = repset[0] else: return info # here we have either an expid or a repsetid if repsetid: # get 2 fields and get an expt to get other info rep_set_info = get_item_or_none(request, repsetid) if not rep_set_info: return info # pieces of info to get from the repset if there is one ds, c, el = self._get_ds_cond_lab_from_repset(request, rep_set_info) info['dataset'] = ds info['condition'] = c info['experimental_lab'] = el expts_in_set = rep_set_info.get('experiments_in_set', []) if not expts_in_set: return info elif len(expts_in_set) == 1: info['replicate_info'] = 'unreplicated' else: info['replicate_info'] = 'merged replicates' info['experiment_bucket'] = self._get_file_expt_bucket(request, rep_set_info) # get the first experiment of set and set to experiment of file shared info expid = expts_in_set[0] if expid: exp_info = get_item_or_none(request, expid) if not exp_info: # sonmethings fishy - abort return info # check to see if we have experimental lab if 'experimental_lab' not in info or info.get('experimental_lab') is None: elab = get_item_or_none(request, exp_info.get('lab')) if elab: info['experimental_lab'] = elab.get('display_title') exp_type = get_item_or_none(request, exp_info.get('experiment_type')) if exp_type is not None: info['experiment_type'] = exp_type.get('title') if 'experiment_bucket' not in info: # did not get it from rep_set info['experiment_bucket'] = self._get_file_expt_bucket(request, exp_info) assay_info = exp_info.get('experiment_categorizer') if assay_info: info['assay_info'] = assay_info.get('value') if 'replicate_info' not in info: # we did not get repinfo from a repset so rep nos for an expt are relevant possible_repsets = exp_info.get('experiment_sets', []) # only check experiment-set-replicate items for replicate_exps repset = [rs for rs in possible_repsets if 'replicate' in rs] if repset: repset = repset[0] rep_set_info = get_item_or_none(request, repset) if rep_set_info is not None: ds, c, el = self._get_ds_cond_lab_from_repset(request, rep_set_info) info['dataset'] = ds info['condition'] = c if info.get('experimental_lab') is None: info['experimental_lab'] = el rep_exps = rep_set_info.get('replicate_exps', []) for rep in rep_exps: if rep.get('replicate_exp') == expid: repstring = 'Biorep ' + str(rep.get('bio_rep_no')) + ', Techrep ' + str(rep.get('tec_rep_no')) info['replicate_info'] = repstring if 'biosource_name' not in currinfo: sample_id = exp_info.get('biosample') if sample_id is not None: sample = get_item_or_none(request, sample_id) if sample is not None: info['biosource_name'] = sample.get('biosource_summary') return {k: v for k, v in info.items() if v is not None} @calculated_property(schema={ "title": "Track and Facet Info", "description": "Useful faceting and visualization info", "type": "object", "properties": { "experiment_type": { "type": "string" }, "assay_info": { "type": "string" }, "lab_name": { "type": "string" }, "experimental_lab": { "type": "string" }, "biosource_name": { "type": "string" }, "replicate_info": { "type": "string" }, "experiment_bucket": { "type": "string" }, "dataset": { "type": "string" }, "condition": { "type": "string" }, "track_title": { "type": "string" } } }) def track_and_facet_info(self, request, biosource_name=None): props = self.upgrade_properties() fields = ['experiment_type', 'assay_info', 'lab_name', 'experimental_lab', 'dataset', 'condition', 'biosource_name', 'replicate_info', 'experiment_bucket'] # look for existing _props track_info = {field: props.get('override_' + field) for field in fields} track_info = {k: v for k, v in track_info.items() if v is not None} # vistrack only pass in biosource_name because _biosource_name is # a calc prop of vistrack - from linked Biosource if biosource_name and 'biosource_name' not in track_info: track_info['biosource_name'] = biosource_name if len(track_info) != len(fields): # if track_info has same number of items as fields we have everything we need if not (len(track_info) == len(fields) - 1 and 'lab_name' not in track_info): # only if everything but lab exists can we avoid getting expt einfo = self._get_file_experiment_info(request, track_info) track_info.update({k: v for k, v in einfo.items() if k not in track_info}) # file lab_name is same as lab - we need this property to account for FileVistrack # or any other file that are generated with override_ values if 'lab_name' not in track_info: labid = props.get('lab') lab = get_item_or_none(request, labid) if lab: track_info['lab_name'] = lab.get('display_title') track_title = self.generate_track_title(track_info, props) if track_title is not None: track_info['track_title'] = track_title return track_info def _update(self, properties, sheets=None): if not properties: return # ensure we always have s3 links setup sheets = {} if sheets is None else sheets.copy() uuid = self.uuid old_creds = self.propsheets.get('external', None) new_creds = old_creds # don't get new creds if properties.get('status', None) in ('uploading', 'to be uploaded by workflow', 'upload failed'): new_creds = self.build_external_creds(self.registry, uuid, properties) sheets['external'] = new_creds # handle extra files updated_extra_files = [] extra_files = properties.get('extra_files', []) if extra_files: # get @id for parent file try: at_id = resource_path(self) except Exception: at_id = "/" + str(uuid) + "/" # ensure at_id ends with a slash if not at_id.endswith('/'): at_id += '/' file_formats = [] for xfile in extra_files: # ensure a file_format (identifier for extra_file) is given and non-null if not('file_format' in xfile and bool(xfile['file_format'])): continue eformat = xfile['file_format'] if eformat.startswith('/file-formats/'): eformat = eformat[len('/file-formats/'):-1] xfile_format = self.registry['collections']['FileFormat'].get(eformat) xff_uuid = str(xfile_format.uuid) if not xff_uuid: raise Exception("Cannot find format item for the extra file") if xff_uuid in file_formats: raise Exception("Each file in extra_files must have unique file_format") file_formats.append(xff_uuid) xfile['file_format'] = xff_uuid xfile['accession'] = properties.get('accession') # just need a filename to trigger creation of credentials xfile['filename'] = xfile['accession'] xfile['uuid'] = str(uuid) # if not 'status' in xfile or not bool(xfile['status']): # xfile['status'] = properties.get('status') ext = self.build_external_creds(self.registry, uuid, xfile) # build href file_extension = xfile_format.properties.get('standard_file_extension') filename = '{}.{}'.format(xfile['accession'], file_extension) xfile['href'] = at_id + '@@download/' + filename xfile['upload_key'] = ext['key'] sheets['external' + xfile['file_format']] = ext updated_extra_files.append(xfile) if extra_files: properties['extra_files'] = updated_extra_files if old_creds: if old_creds.get('key') != new_creds.get('key'): try: # delete the old sumabeach conn = boto3.client('s3') bname = old_creds['bucket'] conn.delete_object(Bucket=bname, Key=old_creds['key']) except Exception as e: print(e) # update self first to ensure 'related_files' are stored in self.properties super(File, self)._update(properties, sheets) # handle related_files. This is quite janky; must manually invalidate # the relation made on `related_fl` item because we are calling its # update() method directly, which circumvents snovault.crud_view.item_edit DicRefRelation = { "derived from": "parent of", "parent of": "derived from", "supercedes": "is superceded by", "is superceded by": "supercedes", "paired with": "paired with", # "grouped with": "grouped with" } if 'related_files' in properties: my_uuid = str(self.uuid) # save these values curr_txn = None curr_request = None for relation in properties["related_files"]: # skip "grouped with" type from update, to avoid circularity issues # which are more likely to arise with larger groups if relation["relationship_type"] == "grouped with": continue try: switch = relation["relationship_type"] rev_switch = DicRefRelation[switch] related_fl = relation["file"] relationship_entry = {"relationship_type": rev_switch, "file": my_uuid} except Exception: log.error('Error updating related_files on %s _update. %s' % (my_uuid, relation)) continue target_fl = self.collection.get(related_fl) target_fl_props = deepcopy(target_fl.properties) # This is a cool python feature. If break is not hit in the loop, # go to the `else` statement. Works for empty lists as well for target_relation in target_fl_props.get('related_files', []): if (target_relation.get('file') == my_uuid and target_relation.get('relationship_type') == rev_switch): break else: # Get the current request in order to queue the forced # update for indexing. This is bad form. # Don't do this anywhere else, please! if curr_txn is None: curr_txn = transaction.get() if curr_request is None: curr_request = get_current_request() # handle related_files whether or not any currently exist target_related_files = target_fl_props.get('related_files', []) target_related_files.append(relationship_entry) target_fl_props.update({'related_files': target_related_files}) target_fl._update(target_fl_props) to_queue = {'uuid': str(target_fl.uuid), 'sid': target_fl.sid, 'info': 'queued from %s _update' % my_uuid} curr_txn.addAfterCommitHook(add_to_indexing_queue, args=(curr_request, to_queue, 'edit')) @property def __name__(self): properties = self.upgrade_properties() if properties.get('status') == 'replaced': return self.uuid return properties.get(self.name_key, None) or self.uuid def unique_keys(self, properties): keys = super(File, self).unique_keys(properties) if properties.get('status') != 'replaced': if 'md5sum' in properties: value = 'md5:{md5sum}'.format(**properties) keys.setdefault('alias', []).append(value) return keys @calculated_property(schema={ "title": "Title", "type": "string", "description": "Accession of this file" }) def title(self, accession=None, external_accession=None): return accession or external_accession @calculated_property(schema={ "title": "Download URL", "type": "string", "description": "Use this link to download this file." }) def href(self, request, file_format, accession=None, external_accession=None): fformat = get_item_or_none(request, file_format, 'file-formats') try: file_extension = '.' + fformat.get('standard_file_extension') except AttributeError: file_extension = '' accession = accession or external_accession filename = '{}{}'.format(accession, file_extension) return request.resource_path(self) + '@@download/' + filename @calculated_property(schema={ "title": "Upload Key", "type": "string", }) def upload_key(self, request): properties = self.properties external = self.propsheets.get('external', {}) extkey = external.get('key') if not external or not extkey or extkey != self.build_key(self.registry, self.uuid, properties): try: external = self.build_external_creds(self.registry, self.uuid, properties) except ClientError: log.error(os.environ) log.error(properties) return 'UPLOAD KEY FAILED' return external['key'] @calculated_property(condition=show_upload_credentials, schema={ "type": "object", }) def upload_credentials(self): external = self.propsheets.get('external', None) if external is not None: return external['upload_credentials'] @calculated_property(condition=show_upload_credentials, schema={ "type": "object", }) def extra_files_creds(self): external = self.propsheets.get('external', None) if external is not None: extras = [] for extra in self.properties.get('extra_files', []): eformat = extra.get('file_format') xfile_format = self.registry['collections']['FileFormat'].get(eformat) try: xff_uuid = str(xfile_format.uuid) except AttributeError: print("Can't find required format uuid for %s" % eformat) continue extra_creds = self.propsheets.get('external' + xff_uuid) extra['upload_credentials'] = extra_creds['upload_credentials'] extras.append(extra) return extras def get_presigned_url_location(self, external, request, filename) -> str: """ Opens an S3 boto3 client and returns a presigned url for the requested file to be downloaded""" conn = boto3.client('s3') param_get_object = { 'Bucket': external['bucket'], 'Key': external['key'], 'ResponseContentDisposition': "attachment; filename=" + filename } if request.range: param_get_object.update({'Range': request.headers.get('Range')}) location = conn.generate_presigned_url( ClientMethod='get_object', Params=param_get_object, ExpiresIn=36*60*60 ) return location def get_open_data_url_or_presigned_url_location(self, external, request, filename, datastore_is_database) -> str: """ Returns the Open Data S3 url for the file if present (as a calculated property), and otherwise returns a presigned S3 URL to a 4DN bucket. """ open_data_url = None if datastore_is_database: # view model came from DB - must compute calc prop open_data_url = self._open_data_url(self.properties['status'], filename=filename) else: # view model came from elasticsearch - calc props should be here if hasattr(self.model, 'source'): es_model_props = self.model.source['embedded'] open_data_url = es_model_props.get('open_data_url', '') if filename not in open_data_url: # we requested an extra_file, so recompute with correct filename open_data_url = self._open_data_url(self.properties['status'], filename=filename) if not open_data_url: # fallback to DB open_data_url = self._open_data_url(self.properties['status'], filename=filename) if open_data_url: return open_data_url else: location = self.get_presigned_url_location(external, request, filename) return location @staticmethod def _head_s3(client, bucket, key): """ Helper for below method for mocking purposes. """ return client.head_object(Bucket=bucket, Key=key) def _open_data_url(self, status, filename): """ Helper for below method containing core functionality. """ if not filename: return None if status in ['released', 'archived']: open_data_bucket = '4dn-open-data-public' if 'wfoutput' in self.get_bucket(self.registry): bucket_type = 'wfoutput' else: bucket_type = 'files' open_data_key = 'fourfront-webprod/{bucket_type}/{uuid}/{filename}'.format( bucket_type=bucket_type, uuid=self.uuid, filename=filename, ) # Check if the file exists in the Open Data S3 bucket client = boto3.client('s3') try: # If the file exists in the Open Data S3 bucket, client.head_object will succeed (not throw ClientError) # Returning a valid S3 URL to the public url of the file self._head_s3(client, open_data_bucket, open_data_key) location = 'https://{open_data_bucket}.s3.amazonaws.com/{open_data_key}'.format( open_data_bucket=open_data_bucket, open_data_key=open_data_key, ) return location except ClientError: return None else: return None @calculated_property(schema={ "title": "Open Data URL", "description": "Location of file on Open Data Bucket, if it exists", "type": "string" }) def open_data_url(self, request, accession, file_format, status=None): """ Computes the open data URL and checks if it exists. """ fformat = get_item_or_none(request, file_format, frame='raw') # no calc props needed filename = "{}.{}".format(accession, fformat.get('standard_file_extension', '')) return self._open_data_url(status, filename) @classmethod def get_bucket(cls, registry): return registry.settings['file_upload_bucket'] @classmethod def build_key(cls, registry, uuid, properties): fformat = properties.get('file_format') if fformat.startswith('/file-formats/'): fformat = fformat[len('/file-formats/'):-1] prop_format = registry['collections']['FileFormat'].get(fformat) try: file_extension = prop_format.properties['standard_file_extension'] except KeyError: raise Exception('File format not in list of supported file types') return '{uuid}/{accession}.{file_extension}'.format( file_extension=file_extension, uuid=uuid, accession=properties.get('accession')) @classmethod def build_external_creds(cls, registry, uuid, properties): bucket = cls.get_bucket(registry) key = cls.build_key(registry, uuid, properties) # remove the path from the file name and only take first 32 chars fname = properties.get('filename') name = None if fname: name = fname.split('/')[-1][:32] profile_name = registry.settings.get('file_upload_profile_name') return external_creds(bucket, key, name, profile_name) @classmethod def create(cls, registry, uuid, properties, sheets=None): if properties.get('status') in ('uploading', 'to be uploaded by workflow'): sheets = {} if sheets is None else sheets.copy() sheets['external'] = cls.build_external_creds(registry, uuid, properties) return super(File, cls).create(registry, uuid, properties, sheets) class Collection(Item.Collection): pass @calculated_property(schema={ "title": "Notes to tsv file", "description": "Notes that go into the metadata.tsv file", "type": "string" }) def tsv_notes(self, request, notes_to_tsv=None): if notes_to_tsv is None: return '' else: notes_to_tsv_string = ','.join(notes_to_tsv) return notes_to_tsv_string @collection( name='files-fastq', unique_key='accession', properties={ 'title': 'FASTQ Files', 'description': 'Listing of FASTQ Files', }) class FileFastq(File): """Collection for individual fastq files.""" item_type = 'file_fastq' schema = load_schema('encoded:schemas/file_fastq.json') embedded_list = File.embedded_list + file_workflow_run_embeds + [ # QualityMetric linkTo 'quality_metric.overall_quality_status', 'quality_metric.Total Sequences', 'quality_metric.Sequence length', 'quality_metric.url' ] name_key = 'accession' rev = dict(File.rev, **{ 'workflow_run_inputs': ('WorkflowRun', 'input_files.value'), 'workflow_run_outputs': ('WorkflowRun', 'output_files.value'), }) @calculated_property(schema={ "title": "Input of Workflow Runs", "description": "All workflow runs that this file serves as an input to", "type": "array", "items": { "title": "Input of Workflow Run", "type": ["string", "object"], "linkTo": "WorkflowRun" } }) def workflow_run_inputs(self, request): return self.rev_link_atids(request, "workflow_run_inputs") @calculated_property(schema={ "title": "Output of Workflow Runs", "description": "All workflow runs that this file serves as an output from", "type": "array", "items": { "title": "Output of Workflow Run", "type": "string", "linkTo": "WorkflowRun" } }) def workflow_run_outputs(self, request): return self.rev_link_atids(request, "workflow_run_outputs") @collection( name='files-processed', unique_key='accession', properties={ 'title': 'Processed Files', 'description': 'Listing of Processed Files', }) class FileProcessed(File): """Collection for individual processed files.""" item_type = 'file_processed' schema = load_schema('encoded:schemas/file_processed.json') embedded_list = File.embedded_list + file_workflow_run_embeds_processed + [ # ExperimentSet linkTo 'experiment_sets.accession', 'experiment_sets.last_modified.date_modified', # QualityMetric linkTo "quality_metric.Total reads", "quality_metric.Trans reads", "quality_metric.Cis reads (>20kb)", "quality_metric.Short cis reads (<20kb)", "quality_metric.url" ] name_key = 'accession' rev = dict(File.rev, **{ 'workflow_run_inputs': ('WorkflowRun', 'input_files.value'), 'workflow_run_outputs': ('WorkflowRun', 'output_files.value'), 'experiments': ('Experiment', 'processed_files'), 'experiment_sets': ('ExperimentSet', 'processed_files'), 'other_experiments': ('Experiment', 'other_processed_files.files'), 'other_experiment_sets': ('ExperimentSet', 'other_processed_files.files') }) aggregated_items = { "last_modified": [ "date_modified" ], } @classmethod def get_bucket(cls, registry): return registry.settings['file_wfout_bucket'] @calculated_property(schema={ "title": "Input of Workflow Runs", "description": "All workflow runs that this file serves as an input to", "type": "array", "items": { "title": "Input of Workflow Run", "type": ["string", "object"], "linkTo": "WorkflowRun" } }) def workflow_run_inputs(self, request, disable_wfr_inputs=False): # switch this calc prop off for some processed files, i.e. control exp files if not disable_wfr_inputs: return self.rev_link_atids(request, "workflow_run_inputs") else: return [] @calculated_property(schema={ "title": "Output of Workflow Runs", "description": "All workflow runs that this file serves as an output from", "type": "array", "items": { "title": "Output of Workflow Run", "type": "string", "linkTo": "WorkflowRun" } }) def workflow_run_outputs(self, request): return self.rev_link_atids(request, "workflow_run_outputs") @calculated_property(schema={ "title": "Experiment Sets", "description": "All Experiment Sets that this file belongs to", "type": "array", "items": { "title": "Experiment Set", "type": "string", "linkTo": "ExperimentSet" } }) def experiment_sets(self, request): return list(set(self.rev_link_atids(request, "experiment_sets") + self.rev_link_atids(request, "other_experiment_sets"))) @calculated_property(schema={ "title": "Experiments", "description": "Experiments that this file belongs to", "type": "array", "items": { "title": "Experiment", "type": "string", "linkTo": "Experiment" } }) def experiments(self, request): return list(set(self.rev_link_atids(request, "experiments") + self.rev_link_atids(request, "other_experiments"))) @calculated_property(schema={ "title": "Pairsqc Quality Metric Table", "description": "Link to a PairsQC quality metric table tsv file", "type": "string" }) def pairsqc_table(self, request, file_format, accession, quality_metric=None): if file_format.endswith('pairs/') and quality_metric: bucket = request.registry.settings.get('file_wfout_bucket') s3_url = 'https://s3.amazonaws.com/{bucket}/{accession}/{accession}.plot_table.out' return s3_url.format(bucket=bucket, accession=accession) else: return None # processed files don't want md5 as unique key def unique_keys(self, properties): keys = super(FileProcessed, self).unique_keys(properties) if keys.get('alias'): keys['alias'] = [k for k in keys['alias'] if not k.startswith('md5:')] return keys @calculated_property(schema={ "title": "Source", "description": "Gets all experiments (if experiment is found, find its experiment) associated w/ this file", "type": "array", "items": { "title": "Experiment Set", "type": "string", "linkTo": "ExperimentSet" } }) def source_experiment_sets(self, request): exp_sets = set(self.rev_link_atids(request, "experiment_sets") + self.rev_link_atids(request, "other_experiment_sets")) exps = set(self.rev_link_atids(request, "experiments") + self.rev_link_atids(request, "other_experiments")) if not exps == []: for exp in exps: expData = request.embed(exp, '@@object') if not expData['experiment_sets'] == []: exp_sets.update(expData['experiment_sets']) return list(exp_sets) @collection( name='files-reference', unique_key='accession', properties={ 'title': 'Reference Files', 'description': 'Listing of Reference Files', }) class FileReference(File): """Collection for individual reference files.""" item_type = 'file_reference' schema = load_schema('encoded:schemas/file_reference.json') embedded_list = File.embedded_list name_key = 'accession' @collection( name='files-vistrack', unique_key='accession', properties={ 'title': 'Visualization Track Files', 'description': 'Listing of External Files available as HiGlass visualization tracks', }) class FileVistrack(File): """Collection for individual visualization track files.""" item_type = 'file_vistrack' schema = load_schema('encoded:schemas/file_vistrack.json') embedded_list = File.embedded_list name_key = 'accession' @classmethod def get_bucket(cls, registry): return registry.settings['file_wfout_bucket'] @calculated_property(schema={ "title": "Track and Facet Info", "description": "Useful faceting and visualization info", "type": "object", "properties": { "experiment_type": { "type": "string" }, "assay_info": { "type": "string" }, "lab_name": { "type": "string" }, "biosource_name": { "type": "string" }, "replicate_info": { "type": "string" }, "experiment_bucket": { "type": "string" }, "track_title": { "type": "string" } } }) def track_and_facet_info(self, request, biosource_name=None, biosource=None): return super().track_and_facet_info(request, biosource_name=self.override_biosource_name(request, biosource)) @calculated_property(schema={ "title": "Biosource Name", "type": "string" }) def override_biosource_name(self, request, biosource=None): if biosource: return request.embed(biosource, '@@object').get('biosource_name') @calculated_property(schema={ "title": "Display Title", "description": "Name of this File", "type": "string" }) def display_title(self, request, file_format, accession=None, external_accession=None, dbxrefs=None): if dbxrefs: acclist = [d.replace('ENCODE:', '') for d in dbxrefs if 'ENCFF' in d] if acclist: accession = acclist[0] if not accession: accession = accession or external_accession file_format_item = get_item_or_none(request, file_format, 'file-formats') try: file_extension = '.' + file_format_item.get('standard_file_extension') except AttributeError: file_extension = '' return '{}{}'.format(accession, file_extension) @collection( name='files-calibration', unique_key='accession', properties={ 'title': 'Calibration Files', 'description': 'Listing of Calibration Files', }) class FileCalibration(ItemWithAttachment, File): """Collection for individual calibration files.""" item_type = 'file_calibration' schema = load_schema('encoded:schemas/file_calibration.json') embedded_list = File.embedded_list name_key = 'accession' def _build_file_microscopy_embedded_list(): """ Helper function intended to be used to create the embedded list for FileMicroscopy. All types should implement a function like this going forward. """ imaging_path_embeds = DependencyEmbedder.embed_for_type( base_path='experiments.imaging_paths.path', t='imaging_path', additional_embeds=['imaging_rounds', 'experiment_type.title']) imaging_path_target_embeds = DependencyEmbedder.embed_defaults_for_type( base_path='experiments.imaging_paths.path.target', t='bio_feature') return (File.embedded_list + imaging_path_embeds + imaging_path_target_embeds + [ # Experiment linkTo 'experiments.accession', 'experiments.@type', 'experiments.imaging_paths.channel', # Microscope linkTo 'experiments.files.microscope_settings.ch00_light_source_center_wl', 'experiments.files.microscope_settings.ch01_light_source_center_wl', 'experiments.files.microscope_settings.ch02_light_source_center_wl', 'experiments.files.microscope_settings.ch03_light_source_center_wl', 'experiments.files.microscope_settings.ch04_light_source_center_wl', 'experiments.files.microscope_settings.ch00_lasers_diodes', 'experiments.files.microscope_settings.ch01_lasers_diodes', 'experiments.files.microscope_settings.ch02_lasers_diodes', 'experiments.files.microscope_settings.ch03_lasers_diodes', 'experiments.files.microscope_settings.ch04_lasers_diodes', ] ) @collection( name='files-microscopy', unique_key='accession', properties={ 'title': 'Microscopy Files', 'description': 'Listing of Microscopy Files', }) class FileMicroscopy(ItemWithAttachment, File): """Collection for individual microscopy files.""" item_type = 'file_microscopy' schema = load_schema('encoded:schemas/file_microscopy.json') embedded_list = _build_file_microscopy_embedded_list() name_key = 'accession' @view_config(name='upload', context=File, request_method='GET', permission='edit') @debug_log def get_upload(context, request): external = context.propsheets.get('external', {}) upload_credentials = external.get('upload_credentials') # Show s3 location info for files originally submitted to EDW. if upload_credentials is None and external.get('service') == 's3': upload_credentials = { 'upload_url': 's3://{bucket}/{key}'.format(**external), } return { '@graph': [{ '@id': request.resource_path(context), 'upload_credentials': upload_credentials, 'extra_files_creds': context.extra_files_creds(), }], } @view_config(name='upload', context=File, request_method='POST', permission='edit', validators=[schema_validator({"type": "object"})]) @debug_log def post_upload(context, request): properties = context.upgrade_properties() if properties['status'] not in ('uploading', 'to be uploaded by workflow', 'upload failed'): raise HTTPForbidden('status must be "uploading" to issue new credentials') # accession_or_external = properties.get('accession') external = context.propsheets.get('external', None) if external is None: # Handle objects initially posted as another state. bucket = request.registry.settings['file_upload_bucket'] # maybe this should be properties.uuid uuid = context.uuid file_format = get_item_or_none(request, properties.get('file_format'), 'file-formats') try: file_extension = '.' + file_format.get('standard_file_extension') except AttributeError: file_extension = '' key = '{uuid}/{accession}.{file_extension}'.format( file_extension=file_extension, uuid=uuid, **properties) elif external.get('service') == 's3': bucket = external['bucket'] key = external['key'] else: raise ValueError(external.get('service')) # remove the path from the file name and only take first 32 chars name = None if properties.get('filename'): name = properties.get('filename').split('/')[-1][:32] profile_name = request.registry.settings.get('file_upload_profile_name') creds = external_creds(bucket, key, name, profile_name) # in case we haven't uploaded a file before context.propsheets['external'] = creds new_properties = properties.copy() if properties['status'] == 'upload failed': new_properties['status'] = 'uploading' registry = request.registry registry.notify(BeforeModified(context, request)) context.update(new_properties, {'external': creds}) registry.notify(AfterModified(context, request)) rendered = request.embed('/%s/@@object' % context.uuid, as_user=True) result = { 'status': 'success', '@type': ['result'], '@graph': [rendered], } return result def is_file_to_download(properties, file_format, expected_filename=None): try: file_extension = '.' + file_format.get('standard_file_extension') except AttributeError: file_extension = '' accession_or_external = properties.get('accession') or properties.get('external_accession') if not accession_or_external: return False filename = '{accession}{file_extension}'.format( accession=accession_or_external, file_extension=file_extension) if expected_filename is None: return filename elif expected_filename != filename: return False else: return filename def update_google_analytics(context, request, ga_config, filename, file_size_downloaded, file_at_id, lab, user_uuid, user_groups, file_experiment_type, file_type='other'): """ Helper for @@download that updates GA in response to a download. """ ga_cid = request.cookies.get("clientIdentifier") if not ga_cid: # Fallback, potentially can stop working as GA is updated ga_cid = request.cookies.get("_ga") if ga_cid: ga_cid = ".".join(ga_cid.split(".")[2:]) ga_tid = ga_config["hostnameTrackerIDMapping"].get(request.host, ga_config["hostnameTrackerIDMapping"].get("default")) if ga_tid is None: raise Exception("No valid tracker id found in ga_config.json > hostnameTrackerIDMapping") # We're sending 2 things here, an Event and a Transaction of a Product. (Reason 1 for redundancies) # Some fields/names are re-used for multiple things, such as filename for event label + item name dimension + product name + page title dimension (unusued) + ... ga_payload = { "v": 1, "tid": ga_tid, "t": "event", # Hit type. Could also be event, transaction, pageview, etc. # Override IP address. Else will send detail about EC2 server which not too useful. "uip": request.remote_addr, "ua": request.user_agent, "dl": request.url, "dt": filename, # This cid below is a ~ random ID/number (?). Used as fallback, since one is required # if don't provided uid. While we still allow users to not be logged in, # should at least be able to preserve/track their anon downloads.. # '555' is in examples and seemed to be referred to as example for anonymous sessions in some Google doc. # But not 100% sure and wasn't explicitly stated to be "555 for anonymous sessions" aside from usage in example. # Unsure if groups under 1 session or not. "cid": "555", "an": "4DN Data Portal EC2 Server", # App name, unsure if used yet "ec": "Serverside File Download", # Event Category "ea": "Range Query" if request.range else "File Download", # Event Action "el": filename, # Event Label "ev": file_size_downloaded, # Event Value # Product fields "pa": "purchase", "ti": str(uuid4()), # We need to send a unique transaction id along w. 'transactions' like purchases "pr1id": file_at_id, # Product ID/SKU "pr1nm": filename, # Product Name "pr1br": lab.get("display_title"), # Product Branch "pr1qt": 1, # Product Quantity # Product Category from @type, e.g. "File/FileProcessed" "pr1ca": "/".join([ty for ty in reversed(context.jsonld_type()[:-1])]), # Product "Variant" (supposed to be like black, gray, etc), we repurpose for filetype for reporting "pr1va": file_type # "other" MATCHES THAT IN `file_type_detaild` calc property, since file_type_detailed is used on frontend when performing "Select All" files. } # Custom dimensions # See https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters#pr_cm_ if "name" in ga_config["dimensionNameMap"]: ga_payload["dimension" + str(ga_config["dimensionNameMap"]["name"])] = filename ga_payload["pr1cd" + str(ga_config["dimensionNameMap"]["name"])] = filename if "experimentType" in ga_config["dimensionNameMap"]: ga_payload["dimension" + str(ga_config["dimensionNameMap"]["experimentType"])] = file_experiment_type or None ga_payload["pr1cd" + str(ga_config["dimensionNameMap"]["experimentType"])] = file_experiment_type or None if "filesize" in ga_config["metricNameMap"]: ga_payload["metric" + str(ga_config["metricNameMap"]["filesize"])] = file_size_downloaded ga_payload["pr1cm" + str(ga_config["metricNameMap"]["filesize"])] = file_size_downloaded if "downloads" in ga_config["metricNameMap"]: ga_payload["metric" + str(ga_config["metricNameMap"]["downloads"])] = 0 if request.range else 1 ga_payload["pr1cm" + str(ga_config["metricNameMap"]["downloads"])] = 0 if request.range else 1 # client id (`cid`) or user id (`uid`) is required. uid shall be user uuid. # client id might be gotten from Google Analytics cookie, but not stable to use and wont work on programmatic requests... if user_uuid: ga_payload['uid'] = user_uuid if user_groups: groups_json = json.dumps(user_groups, separators=(',', ':')) # Compcact JSON; aligns w. what's passed from JS. ga_payload["dimension" + str(ga_config["dimensionNameMap"]["userGroups"])] = groups_json ga_payload["pr1cd" + str(ga_config["dimensionNameMap"]["userGroups"])] = groups_json if ga_cid: ga_payload['cid'] = ga_cid # Catch error here try: resp = requests.post( "https://ssl.google-analytics.com/collect?z=" + str(datetime.datetime.utcnow().timestamp()), data=urllib.parse.urlencode(ga_payload), timeout=5.0, headers={'user-agent': ga_payload['ua']} ) except Exception as e: log.error('Exception encountered posting to GA: %s' % e) @view_config(name='download', context=File, request_method='GET', permission='view', subpath_segments=[0, 1]) @debug_log def download(context, request): """ Endpoint for handling /@@download/ URLs """ check_user_is_logged_in(request) # first check for restricted status if context.properties.get('status') == 'restricted': raise HTTPForbidden('This is a restricted file not available for download') try: user_props = session_properties(request) except Exception as e: user_props = {"error": str(e)} user_uuid = user_props.get('details', {}).get('uuid', None) user_groups = user_props.get('details', {}).get('groups', None) if user_groups: user_groups.sort() # TODO: # if not user_uuid or file_size_downloaded < 25 * (1024**2): # Downloads, mostly for range queries (HiGlass, etc), are allowed if less than 25mb # raise HTTPForbidden("Must login or provide access keys to download files larger than 5mb") # proxy triggers if we should use Axel-redirect, useful for s3 range byte queries try: use_download_proxy = request.client_addr not in request.registry['aws_ipset'] except TypeError: # this fails in testing due to testapp not having ip use_download_proxy = False # with extra_files the user may be trying to download the main file # or one of the files in extra files, the following logic will # search to find the "right" file and redirect to a download link for that one properties = context.upgrade_properties() file_format = get_item_or_none(request, properties.get('file_format'), 'file-formats') lab = properties.get('lab') and get_item_or_none(request, properties.get('lab'), 'labs') _filename = None if request.subpath: _filename, = request.subpath filename = is_file_to_download(properties, file_format, _filename) if not filename: found = False for extra in properties.get('extra_files', []): eformat = get_item_or_none(request, extra.get('file_format'), 'file-formats') filename = is_file_to_download(extra, eformat, _filename) if filename: found = True properties = extra external = context.propsheets.get('external' + eformat.get('uuid')) break if not found: raise HTTPNotFound(_filename) else: external = context.propsheets.get('external', {}) # Calculate bytes downloaded from Range header headers = None file_size_downloaded = properties.get('file_size', 0) if request.range: file_size_downloaded = 0 headers = {'Range': request.headers.get('Range')} # Assume range unit is bytes. Because there's no spec for others really, atm, afaik.. if hasattr(request.range, "ranges"): for (range_start, range_end) in request.range.ranges: file_size_downloaded += ( (range_end or properties.get('file_size', 0)) - (range_start or 0) ) else: file_size_downloaded = ( (request.range.end or properties.get('file_size', 0)) - (request.range.start or 0) ) request_datastore_is_database = (request.datastore == 'database') if not external: external = context.build_external_creds(request.registry, context.uuid, properties) if external.get('service') == 's3': location = context.get_open_data_url_or_presigned_url_location(external, request, filename, request_datastore_is_database) else: raise ValueError(external.get('service')) # Analytics Stuff ga_config = request.registry.settings.get('ga_config') file_experiment_type = get_file_experiment_type(request, context, properties) file_at_id = context.jsonld_id(request) if ga_config: update_google_analytics(context, request, ga_config, filename, file_size_downloaded, file_at_id, lab, user_uuid, user_groups, file_experiment_type, properties.get('file_type')) # TODO does not handle range queries if asbool(request.params.get('soft')): expires = int(parse_qs(urlparse(location).query)['Expires'][0]) return { '@type': ['SoftRedirect'], 'location': location, 'expires': datetime.datetime.fromtimestamp(expires, pytz.utc).isoformat(), } # We don't use X-Accel-Redirect here so that client behaviour is similar for # both aws and non-aws users. if use_download_proxy: location = request.registry.settings.get('download_proxy', '') + str(location) # 307 redirect specifies to keep original method if headers is not None: # forward Range header to open data, redundant for our buckets raise HTTPTemporaryRedirect(location=location, headers=headers) else: raise HTTPTemporaryRedirect(location=location) def get_file_experiment_type(request, context, properties): """ Get the string experiment_type value given a File context and properties. Checks the source_experiments, rev_linked experiments and experiment_sets """ # identify which experiments to use experiments_using_file = [] if properties.get('source_experiments'): experiments_using_file = properties['source_experiments'] else: rev_exps = context.experiments(request) if rev_exps: experiments_using_file = rev_exps elif hasattr(context, 'experiment_sets'): # FileProcessed only rev_exp_sets = context.experiment_sets(request) if rev_exp_sets: for exp_set in rev_exp_sets: exp_set_info = get_item_or_none(request, exp_set) if exp_set_info: experiments_using_file.extend(exp_set_info.get('experiments_in_set', [])) found_experiment_type = 'None' for file_experiment in experiments_using_file: exp_info = get_item_or_none(request, file_experiment) if exp_info is None: continue exp_type = exp_info.get('experiment_type') if found_experiment_type == 'None' or found_experiment_type == exp_type: found_experiment_type = exp_type else: # multiple experiment types return 'Integrative analysis' if found_experiment_type != 'None': found_item = get_item_or_none(request, found_experiment_type) if found_item is None: found_experiment_type = 'None' else: found_experiment_type = found_item.get('title') return found_experiment_type def validate_file_format_validity_for_file_type(context, request): """Check if the specified file format (e.g. fastq) is allowed for the file type (e.g. FileFastq). """ data = request.json if 'file_format' in data: file_format_item = get_item_or_none(request, data['file_format'], 'file-formats') if not file_format_item: # item level validation will take care of generating the error return file_format_name = file_format_item['file_format'] allowed_types = file_format_item.get('valid_item_types', []) file_type = context.type_info.name if file_type not in allowed_types: msg = 'File format {} is not allowed for {}'.format(file_format_name, file_type) request.errors.add('body', 'File: invalid format', msg) else: request.validated.update({}) def validate_file_filename(context, request): ''' validator for filename field ''' found_match = False data = request.json if 'filename' not in data: # see if there is an existing file_name filename = context.properties.get('filename') if not filename: return else: filename = data['filename'] ff = data.get('file_format') if not ff: ff = context.properties.get('file_format') file_format_item = get_item_or_none(request, ff, 'file-formats') if not file_format_item: msg = 'Problem getting file_format for %s' % filename request.errors.add('body', 'File: no format', msg) return msg = None try: file_extensions = [file_format_item.get('standard_file_extension')] if file_format_item.get('other_allowed_extensions'): file_extensions.extend(file_format_item.get('other_allowed_extensions')) file_extensions = list(set(file_extensions)) except (AttributeError, TypeError): msg = 'Problem getting file_format for %s' % filename else: if file_format_item.get('file_format') == 'other': found_match = True elif not file_extensions: # this shouldn't happen pass for extension in file_extensions: if filename[-(len(extension) + 1):] == '.' + extension: found_match = True break if found_match: request.validated.update({}) else: if not msg: msg = ["'." + ext + "'" for ext in file_extensions] msg = ', '.join(msg) msg = ('Filename %s extension does not agree with specified file format. ' 'Valid extension(s): %s' % (filename, msg)) request.errors.add('body', 'File: invalid extension', msg) def validate_processed_file_unique_md5_with_bypass(context, request): '''validator to check md5 on processed files, unless you tell it not to''' # skip validator if not file processed if context.type_info.item_type != 'file_processed': return data = request.json if 'md5sum' not in data or not data['md5sum']: return if 'force_md5' in request.query_string: return # we can of course patch / put to ourselves the same md5 we previously had if context.properties.get('md5sum') == data['md5sum']: return if ELASTIC_SEARCH in request.registry: search = make_search_subreq(request, '/search/?type=File&md5sum=%s' % data['md5sum']) search_resp = request.invoke_subrequest(search, True) if search_resp.status_int < 400: # already got this md5 found = search_resp.json['@graph'][0]['accession'] request.errors.add('body', 'File: non-unique md5sum', 'md5sum %s already exists for accession %s' % (data['md5sum'], found)) else: # find it in the database conn = request.registry['connection'] res = conn.get_by_json('md5sum', data['md5sum'], 'file_processed') if res is not None: # md5 already exists found = res.properties['accession'] request.errors.add('body', 'File: non-unique md5sum', 'md5sum %s already exists for accession %s' % (data['md5sum'], found)) def validate_processed_file_produced_from_field(context, request): '''validator to make sure that the values in the produced_from field are valid file identifiers''' # skip validator if not file processed if context.type_info.item_type != 'file_processed': return data = request.json if 'produced_from' not in data: return files_ok = True files2chk = data['produced_from'] for i, f in enumerate(files2chk): try: fid = get_item_or_none(request, f, 'files').get('uuid') except AttributeError: files_ok = False request.errors.add('body', 'File: invalid produced_from id', "'%s' not found" % f) # bad_files.append(f) else: if not fid: files_ok = False request.errors.add('body', 'File: invalid produced_from id', "'%s' not found" % f) if files_ok: request.validated.update({}) def validate_extra_file_format(context, request): '''validator to check to be sure that file_format of extrafile is not the same as the file and is a known format for the schema ''' files_ok = True data = request.json if not data.get('extra_files'): return extras = data['extra_files'] # post should always have file_format as it is required patch may or may not ff = data.get('file_format') if not ff: ff = context.properties.get('file_format') file_format_item = get_item_or_none(request, ff, 'file-formats') if not file_format_item or 'standard_file_extension' not in file_format_item: request.errors.add('body', 'File: no extra_file format', "Can't find parent file format for extra_files") return parent_format = file_format_item['uuid'] schema_eformats = file_format_item.get('extrafile_formats') if not schema_eformats: # means this parent file shouldn't have any extra files request.errors.add( 'body', 'File: invalid extra files', "File with format %s should not have extra_files" % file_format_item.get('file_format') ) return else: valid_ext_formats = [] for ok_format in schema_eformats: ok_format_item = get_item_or_none(request, ok_format, 'file-formats') try: off_uuid = ok_format_item.get('uuid') except AttributeError: raise Exception("FileFormat Item %s contains unknown FileFormats" " in the extrafile_formats property" % file_format_item.get('uuid')) valid_ext_formats.append(off_uuid) seen_ext_formats = [] # formats = request.registry['collections']['FileFormat'] for i, ef in enumerate(extras): eformat = ef.get('file_format') if eformat is None: return # will fail the required extra_file.file_format eformat_item = get_item_or_none(request, eformat, 'file-formats') try: ef_uuid = eformat_item.get('uuid') except AttributeError: request.errors.add( 'body', 'File: invalid extra_file format', "'%s' not a valid or known file format" % eformat ) files_ok = False break if ef_uuid in seen_ext_formats: request.errors.add( 'body', 'File: invalid extra_file formats', "Multple extra files with '%s' format cannot be submitted at the same time" % eformat ) files_ok = False break else: seen_ext_formats.append(ef_uuid) if ef_uuid == parent_format: request.errors.add( 'body', 'File: invalid extra_file formats', "'%s' format cannot be the same for file and extra_file" % file_format_item.get('file_format') ) files_ok = False break if ef_uuid not in valid_ext_formats: request.errors.add( 'body', 'File: invalid extra_file formats', "'%s' not a valid extrafile_format for '%s'" % (eformat, file_format_item.get('file_format')) ) files_ok = False if files_ok: request.validated.update({}) @view_config(context=File.Collection, permission='add', request_method='POST', validators=[validate_item_content_post, validate_file_filename, validate_extra_file_format, validate_file_format_validity_for_file_type, validate_processed_file_unique_md5_with_bypass, validate_processed_file_produced_from_field]) @view_config(context=File.Collection, permission='add_unvalidated', request_method='POST', validators=[no_validate_item_content_post], request_param=['validate=false']) @debug_log def file_add(context, request, render=None): return collection_add(context, request, render) @view_config(context=File, permission='edit', request_method='PUT', validators=[validate_item_content_put, validate_file_filename, validate_extra_file_format, validate_file_format_validity_for_file_type, validate_processed_file_unique_md5_with_bypass, validate_processed_file_produced_from_field]) @view_config(context=File, permission='edit', request_method='PATCH', validators=[validate_item_content_patch, validate_file_filename, validate_extra_file_format, validate_file_format_validity_for_file_type, validate_processed_file_unique_md5_with_bypass, validate_processed_file_produced_from_field]) @view_config(context=File, permission='edit_unvalidated', request_method='PUT', validators=[no_validate_item_content_put], request_param=['validate=false']) @view_config(context=File, permission='edit_unvalidated', request_method='PATCH', validators=[no_validate_item_content_patch], request_param=['validate=false']) @view_config(context=File, permission='index', request_method='GET', validators=[validate_item_content_in_place, validate_file_filename, validate_extra_file_format, validate_file_format_validity_for_file_type, validate_processed_file_unique_md5_with_bypass, validate_processed_file_produced_from_field], request_param=['check_only=true']) @debug_log def file_edit(context, request, render=None): return item_edit(context, request, render)
hms-dbmi/fourfront
src/encoded/types/file.py
Python
mit
77,254
from django.contrib.admin.views.main import ChangeList from django.forms import ModelForm, TextInput from django.contrib import admin class NumberInput(TextInput): """ HTML5 Number input Left for backwards compatibility """ input_type = 'number' class SortableModelAdminBase(object): """ Base class for SortableTabularInline and SortableModelAdmin """ sortable = 'order' class Media: js = ('widget/js/sortables.js',) class SortableListForm(ModelForm): """ Just Meta holder class """ class Meta: widgets = { 'order': NumberInput( attrs={'class': 'hide input-mini suit-sortable'}) } class SortableChangeList(ChangeList): """ Class that forces ordering by sortable param only """ def get_ordering(self, request, queryset): return [self.model_admin.sortable, '-' + self.model._meta.pk.name] class SortableTabularInline(SortableModelAdminBase, admin.TabularInline): """ Sortable tabular inline """ def __init__(self, *args, **kwargs): super(SortableTabularInline, self).__init__(*args, **kwargs) self.ordering = (self.sortable,) self.fields = self.fields or [] if self.fields and self.sortable not in self.fields: self.fields = list(self.fields) + [self.sortable] def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == self.sortable: kwargs['widget'] = SortableListForm.Meta.widgets['order'] return super(SortableTabularInline, self).formfield_for_dbfield( db_field, **kwargs)
buremba/django-admin-tools
admin_tools/forms.py
Python
mit
1,640