hexsha
stringlengths
40
40
size
int64
7
1.04M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
247
max_stars_repo_name
stringlengths
4
125
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
247
max_issues_repo_name
stringlengths
4
125
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
247
max_forks_repo_name
stringlengths
4
125
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
1
1.04M
avg_line_length
float64
1.77
618k
max_line_length
int64
1
1.02M
alphanum_fraction
float64
0
1
original_content
stringlengths
7
1.04M
filtered:remove_function_no_docstring
int64
-102
942k
filtered:remove_class_no_docstring
int64
-354
977k
filtered:remove_delete_markers
int64
0
60.1k
e8a7f3571cb178642df008d0c5562b9905d3d883
3,610
py
Python
core/model/metric/proto_net.py
RuiBai1999/myrepo
1cf51db063b922ef58ff11da998c3f12f643420d
[ "MIT" ]
471
2021-09-13T11:28:34.000Z
2022-03-30T07:26:54.000Z
core/model/metric/proto_net.py
liuwenqi528/LibFewShot
ea8d618995a51079c79a6291af2ca02b01b846ea
[ "MIT" ]
24
2021-09-22T02:34:05.000Z
2022-02-19T07:26:39.000Z
core/model/metric/proto_net.py
liuwenqi528/LibFewShot
ea8d618995a51079c79a6291af2ca02b01b846ea
[ "MIT" ]
82
2021-09-16T12:48:01.000Z
2022-03-28T06:57:47.000Z
# -*- coding: utf-8 -*- """ @inproceedings{DBLP:conf/nips/SnellSZ17, author = {Jake Snell and Kevin Swersky and Richard S. Zemel}, title = {Prototypical Networks for Few-shot Learning}, booktitle = {Advances in Neural Information Processing Systems 30: Annual Conference on Neural Information Processing Systems 2017, December 4-9, 2017, Long Beach, CA, {USA}}, pages = {4077--4087}, year = {2017}, url = {https://proceedings.neurips.cc/paper/2017/hash/cb8da6767461f2812ae4290eac7cbc42-Abstract.html} } https://arxiv.org/abs/1703.05175 Adapted from https://github.com/orobix/Prototypical-Networks-for-Few-shot-Learning-PyTorch. """ import torch import torch.nn.functional as F from torch import nn from core.utils import accuracy from .metric_model import MetricModel
33.425926
109
0.599446
# -*- coding: utf-8 -*- """ @inproceedings{DBLP:conf/nips/SnellSZ17, author = {Jake Snell and Kevin Swersky and Richard S. Zemel}, title = {Prototypical Networks for Few-shot Learning}, booktitle = {Advances in Neural Information Processing Systems 30: Annual Conference on Neural Information Processing Systems 2017, December 4-9, 2017, Long Beach, CA, {USA}}, pages = {4077--4087}, year = {2017}, url = {https://proceedings.neurips.cc/paper/2017/hash/cb8da6767461f2812ae4290eac7cbc42-Abstract.html} } https://arxiv.org/abs/1703.05175 Adapted from https://github.com/orobix/Prototypical-Networks-for-Few-shot-Learning-PyTorch. """ import torch import torch.nn.functional as F from torch import nn from core.utils import accuracy from .metric_model import MetricModel class ProtoLayer(nn.Module): def __init__(self): super(ProtoLayer, self).__init__() def forward( self, query_feat, support_feat, way_num, shot_num, query_num, mode="euclidean", ): t, wq, c = query_feat.size() _, ws, _ = support_feat.size() # t, wq, c query_feat = query_feat.reshape(t, way_num * query_num, c) # t, w, c support_feat = support_feat.reshape(t, way_num, shot_num, c) proto_feat = torch.mean(support_feat, dim=2) return { # t, wq, 1, c - t, 1, w, c -> t, wq, w "euclidean": lambda x, y: -torch.sum( torch.pow(x.unsqueeze(2) - y.unsqueeze(1), 2), dim=3, ), # t, wq, c - t, c, w -> t, wq, w "cos_sim": lambda x, y: torch.matmul( F.normalize(x, p=2, dim=-1), torch.transpose(F.normalize(y, p=2, dim=-1), -1, -2) # FEAT did not normalize the query_feat ), }[mode](query_feat, proto_feat) class ProtoNet(MetricModel): def __init__(self, **kwargs): super(ProtoNet, self).__init__(**kwargs) self.proto_layer = ProtoLayer() self.loss_func = nn.CrossEntropyLoss() def set_forward(self, batch): """ :param batch: :return: """ image, global_target = batch image = image.to(self.device) episode_size = image.size(0) // (self.way_num * (self.shot_num + self.query_num)) feat = self.emb_func(image) support_feat, query_feat, support_target, query_target = self.split_by_episode(feat, mode=1) output = self.proto_layer( query_feat, support_feat, self.way_num, self.shot_num, self.query_num ).reshape(episode_size * self.way_num * self.query_num, self.way_num) acc = accuracy(output, query_target.reshape(-1)) return output, acc def set_forward_loss(self, batch): """ :param batch: :return: """ images, global_targets = batch images = images.to(self.device) episode_size = images.size(0) // (self.way_num * (self.shot_num + self.query_num)) emb = self.emb_func(images) support_feat, query_feat, support_target, query_target = self.split_by_episode(emb, mode=1) output = self.proto_layer( query_feat, support_feat, self.way_num, self.shot_num, self.query_num ).reshape(episode_size * self.way_num * self.query_num, self.way_num) loss = self.loss_func(output, query_target.reshape(-1)) acc = accuracy(output, query_target.reshape(-1)) return output, acc, loss
1,162
1,483
99
649554aaf9aaae9d433f8f0efefff7fec94c9eed
1,611
py
Python
apps/verizon/events.py
Poseidon-Dev/wadsworth
d02a5c2ab34cabebc571903c907ee5440aac5b2a
[ "MIT" ]
null
null
null
apps/verizon/events.py
Poseidon-Dev/wadsworth
d02a5c2ab34cabebc571903c907ee5440aac5b2a
[ "MIT" ]
40
2021-03-18T21:28:23.000Z
2021-07-02T05:01:37.000Z
apps/verizon/events.py
Poseidon-Dev/wadsworth
d02a5c2ab34cabebc571903c907ee5440aac5b2a
[ "MIT" ]
null
null
null
import discord, os, platform, asyncio, csv from discord import channel from discord.ext import commands import re import core.config from apps.verizon.utils import verizon_csv, OUT_REPORTS
38.357143
94
0.554314
import discord, os, platform, asyncio, csv from discord import channel from discord.ext import commands import re import core.config from apps.verizon.utils import verizon_csv, OUT_REPORTS class VerizonEvents(commands.Cog, name='verizon_events'): def __init__(self, bot): self.bot = bot if core.config.TESTING: self.channel = self.bot.get_channel(core.config.BOT_CHANNEL) else: self.channel = self.bot.get_channel(core.config.VERIZON_CHANNEL) self.ping_channel = self.channel # Events @commands.Cog.listener() async def on_message(self, message): if str(message.attachments) == "[]": return else: filename = str(message.attachments).split(' ')[2].split("'")[1] filepath = 'media/verizon/' if filename.lower().startswith('verizon') and filename.endswith('.csv'): await message.attachments[0].save(fp=f"{filepath}{filename}") await self.channel.send('Got the csv') try: files = verizon_csv() if files == 'COMPLETE': for div in OUT_REPORTS: await self.channel.send(file=discord.File(f'{filepath}{div}.csv')) else: await self.channel.send(files[1]) for div in files[0]: await self.channel.send(div) except: await self.channel('There was an error in the process') else: return
1,267
132
22
2c0168386a31aecebe6e4bac70dbabb40b6a6459
12,337
py
Python
amfast/class_def/__init__.py
limscoder/amfast
e77162615090b6a1ad03565afcc4bec4b46f6a11
[ "MIT" ]
4
2015-12-12T04:34:34.000Z
2021-07-30T22:11:26.000Z
amfast/class_def/__init__.py
limscoder/amfast
e77162615090b6a1ad03565afcc4bec4b46f6a11
[ "MIT" ]
3
2015-03-23T23:45:30.000Z
2016-08-17T01:32:51.000Z
amfast/class_def/__init__.py
limscoder/amfast
e77162615090b6a1ad03565afcc4bec4b46f6a11
[ "MIT" ]
8
2015-03-23T23:45:34.000Z
2018-01-25T16:16:43.000Z
"""Provides an interface for determining how Python objects are serialized and de-serialized.""" import threading from amfast import AmFastError class ClassDefError(AmFastError): """ClassDef related errors.""" pass class ClassDef(object): """Defines how objects of a given class are serialized and de-serialized. This class can be sub-classed to provide custom serialization. attributes =========== * class_ - class, the class object mapped to this definition * alias - string, the AMF alias name of the mapped class * static_attrs - tuple or list, a tuple of static attribute names, all values must be strings or unicode. * amf3 - bool, if True, this object will be encoded in AMF3. * encode_types - dict, keys = attribute names, values = callables. Callables must accept a single parameter (the object being encoded) and return a new object. * decode_types - dict, keys = attribute names, values = callables. Callables must accept a single parameter (the object being decoded) and return a new object. """ CLASS_DEF = True def __init__(self, class_, alias=None, static_attrs=None, amf3=None, encode_types=None, decode_types=None, _built_in=False): """arguments ============= * class_ - class, the class being mapped. * alias - string, specifies the amf class alias. Default = module.class * static_attrs - tuple or list, a tuple of static attribute strings. Default = empty tuple * amf3 - bool, if True, this object will be encoded in AMF3. Default = True * encode_types - dict, keys = attribute names, values = callables. Default = None * decode_types - dict, keys = attribute names, values = callables. Default = None """ self.class_ = class_ self._built_in = _built_in if alias is None: if hasattr(class_, ALIAS): alias = getattr(class_, ALIAS) else: alias = '.'.join((class_.__module__, class_.__name__)) self.alias = alias if static_attrs is None: if hasattr(class_, STATIC_ATTRS): static_attrs = self.static_attrs = getattr(class_, STATIC_ATTRS) else: static_attrs = () self.static_attrs = static_attrs if amf3 is None: if hasattr(class_, AMF3): amf3 = getattr(class_, AMF3) else: amf3 = True self.amf3 = amf3 self.encode_types = encode_types self.decode_types = decode_types def getStaticAttrVals(self, obj): """Returns a list of values of attributes defined in self.static_attrs If this method is overridden to provide custom behavior, please note: Returned values MUST BE IN THE SAME ORDER AS THEY APPEAR IN self.static_attrs. arguments ========== * obj - object, the object to get attribute values from. """ return [getattr(obj, attr, None) for attr in self.static_attrs] def getInstance(self): """Returns an instance of the mapped class to be used when an object of this type is deserialized. """ return self.class_.__new__(self.class_) def applyAttrVals(self, obj, vals): """Set decoded attribute values on the object. arguments ========== * obj - object, the object to set the attribute values on. * vals - dict, keys == attribute name, values == attribute values. """ [setattr(obj, key, val) for key, val in vals.iteritems()] class DynamicClassDef(ClassDef): """A ClassDef with dynamic attributes.""" DYNAMIC_CLASS_DEF = True def getDynamicAttrVals(self, obj, include_private=False): """Returns a dict where keys are attribute names and values are attribute values. arguments ========== obj - object, the object to get attributes for. include_private - bool, if False do not include attributes with names starting with '_'. Default = False. """ if self.include_private is None: ip = include_private else: ip = self.include_private return get_dynamic_attr_vals(obj, self.static_attrs, ip); class ExternClassDef(ClassDef): """A ClassDef where the byte string encoding/decoding is customized. The Actionscript version of the class must implement IExternalizeable. """ EXTERNALIZABLE_CLASS_DEF = True def writeExternal(self, obj, context): """ This method must be overridden in a sub-class. arguments ========== * obj - object, The object that is being encoded. * context - amfast.decoder.EncoderContext, holds encoding related properties. """ raise ClassDefError("This method must be implemented by a sub-class.") def readExternal(self, obj, context): """ This method must be overridden in a sub-class. arguments ========== * obj - object, The object that the byte string is being applied to. * context - amfast.decoder.DecoderContext, holds decoding related properties. """ raise ClassDefError("This method must be implemented by a sub-class.") class _ProxyClassDef(ExternClassDef): """A special class used internally to encode/decode Proxied objects.""" PROXY_CLASS_DEF = True PROXY_ALIAS = 'proxy' class _ProxyObject(object): """Empty class used for mapping.""" pass class _ArrayCollectionClassDef(_ProxyClassDef): """A special ClassDef used internally to encode/decode an ArrayCollection.""" ARRAY_COLLECTION_CLASS_DEF = True PROXY_ALIAS = 'flex.messaging.io.ArrayCollection' class _ObjectProxyClassDef(_ProxyClassDef): """A special ClassDef used internally to encode/decode an ObjectProxy.""" OBJECT_PROXY_CLASS_DEF = True PROXY_ALIAS = 'flex.messaging.io.ObjectProxy' class ClassDefMapper(object): """Map classes to ClassDefs, retrieve class_defs by class or alias name.""" def __init__(self): """ arguments ========== * class_def_attr - string, an attribute with this name will be added mapped classes. Default = '_amf_alias' """ self._lock = threading.RLock() self._mapped_classes = {} self._mapped_aliases = {} self._mapBuiltIns() def _mapBuiltIns(self): """Map built-in ClassDefs for default behavior.""" from as_types import AsError from amfast.remoting import flex_messages as messaging # Proxy objects self.mapClass(_ArrayCollectionClassDef()) self.mapClass(_ObjectProxyClassDef()) # Exceptions self.mapClass(ClassDef(AsError, _built_in=True)) self.mapClass(ClassDef(messaging.FaultError, _built_in=True)) # Flex remoting messages self.mapClass(ClassDef(messaging.RemotingMessage, _built_in=True)) self.mapClass(messaging.AsyncSmallMsgDef(messaging.AsyncMessage, alias="DSA", _built_in=True)) self.mapClass(ClassDef(messaging.AsyncMessage, _built_in=True)) self.mapClass(messaging.CommandSmallMsgDef(messaging.CommandMessage, alias="DSC", _built_in=True)) self.mapClass(ClassDef(messaging.CommandMessage, _built_in=True)) self.mapClass(ClassDef(messaging.AcknowledgeMessage, _built_in=True)) self.mapClass(ClassDef(messaging.ErrorMessage, _built_in=True)) def mapClass(self, class_def): """Map a class_def implementation, so that it can be retrieved based on class attributes. arguments ========== * class_def - ClassDef, ClassDef being mapped. """ if not hasattr(class_def, 'CLASS_DEF'): raise ClassDefError("class_def argument must be a ClassDef object.") self._lock.acquire() try: self._mapped_classes[class_def.class_] = class_def self._mapped_aliases[class_def.alias] = class_def finally: self._lock.release() def getClassDefByClass(self, class_): """Get a ClassDef. Returns None if ClassDef is not found. arguments ========== * class_ - class, the class to find a ClassDef for. """ return self._mapped_classes.get(class_, None) def getClassDefByAlias(self, alias): """Get a ClassDef. Returns None in not ClassDef is found. arguments ========== * alias - string, the alias to find a ClassDef for. """ return self._mapped_aliases.get(alias, None) def unmapClass(self, class_): """Unmap a class definition. arguments ========== * class_ - class, the class to remove a ClassDef for. """ self._lock.acquire() try: for alias, klass in self._mapped_aliases.iteritems(): if class_ == klass: del self._mapped_aliases[alias] class_id = id(class_) if class_id in self._mapped_classes: del self._mapped_classes[class_id] finally: self._lock.release() # ---- module attributes ---- # def get_dynamic_attr_vals(obj, ignore_attrs=None, include_private=False): """Returns a dict of attribute values to encode. keys = attribute names, values = attribute values. argmuents ========== * obj - object, object to get dynamic attribute values from. * ignore_attrs - list or tuple of attributes to ignore. Default = empty tuple. * include_private - bool, if False do not include attributes that start with '_'. Default = False. """ vals = {} if hasattr(obj, '__dict__'): for attr, val in obj.__dict__.iteritems(): if ignore_attrs is not None: if attr in ignore_attrs: continue if (include_private is False) and (attr.startswith('_')): continue vals[attr] = val return vals # These properties can be set on a class # to map attributes within the class. ALIAS = '_AMFAST_ALIAS' STATIC_ATTRS = '_AMFAST_STATIC_ATTRS' AMF3 = '_AMFAST_AMF3' def assign_attrs(class_, alias=None, static_attrs=None, amf3=None): """ Use to map ClassDef attributes to a class. Useful if you want to keep ClassDef configuration with the class being mapped, instead of at the point where the ClassDef is created. If you assign ClassDef attributes with this method, you can call ClassDef(class_) to create a ClassDef, and the assigned attributes will be applied to the new ClassDef. Arguments provided to the ClassDef() will override attributes that were assigned with this function. arguments ========== * class_ - class, the class to assign attributes to. * alias - string, the amf alias name of the mapped class * static_attrs - tuple, a tuple of static attribute names, all values must be strings or unicode * amf3 - bool, if True, this object will be encoded in AMF3. """ if alias is not None: setattr(class_, ALIAS, alias) if static_attrs is not None: setattr(class_, STATIC_ATTRS, static_attrs) if amf3 is not None: setattr(class_, AMF3, amf3)
34.752113
101
0.638162
"""Provides an interface for determining how Python objects are serialized and de-serialized.""" import threading from amfast import AmFastError class ClassDefError(AmFastError): """ClassDef related errors.""" pass class ClassDef(object): """Defines how objects of a given class are serialized and de-serialized. This class can be sub-classed to provide custom serialization. attributes =========== * class_ - class, the class object mapped to this definition * alias - string, the AMF alias name of the mapped class * static_attrs - tuple or list, a tuple of static attribute names, all values must be strings or unicode. * amf3 - bool, if True, this object will be encoded in AMF3. * encode_types - dict, keys = attribute names, values = callables. Callables must accept a single parameter (the object being encoded) and return a new object. * decode_types - dict, keys = attribute names, values = callables. Callables must accept a single parameter (the object being decoded) and return a new object. """ CLASS_DEF = True def __init__(self, class_, alias=None, static_attrs=None, amf3=None, encode_types=None, decode_types=None, _built_in=False): """arguments ============= * class_ - class, the class being mapped. * alias - string, specifies the amf class alias. Default = module.class * static_attrs - tuple or list, a tuple of static attribute strings. Default = empty tuple * amf3 - bool, if True, this object will be encoded in AMF3. Default = True * encode_types - dict, keys = attribute names, values = callables. Default = None * decode_types - dict, keys = attribute names, values = callables. Default = None """ self.class_ = class_ self._built_in = _built_in if alias is None: if hasattr(class_, ALIAS): alias = getattr(class_, ALIAS) else: alias = '.'.join((class_.__module__, class_.__name__)) self.alias = alias if static_attrs is None: if hasattr(class_, STATIC_ATTRS): static_attrs = self.static_attrs = getattr(class_, STATIC_ATTRS) else: static_attrs = () self.static_attrs = static_attrs if amf3 is None: if hasattr(class_, AMF3): amf3 = getattr(class_, AMF3) else: amf3 = True self.amf3 = amf3 self.encode_types = encode_types self.decode_types = decode_types def getStaticAttrVals(self, obj): """Returns a list of values of attributes defined in self.static_attrs If this method is overridden to provide custom behavior, please note: Returned values MUST BE IN THE SAME ORDER AS THEY APPEAR IN self.static_attrs. arguments ========== * obj - object, the object to get attribute values from. """ return [getattr(obj, attr, None) for attr in self.static_attrs] def getInstance(self): """Returns an instance of the mapped class to be used when an object of this type is deserialized. """ return self.class_.__new__(self.class_) def applyAttrVals(self, obj, vals): """Set decoded attribute values on the object. arguments ========== * obj - object, the object to set the attribute values on. * vals - dict, keys == attribute name, values == attribute values. """ [setattr(obj, key, val) for key, val in vals.iteritems()] class DynamicClassDef(ClassDef): """A ClassDef with dynamic attributes.""" DYNAMIC_CLASS_DEF = True def __init__(self, class_, alias=None, static_attrs=None, amf3=True, encode_types=None, decode_types=None, include_private=None, _built_in=False): ClassDef.__init__(self, class_, alias, static_attrs, amf3, encode_types, decode_types, _built_in) self.include_private = include_private def getDynamicAttrVals(self, obj, include_private=False): """Returns a dict where keys are attribute names and values are attribute values. arguments ========== obj - object, the object to get attributes for. include_private - bool, if False do not include attributes with names starting with '_'. Default = False. """ if self.include_private is None: ip = include_private else: ip = self.include_private return get_dynamic_attr_vals(obj, self.static_attrs, ip); class ExternClassDef(ClassDef): """A ClassDef where the byte string encoding/decoding is customized. The Actionscript version of the class must implement IExternalizeable. """ EXTERNALIZABLE_CLASS_DEF = True def __init__(self, class_, alias=None, static_attrs=None, _built_in=False): ClassDef.__init__(self, class_, alias, static_attrs, amf3=True, _built_in=_built_in) def writeExternal(self, obj, context): """ This method must be overridden in a sub-class. arguments ========== * obj - object, The object that is being encoded. * context - amfast.decoder.EncoderContext, holds encoding related properties. """ raise ClassDefError("This method must be implemented by a sub-class.") def readExternal(self, obj, context): """ This method must be overridden in a sub-class. arguments ========== * obj - object, The object that the byte string is being applied to. * context - amfast.decoder.DecoderContext, holds decoding related properties. """ raise ClassDefError("This method must be implemented by a sub-class.") class _ProxyClassDef(ExternClassDef): """A special class used internally to encode/decode Proxied objects.""" PROXY_CLASS_DEF = True PROXY_ALIAS = 'proxy' class _ProxyObject(object): """Empty class used for mapping.""" pass def __init__(self): ExternClassDef.__init__(self, self._ProxyObject, self.PROXY_ALIAS, None, _built_in=True) class _ArrayCollectionClassDef(_ProxyClassDef): """A special ClassDef used internally to encode/decode an ArrayCollection.""" ARRAY_COLLECTION_CLASS_DEF = True PROXY_ALIAS = 'flex.messaging.io.ArrayCollection' def __init__(self): _ProxyClassDef.__init__(self) class _ObjectProxyClassDef(_ProxyClassDef): """A special ClassDef used internally to encode/decode an ObjectProxy.""" OBJECT_PROXY_CLASS_DEF = True PROXY_ALIAS = 'flex.messaging.io.ObjectProxy' def __init__(self): _ProxyClassDef.__init__(self) class ClassDefMapper(object): """Map classes to ClassDefs, retrieve class_defs by class or alias name.""" def __init__(self): """ arguments ========== * class_def_attr - string, an attribute with this name will be added mapped classes. Default = '_amf_alias' """ self._lock = threading.RLock() self._mapped_classes = {} self._mapped_aliases = {} self._mapBuiltIns() def __iter__(self): return self._mapped_aliases.itervalues() def _mapBuiltIns(self): """Map built-in ClassDefs for default behavior.""" from as_types import AsError from amfast.remoting import flex_messages as messaging # Proxy objects self.mapClass(_ArrayCollectionClassDef()) self.mapClass(_ObjectProxyClassDef()) # Exceptions self.mapClass(ClassDef(AsError, _built_in=True)) self.mapClass(ClassDef(messaging.FaultError, _built_in=True)) # Flex remoting messages self.mapClass(ClassDef(messaging.RemotingMessage, _built_in=True)) self.mapClass(messaging.AsyncSmallMsgDef(messaging.AsyncMessage, alias="DSA", _built_in=True)) self.mapClass(ClassDef(messaging.AsyncMessage, _built_in=True)) self.mapClass(messaging.CommandSmallMsgDef(messaging.CommandMessage, alias="DSC", _built_in=True)) self.mapClass(ClassDef(messaging.CommandMessage, _built_in=True)) self.mapClass(ClassDef(messaging.AcknowledgeMessage, _built_in=True)) self.mapClass(ClassDef(messaging.ErrorMessage, _built_in=True)) def mapClass(self, class_def): """Map a class_def implementation, so that it can be retrieved based on class attributes. arguments ========== * class_def - ClassDef, ClassDef being mapped. """ if not hasattr(class_def, 'CLASS_DEF'): raise ClassDefError("class_def argument must be a ClassDef object.") self._lock.acquire() try: self._mapped_classes[class_def.class_] = class_def self._mapped_aliases[class_def.alias] = class_def finally: self._lock.release() def getClassDefByClass(self, class_): """Get a ClassDef. Returns None if ClassDef is not found. arguments ========== * class_ - class, the class to find a ClassDef for. """ return self._mapped_classes.get(class_, None) def getClassDefByAlias(self, alias): """Get a ClassDef. Returns None in not ClassDef is found. arguments ========== * alias - string, the alias to find a ClassDef for. """ return self._mapped_aliases.get(alias, None) def unmapClass(self, class_): """Unmap a class definition. arguments ========== * class_ - class, the class to remove a ClassDef for. """ self._lock.acquire() try: for alias, klass in self._mapped_aliases.iteritems(): if class_ == klass: del self._mapped_aliases[alias] class_id = id(class_) if class_id in self._mapped_classes: del self._mapped_classes[class_id] finally: self._lock.release() # ---- module attributes ---- # def get_dynamic_attr_vals(obj, ignore_attrs=None, include_private=False): """Returns a dict of attribute values to encode. keys = attribute names, values = attribute values. argmuents ========== * obj - object, object to get dynamic attribute values from. * ignore_attrs - list or tuple of attributes to ignore. Default = empty tuple. * include_private - bool, if False do not include attributes that start with '_'. Default = False. """ vals = {} if hasattr(obj, '__dict__'): for attr, val in obj.__dict__.iteritems(): if ignore_attrs is not None: if attr in ignore_attrs: continue if (include_private is False) and (attr.startswith('_')): continue vals[attr] = val return vals # These properties can be set on a class # to map attributes within the class. ALIAS = '_AMFAST_ALIAS' STATIC_ATTRS = '_AMFAST_STATIC_ATTRS' AMF3 = '_AMFAST_AMF3' def assign_attrs(class_, alias=None, static_attrs=None, amf3=None): """ Use to map ClassDef attributes to a class. Useful if you want to keep ClassDef configuration with the class being mapped, instead of at the point where the ClassDef is created. If you assign ClassDef attributes with this method, you can call ClassDef(class_) to create a ClassDef, and the assigned attributes will be applied to the new ClassDef. Arguments provided to the ClassDef() will override attributes that were assigned with this function. arguments ========== * class_ - class, the class to assign attributes to. * alias - string, the amf alias name of the mapped class * static_attrs - tuple, a tuple of static attribute names, all values must be strings or unicode * amf3 - bool, if True, this object will be encoded in AMF3. """ if alias is not None: setattr(class_, ALIAS, alias) if static_attrs is not None: setattr(class_, STATIC_ATTRS, static_attrs) if amf3 is not None: setattr(class_, AMF3, amf3)
684
0
166
af40a8496ad76d848c92c910a587cb63d768c727
696
py
Python
components/mpas-seaice/testing_and_setup/testcases/single_cell/run_testcase.py
katsmith133/E3SM
996c7e7aa3150822b81b0e34c427b820c74268a2
[ "BSD-3-Clause" ]
1
2022-03-03T19:09:42.000Z
2022-03-03T19:09:42.000Z
components/mpas-seaice/testing_and_setup/testcases/single_cell/run_testcase.py
katsmith133/E3SM
996c7e7aa3150822b81b0e34c427b820c74268a2
[ "BSD-3-Clause" ]
7
2021-11-16T23:50:53.000Z
2022-03-21T17:00:30.000Z
components/mpas-seaice/testing_and_setup/testcases/single_cell/run_testcase.py
katsmith133/E3SM
996c7e7aa3150822b81b0e34c427b820c74268a2
[ "BSD-3-Clause" ]
null
null
null
import os from plot_testcase import plot_testcase #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- if __name__ == "__main__": run_testcase()
26.769231
87
0.524425
import os from plot_testcase import plot_testcase #------------------------------------------------------------------------------- def run_testcase(): # copy namelist and streams file os.system("cp ../../configurations/standard_physics_single_cell/namelist.seaice .") os.system("cp ../../configurations/standard_physics_single_cell/streams.seaice .") # forcing os.system("python ../../testing/DATA/domain_sc_71.35_-156.5/get_domain.py") # run MPAS-Seaice os.system("../../../seaice_model") # plot output plot_testcase() #------------------------------------------------------------------------------- if __name__ == "__main__": run_testcase()
411
0
23
f50fe79d406abfe3d682d940fe0258fd5f8c1809
1,911
py
Python
audio_split.py
grahamheather/MINT-Speech-Recognition
51c0a56088b3b2020be2e125e523df25c0e82621
[ "CC-BY-3.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
audio_split.py
grahamheather/MINT-Speech-Recognition
51c0a56088b3b2020be2e125e523df25c0e82621
[ "CC-BY-3.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
audio_split.py
grahamheather/MINT-Speech-Recognition
51c0a56088b3b2020be2e125e523df25c0e82621
[ "CC-BY-3.0", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
import os import argparse from pydub import AudioSegment from pydub.silence import split_on_silence if __name__ == "__main__": parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Split an audio file on silence.") parser.add_argument('audio_file', help='the audio file to split') parser.add_argument('--min_silence_len', default=400) parser.add_argument('--silence_thresh', default=-36) parser.add_argument('--keep_silence', default=400) args = parser.parse_args() result = splitAudio(os.path.join(os.getcwd(), args.audio_file), AudioSettingsContainer(args.min_silence_len, args.silence_thresh, args.keep_silence)) if not isinstance(result, int): print(result) else: print(str(result) + " audio file(s) successfully created.")
36.75
177
0.773417
import os import argparse from pydub import AudioSegment from pydub.silence import split_on_silence class AudioSettingsContainer: def __init__(self, min_silence_len, silence_thresh, keep_silence): self.min_silence_len = min_silence_len self.silence_thresh = silence_thresh self.keep_silence = keep_silence def splitAudio(audio_file, audioSettings): # read audio pydub_audio = AudioSegment.from_wav(audio_file) # split on silence split_audio = split_on_silence(pydub_audio, min_silence_len=audioSettings.min_silence_len, silence_thresh=audioSettings.silence_thresh, keep_silence=audioSettings.keep_silence) # calculate how many digits to zfill num_digits = len(str(len(split_audio))) # or do int(math.log10(len(words))) + 1 # create folder for the audio files (file, extension) = os.path.splitext(audio_file) base_name = os.path.basename(file) if not os.path.exists(file): os.makedirs(file) else: return "The directory specified for the audio files (" + base_name + ") already exists." # save output count = 0 for single_word in split_audio: count = count + 1 single_word.export(os.path.join(file, base_name + "_" + str(count).zfill(num_digits) + ".wav"), format="wav") return count if __name__ == "__main__": parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Split an audio file on silence.") parser.add_argument('audio_file', help='the audio file to split') parser.add_argument('--min_silence_len', default=400) parser.add_argument('--silence_thresh', default=-36) parser.add_argument('--keep_silence', default=400) args = parser.parse_args() result = splitAudio(os.path.join(os.getcwd(), args.audio_file), AudioSettingsContainer(args.min_silence_len, args.silence_thresh, args.keep_silence)) if not isinstance(result, int): print(result) else: print(str(result) + " audio file(s) successfully created.")
1,042
8
69
69eb9698f7e39688eb5f844d8b2719e92936aaf2
1,794
py
Python
venv/Lib/site-packages/rest_framework_extras/tests/forms.py
LishenZz/my_project
c2ac8199efb467e303d343ea34ed1969b64280d7
[ "Apache-2.0" ]
null
null
null
venv/Lib/site-packages/rest_framework_extras/tests/forms.py
LishenZz/my_project
c2ac8199efb467e303d343ea34ed1969b64280d7
[ "Apache-2.0" ]
null
null
null
venv/Lib/site-packages/rest_framework_extras/tests/forms.py
LishenZz/my_project
c2ac8199efb467e303d343ea34ed1969b64280d7
[ "Apache-2.0" ]
null
null
null
from django import forms from rest_framework_extras.tests import models
29.409836
91
0.613712
from django import forms from rest_framework_extras.tests import models class WithFormForm(forms.ModelForm): class Meta: model = models.WithForm fields = ( "editable_field", "another_editable_field", "foreign_field", "many_field" ) class WithFormTrickyForm(forms.ModelForm): an_integer = forms.IntegerField(initial=1) class Meta: model = models.WithTrickyForm fields = ( "editable_field", "another_editable_field", "foreign_field", "many_field" ) def __init__(self, *args, **kwargs): super(WithFormTrickyForm, self).__init__(*args, **kwargs) if not self.instance: self.fields["editable_field"].initial = "initial" self.fields["editable_field"].label = "An editable field" def clean_editable_field(self): value = self.cleaned_data["editable_field"] if value == "bar": raise forms.ValidationError("Editable field may not be bar.") return value def clean(self): cd = self.cleaned_data if cd["editable_field"] == cd["another_editable_field"]: raise forms.ValidationError( "Editable field and Another editable field may not be the same." ) return cd def save(self, commit=True): instance = super(WithFormTrickyForm, self).save(commit=commit) instance.another_editable_field = "%s%s" % \ (instance.another_editable_field + self.cleaned_data["an_integer"]) #instance.another_editable_field = "%s%s" % \ # (instance.another_editable_field, self.cleaned_data["another_editable_field"]) instance.save() return instance
1,075
597
46
c30631a2186e2da2987d31b03216293e8a47c2b1
16,866
py
Python
tests/unit/async_/work/test_result.py
artcg/neo4j-python-driver
97185f7e435d8f541d8b1445b3164668e56db177
[ "Apache-2.0" ]
null
null
null
tests/unit/async_/work/test_result.py
artcg/neo4j-python-driver
97185f7e435d8f541d8b1445b3164668e56db177
[ "Apache-2.0" ]
null
null
null
tests/unit/async_/work/test_result.py
artcg/neo4j-python-driver
97185f7e435d8f541d8b1445b3164668e56db177
[ "Apache-2.0" ]
null
null
null
# Copyright (c) "Neo4j" # Neo4j Sweden AB [http://neo4j.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unittest import mock import pytest from neo4j import ( Address, AsyncResult, Record, ResultSummary, ServerInfo, SummaryCounters, Version, ) from neo4j._async_compat.util import AsyncUtil from neo4j.data import DataHydrator from neo4j.exceptions import ResultNotSingleError from ...._async_compat import mark_async_test @pytest.mark.parametrize("method", ("for loop", "next", "one iter", "new iter")) @pytest.mark.parametrize("records", ( [], [[42]], [[1], [2], [3], [4], [5]], )) @mark_async_test @pytest.mark.parametrize("method", ("for loop", "next", "one iter", "new iter")) @pytest.mark.parametrize("invert_fetch", (True, False)) @mark_async_test @pytest.mark.parametrize("method", ("for loop", "next", "one iter", "new iter")) @pytest.mark.parametrize("invert_fetch", (True, False)) @mark_async_test @pytest.mark.parametrize("records", ([[1], [2]], [[1]], [])) @pytest.mark.parametrize("fetch_size", (1, 2)) @mark_async_test @pytest.mark.parametrize("records", ([[1], [2]], [[1]], [])) @pytest.mark.parametrize("fetch_size", (1, 2)) @mark_async_test @mark_async_test @pytest.mark.parametrize("records", ([[1], [2]], [[1]], [])) @pytest.mark.parametrize("consume_one", (True, False)) @pytest.mark.parametrize("summary_meta", (None, {"database": "foobar"})) @mark_async_test @pytest.mark.parametrize("t_first", (None, 0, 1, 123456789)) @pytest.mark.parametrize("t_last", (None, 0, 1, 123456789)) @mark_async_test @mark_async_test @pytest.mark.parametrize("query_type", ("r", "w", "rw", "s")) @mark_async_test @pytest.mark.parametrize("num_records", range(0, 5)) @mark_async_test
35.733051
83
0.61206
# Copyright (c) "Neo4j" # Neo4j Sweden AB [http://neo4j.com] # # This file is part of Neo4j. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from unittest import mock import pytest from neo4j import ( Address, AsyncResult, Record, ResultSummary, ServerInfo, SummaryCounters, Version, ) from neo4j._async_compat.util import AsyncUtil from neo4j.data import DataHydrator from neo4j.exceptions import ResultNotSingleError from ...._async_compat import mark_async_test class Records: def __init__(self, fields, records): assert all(len(fields) == len(r) for r in records) self.fields = fields # self.records = [{"record_values": r} for r in records] self.records = records def __len__(self): return self.records.__len__() def __iter__(self): return self.records.__iter__() def __getitem__(self, item): return self.records.__getitem__(item) class AsyncConnectionStub: class Message: def __init__(self, message, *args, **kwargs): self.message = message self.args = args self.kwargs = kwargs async def _cb(self, cb_name, *args, **kwargs): # print(self.message, cb_name.upper(), args, kwargs) cb = self.kwargs.get(cb_name) await AsyncUtil.callback(cb, *args, **kwargs) async def on_success(self, metadata): await self._cb("on_success", metadata) async def on_summary(self): await self._cb("on_summary") async def on_records(self, records): await self._cb("on_records", records) def __eq__(self, other): return self.message == other def __repr__(self): return "Message(%s)" % self.message def __init__(self, records=None, run_meta=None, summary_meta=None, force_qid=False): self._multi_result = isinstance(records, (list, tuple)) if self._multi_result: self._records = records self._use_qid = True else: self._records = records, self._use_qid = force_qid self.fetch_idx = 0 self._qid = -1 self.most_recent_qid = None self.record_idxs = [0] * len(self._records) self.to_pull = [None] * len(self._records) self._exhausted = [False] * len(self._records) self.queued = [] self.sent = [] self.run_meta = run_meta self.summary_meta = summary_meta AsyncConnectionStub.server_info.update({"server": "Neo4j/4.3.0"}) self.unresolved_address = None async def send_all(self): self.sent += self.queued self.queued = [] async def fetch_message(self): if self.fetch_idx >= len(self.sent): pytest.fail("Waits for reply to never sent message") msg = self.sent[self.fetch_idx] if msg == "RUN": self.fetch_idx += 1 self._qid += 1 meta = {"fields": self._records[self._qid].fields, **(self.run_meta or {})} if self._use_qid: meta.update(qid=self._qid) await msg.on_success(meta) elif msg == "DISCARD": self.fetch_idx += 1 qid = msg.kwargs.get("qid", -1) if qid < 0: qid = self._qid self.record_idxs[qid] = len(self._records[qid]) await msg.on_success(self.summary_meta or {}) await msg.on_summary() elif msg == "PULL": qid = msg.kwargs.get("qid", -1) if qid < 0: qid = self._qid if self._exhausted[qid]: pytest.fail("PULLing exhausted result") if self.to_pull[qid] is None: n = msg.kwargs.get("n", -1) if n < 0: n = len(self._records[qid]) self.to_pull[qid] = \ min(n, len(self._records[qid]) - self.record_idxs[qid]) # if to == len(self._records): # self.fetch_idx += 1 if self.to_pull[qid] > 0: record = self._records[qid][self.record_idxs[qid]] self.record_idxs[qid] += 1 self.to_pull[qid] -= 1 await msg.on_records([record]) elif self.to_pull[qid] == 0: self.to_pull[qid] = None self.fetch_idx += 1 if self.record_idxs[qid] < len(self._records[qid]): await msg.on_success({"has_more": True}) else: await msg.on_success( {"bookmark": "foo", **(self.summary_meta or {})} ) self._exhausted[qid] = True await msg.on_summary() async def fetch_all(self): while self.fetch_idx < len(self.sent): await self.fetch_message() def run(self, *args, **kwargs): self.queued.append(AsyncConnectionStub.Message("RUN", *args, **kwargs)) def discard(self, *args, **kwargs): self.queued.append(AsyncConnectionStub.Message("DISCARD", *args, **kwargs)) def pull(self, *args, **kwargs): self.queued.append(AsyncConnectionStub.Message("PULL", *args, **kwargs)) server_info = ServerInfo(Address(("bolt://localhost", 7687)), Version(4, 3)) def defunct(self): return False class HydratorStub(DataHydrator): def hydrate(self, values): return values def noop(*_, **__): pass async def fetch_and_compare_all_records( result, key, expected_records, method, limit=None ): received_records = [] if method == "for loop": async for record in result: assert isinstance(record, Record) received_records.append([record.data().get(key, None)]) if limit is not None and len(received_records) == limit: break if limit is None: assert result._exhausted elif method == "next": n = len(expected_records) if limit is None else limit for _ in range(n): record = await AsyncUtil.next(result) received_records.append([record.get(key, None)]) if limit is None: with pytest.raises(StopAsyncIteration): await AsyncUtil.next(result) assert result._exhausted elif method == "one iter": iter_ = AsyncUtil.iter(result) n = len(expected_records) if limit is None else limit for _ in range(n): record = await AsyncUtil.next(iter_) received_records.append([record.get(key, None)]) if limit is None: with pytest.raises(StopAsyncIteration): await AsyncUtil.next(iter_) assert result._exhausted elif method == "new iter": n = len(expected_records) if limit is None else limit for _ in range(n): iter_ = AsyncUtil.iter(result) record = await AsyncUtil.next(iter_) received_records.append([record.get(key, None)]) if limit is None: iter_ = AsyncUtil.iter(result) with pytest.raises(StopAsyncIteration): await AsyncUtil.next(iter_) assert result._exhausted else: raise ValueError() assert received_records == expected_records @pytest.mark.parametrize("method", ("for loop", "next", "one iter", "new iter")) @pytest.mark.parametrize("records", ( [], [[42]], [[1], [2], [3], [4], [5]], )) @mark_async_test async def test_result_iteration(method, records): connection = AsyncConnectionStub(records=Records(["x"], records)) result = AsyncResult(connection, HydratorStub(), 2, noop, noop) await result._run("CYPHER", {}, None, None, "r", None) await fetch_and_compare_all_records(result, "x", records, method) @pytest.mark.parametrize("method", ("for loop", "next", "one iter", "new iter")) @pytest.mark.parametrize("invert_fetch", (True, False)) @mark_async_test async def test_parallel_result_iteration(method, invert_fetch): records1 = [[i] for i in range(1, 6)] records2 = [[i] for i in range(6, 11)] connection = AsyncConnectionStub( records=(Records(["x"], records1), Records(["x"], records2)) ) result1 = AsyncResult(connection, HydratorStub(), 2, noop, noop) await result1._run("CYPHER1", {}, None, None, "r", None) result2 = AsyncResult(connection, HydratorStub(), 2, noop, noop) await result2._run("CYPHER2", {}, None, None, "r", None) if invert_fetch: await fetch_and_compare_all_records( result2, "x", records2, method ) await fetch_and_compare_all_records( result1, "x", records1, method ) else: await fetch_and_compare_all_records( result1, "x", records1, method ) await fetch_and_compare_all_records( result2, "x", records2, method ) @pytest.mark.parametrize("method", ("for loop", "next", "one iter", "new iter")) @pytest.mark.parametrize("invert_fetch", (True, False)) @mark_async_test async def test_interwoven_result_iteration(method, invert_fetch): records1 = [[i] for i in range(1, 10)] records2 = [[i] for i in range(11, 20)] connection = AsyncConnectionStub( records=(Records(["x"], records1), Records(["y"], records2)) ) result1 = AsyncResult(connection, HydratorStub(), 2, noop, noop) await result1._run("CYPHER1", {}, None, None, "r", None) result2 = AsyncResult(connection, HydratorStub(), 2, noop, noop) await result2._run("CYPHER2", {}, None, None, "r", None) start = 0 for n in (1, 2, 3, 1, None): end = n if n is None else start + n if invert_fetch: await fetch_and_compare_all_records( result2, "y", records2[start:end], method, n ) await fetch_and_compare_all_records( result1, "x", records1[start:end], method, n ) else: await fetch_and_compare_all_records( result1, "x", records1[start:end], method, n ) await fetch_and_compare_all_records( result2, "y", records2[start:end], method, n ) start = end @pytest.mark.parametrize("records", ([[1], [2]], [[1]], [])) @pytest.mark.parametrize("fetch_size", (1, 2)) @mark_async_test async def test_result_peek(records, fetch_size): connection = AsyncConnectionStub(records=Records(["x"], records)) result = AsyncResult(connection, HydratorStub(), fetch_size, noop, noop) await result._run("CYPHER", {}, None, None, "r", None) for i in range(len(records) + 1): record = await result.peek() if i == len(records): assert record is None else: assert isinstance(record, Record) assert record.get("x") == records[i][0] iter_ = AsyncUtil.iter(result) await AsyncUtil.next(iter_) # consume the record @pytest.mark.parametrize("records", ([[1], [2]], [[1]], [])) @pytest.mark.parametrize("fetch_size", (1, 2)) @mark_async_test async def test_result_single(records, fetch_size): connection = AsyncConnectionStub(records=Records(["x"], records)) result = AsyncResult(connection, HydratorStub(), fetch_size, noop, noop) await result._run("CYPHER", {}, None, None, "r", None) try: record = await result.single() except ResultNotSingleError as exc: assert len(records) != 1 if len(records) == 0: assert exc is not None assert "no records" in str(exc).lower() elif len(records) > 1: assert exc is not None assert "more than one record" in str(exc).lower() else: assert len(records) == 1 assert isinstance(record, Record) assert record.get("x") == records[0][0] @mark_async_test async def test_keys_are_available_before_and_after_stream(): connection = AsyncConnectionStub(records=Records(["x"], [[1], [2]])) result = AsyncResult(connection, HydratorStub(), 1, noop, noop) await result._run("CYPHER", {}, None, None, "r", None) assert list(result.keys()) == ["x"] await AsyncUtil.list(result) assert list(result.keys()) == ["x"] @pytest.mark.parametrize("records", ([[1], [2]], [[1]], [])) @pytest.mark.parametrize("consume_one", (True, False)) @pytest.mark.parametrize("summary_meta", (None, {"database": "foobar"})) @mark_async_test async def test_consume(records, consume_one, summary_meta): connection = AsyncConnectionStub( records=Records(["x"], records), summary_meta=summary_meta ) result = AsyncResult(connection, HydratorStub(), 1, noop, noop) await result._run("CYPHER", {}, None, None, "r", None) if consume_one: try: await AsyncUtil.next(AsyncUtil.iter(result)) except StopAsyncIteration: pass summary = await result.consume() assert isinstance(summary, ResultSummary) if summary_meta and "db" in summary_meta: assert summary.database == summary_meta["db"] else: assert summary.database is None server_info = summary.server assert isinstance(server_info, ServerInfo) assert server_info.protocol_version == Version(4, 3) assert isinstance(summary.counters, SummaryCounters) @pytest.mark.parametrize("t_first", (None, 0, 1, 123456789)) @pytest.mark.parametrize("t_last", (None, 0, 1, 123456789)) @mark_async_test async def test_time_in_summary(t_first, t_last): run_meta = None if t_first is not None: run_meta = {"t_first": t_first} summary_meta = None if t_last is not None: summary_meta = {"t_last": t_last} connection = AsyncConnectionStub( records=Records(["n"], [[i] for i in range(100)]), run_meta=run_meta, summary_meta=summary_meta ) result = AsyncResult(connection, HydratorStub(), 1, noop, noop) await result._run("CYPHER", {}, None, None, "r", None) summary = await result.consume() if t_first is not None: assert isinstance(summary.result_available_after, int) assert summary.result_available_after == t_first else: assert summary.result_available_after is None if t_last is not None: assert isinstance(summary.result_consumed_after, int) assert summary.result_consumed_after == t_last else: assert summary.result_consumed_after is None assert not hasattr(summary, "t_first") assert not hasattr(summary, "t_last") @mark_async_test async def test_counts_in_summary(): connection = AsyncConnectionStub(records=Records(["n"], [[1], [2]])) result = AsyncResult(connection, HydratorStub(), 1, noop, noop) await result._run("CYPHER", {}, None, None, "r", None) summary = await result.consume() assert isinstance(summary.counters, SummaryCounters) @pytest.mark.parametrize("query_type", ("r", "w", "rw", "s")) @mark_async_test async def test_query_type(query_type): connection = AsyncConnectionStub( records=Records(["n"], [[1], [2]]), summary_meta={"type": query_type} ) result = AsyncResult(connection, HydratorStub(), 1, noop, noop) await result._run("CYPHER", {}, None, None, "r", None) summary = await result.consume() assert isinstance(summary.query_type, str) assert summary.query_type == query_type @pytest.mark.parametrize("num_records", range(0, 5)) @mark_async_test async def test_data(num_records): connection = AsyncConnectionStub( records=Records(["n"], [[i + 1] for i in range(num_records)]) ) result = AsyncResult(connection, HydratorStub(), 1, noop, noop) await result._run("CYPHER", {}, None, None, "r", None) await result._buffer_all() records = result._record_buffer.copy() assert len(records) == num_records expected_data = [] for i, record in enumerate(records): record.data = mock.Mock() expected_data.append("magic_return_%s" % i) record.data.return_value = expected_data[-1] assert await result.data("hello", "world") == expected_data for record in records: assert record.data.called_once_with("hello", "world")
13,457
543
490
a57a576eda6592f977025fc53370d55ab424d53e
589
py
Python
project_name/tests/fixtures/apps_settings.py
thnee/django-template
d1e4f8dfe65c86f64c9a06c8cc195dbe6658320e
[ "MIT" ]
1
2018-07-20T23:35:32.000Z
2018-07-20T23:35:32.000Z
project_name/tests/fixtures/apps_settings.py
thnee/django-template
d1e4f8dfe65c86f64c9a06c8cc195dbe6658320e
[ "MIT" ]
null
null
null
project_name/tests/fixtures/apps_settings.py
thnee/django-template
d1e4f8dfe65c86f64c9a06c8cc195dbe6658320e
[ "MIT" ]
null
null
null
import importlib import pytest @pytest.fixture @pytest.fixture
20.310345
70
0.716469
import importlib import pytest def load_settings(app_name, settings): APP_SETTINGS = [ 'INSTALLED_APPS', 'ROOT_URLCONF', 'AUTH_USER_MODEL', ] module_name = 'settings.apps.{app_name}'.format(app_name=app_name) app_settings = importlib.import_module(module_name) for setting in APP_SETTINGS: setattr(settings, setting, getattr(app_settings, setting)) @pytest.fixture def frontoffice_app(settings): load_settings('frontoffice', settings) @pytest.fixture def backoffice_app(settings): load_settings('backoffice', settings)
452
0
67
296c37c82ec0c80065e417707dc0dac24a4cc265
2,484
py
Python
smtpdfix/smtp.py
jeremysprofile/smtpdfix
46ead66aafbda18d83b583dff1c4dc0430c85306
[ "MIT" ]
null
null
null
smtpdfix/smtp.py
jeremysprofile/smtpdfix
46ead66aafbda18d83b583dff1c4dc0430c85306
[ "MIT" ]
null
null
null
smtpdfix/smtp.py
jeremysprofile/smtpdfix
46ead66aafbda18d83b583dff1c4dc0430c85306
[ "MIT" ]
null
null
null
import logging from aiosmtpd.smtp import MISSING, SMTP, Session, syntax from .config import Config from .handlers import AUTH_REQUIRED log = logging.getLogger(__name__)
34.985915
80
0.623591
import logging from aiosmtpd.smtp import MISSING, SMTP, Session, syntax from .config import Config from .handlers import AUTH_REQUIRED log = logging.getLogger(__name__) class AuthSession(Session): def __init__(self, loop): super().__init__(loop) self.authenticated = False class AuthSMTP(SMTP): def _create_session(self): # Override the _create_session method to return an AuthSession object. return AuthSession(self.loop) def _set_rset_state(self): super()._set_rset_state() # Set the authenticated state on the session to be False if it exists if self.session: self.session.authenticated = False @syntax('AUTH <mechanism> [args]') async def smtp_AUTH(self, arg): if not self.session.host_name: await self.push('503 Error: send HELO first') return log.debug("===> AUTH command received.") status = await self._call_handler_hook("AUTH", arg) if status is MISSING: status = "502 Command not implemented" await self.push(status) async def smtp_DATA(self, arg): if not self.session.host_name: await self.push('503 Error: send HELO first') return config = Config() if not self.session.authenticated and config.SMTPD_ENFORCE_AUTH: log.debug("Successful authentication required before DATA command") await self.push(AUTH_REQUIRED) return return await super().smtp_DATA(arg) async def smtp_MAIL(self, arg): if not self.session.host_name: await self.push('503 Error: send HELO first') return config = Config() if not self.session.authenticated and config.SMTPD_ENFORCE_AUTH: log.debug("Successful authentication required before MAIL command") await self.push(AUTH_REQUIRED) return return await super().smtp_MAIL(arg) async def smtp_RCPT(self, arg): if not self.session.host_name: await self.push('503 Error: send HELO first') return config = Config() if not self.session.authenticated and config.SMTPD_ENFORCE_AUTH: log.debug("Successful authentication required before RCPT command") await self.push(AUTH_REQUIRED) return return await super().smtp_RCPT(arg)
2,005
219
76
c6f6a44fa1725d55f292b7501c236447623f2d46
942
py
Python
data/external/repositories_2to3/119820/kaggle-seizure-prediction-master/thesis_scripts/params_calc.py
Keesiu/meta-kaggle
87de739aba2399fd31072ee81b391f9b7a63f540
[ "MIT" ]
null
null
null
data/external/repositories_2to3/119820/kaggle-seizure-prediction-master/thesis_scripts/params_calc.py
Keesiu/meta-kaggle
87de739aba2399fd31072ee81b391f9b7a63f540
[ "MIT" ]
null
null
null
data/external/repositories_2to3/119820/kaggle-seizure-prediction-master/thesis_scripts/params_calc.py
Keesiu/meta-kaggle
87de739aba2399fd31072ee81b391f9b7a63f540
[ "MIT" ]
1
2019-12-04T08:23:33.000Z
2019-12-04T08:23:33.000Z
nfreq_bands = 7 win_length_sec = 120 stride_sec = 120 n_channels = 16 n_timesteps = (600-win_length_sec)/stride_sec + 1 global_pooling = 1 nkerns = [16, 32, 512] recept_width = [1, 1] stride = [1, 1] pool_width = [1, 1] n_params = 0 c1_input_width = n_timesteps print('c1:', nkerns[0], '@', ((n_timesteps - recept_width[0]) / stride[0] + 1) / pool_width[0]) n_params += (n_channels * nfreq_bands * recept_width[0] + 1) * nkerns[0] c2_input_width = ((n_timesteps - recept_width[0]) / stride[0] + 1) / pool_width[0] print('c2:', nkerns[1], '@', ((c2_input_width - recept_width[1]) / stride[1] + 1) / pool_width[1]) n_params += (nkerns[0]*recept_width[1] + 1)*nkerns[1] if global_pooling: f3_input_size = 6*nkerns[1] else: f3_input_size = nkerns[1]*((c2_input_width - recept_width[1]) / stride[1] + 1) / pool_width[1] n_params += f3_input_size * nkerns[2] + 1 print('number of parameters', n_params)
30.387097
99
0.653928
nfreq_bands = 7 win_length_sec = 120 stride_sec = 120 n_channels = 16 n_timesteps = (600-win_length_sec)/stride_sec + 1 global_pooling = 1 nkerns = [16, 32, 512] recept_width = [1, 1] stride = [1, 1] pool_width = [1, 1] n_params = 0 c1_input_width = n_timesteps print('c1:', nkerns[0], '@', ((n_timesteps - recept_width[0]) / stride[0] + 1) / pool_width[0]) n_params += (n_channels * nfreq_bands * recept_width[0] + 1) * nkerns[0] c2_input_width = ((n_timesteps - recept_width[0]) / stride[0] + 1) / pool_width[0] print('c2:', nkerns[1], '@', ((c2_input_width - recept_width[1]) / stride[1] + 1) / pool_width[1]) n_params += (nkerns[0]*recept_width[1] + 1)*nkerns[1] if global_pooling: f3_input_size = 6*nkerns[1] else: f3_input_size = nkerns[1]*((c2_input_width - recept_width[1]) / stride[1] + 1) / pool_width[1] n_params += f3_input_size * nkerns[2] + 1 print('number of parameters', n_params)
0
0
0
4393f5f0ca144b153266589c66804471f7553fc2
221
py
Python
source/gps/algorithm/dynamics/config.py
shercklo/LTO-CMA
9ce5cf4a07f9d85360de3bc40c0699ea476a0b39
[ "Apache-2.0" ]
7
2020-08-06T08:59:23.000Z
2021-06-01T08:46:22.000Z
source/gps/algorithm/dynamics/config.py
shercklo/LTO-CMA
9ce5cf4a07f9d85360de3bc40c0699ea476a0b39
[ "Apache-2.0" ]
4
2020-12-08T22:23:16.000Z
2022-02-10T05:12:05.000Z
source/gps/algorithm/dynamics/config.py
shercklo/LTO-CMA
9ce5cf4a07f9d85360de3bc40c0699ea476a0b39
[ "Apache-2.0" ]
1
2021-03-05T14:18:28.000Z
2021-03-05T14:18:28.000Z
""" Default configuration and hyperparameter values for dynamics objects. """ # DynamicsPriorGMM DYN_PRIOR_GMM = { 'min_samples_per_cluster': 20, 'max_clusters': 50, 'max_samples': 20, 'strength': 1.0, }
22.1
77
0.687783
""" Default configuration and hyperparameter values for dynamics objects. """ # DynamicsPriorGMM DYN_PRIOR_GMM = { 'min_samples_per_cluster': 20, 'max_clusters': 50, 'max_samples': 20, 'strength': 1.0, }
0
0
0
296f623cabb173a3999c60c4ec4b232e1bd4e2ad
455
py
Python
Task1B.py
cued-ia-computing/flood-pj354-ystt2
d03644430d3a9b6f52d76129a5854d7eb298715b
[ "MIT" ]
null
null
null
Task1B.py
cued-ia-computing/flood-pj354-ystt2
d03644430d3a9b6f52d76129a5854d7eb298715b
[ "MIT" ]
null
null
null
Task1B.py
cued-ia-computing/flood-pj354-ystt2
d03644430d3a9b6f52d76129a5854d7eb298715b
[ "MIT" ]
null
null
null
from floodsystem.stationdata import build_station_list from floodsystem.geo import stations_by_distance, stations_with_radius, rivers_with_stations, stations_by_river import itertools stations = build_station_list() p = (52.2053, 0.1218) # coords of cambridge print("closest 10 stations from cambridge: {}".format(stations_by_distance(stations, p)[0:10])) print("furthest 10 stations from cambridge: {}".format(stations_by_distance(stations, p)[-10:]))
50.555556
111
0.806593
from floodsystem.stationdata import build_station_list from floodsystem.geo import stations_by_distance, stations_with_radius, rivers_with_stations, stations_by_river import itertools stations = build_station_list() p = (52.2053, 0.1218) # coords of cambridge print("closest 10 stations from cambridge: {}".format(stations_by_distance(stations, p)[0:10])) print("furthest 10 stations from cambridge: {}".format(stations_by_distance(stations, p)[-10:]))
0
0
0
e05c17b9367d48d846795ae4d0215a7b2482006d
811
py
Python
examples/02_simple_attractor_ring_network.py
marsgr6/ann
64c051263fd1f80d8f596b217fe733e0e1b4c2fa
[ "MIT" ]
1
2021-05-25T23:43:44.000Z
2021-05-25T23:43:44.000Z
examples/02_simple_attractor_ring_network.py
marsgr6/ann
64c051263fd1f80d8f596b217fe733e0e1b4c2fa
[ "MIT" ]
null
null
null
examples/02_simple_attractor_ring_network.py
marsgr6/ann
64c051263fd1f80d8f596b217fe733e0e1b4c2fa
[ "MIT" ]
null
null
null
import matplotlib.pyplot as plt from ann import attractor_network as AA from ann import pattern as p import numpy as np N = 1024 # Number of neurons K = 4 # Degree a = 0.5 # Sparseness T = 800 # Steps # Create network with same parameters as above activity_net = AA.SimpleAttractor(N, K, a, "ring") print(activity_net) # Make topology (random by default) activity_net.generate_topology() # Make weights (random -1, 1) activity_net.make_weights() # Initializa network state (binary random with a activity) activity_net.make_initialization() print(activity_net)v t1 = datetime.datetime.now() # Update network T steps (returns activity for each step) activity = activity_net.update_steps(T) t2 = datetime.datetime.now() print(t2-t1) # Plot activity plt.figure(figsize=(20,6)) plt.plot(activity) plt.show()
25.34375
62
0.760789
import matplotlib.pyplot as plt from ann import attractor_network as AA from ann import pattern as p import numpy as np N = 1024 # Number of neurons K = 4 # Degree a = 0.5 # Sparseness T = 800 # Steps # Create network with same parameters as above activity_net = AA.SimpleAttractor(N, K, a, "ring") print(activity_net) # Make topology (random by default) activity_net.generate_topology() # Make weights (random -1, 1) activity_net.make_weights() # Initializa network state (binary random with a activity) activity_net.make_initialization() print(activity_net)v t1 = datetime.datetime.now() # Update network T steps (returns activity for each step) activity = activity_net.update_steps(T) t2 = datetime.datetime.now() print(t2-t1) # Plot activity plt.figure(figsize=(20,6)) plt.plot(activity) plt.show()
0
0
0
f739c519bdff3ea0513a876d0a9b7c47e6b5da68
3,963
py
Python
ClassifierCode/classifier_builder.py
annaw3558/BankNoteClassifier
18605b44f949a84bf78b43dec741ca003d17209c
[ "MIT" ]
null
null
null
ClassifierCode/classifier_builder.py
annaw3558/BankNoteClassifier
18605b44f949a84bf78b43dec741ca003d17209c
[ "MIT" ]
null
null
null
ClassifierCode/classifier_builder.py
annaw3558/BankNoteClassifier
18605b44f949a84bf78b43dec741ca003d17209c
[ "MIT" ]
null
null
null
'''This program contains the functions averageFinder and midpointFinder. AverageData calculates the averages of the "columns" of a list of numbers (a list of lists of numbers) for real and fake samples (separately) and midpointFinder finds the midpoint between the real and fake averages. Data is either given from the test case or from user input, which is run through incomingData. Assignment 2: classifier_builder Name: Anna Wood Student Number: 20091785 NetID: 17aaw2''' def averageFinder(sample_data): '''will take a list of attributes and: averageFinder calculates the average of each of the attributes across all the samples with the same classification (0 or 1) input: sample list / list of numbers output: none, averages are passed to midpointFinder note - 1 IS REAL 0 IS COUNTERFEIT ''' real_avgs_counter = 0 counter_avgs_counter = 0 real_avgs = [] counter_avgs = [] avg_len_real = 0 indx = 0 while indx < 4: # while-loop that sums each attribute and adds it to the list of its category (real or counter) for i in range(0,len(sample_data)): # loop to separate data into 0 and 1 if sample_data[i][4] == 1: real_avgs_counter += sample_data[i][indx]# if real, attribute is summed in counter avg_len_real = avg_len_real + 1 /4 # used to count the length of how many real bills elif sample_data[i][4] == 0: # attribute sum for counterfeit bills counter_avgs_counter += sample_data[i][indx] real_avgs.append(real_avgs_counter) # after each attribute is summed it is added to the final list counter_avgs.append(counter_avgs_counter) real_avgs_counter = 0 # counters are reset to 0 after each list counter_avgs_counter = 0 indx += 1 # index for counting the "columns" avg_len_counter = len(sample_data) - avg_len_real # number of real / counter bills calculated for finding the average for i in range(0, 4): # divides the real, counterfeit sums by the amount of real & counterfeit items respectively real_avgs[i] = round((real_avgs[i] / avg_len_real), 3) counter_avgs[i] = round((counter_avgs[i] / avg_len_counter), 3) # each average rounded to 3 decimal points return real_avgs, counter_avgs def midpointFinder(real_avgs, counter_avgs): '''part 2 of the building classifier, takes the averages of the real and and fake samples and finds the midpoint (divides by 2). midpoints list should then be returned to classifier for further classifying input: averages of real, fake samples output: midpoints (returned to incomingData)''' midpoints = [] # empty list for midpoints for i in range(0,4): # finds midpoints by adding averages and dividing by 2 midpoint = (real_avgs[i] + counter_avgs[i]) / 2 midpoints.append(round(midpoint,3)) return midpoints #returns midpoints to incomingData def incomingData(training_data): '''function runs from here when data is passed from our main interface input: training_data output: midpoints''' real_avgs, counter_avgs = averageFinder(training_data) midpoints = midpointFinder(real_avgs, counter_avgs) return midpoints # midpoints returned to main interface if __name__ == '__main__': sample_data_main = [[ 3, 8, -2, 0, 0], [4, 8, -2, -1,0],[3, -2, 1, 0, 0], [2, 1, 0, -2, 0], # fake samples (5th item 0) [0, 3, -3, -2, 1], [-3, 3, 0, -3, 1], [-6, 7, 0, -3, 1] ] # real samples (5th item is 1) real_avgs , counter_avgs = averageFinder(sample_data_main) midpoints = midpointFinder(real_avgs, counter_avgs) print('real averages (test case)',real_avgs, 'should be -3 , 4.333, -1. -2.667') print('counter averages (test case)',counter_avgs, 'should be 3, 3.75, -0.75, -0.75') print('midpoints (test case)', midpoints, 'should be 0, 4.041 ish, -0.875, -1.708')
43.076087
123
0.685592
'''This program contains the functions averageFinder and midpointFinder. AverageData calculates the averages of the "columns" of a list of numbers (a list of lists of numbers) for real and fake samples (separately) and midpointFinder finds the midpoint between the real and fake averages. Data is either given from the test case or from user input, which is run through incomingData. Assignment 2: classifier_builder Name: Anna Wood Student Number: 20091785 NetID: 17aaw2''' def averageFinder(sample_data): '''will take a list of attributes and: averageFinder calculates the average of each of the attributes across all the samples with the same classification (0 or 1) input: sample list / list of numbers output: none, averages are passed to midpointFinder note - 1 IS REAL 0 IS COUNTERFEIT ''' real_avgs_counter = 0 counter_avgs_counter = 0 real_avgs = [] counter_avgs = [] avg_len_real = 0 indx = 0 while indx < 4: # while-loop that sums each attribute and adds it to the list of its category (real or counter) for i in range(0,len(sample_data)): # loop to separate data into 0 and 1 if sample_data[i][4] == 1: real_avgs_counter += sample_data[i][indx]# if real, attribute is summed in counter avg_len_real = avg_len_real + 1 /4 # used to count the length of how many real bills elif sample_data[i][4] == 0: # attribute sum for counterfeit bills counter_avgs_counter += sample_data[i][indx] real_avgs.append(real_avgs_counter) # after each attribute is summed it is added to the final list counter_avgs.append(counter_avgs_counter) real_avgs_counter = 0 # counters are reset to 0 after each list counter_avgs_counter = 0 indx += 1 # index for counting the "columns" avg_len_counter = len(sample_data) - avg_len_real # number of real / counter bills calculated for finding the average for i in range(0, 4): # divides the real, counterfeit sums by the amount of real & counterfeit items respectively real_avgs[i] = round((real_avgs[i] / avg_len_real), 3) counter_avgs[i] = round((counter_avgs[i] / avg_len_counter), 3) # each average rounded to 3 decimal points return real_avgs, counter_avgs def midpointFinder(real_avgs, counter_avgs): '''part 2 of the building classifier, takes the averages of the real and and fake samples and finds the midpoint (divides by 2). midpoints list should then be returned to classifier for further classifying input: averages of real, fake samples output: midpoints (returned to incomingData)''' midpoints = [] # empty list for midpoints for i in range(0,4): # finds midpoints by adding averages and dividing by 2 midpoint = (real_avgs[i] + counter_avgs[i]) / 2 midpoints.append(round(midpoint,3)) return midpoints #returns midpoints to incomingData def incomingData(training_data): '''function runs from here when data is passed from our main interface input: training_data output: midpoints''' real_avgs, counter_avgs = averageFinder(training_data) midpoints = midpointFinder(real_avgs, counter_avgs) return midpoints # midpoints returned to main interface if __name__ == '__main__': sample_data_main = [[ 3, 8, -2, 0, 0], [4, 8, -2, -1,0],[3, -2, 1, 0, 0], [2, 1, 0, -2, 0], # fake samples (5th item 0) [0, 3, -3, -2, 1], [-3, 3, 0, -3, 1], [-6, 7, 0, -3, 1] ] # real samples (5th item is 1) real_avgs , counter_avgs = averageFinder(sample_data_main) midpoints = midpointFinder(real_avgs, counter_avgs) print('real averages (test case)',real_avgs, 'should be -3 , 4.333, -1. -2.667') print('counter averages (test case)',counter_avgs, 'should be 3, 3.75, -0.75, -0.75') print('midpoints (test case)', midpoints, 'should be 0, 4.041 ish, -0.875, -1.708')
0
0
0
818bf3509597a12f4d23f992682047ce4d0bec6f
7,334
py
Python
scripts/git_remotes_setting.py
lonsty/gitclk
df70bee793225905053066d3b71380908e883a58
[ "MIT" ]
null
null
null
scripts/git_remotes_setting.py
lonsty/gitclk
df70bee793225905053066d3b71380908e883a58
[ "MIT" ]
null
null
null
scripts/git_remotes_setting.py
lonsty/gitclk
df70bee793225905053066d3b71380908e883a58
[ "MIT" ]
null
null
null
#! /usr/bin/python3 # @Author: allen # @Date: Nov 29 11:07 2019 import configparser import json import locale import os import re import sys from collections import OrderedDict import click from dialog import Dialog __author__ = 'Allen Shaw' __version__ = '0.1.1' CONFIG = os.path.expanduser('~/.config/gitclk/config/config.json') TEMPERATE_CONFIG = os.path.expanduser('~/.config/gitclk/config/temperate.json') @click.group(help='Git remotes setting.') @click.command('config', help='Configure the git platforms.') @click.option('-e', '--edit', 'edit', is_flag=True, default=False, help='Edit the config file.') @click.command('set', help='Set remotes setting to git config.') @click.option('-a', '--all', 'set_all', is_flag=True, default=False, show_default=True, help='Set all remotes include ignored.') @click.option('-n', '--repository-name', 'repo', required=True, help='The repository name.') cli.add_command(config) cli.add_command(set_remotes) if __name__ == '__main__': GIT_CONFIG = check_repository() if GIT_CONFIG is False: click.echo('fatal: not in a git directory') sys.exit(1) cli()
35.95098
108
0.593128
#! /usr/bin/python3 # @Author: allen # @Date: Nov 29 11:07 2019 import configparser import json import locale import os import re import sys from collections import OrderedDict import click from dialog import Dialog __author__ = 'Allen Shaw' __version__ = '0.1.1' CONFIG = os.path.expanduser('~/.config/gitclk/config/config.json') TEMPERATE_CONFIG = os.path.expanduser('~/.config/gitclk/config/temperate.json') def load_settings(file): with open(file, 'r') as f: git_platforms = json.loads(f.read()) return git_platforms def save_settings(file, config): with open(file, 'w') as f: f.write(json.dumps(config, ensure_ascii=False, indent=4)) def check_repository(): dirs = os.getcwd().split(r'/') for i in range(len(dirs), 0, -1): repo = f"{'/'.join(dirs[:i])}/.git" if os.path.isdir(repo): return os.path.join(repo, 'config') return False def set_config(): git_platforms = load_settings(CONFIG) all_platforms = git_platforms.get('platforms') try: locale.setlocale(locale.LC_ALL, '') except Exception: pass d = Dialog(dialog="dialog") platforms_to_enable = [(p, '', all_platforms.get(p).get('enabled')) for p in all_platforms.keys()] code, enabled_plats = d.checklist("Git platforms to use ...", choices=platforms_to_enable, title="Enable Git Platforms", height=20, width=75, list_height=15) if code != d.OK: return proxies_to_disabled = [(p, '', all_platforms.get(p).get('prefer_ssh')) for p in enabled_plats] code, ssh_plats = d.checklist("Platforms to use SSH ...", choices=proxies_to_disabled, title="Select Platforms Use SSH", height=20, width=75, list_height=15) if code != d.OK: return enabled_to_ignore = [(p, '', all_platforms.get(p).get('reset_ignored')) for p in enabled_plats] code, ignored_plats = d.checklist("Platforms to ignore when reset ...", choices=enabled_to_ignore, title="Select Ignore Platforms", height=20, width=75, list_height=15) if code != d.OK: return proxies_to_disabled = [(p, '', all_platforms.get(p).get('no_proxy')) for p in enabled_plats] code, noproxy_plats = d.checklist("Platforms do not require proxy ...", choices=proxies_to_disabled, title="Select no-proxy Platforms", height=20, width=75, list_height=15) if code != d.OK: return enabled_to_default = [(p, '', p == git_platforms.get('default_plat')) for p in enabled_plats] code, default_palt = d.radiolist("Default platforms ...", choices=enabled_to_default, title="Set Default Platform", height=20, width=75, list_height=15) if code != d.OK: return git_platforms['default_plat'] = default_palt for p in all_platforms: git_platforms['platforms'][p]['prefer_ssh'] = True if p in ssh_plats else False git_platforms['platforms'][p]['enabled'] = True if p in enabled_plats else False git_platforms['platforms'][p]['reset_ignored'] = True if p in ignored_plats else False git_platforms['platforms'][p]['no_proxy'] = True if p in noproxy_plats else False save_settings(CONFIG, git_platforms) with open(GIT_CONFIG) as f: config = f.read() find_url = re.search(r'url\s*=\s*.*?\n', config) url = find_url.group() if find_url else '' find_repo = re.search(r'(?<=(/))[\w-]*?(?=(.git\n|\n))', url) ori_repo = find_repo.group() if find_repo else '' code, repo = d.inputbox('Enter a repository ...\n\nThen click <OK> to apply changes, <Cancel> to exit.', init=ori_repo, height=20, width=75) if (code == d.OK) and repo: set_remotes_config(False, repo) def set_remotes_config(set_all, repository): git_platforms = load_settings(CONFIG) platforms = git_platforms.get('platforms') default_plat = git_platforms.get('default_plat') sections_ignored = [f'remote "{p}"' for p in platforms if platforms.get(p).get('reset_ignored') is True] remotes = { f'remote "{p}"': { 'url': platforms.get(p).get('ssh' if platforms.get(p).get('prefer_ssh') else 'http') \ .format(user=platforms.get(p).get('user'), repo=repository), 'fetch': '+refs/heads/*:refs/remotes/{remote_name}/*'.format(remote_name=p) } for p in [p for p in platforms if platforms[p].get('enabled') is True] } # set no proxy for p in [p for p in platforms if platforms[p].get('enabled') is True]: if platforms[p].get('no_proxy') is True: remotes[f'remote "{p}"']['proxy'] = '""' remotes['remote "origin"'] = { 'url': platforms.get(default_plat).get('ssh' if platforms.get(p).get('prefer_ssh') else 'http') \ .format(user=platforms.get(default_plat).get('user'), repo=repository), 'fetch': '+refs/heads/*:refs/remotes/origin/*' } ord_remotes = OrderedDict(sorted(remotes.items())) git_config_temperate = OrderedDict(sorted(load_settings(TEMPERATE_CONFIG).items())) git_config_temperate.update(ord_remotes) config = configparser.ConfigParser() config.read(GIT_CONFIG) if set_all is not True: for section in sections_ignored: try: for k, v in config[section].items(): git_config_temperate[section][k] = v except KeyError: pass for section in config.sections(): config.remove_section(section) for section, kvs in git_config_temperate.items(): for k, v in kvs.items(): try: config.set(section, '\t' + k.strip(), v) except configparser.NoSectionError: config.add_section(section) config.set(section, '\t' + k.strip(), v) with open(GIT_CONFIG, 'w') as cf: config.write(cf) @click.group(help='Git remotes setting.') def cli(): ... @click.command('config', help='Configure the git platforms.') @click.option('-e', '--edit', 'edit', is_flag=True, default=False, help='Edit the config file.') def config(edit): if edit is True: os.system(f'vi {CONFIG}') sys.exit(0) set_config() @click.command('set', help='Set remotes setting to git config.') @click.option('-a', '--all', 'set_all', is_flag=True, default=False, show_default=True, help='Set all remotes include ignored.') @click.option('-n', '--repository-name', 'repo', required=True, help='The repository name.') def set_remotes(set_all, repo): set_remotes_config(set_all, repo) cli.add_command(config) cli.add_command(set_remotes) if __name__ == '__main__': GIT_CONFIG = check_repository() if GIT_CONFIG is False: click.echo('fatal: not in a git directory') sys.exit(1) cli()
5,997
0
181
670abde2985288602ad77426b29b42b8ec93d122
7,279
py
Python
python3/test/test_validators.py
zhudanfei/json-schema-dsl
26323e8440a404610998a67912ecefb243bf788c
[ "MIT" ]
null
null
null
python3/test/test_validators.py
zhudanfei/json-schema-dsl
26323e8440a404610998a67912ecefb243bf788c
[ "MIT" ]
null
null
null
python3/test/test_validators.py
zhudanfei/json-schema-dsl
26323e8440a404610998a67912ecefb243bf788c
[ "MIT" ]
null
null
null
import unittest from src import validators if __name__ == '__main__': unittest.main()
27.996154
69
0.588955
import unittest from src import validators class TestNotNull(unittest.TestCase): def test_none(self): try: validators.NotNull(None, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: Cannot be null', ex.args[0]) def test_not_none(self): value = {'user': 11} actual = validators.NotNull(value, []) self.assertEqual(value, actual) class TestNotEmpty(unittest.TestCase): def test_none(self): try: validators.NotEmpty(None, []) self.assertTrue(False) except ValueError as ex: self.assertEqual('Cannot be null', ex.args[0]) def test_empty(self): try: validators.NotEmpty('', ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: Cannot be empty', ex.args[0]) def test_not_empty(self): value = 'abc' actual = validators.NotEmpty(value, []) self.assertEqual(value, actual) class TestMaxLength(unittest.TestCase): def test_none(self): actual = validators.MaxLength(4)(None, []) self.assertIsNone(actual) def test_not_too_long(self): value = 'abcd' actual = validators.MaxLength(4)(value, []) self.assertEqual(value, actual) def test_too_long(self): value = '12345' try: validators.MaxLength(4)(value, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: String is too long', ex.args[0]) class TestMinLength(unittest.TestCase): def test_none(self): actual = validators.MinLength(5)(None, []) self.assertIsNone(actual) def test_not_too_short(self): value = '12345' actual = validators.MinLength(5)(value, []) self.assertEqual(value, actual) def test_too_short(self): value = 'abcd' try: validators.MinLength(5)(value, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: String is too short', ex.args[0]) class TestLengthRange(unittest.TestCase): def test_none(self): actual = validators.LengthRange(4, 5)(None, []) self.assertIsNone(actual) def test_in_range(self): value = 'abcd' actual = validators.LengthRange(4, 5)(value, []) self.assertEqual(value, actual) def test_too_long(self): value = '123456' try: validators.LengthRange(4, 5)(value, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: String is too long', ex.args[0]) def test_too_short(self): value = 'abc' try: validators.LengthRange(4, 5)(value, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: String is too short', ex.args[0]) class TestOnly(unittest.TestCase): def test_none(self): actual = validators.Only('user', 'node')(None, []) self.assertIsNone(actual) def test_in_set(self): value = 'user' actual = validators.Only('user', 'node')(value, []) self.assertEqual(value, actual) def test_not_in_set(self): value = 'abcd' try: validators.Only('user', 'node')(value, ['root']) self.assertTrue(False) except ValueError as ex: self.assertEqual('root: Invalid value', ex.args[0]) class TestMinimum(unittest.TestCase): def test_none(self): actual = validators.Minimum(4)(None, []) self.assertIsNone(actual) def test_in_range(self): value = 4.5 actual = validators.Minimum(4)(value, []) self.assertEqual(value, actual) def test_too_small(self): value = 3.99 try: validators.Minimum(4)(value, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: Value is too small', ex.args[0]) class TestExclusiveMinimum(unittest.TestCase): def test_none(self): actual = validators.ExclusiveMinimum(4)(None, []) self.assertIsNone(actual) def test_in_range(self): value = 4.5 actual = validators.ExclusiveMinimum(4)(value, []) self.assertEqual(value, actual) def test_too_small(self): value = 4 try: validators.ExclusiveMinimum(4)(value, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: Value is too small', ex.args[0]) class TestMaximum(unittest.TestCase): def test_none(self): actual = validators.Maximum(5.3)(None, []) self.assertIsNone(actual) def test_in_range(self): value = 4.5 actual = validators.Maximum(5.3)(value, []) self.assertEqual(value, actual) def test_too_big(self): value = 5.301 try: validators.Maximum(5.3)(value, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: Value is too large', ex.args[0]) class TestExclusiveMaximum(unittest.TestCase): def test_none(self): actual = validators.ExclusiveMaximum(5.3)(None, []) self.assertIsNone(actual) def test_in_range(self): value = 4.5 actual = validators.ExclusiveMaximum(5.3)(value, []) self.assertEqual(value, actual) def test_too_big(self): value = 5.3 try: validators.ExclusiveMaximum(5.3)(value, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: Value is too large', ex.args[0]) class TestRange(unittest.TestCase): def test_none(self): actual = validators.Range(4, 5.3)(None, []) self.assertIsNone(actual) def test_in_range(self): value = 4.5 actual = validators.Range(4, 5.3)(value, []) self.assertEqual(value, actual) def test_too_big(self): value = 6.1 try: validators.Range(4, 5.3)(value, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: Value is too large', ex.args[0]) def test_too_small(self): value = 3 try: validators.Range(4, 5.3)(value, ['node']) self.assertTrue(False) except ValueError as ex: self.assertEqual('node: Value is too small', ex.args[0]) class TestPattern(unittest.TestCase): def test_none(self): actual = validators.Pattern('^[a-zA-Z0-9]{4}$')(None, []) self.assertIsNone(actual) def test_pattern_match(self): value = 'user' actual = validators.Pattern('^[a-zA-Z0-9]{4}$')(value, []) self.assertEqual(value, actual) def test_not_in_set(self): value = 'abcde' try: validators.Pattern('^[a-zA-Z0-9]{4}$')(value, ['root']) self.assertTrue(False) except ValueError as ex: self.assertEqual('root: Pattern not match', ex.args[0]) if __name__ == '__main__': unittest.main()
5,686
214
1,275
84062c4e1a1979d6f1ecbac6fa43902d87783cf9
1,635
py
Python
tvsched/application/exceptions/schedule.py
astsu-dev/tv-schedule
1cea36147e66b7163df6f7098cfda4d43f3bdde2
[ "MIT" ]
null
null
null
tvsched/application/exceptions/schedule.py
astsu-dev/tv-schedule
1cea36147e66b7163df6f7098cfda4d43f3bdde2
[ "MIT" ]
null
null
null
tvsched/application/exceptions/schedule.py
astsu-dev/tv-schedule
1cea36147e66b7163df6f7098cfda4d43f3bdde2
[ "MIT" ]
null
null
null
from tvsched.application.models.schedule import EpisodeInSchedule, ShowInSchedule class ShowAlreadyExistsInScheduleError(Exception): """Will be raised when trying to add already existed in schedule show to schedule""" @property class ShowOrScheduleNotFoundError(Exception): """Will be raised when trying to add not existed show to schedule or show to not existed schedule """ @property class EpisodeOrScheduleNotFoundError(Exception): """Will be raised when trying to add not existed episode to schedule or episode to not existed schedule """ @property class EpisodeAlreadyMarkedAsWatchedError(Exception): """Will be raised when trying to mark as watched already marked episode in schedule. """ @property
31.442308
88
0.744954
from tvsched.application.models.schedule import EpisodeInSchedule, ShowInSchedule class ShowAlreadyExistsInScheduleError(Exception): """Will be raised when trying to add already existed in schedule show to schedule""" def __init__(self, show_in_schedule: ShowInSchedule) -> None: self._show_in_schedule = show_in_schedule @property def show_in_schedule(self) -> ShowInSchedule: return self._show_in_schedule class ShowOrScheduleNotFoundError(Exception): """Will be raised when trying to add not existed show to schedule or show to not existed schedule """ def __init__(self, show_in_schedule: ShowInSchedule) -> None: self._show_in_schedule = show_in_schedule @property def show_in_schedule(self) -> ShowInSchedule: return self._show_in_schedule class EpisodeOrScheduleNotFoundError(Exception): """Will be raised when trying to add not existed episode to schedule or episode to not existed schedule """ def __init__(self, episode_in_schedule: EpisodeInSchedule) -> None: self._episode_in_schedule = episode_in_schedule @property def episode_in_schedule(self) -> EpisodeInSchedule: return self._episode_in_schedule class EpisodeAlreadyMarkedAsWatchedError(Exception): """Will be raised when trying to mark as watched already marked episode in schedule. """ def __init__(self, episode_in_schedule: EpisodeInSchedule) -> None: self._episode_in_schedule = episode_in_schedule @property def episode_in_schedule(self) -> EpisodeInSchedule: return self._episode_in_schedule
650
0
212
e870b60975769c596ce90fae883ceded04583fdc
374
py
Python
tests/unit/backend/corpora/api_server/test_version.py
BuildJet/single-cell-data-portal
080ad03f4745d59ade75c3480149e83bb76cf39b
[ "MIT" ]
16
2020-05-12T23:25:51.000Z
2021-06-17T12:04:13.000Z
tests/unit/backend/corpora/api_server/test_version.py
BuildJet/single-cell-data-portal
080ad03f4745d59ade75c3480149e83bb76cf39b
[ "MIT" ]
943
2020-05-11T18:03:59.000Z
2021-08-18T21:57:51.000Z
tests/unit/backend/corpora/api_server/test_version.py
BuildJet/single-cell-data-portal
080ad03f4745d59ade75c3480149e83bb76cf39b
[ "MIT" ]
2
2020-12-19T10:04:24.000Z
2021-06-19T12:38:23.000Z
import os from mock import patch import json from tests.unit.backend.corpora.api_server.base_api_test import BaseAuthAPITest
28.769231
79
0.73262
import os from mock import patch import json from tests.unit.backend.corpora.api_server.base_api_test import BaseAuthAPITest class TestVersion(BaseAuthAPITest): @patch.dict(os.environ, {"COMMIT_SHA": "test"}) def test_get(self): response = self.app.get("/dp/v1/deployed_version") self.assertEqual("test", json.loads(response.data)["Data Portal"])
132
92
23
8063e17fbc18f29efe1957e1f96a7741bb9bc633
360
py
Python
idprovider/models.py
acdh-oeaw/gtrans
6f56b1d09de0cad503273bf8a01cd81e25220524
[ "MIT" ]
1
2020-03-15T16:14:02.000Z
2020-03-15T16:14:02.000Z
idprovider/models.py
acdh-oeaw/gtrans
6f56b1d09de0cad503273bf8a01cd81e25220524
[ "MIT" ]
14
2018-11-09T08:34:23.000Z
2022-02-10T08:15:53.000Z
idprovider/models.py
acdh-oeaw/gtrans
6f56b1d09de0cad503273bf8a01cd81e25220524
[ "MIT" ]
null
null
null
from django.db import models
24
56
0.669444
from django.db import models class IdProvider(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) checked = models.BooleanField( verbose_name="checked", help_text="Check if everything is ok", default=False ) class Meta: ordering = ('id', )
0
307
23
8823920343f8d62db6c24a665dd5433c43476792
4,498
py
Python
pytilemap/maplegenditem.py
allebacco/PyTileMap
3e83b11b5e023d7ac0f14dd50515250dd020547e
[ "MIT" ]
6
2018-06-13T00:41:05.000Z
2020-10-12T19:48:24.000Z
pytilemap/maplegenditem.py
allebacco/PyTileMap
3e83b11b5e023d7ac0f14dd50515250dd020547e
[ "MIT" ]
1
2017-10-15T20:05:29.000Z
2017-11-20T16:04:17.000Z
pytilemap/maplegenditem.py
allebacco/PyTileMap
3e83b11b5e023d7ac0f14dd50515250dd020547e
[ "MIT" ]
5
2016-04-21T11:59:20.000Z
2020-07-16T03:45:30.000Z
from __future__ import print_function, absolute_import from qtpy.QtCore import Qt, Slot, QRectF, QPointF from qtpy.QtGui import QPen, QBrush, QColor from qtpy.QtWidgets import QGraphicsObject, QGraphicsRectItem, QGraphicsItemGroup, \ QGraphicsSimpleTextItem, QGraphicsEllipseItem, QGraphicsLineItem from .mapitems import MapItem from .functions import makePen, makeBrush from .qtsupport import getQVariantValue
29.592105
84
0.63695
from __future__ import print_function, absolute_import from qtpy.QtCore import Qt, Slot, QRectF, QPointF from qtpy.QtGui import QPen, QBrush, QColor from qtpy.QtWidgets import QGraphicsObject, QGraphicsRectItem, QGraphicsItemGroup, \ QGraphicsSimpleTextItem, QGraphicsEllipseItem, QGraphicsLineItem from .mapitems import MapItem from .functions import makePen, makeBrush from .qtsupport import getQVariantValue class MapLegendEntryItem(QGraphicsItemGroup): def __init__(self, shape, text, parent=None): QGraphicsItemGroup.__init__(self, parent=parent) text = QGraphicsSimpleTextItem(text, parent=shape) br = shape.boundingRect() x = br.right() + 10 y = br.top() + 3 text.setPos(x, y) self.addToGroup(shape) self._text = text def top(self): return self.boundingRect().top() def bottom(self): return self.boundingRect().bottom() def right(self): return self.boundingRect().right() def left(self): return self.boundingRect().left() def text(self): return self._text class MapLegendItem(QGraphicsObject, MapItem): QtParentClass = QGraphicsObject def __init__(self, pos=None, parent=None): QGraphicsObject.__init__(self, parent=parent) MapItem.__init__(self) self.setZValue(200.0) self._anchorPos = QPointF(pos) if pos is not None else QPointF(10.0, 10.0) self._border = QGraphicsRectItem(parent=self) self._border.setPen(QPen(Qt.NoPen)) self._border.setBrush(QBrush(QColor(190, 190, 190, 160))) self._entries = list() self._entriesGroup = QGraphicsItemGroup(parent=self) def _sceneChanged(self, oldScene, newScene): if oldScene is not None: oldScene.sceneRectChanged.disconnect(self.setSceneRect) if newScene is not None: newScene.sceneRectChanged.connect(self.setSceneRect) # Setup the new position of the item self.setSceneRect(newScene.sceneRect()) def updatePosition(self, scene): pass def addPoint(self, text, color, border=None, size=20.0): shape = QGraphicsEllipseItem(size / 2.0, size / 2.0, size, size) brush = makeBrush(color) shape.setBrush(brush) shape.setPen(makePen(border)) self.addEntry(MapLegendEntryItem(shape, text)) def addRect(self, text, color, border=None, size=20.0): shape = QGraphicsRectItem(size / 2.0, size / 2.0, size, size) brush = makeBrush(color) shape.setBrush(brush) shape.setPen(makePen(border)) self.addEntry(MapLegendEntryItem(shape, text)) def addLine(self, text, color, width=1.): shape = QGraphicsLineItem(10., 10., 20., 20.) pen = makePen(color, width=width) shape.setPen(pen) self.addEntry(MapLegendEntryItem(shape, text)) def addEntry(self, entry): self._entries.append(entry) self._entriesGroup.addToGroup(entry) self._updateLayout() def boundingRect(self): return self._border.boundingRect() def paint(*args, **kwargs): pass @Slot(QRectF) def setSceneRect(self, rect): self.setPos(rect.topLeft() + self._anchorPos) def _updateLayout(self): self.prepareGeometryChange() bottom = 0.0 left = 0.0 right = 0.0 for entry in self._entries: entry.setPos(left, bottom) bottom += entry.bottom() + 5.0 right = max(right, entry.right() + 5.0) self._border.setRect(0.0, 0.0, right, bottom + 5.0) def pen(self): """Pen for the background of the legend Returns: QPen: Pen for the background of the legend """ return self._border.pen() def brush(self): """Brush for the background of the legend Returns: QBrush: Brush for the background of the legend """ return self._border.brush() def setPen(self, *args, **kwargs): """Set the pen for the background of the legend The arguments are the same of the :func:`makePen` function """ return self._border.setPen(makePen(*args, **kwargs)) def setBrush(self, *args, **kwargs): """Set the brush for the background of the legend The arguments are the same of the :func:`makeBrush` function """ return self._border.setBrush(makeBrush(*args, **kwargs))
2,601
1,269
208
861affe4f349d0e3e1a09843566f499469ee4d61
139,634
py
Python
src/genie/libs/parser/iosxe/show_lisp.py
mirzawaqasahmed/genieparser
d6ce6f0cfd31aa6b0eef042f184e273e48b9d4d7
[ "Apache-2.0" ]
2
2021-01-27T03:37:39.000Z
2021-01-27T03:40:50.000Z
src/genie/libs/parser/iosxe/show_lisp.py
mirzawaqasahmed/genieparser
d6ce6f0cfd31aa6b0eef042f184e273e48b9d4d7
[ "Apache-2.0" ]
null
null
null
src/genie/libs/parser/iosxe/show_lisp.py
mirzawaqasahmed/genieparser
d6ce6f0cfd31aa6b0eef042f184e273e48b9d4d7
[ "Apache-2.0" ]
null
null
null
''' show_lisp.py IOSXE parsers for the following show commands: * show lisp session * show lisp platform * show lisp all extranet <extranet> instance-id <instance_id> * show lisp all instance-id <instance_id> dynamic-eid detail * show lisp all service ipv4 * show lisp all service ipv6 * show lisp all service ethernet * show lisp all instance-id <instance_id> ipv4 * show lisp all instance-id <instance_id> ipv6 * show lisp all instance-id <instance_id> ethernet * show lisp all instance-id <instance_id> ipv4 map-cache * show lisp all instance-id <instance_id> ipv6 map-cache * show lisp all instance-id <instance_id> ethernet map-cache * show lisp all instance-id <instance_id> ipv4 server rloc members * show lisp all instance-id <instance_id> ipv6 server rloc members * show lisp all instance-id <instance_id> ethernet server rloc members * show lisp all instance-id <instance_id> ipv4 smr * show lisp all instance-id <instance_id> ipv6 smr * show lisp all instance-id <instance_id> ethernet smr * show lisp all service ipv4 summary * show lisp all service ipv6 summary * show lisp all service ethernet summary * show lisp all instance-id <instance_id> ipv4 database * show lisp all instance-id <instance_id> ipv6 database * show lisp all instance-id <instance_id> ethernet database * show lisp all instance-id <instance_id> ipv4 server summary * show lisp all instance-id <instance_id> ipv6 server summary * show lisp all instance-id <instance_id> ethernet server summary * show lisp all instance-id <instance_id> ipv4 server detail internal * show lisp all instance-id <instance_id> ipv6 server detail internal * show lisp all instance-id <instance_id> ethernet server detail internal * show lisp all instance-id <instance_id> ipv4 statistics * show lisp all instance-id <instance_id> ipv6 statistics * show lisp all instance-id <instance_id> ethernet statistics ''' # Python import re # Metaparser from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Schema, Any, Or, Optional from genie.libs.parser.utils.common import Common # ============================== # Schema for 'show lisp session' # ============================== class ShowLispSessionSchema(MetaParser): ''' Schema for "show lisp session" ''' schema = { 'vrf': {Any(): {'sessions': {'total': int, 'established': int, 'peers': {Any(): {'state': str, 'time': str, 'total_in': int, 'total_out': int, 'users': int, }, }, }, }, }, } # ============================== # Parser for 'show lisp session' # ============================== class ShowLispSession(ShowLispSessionSchema): ''' Parser for "show lisp session"''' cli_command = 'show lisp session' exclude = ['time'] # =============================== # Schema for 'show lisp platform' # =============================== class ShowLispPlatformSchema(MetaParser): ''' Schema for "show lisp platform" ''' schema = { 'parallel_lisp_instance_limit': int, 'rloc_forwarding_support': {'local': {'ipv4': str, 'ipv6': str, 'mac': str, }, 'remote': {'ipv4': str, 'ipv6': str, 'mac': str, }, }, 'latest_supported_config_style': str, 'current_config_style': str, } # ============================== # Parser for 'show lisp platform' # ============================== class ShowLispPlatform(ShowLispPlatformSchema): ''' Parser for "show lisp platform" ''' cli_command = 'show lisp platform' # ======================================================================== # Schema for 'show lisp all extranet <extranet> instance-id <instance_id>' # ======================================================================== class ShowLispExtranetSchema(MetaParser): ''' Schema for "show lisp all extranet <extranet> instance-id <instance_id>"''' schema = { 'lisp_router_instances': {Any(): {Optional('service'): {Any(): {Optional('map_server'): {Optional('virtual_network_ids'): {'total_extranet_entries': int, Any(): {'vni': str, 'extranets': {Any(): {'extranet': str, 'home_instance_id': int, Optional('provider'): {Any(): {'eid_record': str, 'bidirectional': bool, }, }, Optional('subscriber'): {Any(): {'eid_record': str, 'bidirectional': bool, }, }, }, }, }, }, }, }, }, }, }, } # ======================================================================== # Parser for 'show lisp all extranet <extranet> instance-id <instance_id>' # ======================================================================== class ShowLispExtranet(ShowLispExtranetSchema): ''' Parser for "show lisp all extranet <extranet> instance-id <instance_id>"''' cli_command = 'show lisp all extranet {extranet} instance-id {instance_id}' # ======================================================================= # Schema for 'show lisp all instance-id <instance_id> dynamic-eid detail' # ======================================================================= class ShowLispDynamicEidDetailSchema(MetaParser): ''' Schema for "show lisp all instance-id <instance_id> dynamic-eid detail" ''' schema = { 'lisp_router_instances': {Any(): {Optional('service'): {Any(): {'etr': {'local_eids': {Any(): {'dynamic_eids': {Any(): {'dynamic_eid_name': str, 'id': str, 'rlocs': str, Optional('registering_more_specific'): bool, Optional('loopback_address'): str, Optional('priority'): int, Optional('weight'): int, Optional('record_ttl'): int, Optional('site_based_multicast_map_notify_group'): str, Optional('proxy_reply'): bool, Optional('registration_interval'): int, Optional('global_map_server'): bool, Optional('num_of_roaming_dynamic_eid'): int, Optional('mapping_servers'): {Any(): {Optional('proxy_reply'): bool, }, }, Optional('last_dynamic_eid'): {Any(): {'last_dynamic_eid_discovery_elaps_time': str, 'eids': {Any(): {'interface': str, 'uptime': str, 'last_activity': str, 'discovered_by': str, }, }, }, }, Optional('eid_address'): {Optional('address_type'): str, Optional('virtual_network_id'): str, }, }, }, }, }, }, }, }, }, }, } # ======================================================================= # Parser for 'show lisp all instance-id <instance_id> dynamic-eid detail' # ======================================================================= class ShowLispDynamicEidDetail(ShowLispDynamicEidDetailSchema): ''' Parser for "show lisp all instance-id <instance_id> dynamic-eid detail"''' cli_command = 'show lisp all instance-id {instance_id} dynamic-eid detail' # ============================================================== # Schema for 'show lisp all instance-id <instance_id> <service>' # ============================================================== class ShowLispServiceSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service>" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, Optional('lisp_router_id'): {'site_id': str, 'xtr_id': str, }, Optional('service'): {Any(): {'service': str, 'delegated_database_tree': bool, 'locator_table': str, 'mobility_first_hop_router': bool, 'nat_traversal_router': bool, 'instance_id': {Any(): {Optional('eid_table'): str, Optional('site_registration_limit'): int, Optional('map_request_source'): str, 'database': {Optional('dynamic_database_limit'): int, Optional('dynamic_database_size'): int, Optional('inactive_deconfig_away_size'): int, Optional('route_import_database_limit'): int, Optional('route_import_database_size'): int, Optional('static_database_size'): int, Optional('static_database_limit'): int, Optional('total_database_mapping_size'): int, Optional('dynamic_database_mapping_limit'): int, Optional('import_site_db_size'): int, Optional('import_site_db_limit'): int, Optional('proxy_db_size'): int, }, Optional('mapping_servers'): {Any(): {'ms_address': str, Optional('uptime'): str, }, }, 'itr': {'local_rloc_last_resort': str, Optional('use_proxy_etr_rloc'): str, }, Optional('map_cache'): {Optional('imported_route_count'): int, Optional('imported_route_limit'): int, Optional('map_cache_size'): int, Optional('persistent_map_cache'): bool, Optional('static_mappings_configured'): int, }, }, }, 'etr': {'enabled': bool, Optional('encapsulation'): str, 'proxy_etr_router': bool, 'accept_mapping_data': str, 'map_cache_ttl': str, Optional('use_petrs'): {Any(): {'use_petr': str, }, }, Optional('mapping_servers'): {Any(): {'ms_address': str, Optional('uptime'): str, }, }, }, 'itr': {'enabled': bool, 'proxy_itr_router': bool, Optional('proxy_itrs'): {Any(): {'proxy_etr_address': str, }, }, 'solicit_map_request': str, 'max_smr_per_map_cache_entry': str, 'multiple_smr_suppression_time': int, Optional('map_resolvers'): {Any(): {'map_resolver': str, }, }, }, 'locator_status_algorithms': {'rloc_probe_algorithm': bool, 'rloc_probe_on_route_change': str, 'rloc_probe_on_member_change': bool, 'lsb_reports': str, 'ipv4_rloc_min_mask_len': int, 'ipv6_rloc_min_mask_len': int, }, 'map_cache': {'map_cache_activity_check_period': int, Optional('map_cache_fib_updates'): str, 'map_cache_limit': int, }, 'map_server': {'enabled': bool, }, 'map_resolver': {'enabled': bool, }, Optional('source_locator_configuration'): {'vlans': {Any(): {'address': str, 'interface': str, }, }, }, }, }, }, }, } # ============================================================== # Parser for 'show lisp all instance-id <instance_id> <service>' # ============================================================== class ShowLispService(ShowLispServiceSchema): '''Parser for "show lisp all instance-id <instance_id> <service>"''' cli_command = ['show lisp all instance-id {instance_id} {service}','show lisp all service {service}'] # ======================================================================== # Schema for 'show lisp all instance-id <instance_id> <service> map-cache' # ======================================================================== class ShowLispServiceMapCacheSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> map-cache" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, Optional('service'): {Any(): {'service': str, 'itr': {'map_cache': {Any(): {'vni': str, 'entries': int, 'mappings': {Any(): {'id': str, 'creation_time': str, 'time_to_live': str, 'via': str, 'eid': {'address_type': str, 'vrf': str, Optional('ipv4'): {'ipv4': str, }, Optional('ipv4_prefix'): {'ipv4_prefix': str, }, Optional('ipv6'): {'ipv6': str, }, Optional('ipv6_prefix'): {'ipv6_prefix': str, }, }, Optional('negative_mapping'): {'map_reply_action': str, }, Optional('positive_mapping'): {'rlocs': {Any(): {'id': str, 'uptime': str, 'state': str, 'priority': int, 'weight': int, Optional('encap_iid'): str, 'locator_address': {'address_type': str, 'virtual_network_id': str, Optional('ipv4'): {'ipv4': str, }, Optional('ipv4_prefix'): {'ipv4_prefix': str, }, Optional('ipv6'): {'ipv6': str, }, Optional('ipv6_prefix'): {'ipv6_prefix': str, }, }, }, }, }, }, }, }, }, }, }, }, }, }, } # ======================================================================== # Parser for 'show lisp all instance-id <instance_id> <service> map-cache' # ======================================================================== class ShowLispServiceMapCache(ShowLispServiceMapCacheSchema): '''Parser for "show lisp all instance-id <instance_id> <service> map-cache"''' cli_command = 'show lisp all instance-id {instance_id} {service} map-cache' exclude = ['creation_time'] # =========================================================================== # Schema for 'show lisp all instance-id <instance_id> <service> rloc members' # =========================================================================== class ShowLispServiceRlocMembersSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> rloc members" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, Optional('service'): {Optional(Any()): {'instance_id': {Any(): {Optional('rloc'): {'total_entries': int, 'valid_entries': int, 'distribution': bool, 'members': {Any(): {'origin': str, 'valid': str, }, }, }, }, }, }, }, }, }, } # =========================================================================== # Parser for 'show lisp all instance-id <instance_id> <service> rloc members' # =========================================================================== class ShowLispServiceRlocMembers(ShowLispServiceRlocMembersSchema): '''Parser for "show lisp all instance-id <instance_id> <service> rloc members"''' cli_command = 'show lisp all instance-id {instance_id} service {service} rloc members' # ================================================================== # Schema for 'show lisp all instance-id <instance_id> <service> smr' # ================================================================== class ShowLispServiceSmrSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> smr" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, Optional('service'): {Optional(Any()): {'instance_id': {Any(): {Optional('smr'): {'vrf': str, 'entries': int, 'prefixes': {Any(): {'producer': str, }, }, }, }, }, }, }, }, }, } # ================================================================== # Parser for 'show lisp all instance-id <instance_id> <service> smr' # ================================================================== class ShowLispServiceSmr(ShowLispServiceSmrSchema): '''Parser for "show lisp all instance-id <instance_id> <service> smr"''' cli_command = 'show lisp all instance-id {instance_id} service {service} smr' # ==================================================== # Schema for 'show lisp all service <service> summary' # ==================================================== class ShowLispServiceSummarySchema(MetaParser): '''Schema for "show lisp all <service> summary" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, Optional('service'): {Optional(Any()): {Optional('virtual_network_ids'): {Any(): {Optional('vrf'): str, 'interface': str, 'db_size': int, 'db_no_route': int, 'cache_size': int, 'incomplete': str, 'cache_idle': str, 'lisp_role': {Any(): {'lisp_role_type': str, }, }, }, }, 'etr': {'summary': {'instance_count': int, 'total_eid_tables': int, 'total_db_entries': int, 'total_map_cache_entries': int, 'total_db_entries_inactive': int, 'eid_tables_inconsistent_locators': int, 'eid_tables_incomplete_map_cache_entries': int, 'eid_tables_pending_map_cache_update_to_fib': int, }, }, }, }, }, }, } # ==================================================== # Parser for 'show lisp all service <service> summary' # ==================================================== class ShowLispServiceSummary(ShowLispServiceSummarySchema): '''Parser for "show lisp all service <service> summary"''' cli_command = 'show lisp all service {service} summary' # ======================================================================= # Schema for 'show lisp all instance-id <instance_id> <service> dabatase' # ======================================================================= class ShowLispServiceDatabaseSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> dabatase" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, 'locator_sets': {Any(): {'locator_set_name': str, }, }, Optional('service'): {Optional(Any()): {'etr': {'local_eids': {Any(): {'vni': str, 'total_eid_entries': int, 'no_route_eid_entries': int, 'inactive_eid_entries': int, Optional('dynamic_eids'): {Any(): {'id': str, Optional('dynamic_eid'): str, 'eid_address': {'address_type': str, 'vrf': str, }, 'rlocs': str, 'loopback_address': str, 'priority': int, 'weight': int, 'source': str, 'state': str, }, }, Optional('eids'): {Any(): {'id': str, 'eid_address': {'address_type': str, 'vrf': str, }, 'rlocs': str, 'loopback_address': str, 'priority': int, 'weight': int, 'source': str, 'state': str, }, }, }, }, }, }, }, }, }, } # ======================================================================= # Parser for 'show lisp all instance-id <instance_id> <service> dabatase' # ======================================================================= class ShowLispServiceDatabase(ShowLispServiceDatabaseSchema): '''Parser for "show lisp all instance-id <instance_id> <service> dabatase"''' cli_command = 'show lisp all instance-id {instance_id} {service} database' # ============================================================================= # Schema for 'show lisp all instance-id <instance_id> <service> server summary' # ============================================================================= class ShowLispServiceServerSummarySchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> server summary" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, 'service': {Any(): {'instance_id': {Any(): {'map_server': {Optional('sites'): {Any(): {'site_id': str, 'configured': int, 'registered': int, 'inconsistent': int, }, }, 'summary': {'number_configured_sites': int, 'number_registered_sites':int, Optional('af_datum'): {Any(): {'address_type': str, Optional('number_configured_eids'): int, Optional('number_registered_eids'): int, }, }, 'sites_with_inconsistent_registrations': int, Optional('site_registration_limit'): int, Optional('site_registration_count'): int, }, }, }, }, }, }, }, }, } # ============================================================================= # Parser for 'show lisp all instance-id <instance_id> <service> server summary' # ============================================================================= class ShowLispServiceServerSummary(ShowLispServiceServerSummarySchema): '''Parser for "show lisp all instance-id <instance_id> <service> server summary"''' cli_command = 'show lisp all instance-id {instance_id} {service} server summary' # ===================================================================================== # Schema for 'show lisp all instance-id <instance_id> <service> server detail internal' # ===================================================================================== class ShowLispServiceServerDetailInternalSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> server detail internal" ''' schema = { 'lisp_router_instances': {Any(): {Optional('service'): {Any(): {'map_server': {'sites': {Any(): {'site_id': str, 'allowed_configured_locators': str, }, }, Optional('virtual_network_ids'): {Any(): {'vni': str, 'mappings': {Any(): {'eid_id': str, 'eid_address': {'address_type': str, 'virtual_network_id': str, Optional('ipv4'): {'ipv4': str, }, Optional('ipv6'): {'ipv6': str, }, Optional('ipv4_prefix'): {'ipv4_prefix': str, }, Optional('ipv6_prefix'): {'ipv6_prefix': str, }, }, 'site_id': str, 'first_registered': str, 'last_registered': str, 'routing_table_tag': int, 'origin': str, Optional('more_specifics_accepted'): bool, 'merge_active': bool, 'proxy_reply': bool, 'ttl': str, 'state': str, 'registration_errors': {'authentication_failures': int, 'allowed_locators_mismatch': int, }, Optional('mapping_records'): {Any(): {'xtr_id': str, 'site_id': str, 'etr': str, 'eid': {'address_type': str, 'virtual_network_id': str, Optional('ipv4'): {'ipv4': str, }, Optional('ipv6'): {'ipv6': str, }, Optional('ipv4_prefix'): {'ipv4_prefix': str, }, Optional('ipv6_prefix'): {'ipv6_prefix': str, }, }, 'ttl': str, 'time_to_live': int, 'creation_time': str, 'merge': bool, 'proxy_reply': bool, 'map_notify': bool, 'hash_function': str, 'nonce': str, 'state': str, 'security_capability': bool, 'sourced_by': str, 'locator': {Any(): {'local': bool, 'state': str, 'priority': int, 'weight': int, 'scope': str, }, }, }, }, }, }, }, }, }, }, }, }, }, } # ===================================================================================== # Parser for 'show lisp all instance-id <instance_id> <service> server detail internal' # ===================================================================================== class ShowLispServiceServerDetailInternal(ShowLispServiceServerDetailInternalSchema): '''Parser for "show lisp all instance-id <instance_id> <service> server detail internal"''' cli_command = 'show lisp all instance-id {instance_id} {service} server detail internal' # ========================================================================= # Schema for 'show lisp all instance-id <instance_id> <service> statistics' # ========================================================================= class ShowLispServiceStatisticsSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> statistics" ''' schema = { 'lisp_router_instances': {Any(): {'service': {Any(): {'statistics': {Any(): {'last_cleared': str, Any(): Any(), Optional('map_resolvers'): {Any(): {'last_reply': str, 'metric': str, 'reqs_sent': int, 'positive': int, 'negative': int, 'no_reply': int, }, }, }, }, }, }, }, }, } # ========================================================================= # Parser for 'show lisp all instance-id <instance_id> <service> statistics' # ========================================================================= class ShowLispServiceStatistics(ShowLispServiceStatisticsSchema): '''Parser for "show lisp all instance-id <instance_id> <service> statistics"''' cli_command = 'show lisp all instance-id {instance_id} {service} statistics' exclude = ['map_register_records_out']
42.990764
105
0.406513
''' show_lisp.py IOSXE parsers for the following show commands: * show lisp session * show lisp platform * show lisp all extranet <extranet> instance-id <instance_id> * show lisp all instance-id <instance_id> dynamic-eid detail * show lisp all service ipv4 * show lisp all service ipv6 * show lisp all service ethernet * show lisp all instance-id <instance_id> ipv4 * show lisp all instance-id <instance_id> ipv6 * show lisp all instance-id <instance_id> ethernet * show lisp all instance-id <instance_id> ipv4 map-cache * show lisp all instance-id <instance_id> ipv6 map-cache * show lisp all instance-id <instance_id> ethernet map-cache * show lisp all instance-id <instance_id> ipv4 server rloc members * show lisp all instance-id <instance_id> ipv6 server rloc members * show lisp all instance-id <instance_id> ethernet server rloc members * show lisp all instance-id <instance_id> ipv4 smr * show lisp all instance-id <instance_id> ipv6 smr * show lisp all instance-id <instance_id> ethernet smr * show lisp all service ipv4 summary * show lisp all service ipv6 summary * show lisp all service ethernet summary * show lisp all instance-id <instance_id> ipv4 database * show lisp all instance-id <instance_id> ipv6 database * show lisp all instance-id <instance_id> ethernet database * show lisp all instance-id <instance_id> ipv4 server summary * show lisp all instance-id <instance_id> ipv6 server summary * show lisp all instance-id <instance_id> ethernet server summary * show lisp all instance-id <instance_id> ipv4 server detail internal * show lisp all instance-id <instance_id> ipv6 server detail internal * show lisp all instance-id <instance_id> ethernet server detail internal * show lisp all instance-id <instance_id> ipv4 statistics * show lisp all instance-id <instance_id> ipv6 statistics * show lisp all instance-id <instance_id> ethernet statistics ''' # Python import re # Metaparser from genie.metaparser import MetaParser from genie.metaparser.util.schemaengine import Schema, Any, Or, Optional from genie.libs.parser.utils.common import Common # ============================== # Schema for 'show lisp session' # ============================== class ShowLispSessionSchema(MetaParser): ''' Schema for "show lisp session" ''' schema = { 'vrf': {Any(): {'sessions': {'total': int, 'established': int, 'peers': {Any(): {'state': str, 'time': str, 'total_in': int, 'total_out': int, 'users': int, }, }, }, }, }, } # ============================== # Parser for 'show lisp session' # ============================== class ShowLispSession(ShowLispSessionSchema): ''' Parser for "show lisp session"''' cli_command = 'show lisp session' exclude = ['time'] def cli(self, output=None): if output is None: out = self.device.execute(self.cli_command) else: out = output # Init vars parsed_dict = {} # Sessions for VRF default, total: 3, established: 3 p1 = re.compile(r'Sessions +for +VRF +(?P<vrf>\S+),' ' +total: +(?P<total>\d+),' ' +established: +(?P<established>\d+)$') # Peer State Up/Down In/Out Users # 10.16.2.2 Up 00:51:38 8/13 3 # 2001:DB8:B:2::2 Init never 0/0 1 p2 = re.compile(r'(?P<peer>\S+) +(?P<state>\S+) +(?P<time>\S+)' ' +(?P<in>\d+)\/(?P<out>\d+) +(?P<users>\d+)$') for line in out.splitlines(): line = line.strip() # Sessions for VRF default, total: 3, established: 3 m = p1.match(line) if m: group = m.groupdict() vrf = group['vrf'] vrf_dict = parsed_dict.setdefault('vrf', {}).\ setdefault(vrf, {}).setdefault('sessions', {}) vrf_dict['total'] = int(group['total']) vrf_dict['established'] = int(group['established']) continue # 10.1.8.8 Up 00:52:15 8/13 3 m = p2.match(line) if m: group = m.groupdict() peer = group['peer'] peer_dict = vrf_dict.setdefault('peers', {}).setdefault(peer, {}) peer_dict['state'] = group['state'].lower() peer_dict['time'] = group['time'] peer_dict['total_in'] = int(group['in']) peer_dict['total_out'] = int(group['out']) peer_dict['users'] = int(group['users']) continue return parsed_dict # =============================== # Schema for 'show lisp platform' # =============================== class ShowLispPlatformSchema(MetaParser): ''' Schema for "show lisp platform" ''' schema = { 'parallel_lisp_instance_limit': int, 'rloc_forwarding_support': {'local': {'ipv4': str, 'ipv6': str, 'mac': str, }, 'remote': {'ipv4': str, 'ipv6': str, 'mac': str, }, }, 'latest_supported_config_style': str, 'current_config_style': str, } # ============================== # Parser for 'show lisp platform' # ============================== class ShowLispPlatform(ShowLispPlatformSchema): ''' Parser for "show lisp platform" ''' cli_command = 'show lisp platform' def cli(self, output=None): if output is None: out = self.device.execute(self.cli_command) else: out = output # Init vars parsed_dict = {} # Parallel LISP instance limit: 2000 p1 = re.compile(r'Parallel +LISP +instance +limit: +(?P<limit>(\d+))$') # IPv4 RLOC, local: OK # IPv6 RLOC, local: OK # MAC RLOC, local: Unsupported p2 = re.compile(r'(?P<type>(IPv4|IPv6|MAC)) RLOC,' ' +local: +(?P<local>(\S+))$') # IPv4 RLOC, remote: OK # IPv6 RLOC, remote: OK # MAC RLOC, remote: Unsupported p3 = re.compile(r'(?P<type>(IPv4|IPv6|MAC)) RLOC,' ' +remote: +(?P<remote>(\S+))$') # Latest supported config style: Service and instance p4 = re.compile(r'Latest +supported +config +style:' ' +(?P<supported>([a-zA-Z\s]+))$') # Current config style: Service and instance p5 = re.compile(r'Current +config +style:' ' +(?P<current>([a-zA-Z\s]+))$') for line in out.splitlines(): line = line.strip() # Parallel LISP instance limit: 2000 m = p1.match(line) if m: parsed_dict['parallel_lisp_instance_limit'] = \ int(m.groupdict()['limit']) continue # IPv4 RLOC, local: OK # IPv6 RLOC, local: OK # MAC RLOC, local: Unsupported m = p2.match(line) if m: local_type = m.groupdict()['type'].lower() rloc_dict = parsed_dict.\ setdefault('rloc_forwarding_support', {}).\ setdefault('local', {}) rloc_dict[local_type] = m.groupdict()['local'].lower() continue # IPv4 RLOC, remote: OK # IPv6 RLOC, remote: OK # MAC RLOC, remote: Unsupported m = p3.match(line) if m: remote_type = m.groupdict()['type'].lower() rloc_dict = parsed_dict.\ setdefault('rloc_forwarding_support', {}).\ setdefault('remote', {}) rloc_dict[remote_type] = m.groupdict()['remote'].lower() continue # Latest supported config style: Service and instance m = p4.match(line) if m: parsed_dict['latest_supported_config_style'] = \ m.groupdict()['supported'].lower() continue # Current config style: Service and instance m = p5.match(line) if m: parsed_dict['current_config_style'] = \ m.groupdict()['current'].lower() continue return parsed_dict # ======================================================================== # Schema for 'show lisp all extranet <extranet> instance-id <instance_id>' # ======================================================================== class ShowLispExtranetSchema(MetaParser): ''' Schema for "show lisp all extranet <extranet> instance-id <instance_id>"''' schema = { 'lisp_router_instances': {Any(): {Optional('service'): {Any(): {Optional('map_server'): {Optional('virtual_network_ids'): {'total_extranet_entries': int, Any(): {'vni': str, 'extranets': {Any(): {'extranet': str, 'home_instance_id': int, Optional('provider'): {Any(): {'eid_record': str, 'bidirectional': bool, }, }, Optional('subscriber'): {Any(): {'eid_record': str, 'bidirectional': bool, }, }, }, }, }, }, }, }, }, }, }, } # ======================================================================== # Parser for 'show lisp all extranet <extranet> instance-id <instance_id>' # ======================================================================== class ShowLispExtranet(ShowLispExtranetSchema): ''' Parser for "show lisp all extranet <extranet> instance-id <instance_id>"''' cli_command = 'show lisp all extranet {extranet} instance-id {instance_id}' def cli(self, extranet, instance_id, output=None): if output is None: out = self.device.execute(self.cli_command.format(extranet=extranet,instance_id=instance_id)) else: out = output # Init vars parsed_dict = {} # Output for router lisp 0 p1 = re.compile(r'Output +for +router +lisp' ' +(?P<lisp_router_id>(\S+))$') # Home Instance ID: 103 p2 = re.compile(r'Home +Instance +ID *: +(?P<home_inst_id>(\d+))$') # Total entries: 6 p3 = re.compile(r'Total +entries *: +(?P<total_entries>(\d+))$') # Provider/Subscriber Inst ID EID prefix # Provider 103 10.121.88.0/24 # Subscriber 101 192.168.9.0/24 p4 = re.compile(r'(?P<ext_type>(Provider|Subscriber)) +(?P<inst>(\d+))' ' +(?P<eid>(\S+))$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 m = p1.match(line) if m: lisp_router_id = int(m.groupdict()['lisp_router_id']) lisp_dict = parsed_dict.setdefault('lisp_router_instances', {}).\ setdefault(lisp_router_id, {}).\ setdefault('service', {}).\ setdefault('ipv4', {}).setdefault('map_server', {}) continue # Home Instance ID: 103 m = p2.match(line) if m: home_instance_id = int(m.groupdict()['home_inst_id']) continue # Total entries: 6 m = p3.match(line) if m: total_entries = int(m.groupdict()['total_entries']) continue # Provider/Subscriber Inst ID EID prefix # Provider 103 10.121.88.0/24 # Subscriber 101 192.168.9.0/24 m = p4.match(line) if m: group = m.groupdict() extranet_type = group['ext_type'].lower() type_eid = group['eid'] inst = group['inst'] # Create dict vni_dict = lisp_dict.setdefault('virtual_network_ids', {}) # Set total count try: vni_dict['total_extranet_entries'] = total_entries except: pass # Instance vni_val_dict = vni_dict.setdefault(inst, {}) vni_val_dict['vni'] = inst # Extranet dict ext_dict = vni_val_dict.setdefault('extranets', {}).\ setdefault(extranet, {}) ext_dict['extranet'] = extranet try: ext_dict['home_instance_id'] = home_instance_id except: pass # Set extranet types if extranet_type not in ext_dict: ext_dict[extranet_type] = {} if type_eid not in ext_dict[extranet_type]: ext_dict[extranet_type][type_eid] = {} ext_dict[extranet_type][type_eid]['eid_record'] = \ m.groupdict()['eid'] ext_dict[extranet_type][type_eid]['bidirectional'] = True continue return parsed_dict # ======================================================================= # Schema for 'show lisp all instance-id <instance_id> dynamic-eid detail' # ======================================================================= class ShowLispDynamicEidDetailSchema(MetaParser): ''' Schema for "show lisp all instance-id <instance_id> dynamic-eid detail" ''' schema = { 'lisp_router_instances': {Any(): {Optional('service'): {Any(): {'etr': {'local_eids': {Any(): {'dynamic_eids': {Any(): {'dynamic_eid_name': str, 'id': str, 'rlocs': str, Optional('registering_more_specific'): bool, Optional('loopback_address'): str, Optional('priority'): int, Optional('weight'): int, Optional('record_ttl'): int, Optional('site_based_multicast_map_notify_group'): str, Optional('proxy_reply'): bool, Optional('registration_interval'): int, Optional('global_map_server'): bool, Optional('num_of_roaming_dynamic_eid'): int, Optional('mapping_servers'): {Any(): {Optional('proxy_reply'): bool, }, }, Optional('last_dynamic_eid'): {Any(): {'last_dynamic_eid_discovery_elaps_time': str, 'eids': {Any(): {'interface': str, 'uptime': str, 'last_activity': str, 'discovered_by': str, }, }, }, }, Optional('eid_address'): {Optional('address_type'): str, Optional('virtual_network_id'): str, }, }, }, }, }, }, }, }, }, }, } # ======================================================================= # Parser for 'show lisp all instance-id <instance_id> dynamic-eid detail' # ======================================================================= class ShowLispDynamicEidDetail(ShowLispDynamicEidDetailSchema): ''' Parser for "show lisp all instance-id <instance_id> dynamic-eid detail"''' cli_command = 'show lisp all instance-id {instance_id} dynamic-eid detail' def cli(self, instance_id, output=None): if output is None: out = self.device.execute(self.cli_command.format(instance_id=instance_id)) else: out = output # Init vars parsed_dict = {} # Output for router lisp 0 # Output for router lisp 0 instance-id 101 p1 = re.compile(r'Output +for +router +lisp +(?P<lisp_router_id>(\S+))' '(?: +instance-id +(?P<instance_id>(\d+)))?$') # LISP Dynamic EID Information for VRF "red" p2 = re.compile(r'LISP +Dynamic +EID +Information +for +VRF' ' +"(?P<vrf>(\S+))"$') # Dynamic-EID name: 192 p3 = re.compile(r'Dynamic-EID +name: +(?P<eid_id>(\S+))$') # Database-mapping EID-prefix: 192.168.0.0/24, locator-set RLOC p4 = re.compile(r'Database-mapping +EID-prefix: +(?P<dyn_eid>(\S+)),' ' +locator-set +(?P<locator_set_name>(\S+))$') # Registering more-specific dynamic-EIDs p5 = re.compile(r'Registering +more-specific +dynamic-EIDs$') # Map-Server(s): none configured, use global Map-Server p6 = re.compile(r'Map-Server\(s\)\: none configured, use global Map-Server$') # Map-Server(s): 10.64.4.4 (proxy-replying) # Map-Server(s): 10.144.6.6 p6_1 = re.compile(r'Map-Server\(s\)\: +(?P<ms>([0-9\.\:]+))' '(?: +\((?P<pr>(proxy-replying))\))?$') # Site-based multicast Map-Notify group: none configured # Site-based multicast Map-Notify group: 225.1.1.2 p7 = re.compile(r'Site-based +multicast +Map-Notify +group\:' ' +(?P<map_notify>([a-zA-Z0-9\s]+))$') # Number of roaming dynamic-EIDs discovered: 1 p8 = re.compile(r'Number +of +roaming +dynamic-EIDs +discovered:' ' +(?P<roam>(\d+))$') # Last dynamic-EID discovered: 192.168.0.1, 01:17:25 ago p9 = re.compile(r'Last +dynamic-EID +discovered: +(?P<last>(\S+)),' ' +(?P<time>(\S+)) +ago$') # 192.168.0.1, GigabitEthernet5, uptime: 01:17:25 p10 = re.compile(r'(?P<eid>([0-9\.\:]+)), +(?P<interface>(\S+)),' ' +uptime: +(?P<uptime>(\S+))$') # last activity: 00:00:23, discovered by: Packet Reception p11 = re.compile(r'last +activity: +(?P<last>(\S+)), +discovered +by:' ' +(?P<discovered_by>([a-zA-Z\s]+))$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 # Output for router lisp 0 instance-id 101 m = p1.match(line) if m: group = m.groupdict() lisp_router_id = int(group['lisp_router_id']) lisp_dict = parsed_dict.setdefault( 'lisp_router_instances', {}).setdefault(lisp_router_id, {}) if group['instance_id']: instance_id = group['instance_id'] continue # LISP Dynamic EID Information for VRF "red" m = p2.match(line) if m: eid_vrf = m.groupdict()['vrf'] continue # Dynamic-EID name: 192 m = p3.match(line) if m: dynamic_eid_name = m.groupdict()['eid_id'] continue # Database-mapping EID-prefix: 192.168.0.0/24, locator-set RLOC m = p4.match(line) if m: group = m.groupdict() dyn_eid = group['dyn_eid'] dynamic_eids_dict = lisp_dict.setdefault('service', {}).\ setdefault('ipv4', {}).\ setdefault('etr', {}).\ setdefault('local_eids', {}).\ setdefault(instance_id, {}).\ setdefault('dynamic_eids', {}).\ setdefault(dyn_eid, {}) # Set values dynamic_eids_dict['dynamic_eid_name'] = dynamic_eid_name dynamic_eids_dict['id'] = dyn_eid dynamic_eids_dict['rlocs'] = group['locator_set_name'] if 'eid_address' not in dynamic_eids_dict: dynamic_eids_dict['eid_address'] = {} try: dynamic_eids_dict['eid_address']['virtual_network_id'] = eid_vrf except: pass continue # Registering more-specific dynamic-EIDs m = p5.match(line) if m: dynamic_eids_dict['registering_more_specific'] = True continue # Map-Server(s): none configured, use global Map-Server m = p6.match(line) if m: dynamic_eids_dict['global_map_server'] = True continue # Map-Server(s): 10.64.4.4 (proxy-replying) # Map-Server(s): 10.144.6.6 m = p6_1.match(line) if m: group = m.groupdict() mapserver = group['ms'] ms_dict = dynamic_eids_dict.setdefault('mapping_servers', {}).\ setdefault(mapserver, {}) if group['pr']: ms_dict['proxy_reply'] = True continue # Site-based multicast Map-Notify group: none configured # Site-based multicast Map-Notify group: 225.1.1.2 m = p7.match(line) if m: dynamic_eids_dict['site_based_multicast_map_notify_group'] = \ m.groupdict()['map_notify'] continue # Number of roaming dynamic-EIDs discovered: 1 m = p8.match(line) if m: dynamic_eids_dict['num_of_roaming_dynamic_eid'] = int(m.groupdict()['roam']) # Last dynamic-EID discovered: 192.168.0.1, 01:17:25 ago m = p9.match(line) if m: group = m.groupdict() last_eid = group['last'] time = group['time'] # Create dict last_dyn_dict = dynamic_eids_dict.\ setdefault('last_dynamic_eid', {}).\ setdefault(last_eid, {}) last_dyn_dict['last_dynamic_eid_discovery_elaps_time'] = time continue # 192.168.0.1, GigabitEthernet5, uptime: 01:17:25 m = p10.match(line) if m: group = m.groupdict() eid = group['eid'] interface = group['interface'] uptime = group['uptime'] last_eids_dict = last_dyn_dict.setdefault('eids', {}).\ setdefault(eid, {}) last_eids_dict['interface'] = interface last_eids_dict['uptime'] = uptime continue # last activity: 00:00:23, discovered by: Packet Reception m = p11.match(line) if m: group = m.groupdict() last_activity = group['last'] discovered_by = group['discovered_by'].lower() last_eids_dict['last_activity'] = last_activity last_eids_dict['discovered_by'] = discovered_by continue return parsed_dict # ============================================================== # Schema for 'show lisp all instance-id <instance_id> <service>' # ============================================================== class ShowLispServiceSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service>" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, Optional('lisp_router_id'): {'site_id': str, 'xtr_id': str, }, Optional('service'): {Any(): {'service': str, 'delegated_database_tree': bool, 'locator_table': str, 'mobility_first_hop_router': bool, 'nat_traversal_router': bool, 'instance_id': {Any(): {Optional('eid_table'): str, Optional('site_registration_limit'): int, Optional('map_request_source'): str, 'database': {Optional('dynamic_database_limit'): int, Optional('dynamic_database_size'): int, Optional('inactive_deconfig_away_size'): int, Optional('route_import_database_limit'): int, Optional('route_import_database_size'): int, Optional('static_database_size'): int, Optional('static_database_limit'): int, Optional('total_database_mapping_size'): int, Optional('dynamic_database_mapping_limit'): int, Optional('import_site_db_size'): int, Optional('import_site_db_limit'): int, Optional('proxy_db_size'): int, }, Optional('mapping_servers'): {Any(): {'ms_address': str, Optional('uptime'): str, }, }, 'itr': {'local_rloc_last_resort': str, Optional('use_proxy_etr_rloc'): str, }, Optional('map_cache'): {Optional('imported_route_count'): int, Optional('imported_route_limit'): int, Optional('map_cache_size'): int, Optional('persistent_map_cache'): bool, Optional('static_mappings_configured'): int, }, }, }, 'etr': {'enabled': bool, Optional('encapsulation'): str, 'proxy_etr_router': bool, 'accept_mapping_data': str, 'map_cache_ttl': str, Optional('use_petrs'): {Any(): {'use_petr': str, }, }, Optional('mapping_servers'): {Any(): {'ms_address': str, Optional('uptime'): str, }, }, }, 'itr': {'enabled': bool, 'proxy_itr_router': bool, Optional('proxy_itrs'): {Any(): {'proxy_etr_address': str, }, }, 'solicit_map_request': str, 'max_smr_per_map_cache_entry': str, 'multiple_smr_suppression_time': int, Optional('map_resolvers'): {Any(): {'map_resolver': str, }, }, }, 'locator_status_algorithms': {'rloc_probe_algorithm': bool, 'rloc_probe_on_route_change': str, 'rloc_probe_on_member_change': bool, 'lsb_reports': str, 'ipv4_rloc_min_mask_len': int, 'ipv6_rloc_min_mask_len': int, }, 'map_cache': {'map_cache_activity_check_period': int, Optional('map_cache_fib_updates'): str, 'map_cache_limit': int, }, 'map_server': {'enabled': bool, }, 'map_resolver': {'enabled': bool, }, Optional('source_locator_configuration'): {'vlans': {Any(): {'address': str, 'interface': str, }, }, }, }, }, }, }, } # ============================================================== # Parser for 'show lisp all instance-id <instance_id> <service>' # ============================================================== class ShowLispService(ShowLispServiceSchema): '''Parser for "show lisp all instance-id <instance_id> <service>"''' cli_command = ['show lisp all instance-id {instance_id} {service}','show lisp all service {service}'] def cli(self, service, instance_id=None, output=None): if output is None: assert service in ['ipv4', 'ipv6', 'ethernet'] if instance_id: cmd = self.cli_command[0].format(instance_id=instance_id,service=service) else: cmd = self.cli_command[1].format(service=service) out = self.device.execute(cmd) else: out = output # Init vars parsed_dict = {} # State dict state_dict = { 'disabled': False, 'enabled': True} # Output for router lisp 0 # Output for router lisp 0 instance-id 193 p1 = re.compile(r'Output +for +router +lisp +(?P<router_id>(\S+))' '(?: +instance-id +(?P<instance_id>(\d+)))?$') # Instance ID: 101 p2 = re.compile(r'Instance +ID *: +(?P<instance_id>(\d+))$') # Router-lisp ID: 0 p3 = re.compile(r'Router-lisp +ID *: +(?P<router_id>(\d+))$') # Locator table: default p4 = re.compile(r'Locator +table *: +(?P<locator_table>(\S+))$') # EID table: vrf red p5 = re.compile(r'EID +table *: +(?P<eid_table>[a-zA-Z0-9\s]+)$') # Ingress Tunnel Router (ITR): enabled # Egress Tunnel Router (ETR): enabled p6 = re.compile(r'(Ingress|Egress) +Tunnel +Router ' '+\((?P<type>(ITR|ETR))\) *: ' '+(?P<state>(enabled|disabled))$') # Proxy-ITR Router (PITR): disabled # Proxy-ETR Router (PETR): disabled # Proxy-ETR Router (PETR): enabled RLOCs: 10.10.10.10 p7 = re.compile(r'Proxy\-(ITR|ETR) +Router' ' +\((?P<proxy_type>(PITR|PETR))\) *:' ' +(?P<state>(enabled|disabled))' '(?: +RLOCs: +(?P<proxy_itr>(\S+)))?$') # NAT-traversal Router (NAT-RTR): disabled p8 = re.compile(r'NAT-traversal +Router +\(NAT\-RTR\) *:' ' +(?P<state>(enabled|disabled))$') # Mobility First-Hop Router: disabled p9 = re.compile(r'Mobility +First-Hop +Router *:' ' +(?P<state>(enabled|disabled))$') # Map Server (MS): disabled p10 = re.compile(r'Map +Server +\(MS\) *:' ' +(?P<state>(enabled|disabled))$') # Map Resolver (MR): disabled p11 = re.compile(r'Map +Resolver +\(MR\) *:' ' +(?P<state>(enabled|disabled))$') # Delegated Database Tree (DDT): disabled p12 = re.compile(r'Delegated +Database +Tree +\(DDT\) *:' ' +(?P<state>(enabled|disabled))$') # Site Registration Limit: 0 p13 = re.compile(r'Site +Registration +Limit *: +(?P<limit>(\d+))$') # Map-Request source: derived from EID destination p14 = re.compile(r'Map-Request +source *: +(?P<source>(.*))$') # ITR Map-Resolver(s): 10.64.4.4, 10.166.13.13 p15 = re.compile(r'ITR +Map\-Resolver\(s\) *: +(?P<resolvers>(.*))$') # 10.84.66.66 *** not reachable *** p15_1 = re.compile(r'(?P<resolver>([0-9\.\:]+))(?: +\*.*)?$') # ETR Map-Server(s): 10.64.4.4 (17:49:58), 10.166.13.13 (00:00:35) p16 = re.compile(r'ETR +Map\-Server\(s\) *: +(?P<servers>(.*))$') # 10.84.66.66 (never) p16_1 = re.compile(r'(?P<server>([0-9\.\:]+))(?: +\((?P<uptime>(\S+))\))?$') # xTR-ID: 0x730E0861-0x12996F6D-0xEFEA2114-0xE1C951F7 p17 = re.compile(r'xTR-ID *: +(?P<xtr_id>(\S+))$') # site-ID: unspecified p18 = re.compile(r'site-ID *: +(?P<site_id>(\S+))$') # ITR local RLOC (last resort): 10.16.2.2 # ITR local RLOC (last resort): *** NOT FOUND *** p19 = re.compile(r'ITR +local +RLOC +\(last +resort\) *: +(?P<val>(.*))$') # ITR use proxy ETR RLOC(s): 10.10.10.10 p20 = re.compile(r'ITR +use +proxy +ETR +RLOC\(s\) *: +(?P<val>(\S+))$') # ITR Solicit Map Request (SMR): accept and process p21 = re.compile(r'ITR +Solicit +Map +Request +\(SMR\) *: +(?P<val>(.*))$') # Max SMRs per map-cache entry: 8 more specifics p22 = re.compile(r'Max +SMRs +per +map-cache +entry *: +(?P<val>(.*))$') # Multiple SMR suppression time: 20 secs p23 = re.compile(r'Multiple +SMR +suppression +time *: +(?P<time>(\d+))' ' +secs$') # ETR accept mapping data: disabled, verify disabled p24 = re.compile(r'ETR +accept +mapping +data *: +(?P<val>(.*))$') # ETR map-cache TTL: 1d00h p25 = re.compile(r'ETR +map-cache +TTL *: +(?P<val>(\S+))$') # Locator Status Algorithms: p26 = re.compile(r'Locator +Status +Algorithms *:$') # RLOC-probe algorithm: disabled p27 = re.compile(r'RLOC\-probe +algorithm *:' ' +(?P<state>(enabled|disabled))$') # RLOC-probe on route change: N/A (periodic probing disabled) p28 = re.compile(r'RLOC\-probe +on +route +change *: +(?P<state>(.*))$') # RLOC-probe on member change: disabled p29 = re.compile(r'RLOC\-probe +on +member +change *:' ' +(?P<state>(enabled|disabled))$') # LSB reports: process p30 = re.compile(r'LSB +reports *: +(?P<lsb_report>(\S+))$') # IPv4 RLOC minimum mask length: /0 p31 = re.compile(r'IPv4 +RLOC +minimum +mask +length *:' ' +\/(?P<ipv4_mask_len>(\d+))$') # IPv6 RLOC minimum mask length: /0 p32 = re.compile(r'IPv6 +RLOC +minimum +mask +length *:' ' +\/(?P<ipv6_mask_len>(\d+))$') # Map-cache: p33 = re.compile(r'Map\-cache:$') # Static mappings configured: 0 p34 = re.compile(r'Static +mappings +configured *: +(?P<static>(\d+))$') # Map-cache size/limit: 2/1000 p35 = re.compile(r'Map\-cache +size\/+limit *:' ' +(?P<size>(\d+))\/(?P<limit>(\d+))$') # Map-cache limit: 5120 p35_1 = re.compile(r'Map\-cache +limit *: +(?P<limit>(\d+))$') # Imported route count/limit: 0/1000 p36 = re.compile(r'Imported +route +count\/limit *:' ' +(?P<count>(\d+))\/(?P<limit>(\d+))$') # Map-cache activity check period: 60 secs p37 = re.compile(r'Map-cache +activity +check +period *:' ' +(?P<period>(\d+)) +secs$') # Map-cache FIB updates: established p38 = re.compile(r'Map\-cache +FIB +updates *: +(?P<fib_updates>(.*))$') # Persistent map-cache: disabled p39 = re.compile(r'Persistent +map\-cache *:' ' +(?P<state>(enabled|disabled))$') # Source locator configuration: p40 = re.compile(r'Source +locator +configuration:$') # Vlan100: 10.229.11.1 (Loopback0) p41 = re.compile(r'Vlan(?P<vlan>(\d+))\: +(?P<address>([0-9\.\:]+))' ' +\((?P<intf>(\S+))\)$') # Database: p42 = re.compile(r'Database *:$') # Total database mapping size: 1 p43 = re.compile(r'Total +database +mapping +size *:' ' +(?P<map_size>(\d+))$') # Dynamic database mapping limit: 5120 p44 = re.compile(r'Dynamic +database +mapping +limit *:' ' +(?P<map_limit>(\d+))$') # static database size/limit: 1/65535 p45 = re.compile(r'static +database +size\/+limit *:' ' +(?P<size>(\d+))\/(?P<limit>(\d+))$') # dynamic database size/limit: 0/65535 p46 = re.compile(r'dynamic +database +size\/+limit *:' ' +(?P<size>(\d+))\/(?P<limit>(\d+))$') # route-import database size/limit: 0/1000 p47 = re.compile(r'route\-import +database +size\/+limit *:' ' +(?P<size>(\d+))\/(?P<limit>(\d+))$') # Inactive (deconfig/away) size: 0 p48 = re.compile(r'Inactive +\(deconfig\/away\) +size *:' ' +(?P<inactive>(\d+))$') # import-site-reg database size/limit0/65535 p49 = re.compile(r'import\-site\-reg +database +size\/limit *:?' ' *(?P<size>(\d+))\/(?P<limit>(\d+))$') # proxy database size: 0 p50 = re.compile(r'proxy +database +size *: +(?P<size>(\d+))$') # Encapsulation type: lisp p51 = re.compile(r'Encapsulation +type *:' ' +(?P<encap_type>(lisp|vxlan))$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 # Output for router lisp 0 instance-id 193 m = p1.match(line) if m: lisp_router_id = int(m.groupdict()['router_id']) # Set value of instance_id if parsed, else take user input if m.groupdict()['instance_id']: instance_id = m.groupdict()['instance_id'] continue # Instance ID: 101 m = p2.match(line) if m: instance_id = m.groupdict()['instance_id'] continue # Router-lisp ID: 0 m = p3.match(line) if m: lisp_dict = parsed_dict.setdefault('lisp_router_instances', {}).\ setdefault(lisp_router_id, {}) lisp_dict['lisp_router_instance_id'] = lisp_router_id # Create service dict service_dict = lisp_dict.setdefault('service', {}).\ setdefault(service, {}) service_dict['service'] = service # Create instance_id dict iid_dict = service_dict.setdefault('instance_id', {}).\ setdefault(instance_id, {}) continue # Locator table: default m = p4.match(line) if m: service_dict['locator_table'] = m.groupdict()['locator_table'] continue # EID table: vrf red m = p5.match(line) if m: iid_dict['eid_table'] = m.groupdict()['eid_table'] continue # Ingress Tunnel Router (ITR): enabled # Egress Tunnel Router (ETR): enabled m = p6.match(line) if m: tunnel_type = m.groupdict()['type'].lower() if tunnel_type == 'itr': itr_dict = service_dict.setdefault('itr', {}) itr_dict['enabled'] = state_dict[m.groupdict()['state']] elif tunnel_type == 'etr': etr_dict = service_dict.setdefault('etr', {}) etr_dict['enabled'] = state_dict[m.groupdict()['state']] continue # Proxy-ITR Router (PITR): disabled # Proxy-ETR Router (PETR): disabled m = p7.match(line) if m: group = m.groupdict() proxy_type = group['proxy_type'].lower() if proxy_type == 'pitr': itr_dict['proxy_itr_router'] = \ state_dict[group['state']] elif proxy_type == 'petr': etr_dict['proxy_etr_router'] = \ state_dict[group['state']] if group['proxy_itr']: pitr_dict = itr_dict.setdefault('proxy_itrs', {}).\ setdefault(group['proxy_itr'], {}) pitr_dict['proxy_etr_address'] = group['proxy_itr'] continue # NAT-traversal Router (NAT-RTR): disabled m = p8.match(line) if m: service_dict['nat_traversal_router'] = \ state_dict[m.groupdict()['state']] continue # Mobility First-Hop Router: disabled m = p9.match(line) if m: service_dict['mobility_first_hop_router'] = \ state_dict[m.groupdict()['state']] continue # Map Server (MS): disabled m = p10.match(line) if m: map_server_dict = service_dict.setdefault('map_server', {}) map_server_dict['enabled'] = state_dict[m.groupdict()['state']] continue # Map Resolver (MR): disabled m = p11.match(line) if m: map_resolver_dict = service_dict.setdefault('map_resolver', {}) map_resolver_dict['enabled'] = state_dict[m.groupdict()['state']] continue # Delegated Database Tree (DDT): disabled m = p12.match(line) if m: service_dict['delegated_database_tree'] = \ state_dict[m.groupdict()['state']] continue # Site Registration Limit: 0 m = p13.match(line) if m: iid_dict['site_registration_limit'] = int(m.groupdict()['limit']) continue # Map-Request source: derived from EID destination m = p14.match(line) if m: iid_dict['map_request_source'] = m.groupdict()['source'] continue # ITR Map-Resolver(s): 10.64.4.4, 10.166.13.13 m = p15.match(line) if m: map_resolvers = m.groupdict()['resolvers'].split(',') for mr in map_resolvers: itr_mr_dict = itr_dict.setdefault('map_resolvers', {}).\ setdefault(mr.strip(), {}) itr_mr_dict['map_resolver'] = mr.strip() continue m = p15_1.match(line) if m: itr_dict['map_resolvers'].setdefault( m.groupdict()['resolver'], {})['map_resolver'] = \ m.groupdict()['resolver'] continue # ETR Map-Server(s): 10.64.4.4 (17:49:58), 10.166.13.13 (00:00:35) m = p16.match(line) if m: map_servers = m.groupdict()['servers'].split(',') for ms in map_servers: try: map_server, uptime = ms.split() map_server = map_server.replace(' ', '') uptime = uptime.replace('(', '').replace(')', '') except: map_server = ms.replace(' ', '') uptime = None # Set etr_dict under service etr_ms_dict = etr_dict.setdefault('mapping_servers', {}).\ setdefault(map_server, {}) etr_ms_dict['ms_address'] = map_server if uptime: etr_ms_dict['uptime'] = uptime # Set etr_dict under instance_id iid_ms_dict = iid_dict.setdefault('mapping_servers', {}).\ setdefault(map_server, {}) iid_ms_dict['ms_address'] = map_server if uptime: iid_ms_dict['uptime'] = uptime continue # 10.84.66.66 (never) m = p16_1.match(line) if m: temp1 = etr_dict['mapping_servers'].setdefault( m.groupdict()['server'], {}) temp2 = iid_dict['mapping_servers'].setdefault( m.groupdict()['server'], {}) temp1['ms_address'] = m.groupdict()['server'] temp2['ms_address'] = m.groupdict()['server'] if m.groupdict()['uptime']: temp1['uptime'] = m.groupdict()['uptime'] temp2['uptime'] = m.groupdict()['uptime'] continue # xTR-ID: 0x730E0861-0x12996F6D-0xEFEA2114-0xE1C951F7 m = p17.match(line) if m: lrouterid_dict = lisp_dict.setdefault('lisp_router_id', {}) lrouterid_dict['xtr_id'] = m.groupdict()['xtr_id'] continue # site-ID: unspecified m = p18.match(line) if m: lrouterid_dict['site_id'] = m.groupdict()['site_id'] continue # ITR local RLOC (last resort): 10.16.2.2 m = p19.match(line) if m: iid_itr_dict = iid_dict.setdefault('itr', {}) iid_itr_dict['local_rloc_last_resort'] = m.groupdict()['val'] continue # ITR use proxy ETR RLOC(s): 10.10.10.10 m = p20.match(line) if m: group = m.groupdict() iid_itr_dict['use_proxy_etr_rloc'] = group['val'] use_petr_dict = etr_dict.\ setdefault('use_petrs', {}).\ setdefault(group['val'], {}) use_petr_dict['use_petr'] = group['val'] continue # ITR Solicit Map Request (SMR): accept and process m = p21.match(line) if m: itr_dict['solicit_map_request'] = m.groupdict()['val'] continue # Max SMRs per map-cache entry: 8 more specifics m = p22.match(line) if m: itr_dict['max_smr_per_map_cache_entry'] = m.groupdict()['val'] continue # Multiple SMR suppression time: 20 secs m = p23.match(line) if m: itr_dict['multiple_smr_suppression_time'] = \ int(m.groupdict()['time']) continue # ETR accept mapping data: disabled, verify disabled m = p24.match(line) if m: etr_dict['accept_mapping_data'] = m.groupdict()['val'] continue # ETR map-cache TTL: 1d00h m = p25.match(line) if m: etr_dict['map_cache_ttl'] = m.groupdict()['val'] continue # Locator Status Algorithms: m = p26.match(line) if m: locator_dict = service_dict.\ setdefault('locator_status_algorithms', {}) continue # RLOC-probe algorithm: disabled m = p27.match(line) if m: locator_dict['rloc_probe_algorithm'] = \ state_dict[m.groupdict()['state']] continue # RLOC-probe on route change: N/A (periodic probing disabled) m = p28.match(line) if m: locator_dict['rloc_probe_on_route_change'] = \ m.groupdict()['state'] continue # RLOC-probe on member change: disabled m = p29.match(line) if m: locator_dict['rloc_probe_on_member_change'] = \ state_dict[m.groupdict()['state']] continue # LSB reports: process m = p30.match(line) if m: locator_dict['lsb_reports'] = m.groupdict()['lsb_report'] continue # IPv4 RLOC minimum mask length: /0 m = p31.match(line) if m: locator_dict['ipv4_rloc_min_mask_len'] = \ int(m.groupdict()['ipv4_mask_len']) continue # IPv6 RLOC minimum mask length: /0 m = p32.match(line) if m: locator_dict['ipv6_rloc_min_mask_len'] = \ int(m.groupdict()['ipv6_mask_len']) continue # Map-cache: m = p33.match(line) if m: map_cache_dict = service_dict.setdefault('map_cache', {}) iid_map_cache_dict = iid_dict.setdefault('map_cache', {}) continue # Static mappings configured: 0 m = p34.match(line) if m: iid_map_cache_dict['static_mappings_configured'] = \ int(m.groupdict()['static']) continue # Map-cache size/limit: 2/1000 m = p35.match(line) if m: iid_map_cache_dict['map_cache_size'] = int(m.groupdict()['size']) map_cache_dict['map_cache_limit'] = int(m.groupdict()['limit']) continue # Map-cache limit: 5120 m = p35_1.match(line) if m: map_cache_dict['map_cache_limit'] = int(m.groupdict()['limit']) continue # Imported route count/limit: 0/1000 m = p36.match(line) if m: iid_map_cache_dict['imported_route_count'] = \ int(m.groupdict()['count']) iid_map_cache_dict['imported_route_limit'] = \ int(m.groupdict()['limit']) continue # Map-cache activity check period: 60 secs m = p37.match(line) if m: map_cache_dict['map_cache_activity_check_period'] = \ int(m.groupdict()['period']) continue # Map-cache FIB updates: established m = p38.match(line) if m: map_cache_dict['map_cache_fib_updates'] = \ m.groupdict()['fib_updates'] continue # Persistent map-cache: disabled m = p39.match(line) if m: iid_map_cache_dict['persistent_map_cache'] = \ state_dict[m.groupdict()['state']] continue # Source locator configuration: m = p40.match(line) if m: src_locator_dict = service_dict.setdefault( 'source_locator_configuration', {}) continue # Vlan100: 10.229.11.1 (Loopback0) # Vlan101: 10.229.11.1 (Loopback0) m = p41.match(line) if m: vlan = 'vlan' + m.groupdict()['vlan'] src_locator_vlan_dict = src_locator_dict.setdefault( 'vlans', {}).setdefault(vlan, {}) src_locator_vlan_dict['address'] = m.groupdict()['address'] src_locator_vlan_dict['interface'] = m.groupdict()['intf'] continue # Database: m = p42.match(line) if m: db_dict = iid_dict.setdefault('database', {}) continue # Total database mapping size: 1 m = p43.match(line) if m: db_dict['total_database_mapping_size'] = \ int(m.groupdict()['map_size']) continue # Dynamic database mapping limit: 5120 m = p44.match(line) if m: db_dict['dynamic_database_mapping_limit'] = \ int(m.groupdict()['map_limit']) continue # static database size/limit: 1/65535 m = p45.match(line) if m: db_dict['static_database_size'] = int(m.groupdict()['size']) db_dict['static_database_limit'] = int(m.groupdict()['limit']) continue # dynamic database size/limit: 0/65535 m = p46.match(line) if m: db_dict['dynamic_database_size'] = int(m.groupdict()['size']) db_dict['dynamic_database_limit'] = int(m.groupdict()['limit']) continue # route-import database size/limit: 0/1000 m = p47.match(line) if m: db_dict['route_import_database_size'] = \ int(m.groupdict()['size']) db_dict['route_import_database_limit'] = \ int(m.groupdict()['limit']) continue # Inactive (deconfig/away) size: 0 m = p48.match(line) if m: db_dict['inactive_deconfig_away_size'] = \ int(m.groupdict()['inactive']) continue # import-site-reg database size/limit0/65535 m = p49.match(line) if m: db_dict['import_site_db_size'] = int(m.groupdict()['size']) db_dict['import_site_db_limit'] = int(m.groupdict()['limit']) continue # proxy database size: 0 m = p50.match(line) if m: db_dict['proxy_db_size'] = int(m.groupdict()['size']) continue # Encapsulation type: lisp m = p51.match(line) if m: etr_dict['encapsulation'] = m.groupdict()['encap_type'] continue return parsed_dict # ======================================================================== # Schema for 'show lisp all instance-id <instance_id> <service> map-cache' # ======================================================================== class ShowLispServiceMapCacheSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> map-cache" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, Optional('service'): {Any(): {'service': str, 'itr': {'map_cache': {Any(): {'vni': str, 'entries': int, 'mappings': {Any(): {'id': str, 'creation_time': str, 'time_to_live': str, 'via': str, 'eid': {'address_type': str, 'vrf': str, Optional('ipv4'): {'ipv4': str, }, Optional('ipv4_prefix'): {'ipv4_prefix': str, }, Optional('ipv6'): {'ipv6': str, }, Optional('ipv6_prefix'): {'ipv6_prefix': str, }, }, Optional('negative_mapping'): {'map_reply_action': str, }, Optional('positive_mapping'): {'rlocs': {Any(): {'id': str, 'uptime': str, 'state': str, 'priority': int, 'weight': int, Optional('encap_iid'): str, 'locator_address': {'address_type': str, 'virtual_network_id': str, Optional('ipv4'): {'ipv4': str, }, Optional('ipv4_prefix'): {'ipv4_prefix': str, }, Optional('ipv6'): {'ipv6': str, }, Optional('ipv6_prefix'): {'ipv6_prefix': str, }, }, }, }, }, }, }, }, }, }, }, }, }, }, } # ======================================================================== # Parser for 'show lisp all instance-id <instance_id> <service> map-cache' # ======================================================================== class ShowLispServiceMapCache(ShowLispServiceMapCacheSchema): '''Parser for "show lisp all instance-id <instance_id> <service> map-cache"''' cli_command = 'show lisp all instance-id {instance_id} {service} map-cache' exclude = ['creation_time'] def cli(self, service, instance_id, output=None): if output is None: assert service in ['ipv4', 'ipv6', 'ethernet'] out = self.device.execute(self.cli_command.format(instance_id=instance_id,service=service)) else: out = output # Init vars parsed_dict = {} # State dict state_dict = { 'disabled': False, 'enabled': True} # Output for router lisp 0 # Output for router lisp 0 instance-id 193 p1 = re.compile(r'Output +for +router +lisp +(?P<router_id>(\S+))' '(?: +instance-id +(?P<instance_id>(\d+)))?$') # LISP IPv4 Mapping Cache for EID-table default (IID 101), 2 entries # LISP IPv6 Mapping Cache for EID-table vrf red (IID 101), 2 entries # LISP MAC Mapping Cache for EID-table Vlan 101 (IID 1), 4 entries p2 = re.compile(r'LISP +(?P<type>(IPv4|IPv6|MAC)) +Mapping +Cache +for' ' +EID\-table +(default|(vrf|Vlan) +(?P<vrf>(\S+)))' ' +\(IID +(?P<iid>(\d+))\), +(?P<entries>(\d+))' ' +entries$') # 0.0.0.0/0, uptime: 15:23:50, expires: never, via static-send-map-request # ::/0, uptime: 00:11:28, expires: never, via static-send-map-request # b827.ebff.4720/48, uptime: 22:49:42, expires: 01:10:17, via WLC Map-Notify, complete # 192.168.9.0/24, uptime: 00:04:02, expires: 23:55:57, via map-reply, complete p3 = re.compile(r'(?P<map_id>(\S+)), +uptime: +(?P<uptime>(\S+)),' ' +expires: +(?P<expires>(\S+)), +via +(?P<via>(.*))$') # Negative cache entry, action: send-map-request p4 = re.compile(r'Negative +cache +entry, +action: +(?P<action>(.*))$') # Locator Uptime State Pri/Wgt Encap-IID # 10.1.8.8 00:04:02 up 50/50 - p5 = re.compile(r'(?P<locator>(\S+)) +(?P<uptime>(\S+))' ' +(?P<state>(up|down))' ' +(?P<priority>(\d+))\/(?P<weight>(\d+))' '(?: +(?P<encap_iid>(\S+)))?$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 # Output for router lisp 0 instance-id 193 m = p1.match(line) if m: group = m.groupdict() lisp_router_id = int(group['router_id']) lisp_dict = parsed_dict.setdefault('lisp_router_instances', {}).\ setdefault(lisp_router_id, {}) lisp_dict['lisp_router_instance_id'] = lisp_router_id if group['instance_id']: instance_id = group['instance_id'] continue # LISP IPv4 Mapping Cache for EID-table default (IID 101), 2 entries # LISP IPv6 Mapping Cache for EID-table vrf red (IID 101), 2 entries # LISP MAC Mapping Cache for EID-table Vlan 101 (IID 1), 4 entries m = p2.match(line) if m: group = m.groupdict() address_type = group['type'] vrf_name = group['vrf'] if group['vrf'] else 'default' # Create dict service_dict = lisp_dict.setdefault('service', {}).\ setdefault(service, {}) service_dict['service'] = service itr_dict = service_dict.setdefault('itr', {}) map_cache_dict = itr_dict.setdefault('map_cache', {}).\ setdefault(instance_id, {}) map_cache_dict['vni'] = str(instance_id) map_cache_dict['entries'] = int(group['entries']) continue # # 0.0.0.0/0, uptime: 15:23:50, expires: never, via static-send-map-request # ::/0, uptime: 00:11:28, expires: never, via static-send-map-request # b827.ebff.4720/48, uptime: 22:49:42, expires: 01:10:17, via WLC Map-Notify, complete # 192.168.9.0/24, uptime: 00:04:02, expires: 23:55:57, via map-reply, complete m = p3.match(line) if m: # reset rloc counter rloc_id = 1 group = m.groupdict() mapping_dict = map_cache_dict.\ setdefault('mappings', {}).\ setdefault(group['map_id'], {}) mapping_dict['id'] = group['map_id'] mapping_dict['creation_time'] = group['uptime'] mapping_dict['time_to_live'] = group['expires'] mapping_dict['via'] = group['via'] eid_dict = mapping_dict.setdefault('eid', {}) if ':' in group['map_id']: ipv6_dict = eid_dict.setdefault('ipv6', {}) ipv6_dict['ipv6'] = group['map_id'] eid_dict['address_type'] = 'ipv6-afi' else: ipv4_dict = eid_dict.setdefault('ipv4', {}) ipv4_dict['ipv4'] = group['map_id'] eid_dict['address_type'] = 'ipv4-afi' try: eid_dict['vrf'] = vrf_name except: pass # Negative cache entry, action: send-map-request m = p4.match(line) if m: neg_dict = mapping_dict.setdefault('negative_mapping', {}) neg_dict['map_reply_action'] = m.groupdict()['action'] continue # Locator Uptime State Pri/Wgt Encap-IID # 10.1.8.8 00:04:02 up 50/50 - m = p5.match(line) if m: group = m.groupdict() # positive_mapping postive_dict = mapping_dict.\ setdefault('positive_mapping', {}).\ setdefault('rlocs', {}).\ setdefault(rloc_id, {}) postive_dict['id'] = str(rloc_id) postive_dict['uptime'] = group['uptime'] postive_dict['state'] = group['state'] postive_dict['priority'] = int(group['priority']) postive_dict['weight'] = int(group['weight']) if group['encap_iid']: postive_dict['encap_iid'] = group['encap_iid'] # locator_address locator_dict = postive_dict.setdefault('locator_address', {}) locator_dict['virtual_network_id'] = str(instance_id) if ':' in group['locator']: ipv6_dict = locator_dict.setdefault('ipv6', {}) ipv6_dict['ipv6'] = group['locator'] locator_dict['address_type'] = 'ipv6-afi' else: ipv4_dict = locator_dict.setdefault('ipv4', {}) ipv4_dict['ipv4'] = group['locator'] locator_dict['address_type'] = 'ipv4-afi' # Increment entry rloc_id += 1 continue return parsed_dict # =========================================================================== # Schema for 'show lisp all instance-id <instance_id> <service> rloc members' # =========================================================================== class ShowLispServiceRlocMembersSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> rloc members" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, Optional('service'): {Optional(Any()): {'instance_id': {Any(): {Optional('rloc'): {'total_entries': int, 'valid_entries': int, 'distribution': bool, 'members': {Any(): {'origin': str, 'valid': str, }, }, }, }, }, }, }, }, }, } # =========================================================================== # Parser for 'show lisp all instance-id <instance_id> <service> rloc members' # =========================================================================== class ShowLispServiceRlocMembers(ShowLispServiceRlocMembersSchema): '''Parser for "show lisp all instance-id <instance_id> <service> rloc members"''' cli_command = 'show lisp all instance-id {instance_id} service {service} rloc members' def cli(self, service, instance_id, output=None): if output is None: assert service in ['ipv4', 'ipv6', 'ethernet'] out = self.device.execute(self.cli_command.format(instance_id=instance_id, service=service)) else: out = output # Init vars parsed_dict = {} # State dict state_dict = { 'disabled': False, 'enabled': True} # Output for router lisp 0 # Output for router lisp 0 instance-id 193 # Output for router lisp 2 instance-id 101 p1 = re.compile(r'Output +for +router +lisp +(?P<router_id>(\S+))' '(?: +instance-id +(?P<instance_id>(\d+)))?$') # LISP RLOC Membership for router lisp 0 IID 101 p2 = re.compile(r'LISP +RLOC +Membership +for +router +lisp' ' +(?P<router_id>(\S+)) +IID +(?P<instance_id>(\d+))$') # Entries: 2 valid / 2 total, Distribution disabled p3 = re.compile(r'Entries: +(?P<valid>(\d+)) +valid +\/' ' +(?P<total>(\d+)) +total, +Distribution' ' +(?P<distribution>(enabled|disabled))$') # RLOC Origin Valid # 10.16.2.2 Registration Yes p4 = re.compile(r'(?P<member>([0-9\.\:]+)) +(?P<origin>(\S+))' ' +(?P<valid>(\S+))$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 # Output for router lisp 0 instance-id 193 m = p1.match(line) if m: group = m.groupdict() lisp_router_id = int(group['router_id']) if group['instance_id']: instance_id = group['instance_id'] # Create lisp_dict lisp_dict = parsed_dict.setdefault('lisp_router_instances', {}).\ setdefault(lisp_router_id, {}) lisp_dict['lisp_router_instance_id'] = lisp_router_id # Create service_dict iid_dict = lisp_dict.setdefault('service', {}).\ setdefault(service, {}).\ setdefault('instance_id', {}).\ setdefault(str(instance_id), {}) continue # Entries: 2 valid / 2 total, Distribution disabled m = p3.match(line) if m: group = m.groupdict() # Create rloc_dict rloc_dict = iid_dict.setdefault('rloc', {}) rloc_dict['valid_entries'] = int(group['valid']) rloc_dict['total_entries'] = int(group['total']) rloc_dict['distribution'] = state_dict[group['distribution']] continue # RLOC Origin Valid # 10.16.2.2 Registration Yes m = p4.match(line) if m: group = m.groupdict() members_dict = rloc_dict.setdefault('members', {}).\ setdefault(group['member'], {}) members_dict['origin'] = group['origin'].lower() members_dict['valid'] = group['valid'].lower() continue return parsed_dict # ================================================================== # Schema for 'show lisp all instance-id <instance_id> <service> smr' # ================================================================== class ShowLispServiceSmrSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> smr" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, Optional('service'): {Optional(Any()): {'instance_id': {Any(): {Optional('smr'): {'vrf': str, 'entries': int, 'prefixes': {Any(): {'producer': str, }, }, }, }, }, }, }, }, }, } # ================================================================== # Parser for 'show lisp all instance-id <instance_id> <service> smr' # ================================================================== class ShowLispServiceSmr(ShowLispServiceSmrSchema): '''Parser for "show lisp all instance-id <instance_id> <service> smr"''' cli_command = 'show lisp all instance-id {instance_id} service {service} smr' def cli(self, service, instance_id, output=None): if output is None: assert service in ['ipv4', 'ipv6', 'ethernet'] out = self.device.execute(self.cli_command.format(instance_id=instance_id, service=service)) else: out = output # Init vars parsed_dict = {} # State dict state_dict = { 'disabled': False, 'enabled': True} # Output for router lisp 0 # Output for router lisp 0 instance-id 193 # Output for router lisp 2 instance-id 101 p1 = re.compile(r'Output +for +router +lisp +(?P<router_id>(\S+))' '(?: +instance-id +(?P<instance_id>(\d+)))?$') # LISP SMR Table for router lisp 0 (red) IID 101 p2 = re.compile(r'LISP +SMR +Table +for +router +lisp +(\d+)' ' +\((?P<vrf>(\S+))\) +IID +(?P<instance_id>(\S+))$') # Entries: 1 p3 = re.compile(r'Entries: +(?P<entries>(\d+))$') # Prefix Producer # 192.168.0.0/24 local EID p4 = re.compile(r'(?P<prefix>([0-9\.\/\:]+)) +(?P<producer>(.*))$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 # Output for router lisp 0 instance-id 193 m = p1.match(line) if m: group = m.groupdict() lisp_router_id = int(group['router_id']) if group['instance_id']: instance_id = group['instance_id'] # Create lisp_dict lisp_dict = parsed_dict.setdefault('lisp_router_instances', {}).\ setdefault(lisp_router_id, {}) lisp_dict['lisp_router_instance_id'] = lisp_router_id # Create service_dict smr_dict = lisp_dict.setdefault('service', {}).\ setdefault(service, {}).\ setdefault('instance_id', {}).\ setdefault(str(instance_id), {}).\ setdefault('smr', {}) continue # LISP SMR Table for router lisp 0 (red) IID 101 m = p2.match(line) if m: smr_dict['vrf'] = m.groupdict()['vrf'] continue # Entries: 1 m = p3.match(line) if m: smr_dict['entries'] = int(m.groupdict()['entries']) continue # Prefix Producer # 192.168.0.0/24 local EID m = p4.match(line) if m: prefix_dict = smr_dict.setdefault('prefixes', {}).\ setdefault(m.groupdict()['prefix'], {}) prefix_dict['producer'] = m.groupdict()['producer'] continue return parsed_dict # ==================================================== # Schema for 'show lisp all service <service> summary' # ==================================================== class ShowLispServiceSummarySchema(MetaParser): '''Schema for "show lisp all <service> summary" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, Optional('service'): {Optional(Any()): {Optional('virtual_network_ids'): {Any(): {Optional('vrf'): str, 'interface': str, 'db_size': int, 'db_no_route': int, 'cache_size': int, 'incomplete': str, 'cache_idle': str, 'lisp_role': {Any(): {'lisp_role_type': str, }, }, }, }, 'etr': {'summary': {'instance_count': int, 'total_eid_tables': int, 'total_db_entries': int, 'total_map_cache_entries': int, 'total_db_entries_inactive': int, 'eid_tables_inconsistent_locators': int, 'eid_tables_incomplete_map_cache_entries': int, 'eid_tables_pending_map_cache_update_to_fib': int, }, }, }, }, }, }, } # ==================================================== # Parser for 'show lisp all service <service> summary' # ==================================================== class ShowLispServiceSummary(ShowLispServiceSummarySchema): '''Parser for "show lisp all service <service> summary"''' cli_command = 'show lisp all service {service} summary' def cli(self, service, output=None): if output is None: assert service in ['ipv4', 'ipv6', 'ethernet'] out = self.device.execute(self.cli_command.format(service=service)) else: out = output # Init vars parsed_dict = {} # State dict state_dict = { 'disabled': False, 'enabled': True} # Output for router lisp 0 p1 = re.compile(r'Output +for +router +lisp +(?P<router_id>(\S+))$') # Router-lisp ID: 0 p2 = re.compile(r'Router-lisp +ID: +(?P<router_id>(\S+))$') # Instance count: 2 p3 = re.compile(r'Instance +count: +(?P<val>(\d+))$') # Key: DB - Local EID Database entry count (@ - RLOC check pending # * - RLOC consistency problem), # DB no route - Local EID DB entries with no matching RIB route, # Cache - Remote EID mapping cache size, IID - Instance ID, # Role - Configured Role # Interface DB DB no Cache Incom Cache # EID VRF name (.IID) size route size plete Idle Role # red LISP0.101 1 0 2 0.0% 0.0% ITR-ETR # blue LISP0.102 1 0 1 0.0% 0% ITR-ETR p4_1 = re.compile(r'(?P<vrf>(\S+)) +(?P<interface>(\S+))\.(?P<iid>(\d+))' ' +(?P<db_size>(\d+)) +(?P<db_no_route>(\d+))' ' +(?P<cache_size>(\d+)) +(?P<incomplete>(\S+))' ' +(?P<cache_idle>(\S+)) +(?P<role>(\S+))$') p4_2 = re.compile(r'(?P<interface>(\S+))\.(?P<iid>(\d+))' ' +(?P<db_size>(\d+)) +(?P<db_no_route>(\d+))' ' +(?P<cache_size>(\d+)) +(?P<incomplete>(\S+))' ' +(?P<cache_idle>(\S+)) +(?P<role>(\S+))$') # Number of eid-tables: 2 p5 = re.compile(r'Number +of +eid-tables: +(?P<val>(\d+))$') # Total number of database entries: 2 (inactive 0) p6 = re.compile(r'Total +number +of +database +entries:' ' +(?P<val>(\d+))(?: +\(inactive' ' +(?P<inactive>(\d+))\))?$') # EID-tables with inconsistent locators: 0 p7 = re.compile(r'EID-tables +with +inconsistent +locators:' ' +(?P<val>(\d+))$') # Total number of map-cache entries: 3 p8 = re.compile(r'Total +number +of +map-cache +entries:' ' +(?P<val>(\d+))$') # EID-tables with incomplete map-cache entries: 0 p9 = re.compile(r'EID-tables +with +incomplete +map-cache +entries:' ' +(?P<val>(\d+))$') # EID-tables pending map-cache update to FIB: 0 p10 = re.compile(r'EID-tables +pending +map-cache +update +to +FIB:' ' +(?P<val>(\d+))$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 m = p1.match(line) if m: group = m.groupdict() lisp_router_id = int(group['router_id']) continue # Router-lisp ID: 0 m = p2.match(line) if m: if int(m.groupdict()['router_id']) == lisp_router_id: # Create lisp_dict lisp_dict = parsed_dict.\ setdefault('lisp_router_instances', {}).\ setdefault(lisp_router_id, {}) lisp_dict['lisp_router_instance_id'] = lisp_router_id # Create summary dict sum_dict = lisp_dict.setdefault('service', {}).\ setdefault(service, {}).\ setdefault('etr', {}).\ setdefault('summary', {}) continue # Instance count: 2 m = p3.match(line) if m: sum_dict['instance_count'] = int(m.groupdict()['val']) continue # blue LISP0.102 1 0 1 0.0% 0% ITR-ETR # LISP0.2 2 0 0 0% 0% NONE m1 = p4_1.match(line) m2 = p4_2.match(line) m = m1 if m1 else m2 if m: group = m.groupdict() vni_dict = lisp_dict.setdefault('service', {}).\ setdefault(service, {}).\ setdefault('virtual_network_ids', {}).\ setdefault(group['iid'], {}) vni_dict['interface'] = group['interface'] + '.' + group['iid'] vni_dict['db_size'] = int(group['db_size']) vni_dict['db_no_route'] = int(group['db_no_route']) vni_dict['cache_size'] = int(group['cache_size']) vni_dict['incomplete'] = group['incomplete'] vni_dict['cache_idle'] = group['cache_idle'] role_dict = vni_dict.setdefault('lisp_role', {}).\ setdefault(group['role'].lower(), {}) role_dict['lisp_role_type'] = group['role'].lower() if 'vrf' in group: vni_dict['vrf'] = group['vrf'] continue # Number of eid-tables: 2 m = p5.match(line) if m: sum_dict['total_eid_tables'] = int(m.groupdict()['val']) continue # Total number of database entries: 2 (inactive 0) m = p6.match(line) if m: sum_dict['total_db_entries'] = int(m.groupdict()['val']) if m.groupdict()['inactive']: sum_dict['total_db_entries_inactive'] = \ int(m.groupdict()['inactive']) continue # EID-tables with inconsistent locators: 0 m = p7.match(line) if m: sum_dict['eid_tables_inconsistent_locators'] = \ int(m.groupdict()['val']) continue # Total number of map-cache entries: 3 m = p8.match(line) if m: sum_dict['total_map_cache_entries'] = int(m.groupdict()['val']) continue # EID-tables with incomplete map-cache entries: 0 m = p9.match(line) if m: sum_dict['eid_tables_incomplete_map_cache_entries'] = \ int(m.groupdict()['val']) continue # EID-tables pending map-cache update to FIB: 0 m = p10.match(line) if m: sum_dict['eid_tables_pending_map_cache_update_to_fib'] = \ int(m.groupdict()['val']) continue return parsed_dict # ======================================================================= # Schema for 'show lisp all instance-id <instance_id> <service> dabatase' # ======================================================================= class ShowLispServiceDatabaseSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> dabatase" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, 'locator_sets': {Any(): {'locator_set_name': str, }, }, Optional('service'): {Optional(Any()): {'etr': {'local_eids': {Any(): {'vni': str, 'total_eid_entries': int, 'no_route_eid_entries': int, 'inactive_eid_entries': int, Optional('dynamic_eids'): {Any(): {'id': str, Optional('dynamic_eid'): str, 'eid_address': {'address_type': str, 'vrf': str, }, 'rlocs': str, 'loopback_address': str, 'priority': int, 'weight': int, 'source': str, 'state': str, }, }, Optional('eids'): {Any(): {'id': str, 'eid_address': {'address_type': str, 'vrf': str, }, 'rlocs': str, 'loopback_address': str, 'priority': int, 'weight': int, 'source': str, 'state': str, }, }, }, }, }, }, }, }, }, } # ======================================================================= # Parser for 'show lisp all instance-id <instance_id> <service> dabatase' # ======================================================================= class ShowLispServiceDatabase(ShowLispServiceDatabaseSchema): '''Parser for "show lisp all instance-id <instance_id> <service> dabatase"''' cli_command = 'show lisp all instance-id {instance_id} {service} database' def cli(self, service, instance_id, output=None): if output is None: assert service in ['ipv4', 'ipv6', 'ethernet'] out = self.device.execute(self.cli_command.format(instance_id=instance_id, service=service)) else: out = output # Init vars parsed_dict = {} # Output for router lisp 0 # Output for router lisp 0 instance-id 193 # Output for router lisp 2 instance-id 101 p1 = re.compile(r'Output +for +router +lisp +(?P<router_id>(\S+))' '(?: +instance-id +(?P<instance_id>(\d+)))?$') # LISP ETR IPv4 Mapping Database for EID-table default (IID 101), LSBs: 0x1 # LISP ETR IPv6 Mapping Database for EID-table vrf red (IID 101), LSBs: 0x1 # LISP ETR MAC Mapping Database for EID-table Vlan 101 (IID 1), LSBs: 0x1 p2 = re.compile(r'LISP +ETR +(IPv4|IPv6|MAC) +Mapping +Database +for' ' +EID\-table +(default|(vrf|Vlan) +(?P<vrf>(\S+)))' ' +\(IID +(?P<instance_id>(\d+))\),' ' +LSBs: +(?P<lsb>(\S+))$') # Entries total 1, no-route 0, inactive 0 # Entries total 2, no-route 0, inactive 0 p3 = re.compile(r'Entries +total +(?P<total>(\d+)), +no-route' ' +(?P<no_route>(\d+)),' ' +inactive +(?P<inactive>(\d+))$') # 192.168.0.0/24, locator-set RLOC # 2001:192:168::/64, locator-set RLOC # 0050.56ff.1bbe/48, dynamic-eid Auto-L2-group-1, inherited from default locator-set RLOC # cafe.caff.c9fd/48, dynamic-eid Auto-L2-group-1, inherited from default locator-set RLOC p4 = re.compile(r'(?P<etr_eid>(\S+)),' '(?: +dynamic-eid +(?P<dyn_eid>(\S+)),' ' +inherited +from +default)?' ' +locator-set +(?P<locator_set>(\S+))$') # Locator Pri/Wgt Source State # 10.16.2.2 50/50 cfg-intf site-self, reachable # 10.229.11.1 1/100 cfg-intf site-self, reachable p5 = re.compile(r'(?P<locator>(\S+))' ' +(?P<priority>(\d+))\/(?P<weight>(\d+))' ' +(?P<source>(\S+)) +(?P<state>(.*))$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 m = p1.match(line) if m: group = m.groupdict() lisp_router_id = int(group['router_id']) if group['instance_id']: instance_id = group['instance_id'] continue # LISP ETR IPv6 Mapping Database for EID-table vrf red (IID 101), LSBs: 0x1 m = p2.match(line) if m: group = m.groupdict() etr_eid_vrf = group['vrf'] if group['vrf'] else 'default' lsb = group['lsb'] # Create lisp_dict lisp_dict = parsed_dict.\ setdefault('lisp_router_instances', {}).\ setdefault(lisp_router_id, {}) lisp_dict['lisp_router_instance_id'] = lisp_router_id continue # Entries total 2, no-route 0, inactive 0 m = p3.match(line) if m: group = m.groupdict() total_entries = int(group['total']) no_route_entries = int(group['no_route']) inactive_entries = int(group['inactive']) continue # 192.168.0.0/24, locator-set RLOC # cafe.caff.c9fd/48, dynamic-eid Auto-L2-group-1, inherited from default locator-set RLOC m = p4.match(line) if m: group = m.groupdict() # Create locator_set_dict ls_dict = lisp_dict.setdefault('locator_sets', {}).\ setdefault(group['locator_set'], {}) ls_dict['locator_set_name'] = group['locator_set'] etr_dict = lisp_dict.setdefault('service', {}).\ setdefault(service, {}).\ setdefault('etr', {}).\ setdefault('local_eids', {}).\ setdefault(instance_id, {}) etr_dict['vni'] = instance_id etr_dict['total_eid_entries'] = total_entries etr_dict['no_route_eid_entries'] = no_route_entries etr_dict['inactive_eid_entries'] = inactive_entries # Create eid dict if group['dyn_eid']: eid_dict_name = 'dynamic_eids' else: eid_dict_name = 'eids' eid_dict = etr_dict.setdefault(eid_dict_name, {}).\ setdefault(group['etr_eid'], {}) eid_dict['id'] = group['etr_eid'] eid_dict['rlocs'] = group['locator_set'] if group['dyn_eid']: eid_dict['dynamic_eid'] = group['dyn_eid'] # Create eid_addr_dict eid_addr_dict = eid_dict.setdefault('eid_address', {}) eid_addr_dict['address_type'] = service eid_addr_dict['vrf'] = etr_eid_vrf continue # Locator Pri/Wgt Source State # 10.16.2.2 50/50 cfg-intf site-self, reachable m = p5.match(line) if m: group = m.groupdict() eid_dict['loopback_address'] = group['locator'] eid_dict['priority'] = int(group['priority']) eid_dict['weight'] = int(group['weight']) eid_dict['source'] = group['source'] eid_dict['state'] = group['state'] continue return parsed_dict # ============================================================================= # Schema for 'show lisp all instance-id <instance_id> <service> server summary' # ============================================================================= class ShowLispServiceServerSummarySchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> server summary" ''' schema = { 'lisp_router_instances': {Any(): {'lisp_router_instance_id': int, 'service': {Any(): {'instance_id': {Any(): {'map_server': {Optional('sites'): {Any(): {'site_id': str, 'configured': int, 'registered': int, 'inconsistent': int, }, }, 'summary': {'number_configured_sites': int, 'number_registered_sites':int, Optional('af_datum'): {Any(): {'address_type': str, Optional('number_configured_eids'): int, Optional('number_registered_eids'): int, }, }, 'sites_with_inconsistent_registrations': int, Optional('site_registration_limit'): int, Optional('site_registration_count'): int, }, }, }, }, }, }, }, }, } # ============================================================================= # Parser for 'show lisp all instance-id <instance_id> <service> server summary' # ============================================================================= class ShowLispServiceServerSummary(ShowLispServiceServerSummarySchema): '''Parser for "show lisp all instance-id <instance_id> <service> server summary"''' cli_command = 'show lisp all instance-id {instance_id} {service} server summary' def cli(self, service, instance_id, output=None): if output is None: assert service in ['ipv4', 'ipv6', 'ethernet'] out = self.device.execute(self.cli_command.format(instance_id=instance_id, service=service)) else: out = output # Init vars parsed_dict = {} # Output for router lisp 0 # Output for router lisp 0 instance-id 193 # Output for router lisp 2 instance-id 101 p1 = re.compile(r'Output +for +router +lisp +(?P<router_id>(\S+))' '(?: +instance-id +(?P<instance_id>(\d+)))?$') # ----------- IPv4 ----------- # Site name Configured Registered Incons # xtr1_1 1 1 0 # xtr2 1 1 0 p2 = re.compile(r'(?P<site_name>(\S+)) +(?P<cfgd>(\d+))' ' +(?P<registered>(\d+)) +(?P<incons>(\d+))$') # Number of configured sites: 2 p3 = re.compile(r'Number +of +configured +sites: +(?P<val>(\d+))$') # Number of registered sites: 2 p4 = re.compile(r'Number +of +registered +sites: +(?P<val>(\d+))$') # Number of configured EID prefixes: 2 p5 = re.compile(r'Number +of +configured +EID +prefixes:' ' +(?P<val>(\d+))$') # Number of registered EID prefixes: 2 p6 = re.compile(r'Number +of +registered +EID +prefixes:' ' +(?P<val>(\d+))$') # Site-registration limit for router lisp 2: 0 p7 = re.compile(r'Site-registration +limit +for +router +lisp' ' +(?P<router_id>(\d+)): +(?P<val>(\d+))$') # Site-registration count for router lisp 2: 0 p8 = re.compile(r'Site-registration +count +for +router +lisp' ' +(?P<router_id>(\d+)): +(?P<val>(\d+))$') # Sites with inconsistent registrations: 0 p9 = re.compile(r'Sites +with +inconsistent +registrations:' ' +(?P<val>(\d+))$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 m = p1.match(line) if m: group = m.groupdict() lisp_router_id = int(group['router_id']) if group['instance_id']: instance_id = group['instance_id'] # Create lisp_dict lisp_dict = parsed_dict.\ setdefault('lisp_router_instances', {}).\ setdefault(lisp_router_id, {}) lisp_dict['lisp_router_instance_id'] = lisp_router_id # Create ms dict ms_dict = lisp_dict.setdefault('service', {}).\ setdefault(service, {}).\ setdefault('instance_id', {}).\ setdefault(instance_id, {}).\ setdefault('map_server', {}) # Create counters dict summary_dict = ms_dict.setdefault('summary', {}) continue # Site name Configured Registered Incons # xtr2 1 1 0 m = p2.match(line) if m: group = m.groupdict() # Create sites dict sites_dict = ms_dict.setdefault('sites', {}).\ setdefault(group['site_name'], {}) sites_dict['site_id'] = group['site_name'] sites_dict['configured'] = int(group['cfgd']) sites_dict['registered'] = int(group['registered']) sites_dict['inconsistent'] = int(group['incons']) continue # Number of configured sites: 2 m = p3.match(line) if m: summary_dict['number_configured_sites'] = \ int(m.groupdict()['val']) continue # Number of registered sites: 2 m = p4.match(line) if m: summary_dict['number_registered_sites'] = \ int(m.groupdict()['val']) continue # Number of configured EID prefixes: 2 m = p5.match(line) if m: address_type = service + '-afi' datum_dict = summary_dict.setdefault('af_datum', {}).\ setdefault(address_type, {}) datum_dict['address_type'] = address_type datum_dict['number_configured_eids'] = \ int(m.groupdict()['val']) continue # Number of registered EID prefixes: 2 m = p6.match(line) if m: datum_dict['number_registered_eids'] = \ int(m.groupdict()['val']) continue # Site-registration limit for router lisp 2: 0 m = p7.match(line) if m: summary_dict['site_registration_limit'] = \ int(m.groupdict()['val']) continue # Site-registration count for router lisp 2: 0 m = p8.match(line) if m: summary_dict['site_registration_count'] = \ int(m.groupdict()['val']) continue # Sites with inconsistent registrations: 0 m = p9.match(line) if m: summary_dict['sites_with_inconsistent_registrations'] = \ int(m.groupdict()['val']) continue return parsed_dict # ===================================================================================== # Schema for 'show lisp all instance-id <instance_id> <service> server detail internal' # ===================================================================================== class ShowLispServiceServerDetailInternalSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> server detail internal" ''' schema = { 'lisp_router_instances': {Any(): {Optional('service'): {Any(): {'map_server': {'sites': {Any(): {'site_id': str, 'allowed_configured_locators': str, }, }, Optional('virtual_network_ids'): {Any(): {'vni': str, 'mappings': {Any(): {'eid_id': str, 'eid_address': {'address_type': str, 'virtual_network_id': str, Optional('ipv4'): {'ipv4': str, }, Optional('ipv6'): {'ipv6': str, }, Optional('ipv4_prefix'): {'ipv4_prefix': str, }, Optional('ipv6_prefix'): {'ipv6_prefix': str, }, }, 'site_id': str, 'first_registered': str, 'last_registered': str, 'routing_table_tag': int, 'origin': str, Optional('more_specifics_accepted'): bool, 'merge_active': bool, 'proxy_reply': bool, 'ttl': str, 'state': str, 'registration_errors': {'authentication_failures': int, 'allowed_locators_mismatch': int, }, Optional('mapping_records'): {Any(): {'xtr_id': str, 'site_id': str, 'etr': str, 'eid': {'address_type': str, 'virtual_network_id': str, Optional('ipv4'): {'ipv4': str, }, Optional('ipv6'): {'ipv6': str, }, Optional('ipv4_prefix'): {'ipv4_prefix': str, }, Optional('ipv6_prefix'): {'ipv6_prefix': str, }, }, 'ttl': str, 'time_to_live': int, 'creation_time': str, 'merge': bool, 'proxy_reply': bool, 'map_notify': bool, 'hash_function': str, 'nonce': str, 'state': str, 'security_capability': bool, 'sourced_by': str, 'locator': {Any(): {'local': bool, 'state': str, 'priority': int, 'weight': int, 'scope': str, }, }, }, }, }, }, }, }, }, }, }, }, }, } # ===================================================================================== # Parser for 'show lisp all instance-id <instance_id> <service> server detail internal' # ===================================================================================== class ShowLispServiceServerDetailInternal(ShowLispServiceServerDetailInternalSchema): '''Parser for "show lisp all instance-id <instance_id> <service> server detail internal"''' cli_command = 'show lisp all instance-id {instance_id} {service} server detail internal' def cli(self, service, instance_id, output=None): if output is None: assert service in ['ipv4', 'ipv6', 'ethernet'] out = self.device.execute(self.cli_command.format(instance_id=instance_id, service=service)) else: out = output # Init vars parsed_dict = {} # state dict state_dict = { 'yes': True, 'no': False, } # Output for router lisp 0 # Output for router lisp 0 instance-id 193 # Output for router lisp 2 instance-id 101 p1 = re.compile(r'Output +for +router +lisp +(?P<router_id>(\S+))' '(?: +instance-id +(?P<instance_id>(\d+)))?$') # Site name: prov1 # Site name: provider p2 = re.compile(r'Site +name: +(?P<site_name>(\S+))$') # Allowed configured locators: any p3 = re.compile(r'Allowed +configured +locators: +(?P<val>(\S+))$') # EID-prefix: 192.168.0.1/32 instance-id 101 p4 = re.compile(r'EID-prefix: +(?P<eid>(\S+)) +instance-id' ' +(?P<iid>(\d+))$') # First registered: 01:12:41 p5 = re.compile(r'First +registered: +(?P<first>(\S+))$') # Last registered: 01:12:41 p6 = re.compile(r'Last +registered: +(?P<last>(\S+))$') # Routing table tag: 0 p7 = re.compile(r'Routing +table +tag: +(?P<rtt>(\d+))$') # Origin: Dynamic, more specific of 192.168.0.0/24 p8_1 = re.compile(r'Origin: +(?P<origin>(\S+))(?:, +more +specific +of' ' +(\S+))?$') # Origin: Configuration, accepting more specifics p8_2 = re.compile(r'Origin: +(?P<origin>(\S+))(?:,' ' +(?P<more_specific>(accepting more specifics)))?$') # Merge active: No p9 = re.compile(r'Merge +active: +(?P<merge>(Yes|No))$') # Proxy reply: Yes p10 = re.compile(r'Proxy +reply: +(?P<proxy>(Yes|No))$') # TTL: 1d00h p11 = re.compile(r'TTL: +(?P<ttl>(\S+))$') # State: complete p12 = re.compile(r'State: +(?P<state>(\S+))$') # Registration errors: # Authentication failures: 0 p13 = re.compile(r'Authentication +failures: +(?P<auth_failures>(\d+))$') # Allowed locators mismatch: 0 p14 = re.compile(r'Allowed +locators +mismatch: +(?P<mismatch>(\d+))$') # ETR 10.16.2.2, last registered 01:12:41, proxy-reply, map-notify p15 = re.compile(r'ETR +(?P<etr>(\S+)), +last +registered' ' +(?P<last_registered>(\S+)),' '(?: +(?P<proxy_reply>(proxy-reply)),)?' '(?: +(?P<map_notify>(map-notify)))?$') # TTL 1d00h, no merge, hash-function sha1, nonce 0x70D18EF4-0x3A605D67 p16 = re.compile(r'TTL +(?P<ttl>(\S+)),(?: +(?P<merge>(no merge)),)?' ' +hash-function +(?P<hash>(\S+)) +nonce' ' +(?P<nonce>(\S+))$') # state complete, no security-capability p17 = re.compile(r'state +(?P<state>(\S+))' '(?:, +(?P<security>(no security-capability)))?$') # xTR-ID 0x21EDD25F-0x7598784C-0x769C8E4E-0xC04926EC p18 = re.compile(r'xTR-ID +(?P<xtr_id>(.*))$') # site-ID unspecified p19 = re.compile(r'site-ID +(?P<site_id>(.*))$') # sourced by reliable transport p20 = re.compile(r'sourced +by +(?P<source>(.*))$') # Locator Local State Pri/Wgt Scope # 10.16.2.2 yes up 50/50 IPv4 none p21 = re.compile(r'(?P<locator>(\S+)) +(?P<local>(\S+))' ' +(?P<state>(\S+)) +(?P<priority>(\d+))\/' '(?P<weight>(\d+)) +(?P<scope>(.*))$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 m = p1.match(line) if m: group = m.groupdict() lisp_router_id = int(group['router_id']) if group['instance_id']: instance_id = group['instance_id'] continue # Site name: prov1 m = p2.match(line) if m: site_id = m.groupdict()['site_name'] # Create service dict ms_dict = parsed_dict.\ setdefault('lisp_router_instances', {}).\ setdefault(lisp_router_id, {}).\ setdefault('service', {}).\ setdefault(service, {}).\ setdefault('map_server', {}) # Create sites dict sites_dict = ms_dict.setdefault('sites', {}).\ setdefault(site_id, {}) sites_dict['site_id'] = site_id continue # Allowed configured locators: any m = p3.match(line) if m: sites_dict['allowed_configured_locators'] = m.groupdict()['val'] continue # EID-prefix: 192.168.0.1/32 instance-id 101 m = p4.match(line) if m: group = m.groupdict() eid = group['eid'] # Create vni dict vni_dict = ms_dict.setdefault('virtual_network_ids', {}).\ setdefault(group['iid'], {}) vni_dict['vni'] = group['iid'] mappings_dict = vni_dict.setdefault('mappings', {}).\ setdefault(eid, {}) mappings_dict['eid_id'] = eid eid_address_dict = mappings_dict.setdefault('eid_address', {}) eid_address_dict['virtual_network_id'] = group['iid'] if ":" not in eid: eid_address_dict['address_type'] = 'ipv4-afi' eid_address_dict.setdefault('ipv4', {})['ipv4'] = eid else: eid_address_dict['address_type'] = 'ipv6-afi' eid_address_dict.setdefault('ipv6', {})['ipv6'] = eid mappings_dict['site_id'] = site_id continue # First registered: 01:12:41 m = p5.match(line) if m: mappings_dict['first_registered'] = m.groupdict()['first'] continue # Last registered: 01:12:41 m = p6.match(line) if m: mappings_dict['last_registered'] = m.groupdict()['last'] continue # Routing table tag: 0 m = p7.match(line) if m: mappings_dict['routing_table_tag'] = int(m.groupdict()['rtt']) continue # Origin: Dynamic, more specific of 192.168.0.0/24 m = p8_1.match(line) if m: mappings_dict['origin'] = m.groupdict()['origin'] continue # Origin: Configuration, accepting more specifics m = p8_2.match(line) if m: mappings_dict['origin'] = m.groupdict()['origin'] if m.groupdict()['more_specific']: mappings_dict['more_specifics_accepted'] = True continue # Merge active: No m = p9.match(line) if m: mappings_dict['merge_active'] = \ state_dict[m.groupdict()['merge'].lower()] continue # Proxy reply: Yes m = p10.match(line) if m: mappings_dict['proxy_reply'] = \ state_dict[m.groupdict()['proxy'].lower()] continue # TTL: 1d00h m = p11.match(line) if m: mappings_dict['ttl'] = m.groupdict()['ttl'] continue # State: complete m = p12.match(line) if m: mappings_dict['state'] = m.groupdict()['state'] continue # Registration errors: # Authentication failures: 0 m = p13.match(line) if m: reg_errors_dict = mappings_dict.\ setdefault('registration_errors', {}) reg_errors_dict['authentication_failures'] = \ int(m.groupdict()['auth_failures']) continue # Allowed locators mismatch: 0 m = p14.match(line) if m: reg_errors_dict['allowed_locators_mismatch'] = \ int(m.groupdict()['mismatch']) continue # ETR 10.16.2.2, last registered 01:12:41, proxy-reply, map-notify m = p15.match(line) if m: group = m.groupdict() etr = group['etr'] creation_time = group['last_registered'] if group['proxy_reply']: proxy_reply = True if group['map_notify']: map_notify = True continue # TTL 1d00h, no merge, hash-function sha1, nonce 0x70D18EF4-0x3A605D67 m = p16.match(line) if m: group = m.groupdict() ttl = group['ttl'] n = re.match('(?P<day>(\d+))d(?P<hours>(\d+))h', ttl) days = n.groupdict()['day'] ; hours = n.groupdict()['hours'] time_to_live = (int(days) * 86400) + (int(hours) * 3600) if group['merge'] == 'no merge': merge_active = False hash_function = group['hash'] nonce = group['nonce'] continue # state complete, no security-capability m = p17.match(line) if m: group = m.groupdict() state = group['state'] if 'no' in group['security']: security_capability = False else: security_capability = True continue # xTR-ID 0x21EDD25F-0x7598784C-0x769C8E4E-0xC04926EC m = p18.match(line) if m: group = m.groupdict() mapping_records_dict = mappings_dict.\ setdefault('mapping_records', {}).\ setdefault(group['xtr_id'], {}) mapping_records_dict['xtr_id'] = group['xtr_id'] mapping_records_dict['etr'] = etr mr_eid_dict = mapping_records_dict.setdefault('eid', {}) mr_eid_dict['virtual_network_id'] = instance_id if ":" not in eid: mr_eid_dict['address_type'] = 'ipv4-afi' mr_eid_dict.setdefault('ipv4', {})['ipv4'] = eid else: mr_eid_dict['address_type'] = 'ipv6-afi' mr_eid_dict.setdefault('ipv6', {})['ipv6'] = eid # Set previously parsed values mapping_records_dict['security_capability'] = security_capability mapping_records_dict['state'] = state mapping_records_dict['nonce'] = nonce mapping_records_dict['hash_function'] = hash_function mapping_records_dict['merge'] = merge_active mapping_records_dict['ttl'] = ttl mapping_records_dict['time_to_live'] = time_to_live mapping_records_dict['map_notify'] = map_notify mapping_records_dict['proxy_reply'] = proxy_reply mapping_records_dict['map_notify'] = map_notify mapping_records_dict['creation_time'] = creation_time continue # site-ID unspecified m = p19.match(line) if m: mapping_records_dict['site_id'] = m.groupdict()['site_id'] continue # sourced by reliable transport m = p20.match(line) if m: mapping_records_dict['sourced_by'] = m.groupdict()['source'] continue # Locator Local State Pri/Wgt Scope # 10.16.2.2 yes up 50/50 IPv4 none m = p21.match(line) if m: group = m.groupdict() locator_dict = mapping_records_dict.setdefault('locator', {}).\ setdefault(group['locator'], {}) locator_dict['local'] = state_dict[group['local']] locator_dict['state'] = group['state'] locator_dict['priority'] = int(group['priority']) locator_dict['weight'] = int(group['weight']) locator_dict['scope'] = group['scope'] continue return parsed_dict # ========================================================================= # Schema for 'show lisp all instance-id <instance_id> <service> statistics' # ========================================================================= class ShowLispServiceStatisticsSchema(MetaParser): '''Schema for "show lisp all instance-id <instance_id> <service> statistics" ''' schema = { 'lisp_router_instances': {Any(): {'service': {Any(): {'statistics': {Any(): {'last_cleared': str, Any(): Any(), Optional('map_resolvers'): {Any(): {'last_reply': str, 'metric': str, 'reqs_sent': int, 'positive': int, 'negative': int, 'no_reply': int, }, }, }, }, }, }, }, }, } # ========================================================================= # Parser for 'show lisp all instance-id <instance_id> <service> statistics' # ========================================================================= class ShowLispServiceStatistics(ShowLispServiceStatisticsSchema): '''Parser for "show lisp all instance-id <instance_id> <service> statistics"''' cli_command = 'show lisp all instance-id {instance_id} {service} statistics' exclude = ['map_register_records_out'] def cli(self, service, instance_id, output=None): if output is None: assert service in ['ipv4', 'ipv6', 'ethernet'] out = self.device.execute(self.cli_command.format(instance_id=instance_id, service=service)) else: out = output # Init vars parsed_dict = {} # state dict state_dict = { 'yes': True, 'no': False, } # Output for router lisp 0 # Output for router lisp 0 instance-id 193 # Output for router lisp 2 instance-id 101 p1 = re.compile(r'^Output +for +router +lisp +(?P<router_id>(\S+))' '(?: +instance-id +(?P<instance_id>(\d+)))?$') # LISP EID Statistics for instance ID 1 - last cleared: never # LISP RLOC Statistics - last cleared: never # LISP Miscellaneous Statistics - last cleared: never p2 = re.compile(r'LISP +(?P<stat_type>(\S+)) +Statistics' '(?: +for +instance +ID +(?P<iid>(\d+)))?' ' +\- +last +cleared: +(?P<last_cleared>(\S+))$') # Control Packets: p3_1 = re.compile(r'Control Packets:$') # Errors: p3_2 = re.compile(r'Errors:$') # Map-Register records in/out: 0/52 p4 = re.compile(r'Map-Register +records +in\/out: +(?P<in>(\d+))\/(?P<out>(\d+))$') # Map-Notify records in/out: 2/0 p5 = re.compile(r'Map-Notify +records +in\/out: +(?P<in>(\d+))\/(?P<out>(\d+))$') # Authentication failures: 0 p6 = re.compile(r'Authentication +failures: +(?P<auth_failures>(\d+))$') # Map-Requests in/out: 8/40 # Encapsulated Map-Requests in/out: 8/36 # RLOC-probe Map-Requests in/out: 0/4 # SMR-based Map-Requests in/out: 0/4 # Extranet SMR cross-IID Map-Requests in: 0 # Map-Requests expired on-queue/no-reply 0/13 # Map-Resolver Map-Requests forwarded: 0 # Map-Server Map-Requests forwarded: 0 p7 = re.compile(r'^(?P<key>([a-zA-Z\-\/\s]+))\: +(?P<value>(.*))$') # Map-Resolver LastReply Metric ReqsSent Positive Negative No-Reply # 10.94.44.44 never 1 306 18 0 66 # 10.84.66.66 never Unreach 0 0 0 0 p8 = re.compile(r'(?P<mr>([a-zA-Z0-9\.\:]+)) +(?P<last_reply>(\S+))' ' +(?P<metric>(\S+)) +(?P<sent>(\d+))' ' +(?P<positive>(\d+)) +(?P<negative>(\d+))' ' +(?P<no_reply>(\d+))$') for line in out.splitlines(): line = line.strip() # Output for router lisp 0 m = p1.match(line) if m: group = m.groupdict() lisp_router_id = int(group['router_id']) if group['instance_id']: instance_id = group['instance_id'] continue # LISP EID Statistics for instance ID 1 - last cleared: never m = p2.match(line) if m: group = m.groupdict() # Create stats dict stats_dict = parsed_dict.\ setdefault('lisp_router_instances', {}).\ setdefault(lisp_router_id, {}).\ setdefault('service', {}).\ setdefault(service, {}).\ setdefault('statistics', {}).\ setdefault(group['stat_type'], {}) stats_dict['last_cleared'] = m.groupdict()['last_cleared'] continue # Control Packets: m = p3_1.match(line) if m: last_dict = stats_dict.setdefault('control', {}) continue # Errors: m = p3_2.match(line) if m: last_dict = stats_dict.setdefault('errors', {}) continue # Map-Register records in/out: 0/52 m = p4.match(line) if m: group = m.groupdict() last_dict['map_register_records_in'] = group['in'] last_dict['map_register_records_out'] = group['out'] map_register = True continue # Map-Notify records in/out: 2/0 m = p5.match(line) if m: group = m.groupdict() last_dict['map_notify_records_in'] = group['in'] last_dict['map_notify_records_out'] = group['out'] map_register = False continue # Authentication failures: 0 m = p6.match(line) if m: failures = m.groupdict()['auth_failures'] if map_register: last_dict['map_registers_in_auth_failed'] = failures else: last_dict['map_notify_auth_failures'] = failures continue # Map-Requests in/out: 8/40 # Encapsulated Map-Requests in/out: 8/36 # RLOC-probe Map-Requests in/out: 0/4 # SMR-based Map-Requests in/out: 0/4 # Extranet SMR cross-IID Map-Requests in: 0 # Map-Requests expired on-queue/no-reply 0/13 # Map-Resolver Map-Requests forwarded: 0 # Map-Server Map-Requests forwarded: 0 m = p7.match(line) if m: group = m.groupdict() if "/" in group['key']: # split the key into 2 splitkey = re.search('(?P<splitkey>(\S+\/\S+))', group['key'])\ .groupdict()['splitkey'] splitkey1, splitkey2 = splitkey.split("/") key = group['key'].replace(splitkey, "").strip().lower().\ replace(" ", "_").replace("-", "_") key1 = key + "_" + splitkey1 key2 = key + "_" + splitkey2 # set values val1, val2 = group['value'].split("/") last_dict[key1] = val1 last_dict[key2] = val2 else: key = group['key'].lower().replace(" ", "_").\ replace("-", "_") last_dict[key] = group['value'] continue # Map-Resolver LastReply Metric ReqsSent Positive Negative No-Reply # 10.94.44.44 never 1 306 18 0 66 # 10.84.66.66 never Unreach 0 0 0 0 m = p8.match(line) if m: group = m.groupdict() mr_dict = last_dict.setdefault('map_rseolvers', {}).\ setdefault(group['mr'], {}) mr_dict['last_reply'] = group['last_reply'] mr_dict['metric'] = group['metric'] mr_dict['reqs_sent'] = int(group['sent']) mr_dict['positive'] = int(group['positive']) mr_dict['negative'] = int(group['negative']) mr_dict['no_reply'] = int(group['no_reply']) continue return parsed_dict
96,030
0
351
5e78f403cc852ace716d8b2f648ee3e2ff373ed8
1,771
py
Python
alipay/aop/api/domain/AftFinsecureRiskplusSecurityPolicyQueryModel.py
articuly/alipay-sdk-python-all
0259cd28eca0f219b97dac7f41c2458441d5e7a6
[ "Apache-2.0" ]
null
null
null
alipay/aop/api/domain/AftFinsecureRiskplusSecurityPolicyQueryModel.py
articuly/alipay-sdk-python-all
0259cd28eca0f219b97dac7f41c2458441d5e7a6
[ "Apache-2.0" ]
null
null
null
alipay/aop/api/domain/AftFinsecureRiskplusSecurityPolicyQueryModel.py
articuly/alipay-sdk-python-all
0259cd28eca0f219b97dac7f41c2458441d5e7a6
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.EventInfo import EventInfo
29.516667
89
0.644833
#!/usr/bin/env python # -*- coding: utf-8 -*- import simplejson as json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.EventInfo import EventInfo class AftFinsecureRiskplusSecurityPolicyQueryModel(object): def __init__(self): self._event_info = None self._product_instance_id = None @property def event_info(self): return self._event_info @event_info.setter def event_info(self, value): if isinstance(value, EventInfo): self._event_info = value else: self._event_info = EventInfo.from_alipay_dict(value) @property def product_instance_id(self): return self._product_instance_id @product_instance_id.setter def product_instance_id(self, value): self._product_instance_id = value def to_alipay_dict(self): params = dict() if self.event_info: if hasattr(self.event_info, 'to_alipay_dict'): params['event_info'] = self.event_info.to_alipay_dict() else: params['event_info'] = self.event_info if self.product_instance_id: if hasattr(self.product_instance_id, 'to_alipay_dict'): params['product_instance_id'] = self.product_instance_id.to_alipay_dict() else: params['product_instance_id'] = self.product_instance_id return params @staticmethod def from_alipay_dict(d): if not d: return None o = AftFinsecureRiskplusSecurityPolicyQueryModel() if 'event_info' in d: o.event_info = d['event_info'] if 'product_instance_id' in d: o.product_instance_id = d['product_instance_id'] return o
1,237
328
23
0aee884f4044f7b6ddda2ef8e3a002ffad99c836
1,972
py
Python
coursecake/scrapers/course.py
nananananate/CourseScraper
4ef40cb2bd5f42177c8596fd18ead66b4a9d2379
[ "MIT" ]
21
2020-07-18T01:17:53.000Z
2021-09-11T08:28:59.000Z
coursecake/scrapers/course.py
AlfiyaZi/CourseCake
be2af4d0025f2963ed83001004f87df2c6d8b71d
[ "MIT" ]
4
2020-10-03T00:22:20.000Z
2021-03-31T19:54:33.000Z
coursecake/scrapers/course.py
AlfiyaZi/CourseCake
be2af4d0025f2963ed83001004f87df2c6d8b71d
[ "MIT" ]
4
2020-09-05T05:17:26.000Z
2020-10-16T05:49:34.000Z
import copy class Course: """ All information needed to be collected about a course """ def __init__( self, course_dict=None, course=None, ): """ All None attributes must be provided Can be constructed as empty, from a dictionary """ ### Mandatory attributes ### ### Strings # The formal name of the course which acts as an ID self.course_id = None # The Title of the course; more human readable self.title = None self.department = None ### Optional Attributes ### # nullable in our db models self.classes = list() self.units = -1 self.prerequisites_str = "" self.restrictions = "" self.school = "" # a more readable department name # Ex: COMSPSCI -> Computer Science self.department_title = "" # Who provided this data (3rd party API? coded in-house? team member?) self.provider = "" if course_dict != None: self._init_from_dict(course_dict) if course != None: self._init_from_dict(course.__dict__) # must deep copy list self.classes = copy.deepcopy(course.classes)
23.2
78
0.533976
import copy class Course: """ All information needed to be collected about a course """ def __init__( self, course_dict=None, course=None, ): """ All None attributes must be provided Can be constructed as empty, from a dictionary """ ### Mandatory attributes ### ### Strings # The formal name of the course which acts as an ID self.course_id = None # The Title of the course; more human readable self.title = None self.department = None ### Optional Attributes ### # nullable in our db models self.classes = list() self.units = -1 self.prerequisites_str = "" self.restrictions = "" self.school = "" # a more readable department name # Ex: COMSPSCI -> Computer Science self.department_title = "" # Who provided this data (3rd party API? coded in-house? team member?) self.provider = "" if course_dict != None: self._init_from_dict(course_dict) if course != None: self._init_from_dict(course.__dict__) # must deep copy list self.classes = copy.deepcopy(course.classes) def _init_from_dict(self, course_dict: dict): # print(course_dict) for key in course_dict: # DONT COPY CLASSES if key != "classes": self.__dict__[key] = course_dict[key] else: pass def is_valid_course(self) -> bool: for value in self.__dict__.values(): if value == None: return False return True def toInt(self, s: str) -> int: try: return int(s) except ValueError: return -1 def __str__(self) -> str: return f"""Course: {self.title} {self.course_id} {self.units} """
590
0
108
296da7520a82e6b39740ad3971be880ce675dc15
265
py
Python
widget_periodictable/tests/test_example.py
osscar-org/widget-periodictable
35264ce79e6b9e82dcdfe17558a7a17ac6c24e96
[ "BSD-3-Clause" ]
2
2020-03-27T04:20:55.000Z
2020-08-25T18:20:57.000Z
widget_periodictable/tests/test_example.py
osscar-org/widget-periodictable
35264ce79e6b9e82dcdfe17558a7a17ac6c24e96
[ "BSD-3-Clause" ]
15
2020-05-06T17:03:16.000Z
2021-11-08T15:41:51.000Z
widget_periodictable/tests/test_example.py
osscar-org/widget-periodictable
35264ce79e6b9e82dcdfe17558a7a17ac6c24e96
[ "BSD-3-Clause" ]
2
2020-07-07T19:07:04.000Z
2022-03-01T02:52:58.000Z
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Dou Du. # Distributed under the terms of the Modified BSD License. import pytest from ..periodic_table import PTableWidget
17.666667
58
0.724528
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Dou Du. # Distributed under the terms of the Modified BSD License. import pytest from ..periodic_table import PTableWidget def test_example_creation_blank(): w = PTableWidget() assert w.states == 1
61
0
23
6d19afbc06ea546d7bf71d5095659e63bc2f564e
1,634
py
Python
scripts/datasets/mvsec_convert_night_groundtruth.py
SensorsINI/v2e_exps_public
d3ec8c2ecda29eb8cae8dd47869449f8cdcbd87a
[ "MIT" ]
3
2022-01-03T15:29:24.000Z
2022-03-04T13:43:37.000Z
scripts/datasets/mvsec_convert_night_groundtruth.py
SensorsINI/v2e_exps_public
d3ec8c2ecda29eb8cae8dd47869449f8cdcbd87a
[ "MIT" ]
null
null
null
scripts/datasets/mvsec_convert_night_groundtruth.py
SensorsINI/v2e_exps_public
d3ec8c2ecda29eb8cae8dd47869449f8cdcbd87a
[ "MIT" ]
null
null
null
"""Groundtruth saved in XML, saved as compatible format in txt. Author: Yuhuang Hu Email : yuhuang.hu@ini.uch.ch """ import argparse import os import glob import json import xmltodict from v2e_exps.utils import expandpath parser = argparse.ArgumentParser() parser.add_argument("--data_root", type=expandpath) parser.add_argument("--output_root", type=expandpath) args = parser.parse_args() file_list = sorted( glob.glob( os.path.join(args.data_root, "*.xml"))) if not os.path.isdir(args.output_root): os.makedirs(args.output_root) for file_path in file_list: file_base = os.path.basename(file_path) output_path = os.path.join( args.output_root, file_base[:-4]+".txt") with open(file_path) as f: data = xmltodict.parse(f.read()) objects = data["annotation"]["object"] # print(output_path, len(objects)) # print(json.dumps(data, # indent=4, sort_keys=True)) if type(objects) is list: for obj in objects: bndbox = obj["bndbox"] xmin = bndbox["xmin"] ymin = bndbox["ymin"] xmax = bndbox["xmax"] ymax = bndbox["ymax"] with open(output_path, "a+") as f: f.write("car {} {} {} {}\n".format(xmin, ymin, xmax, ymax)) else: bndbox = objects["bndbox"] xmin = bndbox["xmin"] ymin = bndbox["ymin"] xmax = bndbox["xmax"] ymax = bndbox["ymax"] with open(output_path, "a+") as f: f.write("car {} {} {} {}\n".format(xmin, ymin, xmax, ymax)) print("Write to {}".format(output_path))
23.681159
75
0.596083
"""Groundtruth saved in XML, saved as compatible format in txt. Author: Yuhuang Hu Email : yuhuang.hu@ini.uch.ch """ import argparse import os import glob import json import xmltodict from v2e_exps.utils import expandpath parser = argparse.ArgumentParser() parser.add_argument("--data_root", type=expandpath) parser.add_argument("--output_root", type=expandpath) args = parser.parse_args() file_list = sorted( glob.glob( os.path.join(args.data_root, "*.xml"))) if not os.path.isdir(args.output_root): os.makedirs(args.output_root) for file_path in file_list: file_base = os.path.basename(file_path) output_path = os.path.join( args.output_root, file_base[:-4]+".txt") with open(file_path) as f: data = xmltodict.parse(f.read()) objects = data["annotation"]["object"] # print(output_path, len(objects)) # print(json.dumps(data, # indent=4, sort_keys=True)) if type(objects) is list: for obj in objects: bndbox = obj["bndbox"] xmin = bndbox["xmin"] ymin = bndbox["ymin"] xmax = bndbox["xmax"] ymax = bndbox["ymax"] with open(output_path, "a+") as f: f.write("car {} {} {} {}\n".format(xmin, ymin, xmax, ymax)) else: bndbox = objects["bndbox"] xmin = bndbox["xmin"] ymin = bndbox["ymin"] xmax = bndbox["xmax"] ymax = bndbox["ymax"] with open(output_path, "a+") as f: f.write("car {} {} {} {}\n".format(xmin, ymin, xmax, ymax)) print("Write to {}".format(output_path))
0
0
0
a6ae443d9b80e2602554220cec23dc5bc418d79f
4,712
py
Python
xga/models/__init__.py
DavidT3/XGA
cde51c3f29f98b5f1e981fb6d327c04072b0ba38
[ "BSD-3-Clause" ]
12
2020-05-16T09:45:45.000Z
2022-02-14T14:41:46.000Z
xga/models/__init__.py
DavidT3/XGA
cde51c3f29f98b5f1e981fb6d327c04072b0ba38
[ "BSD-3-Clause" ]
684
2020-05-28T08:52:09.000Z
2022-03-31T10:56:24.000Z
xga/models/__init__.py
DavidT3/XGA
cde51c3f29f98b5f1e981fb6d327c04072b0ba38
[ "BSD-3-Clause" ]
2
2022-02-04T10:55:55.000Z
2022-02-04T11:30:56.000Z
# This code is a part of XMM: Generate and Analyse (XGA), a module designed for the XMM Cluster Survey (XCS). # Last modified by David J Turner (david.turner@sussex.ac.uk) 08/03/2021, 17:29. Copyright (c) David J Turner import inspect from types import FunctionType # Doing star imports just because its more convenient, and there won't ever be enough code in these that # it becomes a big inefficiency from .density import * from .misc import * from .sb import * from .temperature import * # This dictionary is meant to provide pretty versions of model/function names to go in plots # This method of merging dictionaries only works in Python 3.5+, but that should be fine MODEL_PUBLICATION_NAMES = {**DENS_MODELS_PUB_NAMES, **MISC_MODELS_PUB_NAMES, **SB_MODELS_PUB_NAMES, **TEMP_MODELS_PUB_NAMES} MODEL_PUBLICATION_PAR_NAMES = {**DENS_MODELS_PAR_NAMES, **MISC_MODELS_PAR_NAMES, **SB_MODELS_PAR_NAMES, **TEMP_MODELS_PAR_NAMES} # These dictionaries tell the profile fitting function what models, start pars, and priors are allowed PROF_TYPE_MODELS = {"brightness": SB_MODELS, "gas_density": DENS_MODELS, "gas_temperature": TEMP_MODELS} def convert_to_odr_compatible(model_func: FunctionType, new_par_name: str = 'β', new_data_name: str = 'x_values') \ -> FunctionType: """ This is a bit of a weird one; its meant to convert model functions from the standard XGA setup (i.e. pass x values, then parameters as individual variables), into the form expected by Scipy's ODR. I'd recommend running a check to compare results from the original and converted functions where-ever this function is called - I don't completely trust it. :param FunctionType model_func: The original model function to be converted. :param str new_par_name: The name we want to use for the new list/array of fit parameters. :param str new_data_name: The new name we want to use for the x_data. :return: A successfully converted model function (hopefully) which can be used with ODR. :rtype: FunctionType """ # This is not at all perfect, but its a bodge that will do for now. If type hints are included in # the signature (as they should be in all XGA models), then np.ndarray will be numpy.ndarray in the # signature I extract. This dictionary will be used to swap that out, along with any similar problems I encounter common_conversions = {'numpy': 'np'} # This reads out the function signature - which should be structured as x_values, par1, par2, par3 etc. mod_sig = inspect.signature(model_func) # Convert that signature into a string str_mod_sig = str(mod_sig) # Go through the conversion dictionary and 'correct' the signature for conv in common_conversions: str_mod_sig = str_mod_sig.replace(conv, common_conversions[conv]) # For ODR I've decided that β is the name of the new fit parameter array, and x_values the name of the # x data. This will replace the current signature of the function. new_mod_sig = '({np}, {nd})'.format(np=new_par_name, nd=new_data_name) # I find the current names of the parameters in the signature, excluding the x value name in the original function # and reading that into a separate variable mod_sig_pars = list(mod_sig.parameters.keys()) par_names = mod_sig_pars[1:] # Store the name of the x data here data_name = mod_sig_pars[0] # This gets the source code of the function as a string mod_code = inspect.getsource(model_func) # I swap in the new signature new_mod_code = mod_code.replace(str_mod_sig, new_mod_sig) # And now I know the exact form of the whole def line I can define that as a variable and then temporarily # remove it from the source code known_def = 'def {mn}'.format(mn=model_func.__name__) + new_mod_sig + ':' new_mod_code = new_mod_code.replace(known_def, '') # Then I swing through all the original parameter names and replace them with accessing elements of our # new beta parameter list/array. for par_ind, par_name in enumerate(par_names): new_mod_code = new_mod_code.replace(par_name, '{np}[{i}]'.format(np=new_par_name, i=par_ind)) # Then I do the same thing for the new x data variable name new_mod_code = new_mod_code.replace(data_name, new_data_name) # Adds the def SIGNATURE line back in new_mod_code = known_def + new_mod_code # This compiles the code and creates a new function new_model_func_code = compile(new_mod_code, '<string>', 'exec') new_model_func = FunctionType(new_model_func_code.co_consts[0], globals(), model_func.__name__) return new_model_func
50.666667
118
0.732598
# This code is a part of XMM: Generate and Analyse (XGA), a module designed for the XMM Cluster Survey (XCS). # Last modified by David J Turner (david.turner@sussex.ac.uk) 08/03/2021, 17:29. Copyright (c) David J Turner import inspect from types import FunctionType # Doing star imports just because its more convenient, and there won't ever be enough code in these that # it becomes a big inefficiency from .density import * from .misc import * from .sb import * from .temperature import * # This dictionary is meant to provide pretty versions of model/function names to go in plots # This method of merging dictionaries only works in Python 3.5+, but that should be fine MODEL_PUBLICATION_NAMES = {**DENS_MODELS_PUB_NAMES, **MISC_MODELS_PUB_NAMES, **SB_MODELS_PUB_NAMES, **TEMP_MODELS_PUB_NAMES} MODEL_PUBLICATION_PAR_NAMES = {**DENS_MODELS_PAR_NAMES, **MISC_MODELS_PAR_NAMES, **SB_MODELS_PAR_NAMES, **TEMP_MODELS_PAR_NAMES} # These dictionaries tell the profile fitting function what models, start pars, and priors are allowed PROF_TYPE_MODELS = {"brightness": SB_MODELS, "gas_density": DENS_MODELS, "gas_temperature": TEMP_MODELS} def convert_to_odr_compatible(model_func: FunctionType, new_par_name: str = 'β', new_data_name: str = 'x_values') \ -> FunctionType: """ This is a bit of a weird one; its meant to convert model functions from the standard XGA setup (i.e. pass x values, then parameters as individual variables), into the form expected by Scipy's ODR. I'd recommend running a check to compare results from the original and converted functions where-ever this function is called - I don't completely trust it. :param FunctionType model_func: The original model function to be converted. :param str new_par_name: The name we want to use for the new list/array of fit parameters. :param str new_data_name: The new name we want to use for the x_data. :return: A successfully converted model function (hopefully) which can be used with ODR. :rtype: FunctionType """ # This is not at all perfect, but its a bodge that will do for now. If type hints are included in # the signature (as they should be in all XGA models), then np.ndarray will be numpy.ndarray in the # signature I extract. This dictionary will be used to swap that out, along with any similar problems I encounter common_conversions = {'numpy': 'np'} # This reads out the function signature - which should be structured as x_values, par1, par2, par3 etc. mod_sig = inspect.signature(model_func) # Convert that signature into a string str_mod_sig = str(mod_sig) # Go through the conversion dictionary and 'correct' the signature for conv in common_conversions: str_mod_sig = str_mod_sig.replace(conv, common_conversions[conv]) # For ODR I've decided that β is the name of the new fit parameter array, and x_values the name of the # x data. This will replace the current signature of the function. new_mod_sig = '({np}, {nd})'.format(np=new_par_name, nd=new_data_name) # I find the current names of the parameters in the signature, excluding the x value name in the original function # and reading that into a separate variable mod_sig_pars = list(mod_sig.parameters.keys()) par_names = mod_sig_pars[1:] # Store the name of the x data here data_name = mod_sig_pars[0] # This gets the source code of the function as a string mod_code = inspect.getsource(model_func) # I swap in the new signature new_mod_code = mod_code.replace(str_mod_sig, new_mod_sig) # And now I know the exact form of the whole def line I can define that as a variable and then temporarily # remove it from the source code known_def = 'def {mn}'.format(mn=model_func.__name__) + new_mod_sig + ':' new_mod_code = new_mod_code.replace(known_def, '') # Then I swing through all the original parameter names and replace them with accessing elements of our # new beta parameter list/array. for par_ind, par_name in enumerate(par_names): new_mod_code = new_mod_code.replace(par_name, '{np}[{i}]'.format(np=new_par_name, i=par_ind)) # Then I do the same thing for the new x data variable name new_mod_code = new_mod_code.replace(data_name, new_data_name) # Adds the def SIGNATURE line back in new_mod_code = known_def + new_mod_code # This compiles the code and creates a new function new_model_func_code = compile(new_mod_code, '<string>', 'exec') new_model_func = FunctionType(new_model_func_code.co_consts[0], globals(), model_func.__name__) return new_model_func
0
0
0
3d8fdf51b23b1b165c83279b6f8d9cd73fbc3e82
5,308
py
Python
os3_rll/operations/challenge.py
Erik-Lamers1/OS3-RRL-Python
c1fbc1f2279f1b43290582ee39ed226d8173a101
[ "MIT" ]
null
null
null
os3_rll/operations/challenge.py
Erik-Lamers1/OS3-RRL-Python
c1fbc1f2279f1b43290582ee39ed226d8173a101
[ "MIT" ]
null
null
null
os3_rll/operations/challenge.py
Erik-Lamers1/OS3-RRL-Python
c1fbc1f2279f1b43290582ee39ed226d8173a101
[ "MIT" ]
null
null
null
from logging import getLogger from datetime import datetime from os3_rll.models.challenge import Challenge, ChallengeException from os3_rll.models.player import Player, PlayerException from os3_rll.models.db import Database logger = getLogger(__name__) def do_challenge_sanity_check(p1, p2, may_already_by_challenged=False, may_be_expired=False): """ Preform checks for a new challenge to be created param os3_rll.models.player.Player() p1: The player model for player 1 param os3_rll.models.player.Player() p2: The player model for player 2 param bool may_already_by_challenged: If True skips the player.challenged check param bool may_be_expired: Skips the date check if set raises ChallengeException on sanity check failure """ if p1.challenged and not may_already_by_challenged: raise ChallengeException("{} is already challenged".format(p1.gamertag)) if p2.challenged and not may_already_by_challenged: raise ChallengeException("{} is already challenged".format(p2.gamertag)) # Check if the rank of player 1 is lower than the rank of player 2: if p1.rank < p2.rank: raise ChallengeException("The rank of {} is lower than of {}".format(p1.gamertag, p2.gamertag)) # Check if the ranks are the same; this should not happen if p1.rank == p2.rank: raise ChallengeException( "The ranks of both player {} and player {} are the same. This should not happen. EVERYBODY PANIC!!!".format( p1.gamertag, p2.gamertag ) ) # Check if the timeout of player 1 has expired if p1.timeout > datetime.now() and not may_be_expired: raise ChallengeException("The timeout counter of {} is still active".format(p1.gamertag)) def process_completed_challenge_args(args): """ Processes the completed challenge arguments args str: of the played matches separated by spaces and scores by dashes. Example "1-2 5-3 2-4" corresponds to 3 matches played with the first match ending in 1-2, the second in 5-3 ect. """ p1_wins, p2_wins, p1_score, p2_score = 0, 0, 0, 0 logger.debug("Trying to parse challenge result, got the following user input {}".format(args)) matches = args.split() for match in matches: scores = list(filter(None, match.split("-"))) if len(scores) != 2: raise ChallengeException("Unable to parse challenge arguments") # Check for dummies who didn't pass the last score # Assign the win to the player with the highest score scores[0] = int(scores[0]) scores[1] = int(scores[1]) if scores[0] > scores[1]: p1_wins += 1 elif scores[1] > scores[0]: p2_wins += 1 # Assign the amount of goals p1_score += scores[0] p2_score += scores[1] # Check for a draw if p1_wins == p2_wins: raise ChallengeException("Draws are not allowed") return p1_wins, p2_wins, p1_score, p2_score def get_player_objects_from_challenge_info(player, should_be_completed=False, search_by_discord_name=True): """ Search for a challenge in the DB corresponding to the player param str/int player: The gamertag or id of the player to search for param bool should_be_completed: If the challenge should already be completed or not param bool search_by_discord_name: Searches for player by full discord_name instead of gamertag param str message_author: The discord_user that send the message (eg. Pandabeer#2202) returns tuple os3_rll.models.player.Player: (p1, p2) """ if isinstance(player, str): player = Player.get_player_id_by_username(player, discord_name=search_by_discord_name) with Database() as db: db.execute_prepared_statement( "SELECT `p1`, `p2` FROM `challenges` WHERE (`p1`=%s OR `p2`=%s) AND `winner` IS {} NULL ORDER BY `id` DESC".format( "NOT" if should_be_completed else "" ), (player, player), ) if db.rowcount == 0: raise ChallengeException("No challenges found") p1, p2 = db.fetchone() return Player(p1), Player(p2) def get_latest_challenge_from_player_id(player, should_be_completed=False): """ Tries to find the latest challenge belonging to a player param int player: The player ID to search the challenges for param bool should_be_completed: If the challenge should already be completed or not returns os3_rll.models.challenge: if a challenge is found raises ChallengeException/PlayerException: on not found / on error """ logger.info("Trying to get latest challenge from player with id {}".format(player)) with Player(player) as p: if not p.challenged and not should_be_completed: raise PlayerException("Player {} is currently not in an active challenge".format(p.gamertag)) # Try to find a challenge p.db.execute( "SELECT `id` FROM `challenges` WHERE (`p1`={0} OR `p2`={0}) AND `winner` is {1} NULL ORDER BY `id` LIMIT 1".format( p.id, "NOT" if should_be_completed else "" ) ) p.check_row_count() challenge = p.db.fetchone()[0] # Return the Challenge model return Challenge(challenge)
43.508197
127
0.681424
from logging import getLogger from datetime import datetime from os3_rll.models.challenge import Challenge, ChallengeException from os3_rll.models.player import Player, PlayerException from os3_rll.models.db import Database logger = getLogger(__name__) def do_challenge_sanity_check(p1, p2, may_already_by_challenged=False, may_be_expired=False): """ Preform checks for a new challenge to be created param os3_rll.models.player.Player() p1: The player model for player 1 param os3_rll.models.player.Player() p2: The player model for player 2 param bool may_already_by_challenged: If True skips the player.challenged check param bool may_be_expired: Skips the date check if set raises ChallengeException on sanity check failure """ if p1.challenged and not may_already_by_challenged: raise ChallengeException("{} is already challenged".format(p1.gamertag)) if p2.challenged and not may_already_by_challenged: raise ChallengeException("{} is already challenged".format(p2.gamertag)) # Check if the rank of player 1 is lower than the rank of player 2: if p1.rank < p2.rank: raise ChallengeException("The rank of {} is lower than of {}".format(p1.gamertag, p2.gamertag)) # Check if the ranks are the same; this should not happen if p1.rank == p2.rank: raise ChallengeException( "The ranks of both player {} and player {} are the same. This should not happen. EVERYBODY PANIC!!!".format( p1.gamertag, p2.gamertag ) ) # Check if the timeout of player 1 has expired if p1.timeout > datetime.now() and not may_be_expired: raise ChallengeException("The timeout counter of {} is still active".format(p1.gamertag)) def process_completed_challenge_args(args): """ Processes the completed challenge arguments args str: of the played matches separated by spaces and scores by dashes. Example "1-2 5-3 2-4" corresponds to 3 matches played with the first match ending in 1-2, the second in 5-3 ect. """ p1_wins, p2_wins, p1_score, p2_score = 0, 0, 0, 0 logger.debug("Trying to parse challenge result, got the following user input {}".format(args)) matches = args.split() for match in matches: scores = list(filter(None, match.split("-"))) if len(scores) != 2: raise ChallengeException("Unable to parse challenge arguments") # Check for dummies who didn't pass the last score # Assign the win to the player with the highest score scores[0] = int(scores[0]) scores[1] = int(scores[1]) if scores[0] > scores[1]: p1_wins += 1 elif scores[1] > scores[0]: p2_wins += 1 # Assign the amount of goals p1_score += scores[0] p2_score += scores[1] # Check for a draw if p1_wins == p2_wins: raise ChallengeException("Draws are not allowed") return p1_wins, p2_wins, p1_score, p2_score def get_player_objects_from_challenge_info(player, should_be_completed=False, search_by_discord_name=True): """ Search for a challenge in the DB corresponding to the player param str/int player: The gamertag or id of the player to search for param bool should_be_completed: If the challenge should already be completed or not param bool search_by_discord_name: Searches for player by full discord_name instead of gamertag param str message_author: The discord_user that send the message (eg. Pandabeer#2202) returns tuple os3_rll.models.player.Player: (p1, p2) """ if isinstance(player, str): player = Player.get_player_id_by_username(player, discord_name=search_by_discord_name) with Database() as db: db.execute_prepared_statement( "SELECT `p1`, `p2` FROM `challenges` WHERE (`p1`=%s OR `p2`=%s) AND `winner` IS {} NULL ORDER BY `id` DESC".format( "NOT" if should_be_completed else "" ), (player, player), ) if db.rowcount == 0: raise ChallengeException("No challenges found") p1, p2 = db.fetchone() return Player(p1), Player(p2) def get_latest_challenge_from_player_id(player, should_be_completed=False): """ Tries to find the latest challenge belonging to a player param int player: The player ID to search the challenges for param bool should_be_completed: If the challenge should already be completed or not returns os3_rll.models.challenge: if a challenge is found raises ChallengeException/PlayerException: on not found / on error """ logger.info("Trying to get latest challenge from player with id {}".format(player)) with Player(player) as p: if not p.challenged and not should_be_completed: raise PlayerException("Player {} is currently not in an active challenge".format(p.gamertag)) # Try to find a challenge p.db.execute( "SELECT `id` FROM `challenges` WHERE (`p1`={0} OR `p2`={0}) AND `winner` is {1} NULL ORDER BY `id` LIMIT 1".format( p.id, "NOT" if should_be_completed else "" ) ) p.check_row_count() challenge = p.db.fetchone()[0] # Return the Challenge model return Challenge(challenge)
0
0
0
b1654dcf2537d523059b746f07e020438c1477d6
10,517
py
Python
pyod/models/suod.py
BillyGareth/pyod
4ad1ab8cd88382fe15c237e8db8ad8e3a9302eaf
[ "BSD-2-Clause" ]
5,126
2018-11-09T06:05:38.000Z
2022-03-31T14:25:14.000Z
pyod/models/suod.py
durgeshsamariya/pyod
dfafc57f74dc3d49d0166f21ab2ddb97e3d1d898
[ "BSD-2-Clause" ]
325
2018-11-14T20:02:39.000Z
2022-03-30T22:49:38.000Z
pyod/models/suod.py
durgeshsamariya/pyod
dfafc57f74dc3d49d0166f21ab2ddb97e3d1d898
[ "BSD-2-Clause" ]
1,049
2018-11-09T06:12:12.000Z
2022-03-31T06:21:28.000Z
# -*- coding: utf-8 -*- """SUOD """ # Author: Yue Zhao <zhaoy@cmu.edu> # License: BSD 2 clause from __future__ import division from __future__ import print_function import numpy as np from sklearn.utils import check_array from sklearn.utils.validation import check_is_fitted try: import suod except ImportError: print('please install suod first for SUOD by `pip install suod`') from suod.models.base import SUOD as SUOD_model from .base import BaseDetector from .lof import LOF from .hbos import HBOS from .iforest import IForest from .copod import COPOD from .combination import average, maximization from ..utils.utility import standardizer class SUOD(BaseDetector): # noinspection PyPep8 """SUOD (Scalable Unsupervised Outlier Detection) is an acceleration framework for large scale unsupervised outlier detector training and prediction. See :cite:`zhao2021suod` for details. Parameters ---------- base_estimators : list, length must be greater than 1 A list of base estimators. Certain methods must be present, e.g., `fit` and `predict`. combination : str, optional (default='average') Decide how to aggregate the results from multiple models: - "average" : average the results from all base detectors - "maximization" : output the max value across all base detectors contamination : float in (0., 0.5), optional (default=0.1) The amount of contamination of the data set, i.e. the proportion of outliers in the data set. Used when fitting to define the threshold on the decision function. n_jobs : optional (default=1) The number of jobs to run in parallel for both `fit` and `predict`. If -1, then the number of jobs is set to the the number of jobs that can actually run in parallel. rp_clf_list : list, optional (default=None) The list of outlier detection models to use random projection. The detector name should be consistent with PyOD. rp_ng_clf_list : list, optional (default=None) The list of outlier detection models NOT to use random projection. The detector name should be consistent with PyOD. rp_flag_global : bool, optional (default=True) If set to False, random projection is turned off for all base models. target_dim_frac : float in (0., 1), optional (default=0.5) The target compression ratio. jl_method : string, optional (default = 'basic') The JL projection method: - "basic": each component of the transformation matrix is taken at random in N(0,1). - "discrete", each component of the transformation matrix is taken at random in {-1,1}. - "circulant": the first row of the transformation matrix is taken at random in N(0,1), and each row is obtained from the previous one by a one-left shift. - "toeplitz": the first row and column of the transformation matrix is taken at random in N(0,1), and each diagonal has a constant value taken from these first vector. bps_flag : bool, optional (default=True) If set to False, balanced parallel scheduling is turned off. approx_clf_list : list, optional (default=None) The list of outlier detection models to use pseudo-supervised approximation. The detector name should be consistent with PyOD. approx_ng_clf_list : list, optional (default=None) The list of outlier detection models NOT to use pseudo-supervised approximation. The detector name should be consistent with PyOD. approx_flag_global : bool, optional (default=True) If set to False, pseudo-supervised approximation is turned off. approx_clf : object, optional (default: sklearn RandomForestRegressor) The supervised model used to approximate unsupervised models. cost_forecast_loc_fit : str, optional The location of the pretrained cost prediction forecast for training. cost_forecast_loc_pred : str, optional The location of the pretrained cost prediction forecast for prediction. verbose : int, optional (default=0) Controls the verbosity of the building process. Attributes ---------- decision_scores_ : numpy array of shape (n_samples,) The outlier scores of the training data. The higher, the more abnormal. Outliers tend to have higher scores. This value is available once the detector is fitted. threshold_ : float The threshold is based on ``contamination``. It is the ``n_samples * contamination`` most abnormal samples in ``decision_scores_``. The threshold is calculated for generating binary outlier labels. labels_ : int, either 0 or 1 The binary labels of the training data. 0 stands for inliers and 1 for outliers/anomalies. It is generated by applying ``threshold_`` on ``decision_scores_``. """ def fit(self, X, y=None): """Fit detector. y is ignored in unsupervised methods. Parameters ---------- X : numpy array of shape (n_samples, n_features) The input samples. y : Ignored Not used, present for API consistency by convention. Returns ------- self : object Fitted estimator. """ # validate inputs X and y (optional) X = check_array(X) n_samples, n_features = X.shape[0], X.shape[1] self._set_n_classes(y) # fit the model and then approximate it self.model_.fit(X) self.model_.approximate(X) # get the decision scores from each base estimators decision_score_mat = np.zeros([n_samples, self.n_estimators]) for i in range(self.n_estimators): decision_score_mat[:, i] = self.model_.base_estimators[ i].decision_scores_ # the scores must be standardized before combination decision_score_mat, self.score_scalar_ = standardizer( decision_score_mat, keep_scalar=True) # todo: may support other combination if self.combination == 'average': decision_score = average(decision_score_mat) else: decision_score = maximization(decision_score_mat) assert (len(decision_score) == n_samples) self.decision_scores_ = decision_score.ravel() self._process_decision_scores() return self def decision_function(self, X): """Predict raw anomaly score of X using the fitted detectors. The anomaly score of an input sample is computed based on different detector algorithms. For consistency, outliers are assigned with larger anomaly scores. Parameters ---------- X : numpy array of shape (n_samples, n_features) The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns ------- anomaly_scores : numpy array of shape (n_samples,) The anomaly score of the input samples. """ check_is_fitted(self, ['model_', 'decision_scores_', 'threshold_', 'labels_']) X = check_array(X) # initialize the output score predicted_scores = self.model_.decision_function(X) # standardize the score and combine predicted_scores = self.score_scalar_.transform(predicted_scores) # todo: may support other combination if self.combination == 'average': decision_score = average(predicted_scores) else: decision_score = maximization(predicted_scores) assert (len(decision_score) == X.shape[0]) return decision_score.ravel()
38.383212
79
0.658458
# -*- coding: utf-8 -*- """SUOD """ # Author: Yue Zhao <zhaoy@cmu.edu> # License: BSD 2 clause from __future__ import division from __future__ import print_function import numpy as np from sklearn.utils import check_array from sklearn.utils.validation import check_is_fitted try: import suod except ImportError: print('please install suod first for SUOD by `pip install suod`') from suod.models.base import SUOD as SUOD_model from .base import BaseDetector from .lof import LOF from .hbos import HBOS from .iforest import IForest from .copod import COPOD from .combination import average, maximization from ..utils.utility import standardizer class SUOD(BaseDetector): # noinspection PyPep8 """SUOD (Scalable Unsupervised Outlier Detection) is an acceleration framework for large scale unsupervised outlier detector training and prediction. See :cite:`zhao2021suod` for details. Parameters ---------- base_estimators : list, length must be greater than 1 A list of base estimators. Certain methods must be present, e.g., `fit` and `predict`. combination : str, optional (default='average') Decide how to aggregate the results from multiple models: - "average" : average the results from all base detectors - "maximization" : output the max value across all base detectors contamination : float in (0., 0.5), optional (default=0.1) The amount of contamination of the data set, i.e. the proportion of outliers in the data set. Used when fitting to define the threshold on the decision function. n_jobs : optional (default=1) The number of jobs to run in parallel for both `fit` and `predict`. If -1, then the number of jobs is set to the the number of jobs that can actually run in parallel. rp_clf_list : list, optional (default=None) The list of outlier detection models to use random projection. The detector name should be consistent with PyOD. rp_ng_clf_list : list, optional (default=None) The list of outlier detection models NOT to use random projection. The detector name should be consistent with PyOD. rp_flag_global : bool, optional (default=True) If set to False, random projection is turned off for all base models. target_dim_frac : float in (0., 1), optional (default=0.5) The target compression ratio. jl_method : string, optional (default = 'basic') The JL projection method: - "basic": each component of the transformation matrix is taken at random in N(0,1). - "discrete", each component of the transformation matrix is taken at random in {-1,1}. - "circulant": the first row of the transformation matrix is taken at random in N(0,1), and each row is obtained from the previous one by a one-left shift. - "toeplitz": the first row and column of the transformation matrix is taken at random in N(0,1), and each diagonal has a constant value taken from these first vector. bps_flag : bool, optional (default=True) If set to False, balanced parallel scheduling is turned off. approx_clf_list : list, optional (default=None) The list of outlier detection models to use pseudo-supervised approximation. The detector name should be consistent with PyOD. approx_ng_clf_list : list, optional (default=None) The list of outlier detection models NOT to use pseudo-supervised approximation. The detector name should be consistent with PyOD. approx_flag_global : bool, optional (default=True) If set to False, pseudo-supervised approximation is turned off. approx_clf : object, optional (default: sklearn RandomForestRegressor) The supervised model used to approximate unsupervised models. cost_forecast_loc_fit : str, optional The location of the pretrained cost prediction forecast for training. cost_forecast_loc_pred : str, optional The location of the pretrained cost prediction forecast for prediction. verbose : int, optional (default=0) Controls the verbosity of the building process. Attributes ---------- decision_scores_ : numpy array of shape (n_samples,) The outlier scores of the training data. The higher, the more abnormal. Outliers tend to have higher scores. This value is available once the detector is fitted. threshold_ : float The threshold is based on ``contamination``. It is the ``n_samples * contamination`` most abnormal samples in ``decision_scores_``. The threshold is calculated for generating binary outlier labels. labels_ : int, either 0 or 1 The binary labels of the training data. 0 stands for inliers and 1 for outliers/anomalies. It is generated by applying ``threshold_`` on ``decision_scores_``. """ def __init__(self, base_estimators=None, contamination=0.1, combination='average', n_jobs=None, rp_clf_list=None, rp_ng_clf_list=None, rp_flag_global=True, target_dim_frac=0.5, jl_method='basic', bps_flag=True, approx_clf_list=None, approx_ng_clf_list=None, approx_flag_global=True, approx_clf=None, cost_forecast_loc_fit=None, cost_forecast_loc_pred=None, verbose=False): super(SUOD, self).__init__(contamination=contamination) self.base_estimators = base_estimators self.contamination = contamination self.combination = combination self.n_jobs = n_jobs self.rp_clf_list = rp_clf_list self.rp_ng_clf_list = rp_ng_clf_list self.rp_flag_global = rp_flag_global self.target_dim_frac = target_dim_frac self.jl_method = jl_method self.bps_flag = bps_flag self.approx_clf_list = approx_clf_list self.approx_ng_clf_list = approx_ng_clf_list self.approx_flag_global = approx_flag_global self.approx_clf = approx_clf self.cost_forecast_loc_fit = cost_forecast_loc_fit self.cost_forecast_loc_pred = cost_forecast_loc_pred self.verbose = verbose # by default we will provide a group of performing models if self.base_estimators is None: self.base_estimators = [LOF(n_neighbors=15), LOF(n_neighbors=20), HBOS(n_bins=10), HBOS(n_bins=20), COPOD(), IForest(n_estimators=50), IForest(n_estimators=100), IForest(n_estimators=150)] self.n_estimators = len(self.base_estimators) # pass in the arguments for SUOD model self.model_ = SUOD_model( base_estimators=self.base_estimators, contamination=self.contamination, n_jobs=self.n_jobs, rp_clf_list=self.rp_clf_list, rp_ng_clf_list=self.rp_ng_clf_list, rp_flag_global=self.rp_flag_global, target_dim_frac=self.target_dim_frac, jl_method=self.jl_method, approx_clf_list=self.approx_clf_list, approx_ng_clf_list=self.approx_ng_clf_list, approx_flag_global=self.approx_flag_global, approx_clf=self.approx_clf, bps_flag=self.bps_flag, cost_forecast_loc_fit=self.cost_forecast_loc_fit, cost_forecast_loc_pred=self.cost_forecast_loc_pred, verbose=self.verbose, ) def fit(self, X, y=None): """Fit detector. y is ignored in unsupervised methods. Parameters ---------- X : numpy array of shape (n_samples, n_features) The input samples. y : Ignored Not used, present for API consistency by convention. Returns ------- self : object Fitted estimator. """ # validate inputs X and y (optional) X = check_array(X) n_samples, n_features = X.shape[0], X.shape[1] self._set_n_classes(y) # fit the model and then approximate it self.model_.fit(X) self.model_.approximate(X) # get the decision scores from each base estimators decision_score_mat = np.zeros([n_samples, self.n_estimators]) for i in range(self.n_estimators): decision_score_mat[:, i] = self.model_.base_estimators[ i].decision_scores_ # the scores must be standardized before combination decision_score_mat, self.score_scalar_ = standardizer( decision_score_mat, keep_scalar=True) # todo: may support other combination if self.combination == 'average': decision_score = average(decision_score_mat) else: decision_score = maximization(decision_score_mat) assert (len(decision_score) == n_samples) self.decision_scores_ = decision_score.ravel() self._process_decision_scores() return self def decision_function(self, X): """Predict raw anomaly score of X using the fitted detectors. The anomaly score of an input sample is computed based on different detector algorithms. For consistency, outliers are assigned with larger anomaly scores. Parameters ---------- X : numpy array of shape (n_samples, n_features) The training input samples. Sparse matrices are accepted only if they are supported by the base estimator. Returns ------- anomaly_scores : numpy array of shape (n_samples,) The anomaly score of the input samples. """ check_is_fitted(self, ['model_', 'decision_scores_', 'threshold_', 'labels_']) X = check_array(X) # initialize the output score predicted_scores = self.model_.decision_function(X) # standardize the score and combine predicted_scores = self.score_scalar_.transform(predicted_scores) # todo: may support other combination if self.combination == 'average': decision_score = average(predicted_scores) else: decision_score = maximization(predicted_scores) assert (len(decision_score) == X.shape[0]) return decision_score.ravel()
2,629
0
27
0dc105afeb6b53b12ab37cf4662631842f1f18cb
2,004
py
Python
model/evaluate/get_errorrates_direct.py
manojakm/sanskrit-ocr-1
4a7b58dd68ef30e8a849acde3fff1595b4c607c9
[ "MIT" ]
1
2021-08-06T15:29:07.000Z
2021-08-06T15:29:07.000Z
model/evaluate/get_errorrates_direct.py
Sanskrit-Club/sanskrit-ocr
de908c1a62df8539b22a2458b2dfd4bd07462009
[ "MIT" ]
null
null
null
model/evaluate/get_errorrates_direct.py
Sanskrit-Club/sanskrit-ocr
de908c1a62df8539b22a2458b2dfd4bd07462009
[ "MIT" ]
1
2020-11-07T08:37:52.000Z
2020-11-07T08:37:52.000Z
from jiwer import wer import os import sys gt_file = sys.argv[1] pred_file = sys.argv[2] with open(gt_file) as f: gt_lines = f.readlines() gt_lines = [' '.join(x.strip().split()) for x in gt_lines] print(len(gt_lines)) with open(pred_file) as f: pred_lines = f.readlines() pred_lines = [' '.join(x.strip().split()) for x in pred_lines] print(len(pred_lines)) cerr = total_cer(gt_lines, pred_lines) werr = total_wer(gt_lines, pred_lines) serr = total_ser(gt_lines, pred_lines) print("CER:", cerr) print("WER:", werr) print("SER:", serr)
25.05
94
0.613772
from jiwer import wer def levenshteinDistance(s1, s2): if len(s1) > len(s2): s1, s2 = s2, s1 distances = range(len(s1) + 1) for i2, c2 in enumerate(s2): distances_ = [i2+1] for i1, c1 in enumerate(s1): if c1 == c2: distances_.append(distances[i1]) else: distances_.append(1 + min((distances[i1], distances[i1 + 1], distances_[-1]))) distances = distances_ return distances[-1] def calculate_wer(gt,pred): return wer(gt, pred) def total_cer(gt_lines, pred_lines): cer_sum = 0 length_line = 0 for gt, pred in zip(gt_lines, pred_lines): cer_line = levenshteinDistance(gt, pred) # print(cer_line) cer_sum = cer_sum + cer_line length_line = length_line+ len(gt) return 100*cer_sum/length_line def total_wer(gt_lines, pred_lines): wer_sum = 0 total_words = 0 for gt, pred in zip(gt_lines, pred_lines): wer_line = calculate_wer(gt, pred) words = len(gt.split()) total_words = total_words + words wer_sum = wer_sum + (wer_line*words) return 100*wer_sum/total_words def total_ser(gt_lines, pred_lines): ser_sum = 0 total_lines = 0 for gt, pred in zip(gt_lines, pred_lines): err = 0 if gt == pred: err = 0 else: err = 1 total_lines += 1 ser_sum += err return 100*ser_sum/total_lines import os import sys gt_file = sys.argv[1] pred_file = sys.argv[2] with open(gt_file) as f: gt_lines = f.readlines() gt_lines = [' '.join(x.strip().split()) for x in gt_lines] print(len(gt_lines)) with open(pred_file) as f: pred_lines = f.readlines() pred_lines = [' '.join(x.strip().split()) for x in pred_lines] print(len(pred_lines)) cerr = total_cer(gt_lines, pred_lines) werr = total_wer(gt_lines, pred_lines) serr = total_ser(gt_lines, pred_lines) print("CER:", cerr) print("WER:", werr) print("SER:", serr)
1,334
0
115
3eb137437b2d519897daab13ad2a80518b419484
396
py
Python
QQbot/Model/ApiModel/gateway.py
hegugu-ng/qq_guild_bot
dac9b3313f52ed579564a9140dd46212f2249e8b
[ "MIT" ]
15
2021-11-28T03:26:24.000Z
2022-03-31T17:21:05.000Z
QQbot/Model/ApiModel/gateway.py
hegugu-ng/qq_guild_bot
dac9b3313f52ed579564a9140dd46212f2249e8b
[ "MIT" ]
2
2021-11-28T15:02:57.000Z
2021-12-01T09:30:58.000Z
QQbot/Model/ApiModel/gateway.py
hegugu-ng/qq_guild_bot
dac9b3313f52ed579564a9140dd46212f2249e8b
[ "MIT" ]
2
2021-11-27T15:21:11.000Z
2021-12-28T03:21:35.000Z
from pydantic import BaseModel
30.461538
56
0.69697
from pydantic import BaseModel class SessionStartLimit(BaseModel): total:int #每 24 小时可创建 Session 数 remaining:int #目前还可以创建的 Session 数 reset_after:int #重置计数的剩余时间(ms) max_concurrency:int #每 5s 可以创建的 Session 数 class Shards(BaseModel): url:str # WebSocket 的连接地址 shards: int # 建议的 shard 数 session_start_limit:SessionStartLimit #创建Session限制信息
0
413
46
a020e88f0a5ea67f5eab54d5d815db2c78b66f2b
6,109
py
Python
matrix_tree_theorem.py
bekou/eacl-2017-dataset
34d86f87b76118253e24bfa48aac1afa8771546f
[ "MIT" ]
4
2017-10-09T14:15:59.000Z
2021-12-28T20:28:56.000Z
matrix_tree_theorem.py
bekou/eacl-2017-dataset
34d86f87b76118253e24bfa48aac1afa8771546f
[ "MIT" ]
null
null
null
matrix_tree_theorem.py
bekou/eacl-2017-dataset
34d86f87b76118253e24bfa48aac1afa8771546f
[ "MIT" ]
2
2019-05-26T15:55:36.000Z
2021-12-28T20:31:26.000Z
import networkx as nx import numpy as np import math import pandas as pd from networkx.drawing.nx_agraph import graphviz_layout import matplotlib from time import gmtime, strftime import scipy margFeat=[]
28.680751
122
0.50974
import networkx as nx import numpy as np import math import pandas as pd from networkx.drawing.nx_agraph import graphviz_layout import matplotlib from time import gmtime, strftime import scipy margFeat=[] def getAdjacency(theta): adjacency=np.exp(theta) #print "adjacency max "+str(np.amax(adjacency)) np.fill_diagonal(adjacency,0) return adjacency def getmLaplacian(adjacency,root_theta): laplacian=-adjacency for i in range (len(laplacian)): laplacian[i,i]=sum(adjacency[:,i])[0,0] z=np.zeros((root_theta.shape[1],root_theta.shape[1])) np.fill_diagonal(z,np.exp(root_theta)) laplacian[0]=np.exp(root_theta) return laplacian def getMarginal(laplacian,adjacency,root_theta): delta=np.zeros((len(laplacian),len(laplacian))) np.fill_diagonal(delta,1) inv_laplacian=np.linalg.inv(laplacian) marg_p=np.zeros((len(laplacian),len(laplacian))) for h in range (len(laplacian)): for m in range (len(laplacian)): #print str(h) + " " + str(m ) marg_p[h,m]=(1-delta[0,m])*adjacency[h,m]*inv_laplacian[m,m]- (1-delta[h,0])*adjacency[h,m]*inv_laplacian[m,h] root_marg=np.zeros((1,len(laplacian))) for m in range (len(laplacian)): root_marg[0,m]=np.exp(root_theta[0,m])*inv_laplacian[m,0] return marg_p,root_marg def computeTheta(w,train_vec,node_docs,labels=""): theta_list=(train_vec*w.T) ptr=0; theta_doc=[] root_theta_doc=[] theta_active_sum=[] for doc in range (len(node_docs)): theta_active_sum.append(0) nodeDoc=node_docs[doc] rootIndex=nodeDoc.mention.index("ROOT") nodes=len(nodeDoc.mention) thetas=np.asmatrix(np.zeros((nodes,nodes))) root_thetas=np.asmatrix(np.zeros((1,nodes))) for h in range(len(nodeDoc.mention)): for m in range(len(nodeDoc.mention)): if (h!=m and m!=rootIndex): thetas[h,m]=theta_list[ptr] if labels!="" and labels[ptr]=='1': theta_active_sum[doc]+=theta_list[ptr] ptr+=1 root_thetas=np.zeros((1,len(thetas))) theta_doc.append(thetas) root_theta_doc.append(root_thetas) return theta_doc,root_theta_doc,theta_active_sum,theta_list def computeMtx(train_vec,node_docs,theta_doc,root_theta_doc): adjacency_doc=[] laplacian_doc=[] partitionLog=[] marginal_doc=[] root_marg_doc=[] for doc in range (len(theta_doc)): adjacency_doc.append(getAdjacency(theta_doc[doc])) laplacian_doc.append(getmLaplacian(adjacency_doc[doc],root_theta_doc[doc])) (sign, logdet) = np.linalg.slogdet(laplacian_doc[doc]) partitionLog.append(sign*logdet) #partitionLog.append(np.log(np.linalg.det(laplacian_doc[doc]))) marg=getMarginal(laplacian_doc[doc],adjacency_doc[doc],root_theta_doc[doc]) marginal_doc.append(marg[0]) root_marg_doc.append(marg[1]) ptr=0; margs=[] for doc in range (len(marginal_doc)): marginal=marginal_doc[doc] root_marg=root_marg_doc[doc] for h in range(len(marginal)): for m in range(len(marginal)): marg=marginal[h,m] if (h!=m and m<len(marginal)-1): margs.append(marg) ptr+=1 margs=np.asarray(margs) margs = scipy.sparse.csr_matrix(margs) margFeat=margs.T.multiply(train_vec) return adjacency_doc,laplacian_doc,partitionLog,marginal_doc,root_marg_doc,margFeat def printTime(messageBefore): print messageBefore+" : "+strftime("%Y-%m-%d %H:%M:%S") def L(w,train_vec,node_docs,labels,C,featuresSum): w=np.matrix(w) theta=computeTheta(w,train_vec,node_docs,labels) theta_doc=theta[0] root_theta_doc=theta[1] theta_active_sum=theta[2] logSum=0 mtx=computeMtx(train_vec,node_docs,theta_doc,root_theta_doc) adjacency_doc=mtx[0] laplacian_doc=mtx[1] partitionLog=mtx[2] marginal_doc=mtx[3] root_marg_doc=mtx[4] global margFeat margFeat=mtx[5] for doc in range (len(theta_doc)): logSum+=theta_active_sum[doc]-partitionLog[doc] L=-C*logSum+0.5*math.pow(np.linalg.norm(w),2) if logSum>0: raise ValueError('--Log likelihood is positive --') print "----------------------------------------------------------" print "Objective: "+str(L)+ " Likelihood: " + str(logSum) print "----------------------------------------------------------" return L def gradL(w,train_vec,node_docs,labels,C,featuresSum): w=np.matrix(w) sumMargFeat=np.zeros((1,train_vec.shape[1])).astype('double') sumMargFeat=scipy.sparse.csr_matrix.sum(margFeat,axis=0)#np.sum(margFeat,axis=0) dL=w-C*featuresSum+C*sumMargFeat dL=np.squeeze(np.asarray(dL)) return dL
5,689
0
196
a363cb8cd2452287adee8c1d66bd9c7d3d75a36c
11,631
py
Python
app/config_tablero.py
diegoag30/ScrabbleAr
e309b21ec60148b290c45f4edc6bf90d391d144a
[ "MIT" ]
3
2020-05-26T21:02:48.000Z
2020-08-06T03:19:54.000Z
app/config_tablero.py
diegoag30/ScrabbleAr
e309b21ec60148b290c45f4edc6bf90d391d144a
[ "MIT" ]
null
null
null
app/config_tablero.py
diegoag30/ScrabbleAr
e309b21ec60148b290c45f4edc6bf90d391d144a
[ "MIT" ]
null
null
null
class EstadBoton: '''Esta clase maneja la configuracion del tablero, ya sea el valor de las casillas, los colores, y el estado de los botones '''
42.141304
111
0.664861
class EstadBoton: '''Esta clase maneja la configuracion del tablero, ya sea el valor de las casillas, los colores, y el estado de los botones ''' def __init__(self,valor=1,color='',estado=False,tipo='L'): # valor es 1 por defecto para multiplicar la L o P self._estado = estado self._valor = valor self._color = color self._tipo = tipo def get_color(self): return self._color def get_valor(self): return self._valor def get_estado(self): return self._estado def get_tipo(self): return self._tipo def set_estado(self,valor): self._estado=valor def Config1(): configuracion1=[] #row=[] for i in range(15): row=[] for j in range(15): row.append(EstadBoton()) configuracion1.append(row) configuracion1[7][7]=EstadBoton(1,'violet',tipo='P') configuracion1[1][1]=EstadBoton(2,'orange',tipo='P') configuracion1[2][2]=EstadBoton(2,'orange',tipo='P') configuracion1[3][3]=EstadBoton(2,'orange',tipo='P') configuracion1[4][4]=EstadBoton(2,'orange',tipo='P') configuracion1[10][10]=EstadBoton(2,'orange',tipo='P') configuracion1[11][11]=EstadBoton(2,'orange',tipo='P') configuracion1[12][12]=EstadBoton(2,'orange',tipo='P') configuracion1[13][13]=EstadBoton(2,'orange',tipo='P') configuracion1[1][13]=EstadBoton(2,'orange',tipo='P') configuracion1[2][12]=EstadBoton(2,'orange',tipo='P') configuracion1[3][11]=EstadBoton(2,'orange',tipo='P') configuracion1[4][10]=EstadBoton(2,'orange',tipo='P') configuracion1[10][4]=EstadBoton(2,'orange',tipo='P') configuracion1[11][3]=EstadBoton(2,'orange',tipo='P') configuracion1[12][2]=EstadBoton(2,'orange',tipo='P') configuracion1[13][1]=EstadBoton(2,'orange',tipo='P') configuracion1[0][0]=EstadBoton(1,'red',tipo='P') configuracion1[0][7]=EstadBoton(3,'red',tipo='P') configuracion1[0][14]=EstadBoton(3,'red',tipo='P') configuracion1[14][7]=EstadBoton(3,'red',tipo='P') configuracion1[14][14]=EstadBoton(3,'red',tipo='P') configuracion1[7][14]=EstadBoton(3,'red',tipo='P') configuracion1[7][0]=EstadBoton(3,'red',tipo='P') configuracion1[14][0]=EstadBoton(3,'red',tipo='P') configuracion1[7][7]=EstadBoton(0,'violet',tipo='P') configuracion1[1][5]=EstadBoton(3,'blue',tipo='L') configuracion1[1][9]=EstadBoton(3,'blue',tipo='L') configuracion1[5][1]=EstadBoton(3,'blue',tipo='L') configuracion1[5][5]=EstadBoton(3,'blue',tipo='L') configuracion1[5][9]=EstadBoton(3,'blue',tipo='L') configuracion1[5][13]=EstadBoton(3,'blue',tipo='L') configuracion1[9][5]=EstadBoton(3,'blue',tipo='L') configuracion1[9][9]=EstadBoton(3,'blue',tipo='L') configuracion1[9][13]=EstadBoton(3,'blue',tipo='L') configuracion1[13][5]=EstadBoton(3,'blue',tipo='L') configuracion1[13][9]=EstadBoton(3,'blue',tipo='L') configuracion1[9][1]=EstadBoton(3,'blue',tipo='L') configuracion1[0][3]=EstadBoton(2,'green',tipo='L') configuracion1[0][11]=EstadBoton(2,'green',tipo='L') configuracion1[2][6]=EstadBoton(2,'green',tipo='L') configuracion1[2][8]=EstadBoton(2,'green',tipo='L') configuracion1[3][0]=EstadBoton(2,'green',tipo='L') configuracion1[3][7]=EstadBoton(2,'green',tipo='L') configuracion1[3][14]=EstadBoton(2,'green',tipo='L') configuracion1[6][2]=EstadBoton(2,'green',tipo='L') configuracion1[6][6]=EstadBoton(2,'green',tipo='L') configuracion1[6][8]=EstadBoton(2,'green',tipo='L') configuracion1[6][12]=EstadBoton(2,'green',tipo='L') configuracion1[7][3]=EstadBoton(2,'green',tipo='L') configuracion1[7][11]=EstadBoton(2,'green',tipo='L') configuracion1[8][2]=EstadBoton(2,'green',tipo='L') configuracion1[8][6]=EstadBoton(2,'green',tipo='L') configuracion1[8][8]=EstadBoton(2,'green',tipo='L') configuracion1[8][12]=EstadBoton(2,'green',tipo='L') configuracion1[11][0]=EstadBoton(2,'green',tipo='L') configuracion1[11][7]=EstadBoton(2,'green',tipo='L') configuracion1[11][14]=EstadBoton(2,'green',tipo='L') configuracion1[12][6]=EstadBoton(2,'green',tipo='L') configuracion1[12][8]=EstadBoton(2,'green',tipo='L') configuracion1[14][3]=EstadBoton(2,'green',tipo='L') configuracion1[14][11]=EstadBoton(2,'green',tipo='L') return configuracion1 def Config2(): configuracion1=[] #row=[] for i in range(15): row=[] for j in range(15): row.append(EstadBoton()) configuracion1.append(row) #configuracion1[7][7]=EstadBoton(1,'B') configuracion1[1][1]=EstadBoton(-2,'orange',tipo='P') configuracion1[2][2]=EstadBoton(-2,'orange',tipo='P') configuracion1[3][3]=EstadBoton(-2,'orange',tipo='P') configuracion1[4][4]=EstadBoton(-2,'orange',tipo='P') configuracion1[10][10]=EstadBoton(-2,'orange',tipo='P') configuracion1[11][11]=EstadBoton(-2,'orange',tipo='P') configuracion1[12][12]=EstadBoton(-2,'orange',tipo='P') configuracion1[13][13]=EstadBoton(-2,'orange',tipo='P') configuracion1[1][13]=EstadBoton(-2,'orange',tipo='P') configuracion1[2][12]=EstadBoton(-2,'orange',tipo='P') configuracion1[3][11]=EstadBoton(-2,'orange',tipo='P') configuracion1[4][10]=EstadBoton(-2,'orange',tipo='P') configuracion1[10][4]=EstadBoton(-2,'orange',tipo='P') configuracion1[11][3]=EstadBoton(-2,'orange',tipo='P') configuracion1[12][2]=EstadBoton(-2,'orange',tipo='P') configuracion1[13][1]=EstadBoton(-2,'orange',tipo='P') configuracion1[0][0]=EstadBoton(1,'red',tipo='P') configuracion1[0][7]=EstadBoton(3,'red',tipo='P') configuracion1[0][14]=EstadBoton(3,'red',tipo='P') configuracion1[14][7]=EstadBoton(3,'red',tipo='P') configuracion1[14][14]=EstadBoton(3,'red',tipo='P') configuracion1[7][14]=EstadBoton(3,'red',tipo='P') configuracion1[7][0]=EstadBoton(3,'red',tipo='P') configuracion1[14][0]=EstadBoton(3,'red',tipo='P') configuracion1[7][7]=EstadBoton(0,'violet',tipo='P') configuracion1[1][5]=EstadBoton(3,'blue',tipo='L') configuracion1[1][9]=EstadBoton(3,'blue',tipo='L') configuracion1[5][1]=EstadBoton(3,'blue',tipo='L') configuracion1[5][5]=EstadBoton(3,'blue',tipo='L') configuracion1[5][9]=EstadBoton(3,'blue',tipo='L') configuracion1[5][13]=EstadBoton(3,'blue',tipo='L') configuracion1[9][5]=EstadBoton(3,'blue',tipo='L') configuracion1[9][9]=EstadBoton(3,'blue',tipo='L') configuracion1[9][13]=EstadBoton(3,'blue',tipo='L') configuracion1[13][5]=EstadBoton(3,'blue',tipo='L') configuracion1[13][9]=EstadBoton(3,'blue',tipo='L') configuracion1[9][1]=EstadBoton(3,'blue',tipo='L') configuracion1[0][3]=EstadBoton(2,'green',tipo='L') configuracion1[0][11]=EstadBoton(2,'green',tipo='L') configuracion1[2][6]=EstadBoton(2,'green',tipo='L') configuracion1[2][8]=EstadBoton(2,'green',tipo='L') configuracion1[3][0]=EstadBoton(2,'green',tipo='L') configuracion1[3][7]=EstadBoton(2,'green',tipo='L') configuracion1[3][14]=EstadBoton(2,'green',tipo='L') configuracion1[6][2]=EstadBoton(2,'green',tipo='L') configuracion1[6][6]=EstadBoton(2,'green',tipo='L') configuracion1[6][8]=EstadBoton(2,'green',tipo='L') configuracion1[6][12]=EstadBoton(2,'green',tipo='L') configuracion1[7][3]=EstadBoton(2,'green',tipo='L') configuracion1[7][11]=EstadBoton(2,'green',tipo='L') configuracion1[8][2]=EstadBoton(2,'green',tipo='L') configuracion1[8][6]=EstadBoton(2,'green',tipo='L') configuracion1[8][8]=EstadBoton(2,'green',tipo='L') configuracion1[8][12]=EstadBoton(2,'green',tipo='L') configuracion1[11][0]=EstadBoton(2,'green',tipo='L') configuracion1[11][7]=EstadBoton(2,'green',tipo='L') configuracion1[11][14]=EstadBoton(2,'green',tipo='L') configuracion1[12][6]=EstadBoton(2,'green',tipo='L') configuracion1[12][8]=EstadBoton(2,'green',tipo='L') configuracion1[14][3]=EstadBoton(2,'green',tipo='L') configuracion1[14][11]=EstadBoton(2,'green',tipo='L') return configuracion1 def Config3(): configuracion1=[] #row=[] for i in range(15): row=[] for j in range(15): row.append(EstadBoton()) configuracion1.append(row) #configuracion1[7][7]=EstadBoton(1,'Black violet') configuracion1[1][1]=EstadBoton(2,'orange',tipo='P') configuracion1[2][2]=EstadBoton(2,'orange',tipo='P') configuracion1[3][3]=EstadBoton(2,'orange',tipo='P') configuracion1[4][4]=EstadBoton(2,'orange',tipo='P') configuracion1[10][10]=EstadBoton(2,'orange',tipo='P') configuracion1[11][11]=EstadBoton(2,'orange',tipo='P') configuracion1[12][12]=EstadBoton(2,'orange',tipo='P') configuracion1[13][13]=EstadBoton(2,'orange',tipo='P') configuracion1[1][13]=EstadBoton(2,'orange',tipo='P') configuracion1[2][12]=EstadBoton(2,'orange',tipo='P') configuracion1[3][11]=EstadBoton(2,'orange',tipo='P') configuracion1[4][10]=EstadBoton(2,'orange',tipo='P') configuracion1[10][4]=EstadBoton(2,'orange',tipo='P') configuracion1[11][3]=EstadBoton(2,'orange',tipo='P') configuracion1[12][2]=EstadBoton(2,'orange',tipo='P') configuracion1[13][1]=EstadBoton(2,'orange',tipo='P') configuracion1[0][0]=EstadBoton(1,'red',tipo='P') configuracion1[0][7]=EstadBoton(3,'red',tipo='P') configuracion1[0][14]=EstadBoton(3,'red',tipo='P') configuracion1[14][7]=EstadBoton(3,'red',tipo='P') configuracion1[14][14]=EstadBoton(3,'red',tipo='P') configuracion1[7][14]=EstadBoton(3,'red',tipo='P') configuracion1[7][0]=EstadBoton(3,'red',tipo='P') configuracion1[14][0]=EstadBoton(3,'red',tipo='P') configuracion1[7][7]=EstadBoton(0,'violet',tipo='P') configuracion1[1][5]=EstadBoton(-3,'blue',tipo='L') configuracion1[1][9]=EstadBoton(-3,'blue',tipo='L') configuracion1[5][1]=EstadBoton(-3,'blue',tipo='L') configuracion1[5][5]=EstadBoton(-3,'blue',tipo='L') configuracion1[5][9]=EstadBoton(-3,'blue',tipo='L') configuracion1[5][13]=EstadBoton(-3,'blue',tipo='L') configuracion1[9][5]=EstadBoton(-3,'blue',tipo='L') configuracion1[9][9]=EstadBoton(-3,'blue',tipo='L') configuracion1[9][13]=EstadBoton(-3,'blue',tipo='L') configuracion1[13][5]=EstadBoton(-3,'blue',tipo='L') configuracion1[13][9]=EstadBoton(-3,'blue',tipo='L') configuracion1[9][1]=EstadBoton(-3,'blue',tipo='L') configuracion1[0][3]=EstadBoton(-2,'green',tipo='L') configuracion1[0][11]=EstadBoton(-2,'green',tipo='L') configuracion1[2][6]=EstadBoton(-2,'green',tipo='L') configuracion1[2][8]=EstadBoton(-2,'green',tipo='L') configuracion1[3][0]=EstadBoton(-2,'green',tipo='L') configuracion1[3][7]=EstadBoton(-2,'green',tipo='L') configuracion1[3][14]=EstadBoton(-2,'green',tipo='L') configuracion1[6][2]=EstadBoton(-2,'green',tipo='L') configuracion1[6][6]=EstadBoton(-2,'green',tipo='L') configuracion1[6][8]=EstadBoton(-2,'green',tipo='L') configuracion1[6][12]=EstadBoton(-2,'green',tipo='L') configuracion1[7][3]=EstadBoton(-2,'green',tipo='L') configuracion1[7][11]=EstadBoton(2,'green',tipo='L') configuracion1[8][2]=EstadBoton(-2,'green',tipo='L') configuracion1[8][6]=EstadBoton(-2,'green',tipo='L') configuracion1[8][8]=EstadBoton(-2,'green',tipo='L') configuracion1[8][12]=EstadBoton(-2,'green',tipo='L') configuracion1[11][0]=EstadBoton(-2,'green',tipo='L') configuracion1[11][7]=EstadBoton(-2,'green',tipo='L') configuracion1[11][14]=EstadBoton(-2,'green',tipo='L') configuracion1[12][6]=EstadBoton(-2,'green',tipo='L') configuracion1[12][8]=EstadBoton(-2,'green',tipo='L') configuracion1[14][3]=EstadBoton(-2,'green',tipo='L') configuracion1[14][11]=EstadBoton(-2,'green',tipo='L') return configuracion1
11,191
0
230
53b8cce64b74ac679ed9a39c6abcc9ab434be4f6
24,672
py
Python
pandas/stats/plm.py
certik/pandas
758ca05e2eb04532b5d78331ba87c291038e2c61
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
652
2015-07-26T00:00:17.000Z
2022-02-24T18:30:04.000Z
pandas/stats/plm.py
certik/pandas
758ca05e2eb04532b5d78331ba87c291038e2c61
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
8
2015-09-07T03:38:19.000Z
2021-05-23T03:18:51.000Z
pandas/stats/plm.py
certik/pandas
758ca05e2eb04532b5d78331ba87c291038e2c61
[ "PSF-2.0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause" ]
40
2015-07-24T19:45:08.000Z
2021-11-01T14:54:56.000Z
""" Linear regression objects for panel data """ # pylint: disable-msg=W0231 # pylint: disable-msg=E1101,E1103 from __future__ import division from pandas.compat import range from pandas import compat import warnings import numpy as np from pandas.core.panel import Panel from pandas.core.frame import DataFrame from pandas.core.reshape import get_dummies from pandas.core.series import Series from pandas.core.sparse import SparsePanel from pandas.stats.ols import OLS, MovingOLS import pandas.stats.common as com import pandas.stats.math as math from pandas.util.decorators import cache_readonly class PanelOLS(OLS): """Implements panel OLS. See ols function docs """ _panel_model = True def _prepare_data(self): """Cleans and stacks input data into DataFrame objects If time effects is True, then we turn off intercepts and omit an item from every (entity and x) fixed effect. Otherwise: - If we have an intercept, we omit an item from every fixed effect. - Else, we omit an item from every fixed effect except one of them. The categorical variables will get dropped from x. """ (x, x_filtered, y, weights, cat_mapping) = self._filter_data() self.log('Adding dummies to X variables') x = self._add_dummies(x, cat_mapping) self.log('Adding dummies to filtered X variables') x_filtered = self._add_dummies(x_filtered, cat_mapping) if self._x_effects: x = x.drop(self._x_effects, axis=1) x_filtered = x_filtered.drop(self._x_effects, axis=1) if self._time_effects: x_regressor = x.sub(x.mean(level=0), level=0) unstacked_y = y.unstack() y_regressor = unstacked_y.sub(unstacked_y.mean(1), axis=0).stack() y_regressor.index = y.index elif self._intercept: # only add intercept when no time effects self.log('Adding intercept') x = x_regressor = add_intercept(x) x_filtered = add_intercept(x_filtered) y_regressor = y else: self.log('No intercept added') x_regressor = x y_regressor = y if weights is not None: if not y_regressor.index.equals(weights.index): raise AssertionError("y_regressor and weights must have the " "same index") if not x_regressor.index.equals(weights.index): raise AssertionError("x_regressor and weights must have the " "same index") rt_weights = np.sqrt(weights) y_regressor = y_regressor * rt_weights x_regressor = x_regressor.mul(rt_weights, axis=0) return x, x_regressor, x_filtered, y, y_regressor def _filter_data(self): """ """ data = self._x_orig cat_mapping = {} if isinstance(data, DataFrame): data = data.to_panel() else: if isinstance(data, Panel): data = data.copy() if not isinstance(data, SparsePanel): data, cat_mapping = self._convert_x(data) if not isinstance(data, Panel): data = Panel.from_dict(data, intersect=True) x_names = data.items if self._weights is not None: data['__weights__'] = self._weights # Filter x's without y (so we can make a prediction) filtered = data.to_frame() # Filter all data together using to_frame # convert to DataFrame y = self._y_orig if isinstance(y, Series): y = y.unstack() data['__y__'] = y data_long = data.to_frame() x_filt = filtered.filter(x_names) x = data_long.filter(x_names) y = data_long['__y__'] if self._weights is not None and not self._weights.empty: weights = data_long['__weights__'] else: weights = None return x, x_filt, y, weights, cat_mapping def _add_dummies(self, panel, mapping): """ Add entity and / or categorical dummies to input X DataFrame Returns ------- DataFrame """ panel = self._add_entity_effects(panel) panel = self._add_categorical_dummies(panel, mapping) return panel def _add_entity_effects(self, panel): """ Add entity dummies to panel Returns ------- DataFrame """ from pandas.core.reshape import make_axis_dummies if not self._entity_effects: return panel self.log('-- Adding entity fixed effect dummies') dummies = make_axis_dummies(panel, 'minor') if not self._use_all_dummies: if 'entity' in self._dropped_dummies: to_exclude = str(self._dropped_dummies.get('entity')) else: to_exclude = dummies.columns[0] if to_exclude not in dummies.columns: raise Exception('%s not in %s' % (to_exclude, dummies.columns)) self.log('-- Excluding dummy for entity: %s' % to_exclude) dummies = dummies.filter(dummies.columns.difference([to_exclude])) dummies = dummies.add_prefix('FE_') panel = panel.join(dummies) return panel def _add_categorical_dummies(self, panel, cat_mappings): """ Add categorical dummies to panel Returns ------- DataFrame """ if not self._x_effects: return panel dropped_dummy = (self._entity_effects and not self._use_all_dummies) for effect in self._x_effects: self.log('-- Adding fixed effect dummies for %s' % effect) dummies = get_dummies(panel[effect]) val_map = cat_mappings.get(effect) if val_map: val_map = dict((v, k) for k, v in compat.iteritems(val_map)) if dropped_dummy or not self._use_all_dummies: if effect in self._dropped_dummies: to_exclude = mapped_name = self._dropped_dummies.get( effect) if val_map: mapped_name = val_map[to_exclude] else: to_exclude = mapped_name = dummies.columns[0] if mapped_name not in dummies.columns: # pragma: no cover raise Exception('%s not in %s' % (to_exclude, dummies.columns)) self.log( '-- Excluding dummy for %s: %s' % (effect, to_exclude)) dummies = dummies.filter(dummies.columns.difference([mapped_name])) dropped_dummy = True dummies = _convertDummies(dummies, cat_mappings.get(effect)) dummies = dummies.add_prefix('%s_' % effect) panel = panel.join(dummies) return panel @property def _use_all_dummies(self): """ In the case of using an intercept or including time fixed effects, completely partitioning the sample would make the X not full rank. """ return (not self._intercept and not self._time_effects) @cache_readonly def _beta_raw(self): """Runs the regression and returns the beta.""" X = self._x_trans.values Y = self._y_trans.values.squeeze() beta, _, _, _ = np.linalg.lstsq(X, Y) return beta @cache_readonly @cache_readonly def _df_model_raw(self): """Returns the raw model degrees of freedom.""" return self._df_raw - 1 @cache_readonly def _df_resid_raw(self): """Returns the raw residual degrees of freedom.""" return self._nobs - self._df_raw @cache_readonly def _df_raw(self): """Returns the degrees of freedom.""" df = math.rank(self._x_trans.values) if self._time_effects: df += self._total_times return df @cache_readonly @property @cache_readonly def _r2_adj_raw(self): """Returns the raw r-squared adjusted values.""" nobs = self._nobs factors = (nobs - 1) / (nobs - self._df_raw) return 1 - (1 - self._r2_raw) * factors @cache_readonly @cache_readonly @cache_readonly def _rmse_raw(self): """Returns the raw rmse values.""" # X = self._x.values # Y = self._y.values.squeeze() X = self._x_trans.values Y = self._y_trans.values.squeeze() resid = Y - np.dot(X, self._beta_raw) ss = (resid ** 2).sum() return np.sqrt(ss / (self._nobs - self._df_raw)) @cache_readonly @cache_readonly def _y_fitted_raw(self): """Returns the raw fitted y values.""" return np.dot(self._x.values, self._beta_raw) @cache_readonly @cache_readonly @cache_readonly @property def add_intercept(panel, name='intercept'): """ Add column of ones to input panel Parameters ---------- panel: Panel / DataFrame name: string, default 'intercept'] Returns ------- New object (same type as input) """ panel = panel.copy() panel[name] = 1. return panel.consolidate() class MovingPanelOLS(MovingOLS, PanelOLS): """Implements rolling/expanding panel OLS. See ols function docs """ _panel_model = True @cache_readonly @cache_readonly @cache_readonly def y_predict(self): """Returns the predicted y values.""" return self._unstack_y(self._y_predict_raw) def lagged_y_predict(self, lag=1): """ Compute forecast Y value lagging coefficient by input number of time periods Parameters ---------- lag : int Returns ------- DataFrame """ x = self._x.values betas = self._beta_matrix(lag=lag) return self._unstack_y((betas * x).sum(1)) @cache_readonly @cache_readonly def _df_raw(self): """Returns the degrees of freedom.""" df = self._rolling_rank() if self._time_effects: df += self._window_time_obs return df[self._valid_indices] @cache_readonly def _var_beta_raw(self): """Returns the raw covariance of beta.""" x = self._x y = self._y dates = x.index.levels[0] cluster_axis = None if self._cluster == 'time': cluster_axis = 0 elif self._cluster == 'entity': cluster_axis = 1 nobs = self._nobs rmse = self._rmse_raw beta = self._beta_raw df = self._df_raw window = self._window if not self._time_effects: # Non-transformed X cum_xx = self._cum_xx(x) results = [] for n, i in enumerate(self._valid_indices): if self._is_rolling and i >= window: prior_date = dates[i - window + 1] else: prior_date = dates[0] date = dates[i] x_slice = x.truncate(prior_date, date) y_slice = y.truncate(prior_date, date) if self._time_effects: xx = _xx_time_effects(x_slice, y_slice) else: xx = cum_xx[i] if self._is_rolling and i >= window: xx = xx - cum_xx[i - window] result = _var_beta_panel(y_slice, x_slice, beta[n], xx, rmse[n], cluster_axis, self._nw_lags, nobs[n], df[n], self._nw_overlap) results.append(result) return np.array(results) @cache_readonly @cache_readonly @cache_readonly def _y_predict_raw(self): """Returns the raw predicted y values.""" x = self._x.values betas = self._beta_matrix(lag=1) return (betas * x).sum(1) @cache_readonly class NonPooledPanelOLS(object): """Implements non-pooled panel OLS. Parameters ---------- y : DataFrame x : Series, DataFrame, or dict of Series intercept : bool True if you want an intercept. nw_lags : None or int Number of Newey-West lags. window_type : {'full_sample', 'rolling', 'expanding'} 'full_sample' by default window : int size of window (for rolling/expanding OLS) """ ATTRIBUTES = [ 'beta', 'df', 'df_model', 'df_resid', 'f_stat', 'p_value', 'r2', 'r2_adj', 'resid', 'rmse', 'std_err', 'summary_as_matrix', 't_stat', 'var_beta', 'x', 'y', 'y_fitted', 'y_predict' ] def _group_agg(values, bounds, f): """ R-style aggregator Parameters ---------- values : N-length or N x K ndarray bounds : B-length ndarray f : ndarray aggregation function Returns ------- ndarray with same length as bounds array """ if values.ndim == 1: N = len(values) result = np.empty(len(bounds), dtype=float) elif values.ndim == 2: N, K = values.shape result = np.empty((len(bounds), K), dtype=float) testagg = f(values[:min(1, len(values))]) if isinstance(testagg, np.ndarray) and testagg.ndim == 2: raise AssertionError('Function must reduce') for i, left_bound in enumerate(bounds): if i == len(bounds) - 1: right_bound = N else: right_bound = bounds[i + 1] result[i] = f(values[left_bound:right_bound]) return result def _xx_time_effects(x, y): """ Returns X'X - (X'T) (T'T)^-1 (T'X) """ # X'X xx = np.dot(x.values.T, x.values) xt = x.sum(level=0).values count = y.unstack().count(1).values selector = count > 0 # X'X - (T'T)^-1 (T'X) xt = xt[selector] count = count[selector] return xx - np.dot(xt.T / count, xt)
29.09434
83
0.560271
""" Linear regression objects for panel data """ # pylint: disable-msg=W0231 # pylint: disable-msg=E1101,E1103 from __future__ import division from pandas.compat import range from pandas import compat import warnings import numpy as np from pandas.core.panel import Panel from pandas.core.frame import DataFrame from pandas.core.reshape import get_dummies from pandas.core.series import Series from pandas.core.sparse import SparsePanel from pandas.stats.ols import OLS, MovingOLS import pandas.stats.common as com import pandas.stats.math as math from pandas.util.decorators import cache_readonly class PanelOLS(OLS): """Implements panel OLS. See ols function docs """ _panel_model = True def __init__(self, y, x, weights=None, intercept=True, nw_lags=None, entity_effects=False, time_effects=False, x_effects=None, cluster=None, dropped_dummies=None, verbose=False, nw_overlap=False): self._x_orig = x self._y_orig = y self._weights = weights self._intercept = intercept self._nw_lags = nw_lags self._nw_overlap = nw_overlap self._entity_effects = entity_effects self._time_effects = time_effects self._x_effects = x_effects self._dropped_dummies = dropped_dummies or {} self._cluster = com._get_cluster_type(cluster) self._verbose = verbose (self._x, self._x_trans, self._x_filtered, self._y, self._y_trans) = self._prepare_data() self._index = self._x.index.levels[0] self._T = len(self._index) def log(self, msg): if self._verbose: # pragma: no cover print(msg) def _prepare_data(self): """Cleans and stacks input data into DataFrame objects If time effects is True, then we turn off intercepts and omit an item from every (entity and x) fixed effect. Otherwise: - If we have an intercept, we omit an item from every fixed effect. - Else, we omit an item from every fixed effect except one of them. The categorical variables will get dropped from x. """ (x, x_filtered, y, weights, cat_mapping) = self._filter_data() self.log('Adding dummies to X variables') x = self._add_dummies(x, cat_mapping) self.log('Adding dummies to filtered X variables') x_filtered = self._add_dummies(x_filtered, cat_mapping) if self._x_effects: x = x.drop(self._x_effects, axis=1) x_filtered = x_filtered.drop(self._x_effects, axis=1) if self._time_effects: x_regressor = x.sub(x.mean(level=0), level=0) unstacked_y = y.unstack() y_regressor = unstacked_y.sub(unstacked_y.mean(1), axis=0).stack() y_regressor.index = y.index elif self._intercept: # only add intercept when no time effects self.log('Adding intercept') x = x_regressor = add_intercept(x) x_filtered = add_intercept(x_filtered) y_regressor = y else: self.log('No intercept added') x_regressor = x y_regressor = y if weights is not None: if not y_regressor.index.equals(weights.index): raise AssertionError("y_regressor and weights must have the " "same index") if not x_regressor.index.equals(weights.index): raise AssertionError("x_regressor and weights must have the " "same index") rt_weights = np.sqrt(weights) y_regressor = y_regressor * rt_weights x_regressor = x_regressor.mul(rt_weights, axis=0) return x, x_regressor, x_filtered, y, y_regressor def _filter_data(self): """ """ data = self._x_orig cat_mapping = {} if isinstance(data, DataFrame): data = data.to_panel() else: if isinstance(data, Panel): data = data.copy() if not isinstance(data, SparsePanel): data, cat_mapping = self._convert_x(data) if not isinstance(data, Panel): data = Panel.from_dict(data, intersect=True) x_names = data.items if self._weights is not None: data['__weights__'] = self._weights # Filter x's without y (so we can make a prediction) filtered = data.to_frame() # Filter all data together using to_frame # convert to DataFrame y = self._y_orig if isinstance(y, Series): y = y.unstack() data['__y__'] = y data_long = data.to_frame() x_filt = filtered.filter(x_names) x = data_long.filter(x_names) y = data_long['__y__'] if self._weights is not None and not self._weights.empty: weights = data_long['__weights__'] else: weights = None return x, x_filt, y, weights, cat_mapping def _convert_x(self, x): # Converts non-numeric data in x to floats. x_converted is the # DataFrame with converted values, and x_conversion is a dict that # provides the reverse mapping. For example, if 'A' was converted to 0 # for x named 'variety', then x_conversion['variety'][0] is 'A'. x_converted = {} cat_mapping = {} # x can be either a dict or a Panel, but in Python 3, dicts don't have # .iteritems iteritems = getattr(x, 'iteritems', x.items) for key, df in iteritems(): if not isinstance(df, DataFrame): raise AssertionError("all input items must be DataFrames, " "at least one is of " "type {0}".format(type(df))) if _is_numeric(df): x_converted[key] = df else: try: df = df.astype(float) except (TypeError, ValueError): values = df.values distinct_values = sorted(set(values.flat)) cat_mapping[key] = dict(enumerate(distinct_values)) new_values = np.searchsorted(distinct_values, values) x_converted[key] = DataFrame(new_values, index=df.index, columns=df.columns) if len(cat_mapping) == 0: x_converted = x return x_converted, cat_mapping def _add_dummies(self, panel, mapping): """ Add entity and / or categorical dummies to input X DataFrame Returns ------- DataFrame """ panel = self._add_entity_effects(panel) panel = self._add_categorical_dummies(panel, mapping) return panel def _add_entity_effects(self, panel): """ Add entity dummies to panel Returns ------- DataFrame """ from pandas.core.reshape import make_axis_dummies if not self._entity_effects: return panel self.log('-- Adding entity fixed effect dummies') dummies = make_axis_dummies(panel, 'minor') if not self._use_all_dummies: if 'entity' in self._dropped_dummies: to_exclude = str(self._dropped_dummies.get('entity')) else: to_exclude = dummies.columns[0] if to_exclude not in dummies.columns: raise Exception('%s not in %s' % (to_exclude, dummies.columns)) self.log('-- Excluding dummy for entity: %s' % to_exclude) dummies = dummies.filter(dummies.columns.difference([to_exclude])) dummies = dummies.add_prefix('FE_') panel = panel.join(dummies) return panel def _add_categorical_dummies(self, panel, cat_mappings): """ Add categorical dummies to panel Returns ------- DataFrame """ if not self._x_effects: return panel dropped_dummy = (self._entity_effects and not self._use_all_dummies) for effect in self._x_effects: self.log('-- Adding fixed effect dummies for %s' % effect) dummies = get_dummies(panel[effect]) val_map = cat_mappings.get(effect) if val_map: val_map = dict((v, k) for k, v in compat.iteritems(val_map)) if dropped_dummy or not self._use_all_dummies: if effect in self._dropped_dummies: to_exclude = mapped_name = self._dropped_dummies.get( effect) if val_map: mapped_name = val_map[to_exclude] else: to_exclude = mapped_name = dummies.columns[0] if mapped_name not in dummies.columns: # pragma: no cover raise Exception('%s not in %s' % (to_exclude, dummies.columns)) self.log( '-- Excluding dummy for %s: %s' % (effect, to_exclude)) dummies = dummies.filter(dummies.columns.difference([mapped_name])) dropped_dummy = True dummies = _convertDummies(dummies, cat_mappings.get(effect)) dummies = dummies.add_prefix('%s_' % effect) panel = panel.join(dummies) return panel @property def _use_all_dummies(self): """ In the case of using an intercept or including time fixed effects, completely partitioning the sample would make the X not full rank. """ return (not self._intercept and not self._time_effects) @cache_readonly def _beta_raw(self): """Runs the regression and returns the beta.""" X = self._x_trans.values Y = self._y_trans.values.squeeze() beta, _, _, _ = np.linalg.lstsq(X, Y) return beta @cache_readonly def beta(self): return Series(self._beta_raw, index=self._x.columns) @cache_readonly def _df_model_raw(self): """Returns the raw model degrees of freedom.""" return self._df_raw - 1 @cache_readonly def _df_resid_raw(self): """Returns the raw residual degrees of freedom.""" return self._nobs - self._df_raw @cache_readonly def _df_raw(self): """Returns the degrees of freedom.""" df = math.rank(self._x_trans.values) if self._time_effects: df += self._total_times return df @cache_readonly def _r2_raw(self): Y = self._y_trans.values.squeeze() X = self._x_trans.values resid = Y - np.dot(X, self._beta_raw) SSE = (resid ** 2).sum() if self._use_centered_tss: SST = ((Y - np.mean(Y)) ** 2).sum() else: SST = (Y ** 2).sum() return 1 - SSE / SST @property def _use_centered_tss(self): # has_intercept = np.abs(self._resid_raw.sum()) < _FP_ERR return self._intercept or self._entity_effects or self._time_effects @cache_readonly def _r2_adj_raw(self): """Returns the raw r-squared adjusted values.""" nobs = self._nobs factors = (nobs - 1) / (nobs - self._df_raw) return 1 - (1 - self._r2_raw) * factors @cache_readonly def _resid_raw(self): Y = self._y.values.squeeze() X = self._x.values return Y - np.dot(X, self._beta_raw) @cache_readonly def resid(self): return self._unstack_vector(self._resid_raw) @cache_readonly def _rmse_raw(self): """Returns the raw rmse values.""" # X = self._x.values # Y = self._y.values.squeeze() X = self._x_trans.values Y = self._y_trans.values.squeeze() resid = Y - np.dot(X, self._beta_raw) ss = (resid ** 2).sum() return np.sqrt(ss / (self._nobs - self._df_raw)) @cache_readonly def _var_beta_raw(self): cluster_axis = None if self._cluster == 'time': cluster_axis = 0 elif self._cluster == 'entity': cluster_axis = 1 x = self._x y = self._y if self._time_effects: xx = _xx_time_effects(x, y) else: xx = np.dot(x.values.T, x.values) return _var_beta_panel(y, x, self._beta_raw, xx, self._rmse_raw, cluster_axis, self._nw_lags, self._nobs, self._df_raw, self._nw_overlap) @cache_readonly def _y_fitted_raw(self): """Returns the raw fitted y values.""" return np.dot(self._x.values, self._beta_raw) @cache_readonly def y_fitted(self): return self._unstack_vector(self._y_fitted_raw, index=self._x.index) def _unstack_vector(self, vec, index=None): if index is None: index = self._y_trans.index panel = DataFrame(vec, index=index, columns=['dummy']) return panel.to_panel()['dummy'] def _unstack_y(self, vec): unstacked = self._unstack_vector(vec) return unstacked.reindex(self.beta.index) @cache_readonly def _time_obs_count(self): return self._y_trans.count(level=0).values @cache_readonly def _time_has_obs(self): return self._time_obs_count > 0 @property def _nobs(self): return len(self._y) def _convertDummies(dummies, mapping): # cleans up the names of the generated dummies new_items = [] for item in dummies.columns: if not mapping: var = str(item) if isinstance(item, float): var = '%g' % item new_items.append(var) else: # renames the dummies if a conversion dict is provided new_items.append(mapping[int(item)]) dummies = DataFrame(dummies.values, index=dummies.index, columns=new_items) return dummies def _is_numeric(df): for col in df: if df[col].dtype.name == 'object': return False return True def add_intercept(panel, name='intercept'): """ Add column of ones to input panel Parameters ---------- panel: Panel / DataFrame name: string, default 'intercept'] Returns ------- New object (same type as input) """ panel = panel.copy() panel[name] = 1. return panel.consolidate() class MovingPanelOLS(MovingOLS, PanelOLS): """Implements rolling/expanding panel OLS. See ols function docs """ _panel_model = True def __init__(self, y, x, weights=None, window_type='expanding', window=None, min_periods=None, min_obs=None, intercept=True, nw_lags=None, nw_overlap=False, entity_effects=False, time_effects=False, x_effects=None, cluster=None, dropped_dummies=None, verbose=False): self._args = dict(intercept=intercept, nw_lags=nw_lags, nw_overlap=nw_overlap, entity_effects=entity_effects, time_effects=time_effects, x_effects=x_effects, cluster=cluster, dropped_dummies=dropped_dummies, verbose=verbose) PanelOLS.__init__(self, y=y, x=x, weights=weights, **self._args) self._set_window(window_type, window, min_periods) if min_obs is None: min_obs = len(self._x.columns) + 1 self._min_obs = min_obs @cache_readonly def resid(self): return self._unstack_y(self._resid_raw) @cache_readonly def y_fitted(self): return self._unstack_y(self._y_fitted_raw) @cache_readonly def y_predict(self): """Returns the predicted y values.""" return self._unstack_y(self._y_predict_raw) def lagged_y_predict(self, lag=1): """ Compute forecast Y value lagging coefficient by input number of time periods Parameters ---------- lag : int Returns ------- DataFrame """ x = self._x.values betas = self._beta_matrix(lag=lag) return self._unstack_y((betas * x).sum(1)) @cache_readonly def _rolling_ols_call(self): return self._calc_betas(self._x_trans, self._y_trans) @cache_readonly def _df_raw(self): """Returns the degrees of freedom.""" df = self._rolling_rank() if self._time_effects: df += self._window_time_obs return df[self._valid_indices] @cache_readonly def _var_beta_raw(self): """Returns the raw covariance of beta.""" x = self._x y = self._y dates = x.index.levels[0] cluster_axis = None if self._cluster == 'time': cluster_axis = 0 elif self._cluster == 'entity': cluster_axis = 1 nobs = self._nobs rmse = self._rmse_raw beta = self._beta_raw df = self._df_raw window = self._window if not self._time_effects: # Non-transformed X cum_xx = self._cum_xx(x) results = [] for n, i in enumerate(self._valid_indices): if self._is_rolling and i >= window: prior_date = dates[i - window + 1] else: prior_date = dates[0] date = dates[i] x_slice = x.truncate(prior_date, date) y_slice = y.truncate(prior_date, date) if self._time_effects: xx = _xx_time_effects(x_slice, y_slice) else: xx = cum_xx[i] if self._is_rolling and i >= window: xx = xx - cum_xx[i - window] result = _var_beta_panel(y_slice, x_slice, beta[n], xx, rmse[n], cluster_axis, self._nw_lags, nobs[n], df[n], self._nw_overlap) results.append(result) return np.array(results) @cache_readonly def _resid_raw(self): beta_matrix = self._beta_matrix(lag=0) Y = self._y.values.squeeze() X = self._x.values resid = Y - (X * beta_matrix).sum(1) return resid @cache_readonly def _y_fitted_raw(self): x = self._x.values betas = self._beta_matrix(lag=0) return (betas * x).sum(1) @cache_readonly def _y_predict_raw(self): """Returns the raw predicted y values.""" x = self._x.values betas = self._beta_matrix(lag=1) return (betas * x).sum(1) def _beta_matrix(self, lag=0): if lag < 0: raise AssertionError("'lag' must be greater than or equal to 0, " "input was {0}".format(lag)) index = self._y_trans.index major_labels = index.labels[0] labels = major_labels - lag indexer = self._valid_indices.searchsorted(labels, side='left') beta_matrix = self._beta_raw[indexer] beta_matrix[labels < self._valid_indices[0]] = np.NaN return beta_matrix @cache_readonly def _enough_obs(self): # XXX: what's the best way to determine where to start? # TODO: write unit tests for this rank_threshold = len(self._x.columns) + 1 if self._min_obs < rank_threshold: # pragma: no cover warnings.warn('min_obs is smaller than rank of X matrix') enough_observations = self._nobs_raw >= self._min_obs enough_time_periods = self._window_time_obs >= self._min_periods return enough_time_periods & enough_observations def create_ols_dict(attr): def attr_getter(self): d = {} for k, v in compat.iteritems(self.results): result = getattr(v, attr) d[k] = result return d return attr_getter def create_ols_attr(attr): return property(create_ols_dict(attr)) class NonPooledPanelOLS(object): """Implements non-pooled panel OLS. Parameters ---------- y : DataFrame x : Series, DataFrame, or dict of Series intercept : bool True if you want an intercept. nw_lags : None or int Number of Newey-West lags. window_type : {'full_sample', 'rolling', 'expanding'} 'full_sample' by default window : int size of window (for rolling/expanding OLS) """ ATTRIBUTES = [ 'beta', 'df', 'df_model', 'df_resid', 'f_stat', 'p_value', 'r2', 'r2_adj', 'resid', 'rmse', 'std_err', 'summary_as_matrix', 't_stat', 'var_beta', 'x', 'y', 'y_fitted', 'y_predict' ] def __init__(self, y, x, window_type='full_sample', window=None, min_periods=None, intercept=True, nw_lags=None, nw_overlap=False): for attr in self.ATTRIBUTES: setattr(self.__class__, attr, create_ols_attr(attr)) results = {} for entity in y: entity_y = y[entity] entity_x = {} for x_var in x: entity_x[x_var] = x[x_var][entity] from pandas.stats.interface import ols results[entity] = ols(y=entity_y, x=entity_x, window_type=window_type, window=window, min_periods=min_periods, intercept=intercept, nw_lags=nw_lags, nw_overlap=nw_overlap) self.results = results def _var_beta_panel(y, x, beta, xx, rmse, cluster_axis, nw_lags, nobs, df, nw_overlap): xx_inv = math.inv(xx) yv = y.values if cluster_axis is None: if nw_lags is None: return xx_inv * (rmse ** 2) else: resid = yv - np.dot(x.values, beta) m = (x.values.T * resid).T xeps = math.newey_west(m, nw_lags, nobs, df, nw_overlap) return np.dot(xx_inv, np.dot(xeps, xx_inv)) else: Xb = np.dot(x.values, beta).reshape((len(x.values), 1)) resid = DataFrame(yv[:, None] - Xb, index=y.index, columns=['resid']) if cluster_axis == 1: x = x.swaplevel(0, 1).sortlevel(0) resid = resid.swaplevel(0, 1).sortlevel(0) m = _group_agg(x.values * resid.values, x.index._bounds, lambda x: np.sum(x, axis=0)) if nw_lags is None: nw_lags = 0 xox = 0 for i in range(len(x.index.levels[0])): xox += math.newey_west(m[i: i + 1], nw_lags, nobs, df, nw_overlap) return np.dot(xx_inv, np.dot(xox, xx_inv)) def _group_agg(values, bounds, f): """ R-style aggregator Parameters ---------- values : N-length or N x K ndarray bounds : B-length ndarray f : ndarray aggregation function Returns ------- ndarray with same length as bounds array """ if values.ndim == 1: N = len(values) result = np.empty(len(bounds), dtype=float) elif values.ndim == 2: N, K = values.shape result = np.empty((len(bounds), K), dtype=float) testagg = f(values[:min(1, len(values))]) if isinstance(testagg, np.ndarray) and testagg.ndim == 2: raise AssertionError('Function must reduce') for i, left_bound in enumerate(bounds): if i == len(bounds) - 1: right_bound = N else: right_bound = bounds[i + 1] result[i] = f(values[left_bound:right_bound]) return result def _xx_time_effects(x, y): """ Returns X'X - (X'T) (T'T)^-1 (T'X) """ # X'X xx = np.dot(x.values.T, x.values) xt = x.sum(level=0).values count = y.unstack().count(1).values selector = count > 0 # X'X - (T'T)^-1 (T'X) xt = xt[selector] count = count[selector] return xx - np.dot(xt.T / count, xt)
9,684
0
747
409610d1dd2cdf8851c1ac5fbe9219d4daecb716
2,857
py
Python
lightning_transformers/task/nlp/question_answering/config.py
mariomeissner/lightning-transformers
4efda7b4e924b37956c7a008ca01819f5c3f98c8
[ "Apache-2.0" ]
451
2021-04-21T15:53:59.000Z
2022-03-29T10:39:45.000Z
lightning_transformers/task/nlp/question_answering/config.py
mathemusician/lightning-transformers
b2ef06113433e6a178ce4d3c9df7ede8064e247f
[ "Apache-2.0" ]
92
2021-04-21T18:42:58.000Z
2022-03-30T05:29:54.000Z
lightning_transformers/task/nlp/question_answering/config.py
mathemusician/lightning-transformers
b2ef06113433e6a178ce4d3c9df7ede8064e247f
[ "Apache-2.0" ]
51
2021-04-22T05:35:28.000Z
2022-03-17T13:08:12.000Z
# Copyright 2020 The HuggingFace Team 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. # Adapted from: # https://github.com/huggingface/transformers/blob/master/examples/question-answering/run_qa.py # yapf: off from dataclasses import dataclass, field from lightning_transformers.core.nlp import HFTransformerDataConfig @dataclass class QuestionAnsweringDataConfig(HFTransformerDataConfig): """Arguments pertaining to what data we are going to input our model for training and eval.""" max_length: int = field( default=384, metadata={ "help": "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." }, ) version_2_with_negative: bool = field( default=False, metadata={"help": "If true, some of the examples do not have an answer."} ) null_score_diff_threshold: float = field( default=0.0, metadata={ "help": "The threshold used to select the null answer: if the best answer has a score that is less than " "the score of the null answer minus this threshold, the null answer is selected for this example. " "Only useful when `version_2_with_negative=True`." }, ) doc_stride: int = field( default=128, metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}, ) n_best_size: int = field( default=20, metadata={"help": "The total number of n-best predictions to generate when looking for an answer."}, ) max_answer_length: int = field( default=30, metadata={ "help": "The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another." }, )
41.405797
117
0.676234
# Copyright 2020 The HuggingFace Team 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. # Adapted from: # https://github.com/huggingface/transformers/blob/master/examples/question-answering/run_qa.py # yapf: off from dataclasses import dataclass, field from lightning_transformers.core.nlp import HFTransformerDataConfig @dataclass class QuestionAnsweringDataConfig(HFTransformerDataConfig): """Arguments pertaining to what data we are going to input our model for training and eval.""" max_length: int = field( default=384, metadata={ "help": "The maximum total input sequence length after tokenization. Sequences longer " "than this will be truncated, sequences shorter will be padded." }, ) version_2_with_negative: bool = field( default=False, metadata={"help": "If true, some of the examples do not have an answer."} ) null_score_diff_threshold: float = field( default=0.0, metadata={ "help": "The threshold used to select the null answer: if the best answer has a score that is less than " "the score of the null answer minus this threshold, the null answer is selected for this example. " "Only useful when `version_2_with_negative=True`." }, ) doc_stride: int = field( default=128, metadata={"help": "When splitting up a long document into chunks, how much stride to take between chunks."}, ) n_best_size: int = field( default=20, metadata={"help": "The total number of n-best predictions to generate when looking for an answer."}, ) max_answer_length: int = field( default=30, metadata={ "help": "The maximum length of an answer that can be generated. This is needed because the start " "and end predictions are not conditioned on one another." }, ) def __post_init__(self): if self.train_file is not None: extension = self.train_file.split(".")[-1] assert extension in ["csv", "json"], "`train_file` should be a csv or a json file." if self.validation_file is not None: extension = self.validation_file.split(".")[-1] assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."
400
0
27
0e4f69138aecd1313f122259efebb214ee565651
19,502
py
Python
venv/Lib/site-packages/tensorboard/uploader/proto/server_info_pb2.py
masterrey/SmartMachines
e48aff314b1171a13a39c3a41230d900bf090a1f
[ "Apache-2.0" ]
353
2020-12-10T10:47:17.000Z
2022-03-31T23:08:29.000Z
venv/Lib/site-packages/tensorboard/uploader/proto/server_info_pb2.py
masterrey/SmartMachines
e48aff314b1171a13a39c3a41230d900bf090a1f
[ "Apache-2.0" ]
80
2020-12-10T09:54:22.000Z
2022-03-30T22:08:45.000Z
venv/Lib/site-packages/tensorboard/uploader/proto/server_info_pb2.py
masterrey/SmartMachines
e48aff314b1171a13a39c3a41230d900bf090a1f
[ "Apache-2.0" ]
63
2020-12-10T17:10:34.000Z
2022-03-28T16:27:07.000Z
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorboard/uploader/proto/server_info.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='tensorboard/uploader/proto/server_info.proto', package='tensorboard.service', syntax='proto3', serialized_options=None, serialized_pb=_b('\n,tensorboard/uploader/proto/server_info.proto\x12\x13tensorboard.service\"l\n\x11ServerInfoRequest\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x46\n\x14plugin_specification\x18\x02 \x01(\x0b\x32(.tensorboard.service.PluginSpecification\"\xb7\x02\n\x12ServerInfoResponse\x12\x39\n\rcompatibility\x18\x01 \x01(\x0b\x32\".tensorboard.service.Compatibility\x12\x32\n\napi_server\x18\x02 \x01(\x0b\x32\x1e.tensorboard.service.ApiServer\x12<\n\nurl_format\x18\x03 \x01(\x0b\x32(.tensorboard.service.ExperimentUrlFormat\x12:\n\x0eplugin_control\x18\x04 \x01(\x0b\x32\".tensorboard.service.PluginControl\x12\x38\n\rupload_limits\x18\x05 \x01(\x0b\x32!.tensorboard.service.UploadLimits\"\\\n\rCompatibility\x12:\n\x07verdict\x18\x01 \x01(\x0e\x32).tensorboard.service.CompatibilityVerdict\x12\x0f\n\x07\x64\x65tails\x18\x02 \x01(\t\"\x1d\n\tApiServer\x12\x10\n\x08\x65ndpoint\x18\x01 \x01(\t\"?\n\x13\x45xperimentUrlFormat\x12\x10\n\x08template\x18\x01 \x01(\t\x12\x16\n\x0eid_placeholder\x18\x02 \x01(\t\"-\n\x13PluginSpecification\x12\x16\n\x0eupload_plugins\x18\x02 \x03(\t\"(\n\rPluginControl\x12\x17\n\x0f\x61llowed_plugins\x18\x01 \x03(\t\"\x92\x02\n\x0cUploadLimits\x12\x1f\n\x17max_scalar_request_size\x18\x03 \x01(\x03\x12\x1f\n\x17max_tensor_request_size\x18\x04 \x01(\x03\x12\x1d\n\x15max_blob_request_size\x18\x05 \x01(\x03\x12#\n\x1bmin_scalar_request_interval\x18\x06 \x01(\x03\x12#\n\x1bmin_tensor_request_interval\x18\x07 \x01(\x03\x12!\n\x19min_blob_request_interval\x18\x08 \x01(\x03\x12\x15\n\rmax_blob_size\x18\x01 \x01(\x03\x12\x1d\n\x15max_tensor_point_size\x18\x02 \x01(\x03*`\n\x14\x43ompatibilityVerdict\x12\x13\n\x0fVERDICT_UNKNOWN\x10\x00\x12\x0e\n\nVERDICT_OK\x10\x01\x12\x10\n\x0cVERDICT_WARN\x10\x02\x12\x11\n\rVERDICT_ERROR\x10\x03\x62\x06proto3') ) _COMPATIBILITYVERDICT = _descriptor.EnumDescriptor( name='CompatibilityVerdict', full_name='tensorboard.service.CompatibilityVerdict', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='VERDICT_UNKNOWN', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='VERDICT_OK', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='VERDICT_WARN', index=2, number=2, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='VERDICT_ERROR', index=3, number=3, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=1049, serialized_end=1145, ) _sym_db.RegisterEnumDescriptor(_COMPATIBILITYVERDICT) CompatibilityVerdict = enum_type_wrapper.EnumTypeWrapper(_COMPATIBILITYVERDICT) VERDICT_UNKNOWN = 0 VERDICT_OK = 1 VERDICT_WARN = 2 VERDICT_ERROR = 3 _SERVERINFOREQUEST = _descriptor.Descriptor( name='ServerInfoRequest', full_name='tensorboard.service.ServerInfoRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='version', full_name='tensorboard.service.ServerInfoRequest.version', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='plugin_specification', full_name='tensorboard.service.ServerInfoRequest.plugin_specification', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=69, serialized_end=177, ) _SERVERINFORESPONSE = _descriptor.Descriptor( name='ServerInfoResponse', full_name='tensorboard.service.ServerInfoResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='compatibility', full_name='tensorboard.service.ServerInfoResponse.compatibility', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='api_server', full_name='tensorboard.service.ServerInfoResponse.api_server', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='url_format', full_name='tensorboard.service.ServerInfoResponse.url_format', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='plugin_control', full_name='tensorboard.service.ServerInfoResponse.plugin_control', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='upload_limits', full_name='tensorboard.service.ServerInfoResponse.upload_limits', index=4, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=180, serialized_end=491, ) _COMPATIBILITY = _descriptor.Descriptor( name='Compatibility', full_name='tensorboard.service.Compatibility', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='verdict', full_name='tensorboard.service.Compatibility.verdict', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='details', full_name='tensorboard.service.Compatibility.details', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=493, serialized_end=585, ) _APISERVER = _descriptor.Descriptor( name='ApiServer', full_name='tensorboard.service.ApiServer', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='endpoint', full_name='tensorboard.service.ApiServer.endpoint', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=587, serialized_end=616, ) _EXPERIMENTURLFORMAT = _descriptor.Descriptor( name='ExperimentUrlFormat', full_name='tensorboard.service.ExperimentUrlFormat', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='template', full_name='tensorboard.service.ExperimentUrlFormat.template', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='id_placeholder', full_name='tensorboard.service.ExperimentUrlFormat.id_placeholder', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=618, serialized_end=681, ) _PLUGINSPECIFICATION = _descriptor.Descriptor( name='PluginSpecification', full_name='tensorboard.service.PluginSpecification', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='upload_plugins', full_name='tensorboard.service.PluginSpecification.upload_plugins', index=0, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=683, serialized_end=728, ) _PLUGINCONTROL = _descriptor.Descriptor( name='PluginControl', full_name='tensorboard.service.PluginControl', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='allowed_plugins', full_name='tensorboard.service.PluginControl.allowed_plugins', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=730, serialized_end=770, ) _UPLOADLIMITS = _descriptor.Descriptor( name='UploadLimits', full_name='tensorboard.service.UploadLimits', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='max_scalar_request_size', full_name='tensorboard.service.UploadLimits.max_scalar_request_size', index=0, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='max_tensor_request_size', full_name='tensorboard.service.UploadLimits.max_tensor_request_size', index=1, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='max_blob_request_size', full_name='tensorboard.service.UploadLimits.max_blob_request_size', index=2, number=5, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='min_scalar_request_interval', full_name='tensorboard.service.UploadLimits.min_scalar_request_interval', index=3, number=6, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='min_tensor_request_interval', full_name='tensorboard.service.UploadLimits.min_tensor_request_interval', index=4, number=7, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='min_blob_request_interval', full_name='tensorboard.service.UploadLimits.min_blob_request_interval', index=5, number=8, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='max_blob_size', full_name='tensorboard.service.UploadLimits.max_blob_size', index=6, number=1, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='max_tensor_point_size', full_name='tensorboard.service.UploadLimits.max_tensor_point_size', index=7, number=2, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=773, serialized_end=1047, ) _SERVERINFOREQUEST.fields_by_name['plugin_specification'].message_type = _PLUGINSPECIFICATION _SERVERINFORESPONSE.fields_by_name['compatibility'].message_type = _COMPATIBILITY _SERVERINFORESPONSE.fields_by_name['api_server'].message_type = _APISERVER _SERVERINFORESPONSE.fields_by_name['url_format'].message_type = _EXPERIMENTURLFORMAT _SERVERINFORESPONSE.fields_by_name['plugin_control'].message_type = _PLUGINCONTROL _SERVERINFORESPONSE.fields_by_name['upload_limits'].message_type = _UPLOADLIMITS _COMPATIBILITY.fields_by_name['verdict'].enum_type = _COMPATIBILITYVERDICT DESCRIPTOR.message_types_by_name['ServerInfoRequest'] = _SERVERINFOREQUEST DESCRIPTOR.message_types_by_name['ServerInfoResponse'] = _SERVERINFORESPONSE DESCRIPTOR.message_types_by_name['Compatibility'] = _COMPATIBILITY DESCRIPTOR.message_types_by_name['ApiServer'] = _APISERVER DESCRIPTOR.message_types_by_name['ExperimentUrlFormat'] = _EXPERIMENTURLFORMAT DESCRIPTOR.message_types_by_name['PluginSpecification'] = _PLUGINSPECIFICATION DESCRIPTOR.message_types_by_name['PluginControl'] = _PLUGINCONTROL DESCRIPTOR.message_types_by_name['UploadLimits'] = _UPLOADLIMITS DESCRIPTOR.enum_types_by_name['CompatibilityVerdict'] = _COMPATIBILITYVERDICT _sym_db.RegisterFileDescriptor(DESCRIPTOR) ServerInfoRequest = _reflection.GeneratedProtocolMessageType('ServerInfoRequest', (_message.Message,), { 'DESCRIPTOR' : _SERVERINFOREQUEST, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.ServerInfoRequest) }) _sym_db.RegisterMessage(ServerInfoRequest) ServerInfoResponse = _reflection.GeneratedProtocolMessageType('ServerInfoResponse', (_message.Message,), { 'DESCRIPTOR' : _SERVERINFORESPONSE, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.ServerInfoResponse) }) _sym_db.RegisterMessage(ServerInfoResponse) Compatibility = _reflection.GeneratedProtocolMessageType('Compatibility', (_message.Message,), { 'DESCRIPTOR' : _COMPATIBILITY, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.Compatibility) }) _sym_db.RegisterMessage(Compatibility) ApiServer = _reflection.GeneratedProtocolMessageType('ApiServer', (_message.Message,), { 'DESCRIPTOR' : _APISERVER, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.ApiServer) }) _sym_db.RegisterMessage(ApiServer) ExperimentUrlFormat = _reflection.GeneratedProtocolMessageType('ExperimentUrlFormat', (_message.Message,), { 'DESCRIPTOR' : _EXPERIMENTURLFORMAT, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.ExperimentUrlFormat) }) _sym_db.RegisterMessage(ExperimentUrlFormat) PluginSpecification = _reflection.GeneratedProtocolMessageType('PluginSpecification', (_message.Message,), { 'DESCRIPTOR' : _PLUGINSPECIFICATION, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.PluginSpecification) }) _sym_db.RegisterMessage(PluginSpecification) PluginControl = _reflection.GeneratedProtocolMessageType('PluginControl', (_message.Message,), { 'DESCRIPTOR' : _PLUGINCONTROL, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.PluginControl) }) _sym_db.RegisterMessage(PluginControl) UploadLimits = _reflection.GeneratedProtocolMessageType('UploadLimits', (_message.Message,), { 'DESCRIPTOR' : _UPLOADLIMITS, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.UploadLimits) }) _sym_db.RegisterMessage(UploadLimits) # @@protoc_insertion_point(module_scope)
40.127572
1,788
0.762383
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tensorboard/uploader/proto/server_info.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() DESCRIPTOR = _descriptor.FileDescriptor( name='tensorboard/uploader/proto/server_info.proto', package='tensorboard.service', syntax='proto3', serialized_options=None, serialized_pb=_b('\n,tensorboard/uploader/proto/server_info.proto\x12\x13tensorboard.service\"l\n\x11ServerInfoRequest\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x46\n\x14plugin_specification\x18\x02 \x01(\x0b\x32(.tensorboard.service.PluginSpecification\"\xb7\x02\n\x12ServerInfoResponse\x12\x39\n\rcompatibility\x18\x01 \x01(\x0b\x32\".tensorboard.service.Compatibility\x12\x32\n\napi_server\x18\x02 \x01(\x0b\x32\x1e.tensorboard.service.ApiServer\x12<\n\nurl_format\x18\x03 \x01(\x0b\x32(.tensorboard.service.ExperimentUrlFormat\x12:\n\x0eplugin_control\x18\x04 \x01(\x0b\x32\".tensorboard.service.PluginControl\x12\x38\n\rupload_limits\x18\x05 \x01(\x0b\x32!.tensorboard.service.UploadLimits\"\\\n\rCompatibility\x12:\n\x07verdict\x18\x01 \x01(\x0e\x32).tensorboard.service.CompatibilityVerdict\x12\x0f\n\x07\x64\x65tails\x18\x02 \x01(\t\"\x1d\n\tApiServer\x12\x10\n\x08\x65ndpoint\x18\x01 \x01(\t\"?\n\x13\x45xperimentUrlFormat\x12\x10\n\x08template\x18\x01 \x01(\t\x12\x16\n\x0eid_placeholder\x18\x02 \x01(\t\"-\n\x13PluginSpecification\x12\x16\n\x0eupload_plugins\x18\x02 \x03(\t\"(\n\rPluginControl\x12\x17\n\x0f\x61llowed_plugins\x18\x01 \x03(\t\"\x92\x02\n\x0cUploadLimits\x12\x1f\n\x17max_scalar_request_size\x18\x03 \x01(\x03\x12\x1f\n\x17max_tensor_request_size\x18\x04 \x01(\x03\x12\x1d\n\x15max_blob_request_size\x18\x05 \x01(\x03\x12#\n\x1bmin_scalar_request_interval\x18\x06 \x01(\x03\x12#\n\x1bmin_tensor_request_interval\x18\x07 \x01(\x03\x12!\n\x19min_blob_request_interval\x18\x08 \x01(\x03\x12\x15\n\rmax_blob_size\x18\x01 \x01(\x03\x12\x1d\n\x15max_tensor_point_size\x18\x02 \x01(\x03*`\n\x14\x43ompatibilityVerdict\x12\x13\n\x0fVERDICT_UNKNOWN\x10\x00\x12\x0e\n\nVERDICT_OK\x10\x01\x12\x10\n\x0cVERDICT_WARN\x10\x02\x12\x11\n\rVERDICT_ERROR\x10\x03\x62\x06proto3') ) _COMPATIBILITYVERDICT = _descriptor.EnumDescriptor( name='CompatibilityVerdict', full_name='tensorboard.service.CompatibilityVerdict', filename=None, file=DESCRIPTOR, values=[ _descriptor.EnumValueDescriptor( name='VERDICT_UNKNOWN', index=0, number=0, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='VERDICT_OK', index=1, number=1, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='VERDICT_WARN', index=2, number=2, serialized_options=None, type=None), _descriptor.EnumValueDescriptor( name='VERDICT_ERROR', index=3, number=3, serialized_options=None, type=None), ], containing_type=None, serialized_options=None, serialized_start=1049, serialized_end=1145, ) _sym_db.RegisterEnumDescriptor(_COMPATIBILITYVERDICT) CompatibilityVerdict = enum_type_wrapper.EnumTypeWrapper(_COMPATIBILITYVERDICT) VERDICT_UNKNOWN = 0 VERDICT_OK = 1 VERDICT_WARN = 2 VERDICT_ERROR = 3 _SERVERINFOREQUEST = _descriptor.Descriptor( name='ServerInfoRequest', full_name='tensorboard.service.ServerInfoRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='version', full_name='tensorboard.service.ServerInfoRequest.version', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='plugin_specification', full_name='tensorboard.service.ServerInfoRequest.plugin_specification', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=69, serialized_end=177, ) _SERVERINFORESPONSE = _descriptor.Descriptor( name='ServerInfoResponse', full_name='tensorboard.service.ServerInfoResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='compatibility', full_name='tensorboard.service.ServerInfoResponse.compatibility', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='api_server', full_name='tensorboard.service.ServerInfoResponse.api_server', index=1, number=2, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='url_format', full_name='tensorboard.service.ServerInfoResponse.url_format', index=2, number=3, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='plugin_control', full_name='tensorboard.service.ServerInfoResponse.plugin_control', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='upload_limits', full_name='tensorboard.service.ServerInfoResponse.upload_limits', index=4, number=5, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=180, serialized_end=491, ) _COMPATIBILITY = _descriptor.Descriptor( name='Compatibility', full_name='tensorboard.service.Compatibility', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='verdict', full_name='tensorboard.service.Compatibility.verdict', index=0, number=1, type=14, cpp_type=8, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='details', full_name='tensorboard.service.Compatibility.details', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=493, serialized_end=585, ) _APISERVER = _descriptor.Descriptor( name='ApiServer', full_name='tensorboard.service.ApiServer', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='endpoint', full_name='tensorboard.service.ApiServer.endpoint', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=587, serialized_end=616, ) _EXPERIMENTURLFORMAT = _descriptor.Descriptor( name='ExperimentUrlFormat', full_name='tensorboard.service.ExperimentUrlFormat', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='template', full_name='tensorboard.service.ExperimentUrlFormat.template', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='id_placeholder', full_name='tensorboard.service.ExperimentUrlFormat.id_placeholder', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=618, serialized_end=681, ) _PLUGINSPECIFICATION = _descriptor.Descriptor( name='PluginSpecification', full_name='tensorboard.service.PluginSpecification', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='upload_plugins', full_name='tensorboard.service.PluginSpecification.upload_plugins', index=0, number=2, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=683, serialized_end=728, ) _PLUGINCONTROL = _descriptor.Descriptor( name='PluginControl', full_name='tensorboard.service.PluginControl', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='allowed_plugins', full_name='tensorboard.service.PluginControl.allowed_plugins', index=0, number=1, type=9, cpp_type=9, label=3, has_default_value=False, default_value=[], message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=730, serialized_end=770, ) _UPLOADLIMITS = _descriptor.Descriptor( name='UploadLimits', full_name='tensorboard.service.UploadLimits', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='max_scalar_request_size', full_name='tensorboard.service.UploadLimits.max_scalar_request_size', index=0, number=3, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='max_tensor_request_size', full_name='tensorboard.service.UploadLimits.max_tensor_request_size', index=1, number=4, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='max_blob_request_size', full_name='tensorboard.service.UploadLimits.max_blob_request_size', index=2, number=5, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='min_scalar_request_interval', full_name='tensorboard.service.UploadLimits.min_scalar_request_interval', index=3, number=6, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='min_tensor_request_interval', full_name='tensorboard.service.UploadLimits.min_tensor_request_interval', index=4, number=7, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='min_blob_request_interval', full_name='tensorboard.service.UploadLimits.min_blob_request_interval', index=5, number=8, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='max_blob_size', full_name='tensorboard.service.UploadLimits.max_blob_size', index=6, number=1, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='max_tensor_point_size', full_name='tensorboard.service.UploadLimits.max_tensor_point_size', index=7, number=2, type=3, cpp_type=2, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=773, serialized_end=1047, ) _SERVERINFOREQUEST.fields_by_name['plugin_specification'].message_type = _PLUGINSPECIFICATION _SERVERINFORESPONSE.fields_by_name['compatibility'].message_type = _COMPATIBILITY _SERVERINFORESPONSE.fields_by_name['api_server'].message_type = _APISERVER _SERVERINFORESPONSE.fields_by_name['url_format'].message_type = _EXPERIMENTURLFORMAT _SERVERINFORESPONSE.fields_by_name['plugin_control'].message_type = _PLUGINCONTROL _SERVERINFORESPONSE.fields_by_name['upload_limits'].message_type = _UPLOADLIMITS _COMPATIBILITY.fields_by_name['verdict'].enum_type = _COMPATIBILITYVERDICT DESCRIPTOR.message_types_by_name['ServerInfoRequest'] = _SERVERINFOREQUEST DESCRIPTOR.message_types_by_name['ServerInfoResponse'] = _SERVERINFORESPONSE DESCRIPTOR.message_types_by_name['Compatibility'] = _COMPATIBILITY DESCRIPTOR.message_types_by_name['ApiServer'] = _APISERVER DESCRIPTOR.message_types_by_name['ExperimentUrlFormat'] = _EXPERIMENTURLFORMAT DESCRIPTOR.message_types_by_name['PluginSpecification'] = _PLUGINSPECIFICATION DESCRIPTOR.message_types_by_name['PluginControl'] = _PLUGINCONTROL DESCRIPTOR.message_types_by_name['UploadLimits'] = _UPLOADLIMITS DESCRIPTOR.enum_types_by_name['CompatibilityVerdict'] = _COMPATIBILITYVERDICT _sym_db.RegisterFileDescriptor(DESCRIPTOR) ServerInfoRequest = _reflection.GeneratedProtocolMessageType('ServerInfoRequest', (_message.Message,), { 'DESCRIPTOR' : _SERVERINFOREQUEST, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.ServerInfoRequest) }) _sym_db.RegisterMessage(ServerInfoRequest) ServerInfoResponse = _reflection.GeneratedProtocolMessageType('ServerInfoResponse', (_message.Message,), { 'DESCRIPTOR' : _SERVERINFORESPONSE, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.ServerInfoResponse) }) _sym_db.RegisterMessage(ServerInfoResponse) Compatibility = _reflection.GeneratedProtocolMessageType('Compatibility', (_message.Message,), { 'DESCRIPTOR' : _COMPATIBILITY, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.Compatibility) }) _sym_db.RegisterMessage(Compatibility) ApiServer = _reflection.GeneratedProtocolMessageType('ApiServer', (_message.Message,), { 'DESCRIPTOR' : _APISERVER, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.ApiServer) }) _sym_db.RegisterMessage(ApiServer) ExperimentUrlFormat = _reflection.GeneratedProtocolMessageType('ExperimentUrlFormat', (_message.Message,), { 'DESCRIPTOR' : _EXPERIMENTURLFORMAT, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.ExperimentUrlFormat) }) _sym_db.RegisterMessage(ExperimentUrlFormat) PluginSpecification = _reflection.GeneratedProtocolMessageType('PluginSpecification', (_message.Message,), { 'DESCRIPTOR' : _PLUGINSPECIFICATION, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.PluginSpecification) }) _sym_db.RegisterMessage(PluginSpecification) PluginControl = _reflection.GeneratedProtocolMessageType('PluginControl', (_message.Message,), { 'DESCRIPTOR' : _PLUGINCONTROL, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.PluginControl) }) _sym_db.RegisterMessage(PluginControl) UploadLimits = _reflection.GeneratedProtocolMessageType('UploadLimits', (_message.Message,), { 'DESCRIPTOR' : _UPLOADLIMITS, '__module__' : 'tensorboard.uploader.proto.server_info_pb2' # @@protoc_insertion_point(class_scope:tensorboard.service.UploadLimits) }) _sym_db.RegisterMessage(UploadLimits) # @@protoc_insertion_point(module_scope)
0
0
0
5dc6cd1f424f32bce276160e04c696e0871379df
971
py
Python
PycharmProjects/PythonExercicios/ex051.py
RodrigoMASRamos/Projects.py
ed15981b320914c9667305dcd5fb5b7906fd9b00
[ "MIT" ]
null
null
null
PycharmProjects/PythonExercicios/ex051.py
RodrigoMASRamos/Projects.py
ed15981b320914c9667305dcd5fb5b7906fd9b00
[ "MIT" ]
null
null
null
PycharmProjects/PythonExercicios/ex051.py
RodrigoMASRamos/Projects.py
ed15981b320914c9667305dcd5fb5b7906fd9b00
[ "MIT" ]
null
null
null
# Exercício Python #051 - Progressão Aritmética # # Desenvolva um programa que leia o PRIMEIRO TERMO e a RAZÃO de uma PA. No final, mostre os 10 primeiros termos dessa # progressão. # # OBS: Eu tentei realizar esse exercicio, fiz o codígo mas ele apresentou ERRO DE LÓGICA! Estude mais P.A e # esse conteudo! print('\033[0;35m-=-\033[m' * 10) print('\033[1;36mPROGRESSÃO ARITIMÉRICA (P.A)\033[m') print('\033[0;35m-=-\033[m' * 10) t1 = str(input('\033[0;30mDigite o PRIMEIRO TERMO da P.A: \033[m')).strip() r = str(input('\033[0;30mAgora, digite a RAZÃO da P.A: \033[m')).strip() t1 = int(str(t1)) r = int(str(r)) a10 = t1 + (10 - 1) * r # Fórmula da P.A ADAPTADA para a linguagem PYTHON print(' ' * 20) print('\033[1;30mAbaixo,seguem os 10 primeiros termos da Progressão Aritimética: \033[m') for p_a in range(t1 ,a10 + r, r): # Está escrito a10 + r porque o Python ignora o último termo. print(f'\033[0;34m{p_a}\033[m', end=' ') print('\n\033[1;31mFIM!\033[m')
38.84
117
0.677652
# Exercício Python #051 - Progressão Aritmética # # Desenvolva um programa que leia o PRIMEIRO TERMO e a RAZÃO de uma PA. No final, mostre os 10 primeiros termos dessa # progressão. # # OBS: Eu tentei realizar esse exercicio, fiz o codígo mas ele apresentou ERRO DE LÓGICA! Estude mais P.A e # esse conteudo! print('\033[0;35m-=-\033[m' * 10) print('\033[1;36mPROGRESSÃO ARITIMÉRICA (P.A)\033[m') print('\033[0;35m-=-\033[m' * 10) t1 = str(input('\033[0;30mDigite o PRIMEIRO TERMO da P.A: \033[m')).strip() r = str(input('\033[0;30mAgora, digite a RAZÃO da P.A: \033[m')).strip() t1 = int(str(t1)) r = int(str(r)) a10 = t1 + (10 - 1) * r # Fórmula da P.A ADAPTADA para a linguagem PYTHON print(' ' * 20) print('\033[1;30mAbaixo,seguem os 10 primeiros termos da Progressão Aritimética: \033[m') for p_a in range(t1 ,a10 + r, r): # Está escrito a10 + r porque o Python ignora o último termo. print(f'\033[0;34m{p_a}\033[m', end=' ') print('\n\033[1;31mFIM!\033[m')
0
0
0
d65cf02411616f4d20773f38a117a5e0f588a6fa
8,757
py
Python
app/main/lib/shared_models/audio_model.py
meedan/alegre
ad28736f53b8905882e196e90cac66d39db341a3
[ "MIT" ]
11
2018-02-07T00:16:54.000Z
2021-05-13T22:47:07.000Z
app/main/lib/shared_models/audio_model.py
meedan/alegre
ad28736f53b8905882e196e90cac66d39db341a3
[ "MIT" ]
47
2018-11-26T23:17:37.000Z
2022-03-25T16:12:05.000Z
app/main/lib/shared_models/audio_model.py
meedan/alegre
ad28736f53b8905882e196e90cac66d39db341a3
[ "MIT" ]
9
2019-05-23T22:06:03.000Z
2020-10-27T20:45:04.000Z
import json import binascii import uuid import os import tempfile import pathlib import urllib.error import urllib.request import shutil from flask import current_app as app from sqlalchemy.orm.attributes import flag_modified from sqlalchemy import text import tenacity import numpy as np from sqlalchemy.orm.exc import NoResultFound from app.main.lib.shared_models.shared_model import SharedModel from app.main import db from app.main.model.audio import Audio
40.730233
156
0.557383
import json import binascii import uuid import os import tempfile import pathlib import urllib.error import urllib.request import shutil from flask import current_app as app from sqlalchemy.orm.attributes import flag_modified from sqlalchemy import text import tenacity import numpy as np from sqlalchemy.orm.exc import NoResultFound from app.main.lib.shared_models.shared_model import SharedModel from app.main import db from app.main.model.audio import Audio def _after_log(retry_state): app.logger.debug("Retrying audio similarity...") class AudioModel(SharedModel): @tenacity.retry(wait=tenacity.wait_fixed(0.5), stop=tenacity.stop_after_delay(5), after=_after_log) def save(self, audio): saved_audio = None try: # First locate existing audio and append new context existing = db.session.query(Audio).filter(Audio.url==audio.url).one() if existing: if audio.hash_value and not existing.hash_value: existing.hash_value = audio.hash_value flag_modified(existing, 'hash_value') if audio.context not in existing.context: existing.context.append(audio.context) flag_modified(existing, 'context') saved_audio = existing except NoResultFound as e: # Otherwise, add new audio, but with context as an array if audio.context and not isinstance(audio.context, list): audio.context = [audio.context] db.session.add(audio) saved_audio = audio except Exception as e: db.session.rollback() raise e try: db.session.commit() return saved_audio except Exception as e: db.session.rollback() raise e def get_tempfile(self): return tempfile.NamedTemporaryFile() def execute_command(self, command): return os.popen(command).read() def load(self): self.directory = app.config['PERSISTENT_DISK_PATH'] self.ffmpeg_dir = "/usr/local/bin/ffmpeg" pathlib.Path(self.directory).mkdir(parents=True, exist_ok=True) def respond(self, task): if task["command"] == "delete": return self.delete(task) elif task["command"] == "add": return self.add(task) elif task["command"] == "search": return self.search(task) def delete(self, task): if 'doc_id' in task: audios = db.session.query(Audio).filter(Audio.doc_id==task.get("doc_id")).all() if audios: audio = audios[0] elif 'url' in task: audios = db.session.query(Audio).filter(Audio.url==task.get("url")).all() if audios: audio = audios[0] deleted = db.session.query(Audio).filter(Audio.id==audio.id).delete() return {"requested": task, "result": {"url": audio.url, "deleted": deleted}} def add(self, task): try: audio = Audio.from_url(task.get("url"), task.get("doc_id"), task.get("context", {})) audio = self.save(audio) return {"requested": task, "result": {"url": audio.url}, "success": True} except urllib.error.HTTPError: return {"requested": task, "result": {"url": audio.url}, "success": False} @tenacity.retry(wait=tenacity.wait_fixed(0.5), stop=tenacity.stop_after_delay(5), after=_after_log) def search_by_context(self, context): try: context_query, context_hash = self.get_context_query(context) if context_query: cmd = """ SELECT id, doc_id, url, hash_value, context FROM audios WHERE """+context_query else: cmd = """ SELECT id, doc_id, url, hash_value, context FROM audios """ matches = db.session.execute(text(cmd), context_hash).fetchall() keys = ('id', 'doc_id', 'url', 'hash_value', 'context') rows = [dict(zip(keys, values)) for values in matches] for row in rows: row["context"] = [c for c in row["context"] if self.context_matches(context, c)] return rows except Exception as e: db.session.rollback() raise e def context_matches(self, context, search_context): for k,v in context.items(): if search_context.get(k) != v: return False return True @tenacity.retry(wait=tenacity.wait_fixed(0.5), stop=tenacity.stop_after_delay(5), after=_after_log) def search_by_hash_value(self, chromaprint_fingerprint, threshold, context): try: context_query, context_hash = self.get_context_query(context) if context_query: cmd = """ SELECT audio_similarity_functions(); SELECT * FROM ( SELECT id, doc_id, chromaprint_fingerprint, url, context, get_audio_chromaprint_score(chromaprint_fingerprint, :chromaprint_fingerprint) AS score FROM audios ) f WHERE score >= :threshold AND """+context_query+""" ORDER BY score DESC """ else: cmd = """ SELECT audio_similarity_functions(); SELECT * FROM ( SELECT id, doc_id, chromaprint_fingerprint, url, context, get_audio_chromaprint_score(chromaprint_fingerprint, :chromaprint_fingerprint) AS score FROM audios ) f WHERE score >= :threshold ORDER BY score DESC """ matches = db.session.execute(text(cmd), dict(**{ 'chromaprint_fingerprint': chromaprint_fingerprint, 'threshold': threshold, }, **context_hash)).fetchall() keys = ('id', 'doc_id', 'chromaprint_fingerprint', 'url', 'context', 'score') rows = [] for values in matches: row = dict(zip(keys, values)) # row["score"] = get_score(row["chromaprint_fingerprint"], chromaprint_fingerprint, threshold) rows.append(row) return rows except Exception as e: db.session.rollback() raise e def search(self, task): context = {} audio = None temporary = False if task.get('context'): context = task.get('context') if task.get("match_across_content_types"): context.pop("content_type", None) if task.get('doc_id'): audios = db.session.query(Audio).filter(Audio.doc_id==task.get("doc_id")).all() if audios and not audio: audio = audios[0] elif task.get('url'): audios = db.session.query(Audio).filter(Audio.url==task.get("url")).all() if audios and not audio: audio = audios[0] if audio is None: temporary = True if not task.get("doc_id"): task["doc_id"] = str(uuid.uuid4()) self.add(task) audios = db.session.query(Audio).filter(Audio.doc_id==task.get("doc_id")).all() if audios and not audio: audio = audios[0] if audio: threshold = task.get('threshold', 1.0) matches = self.search_by_hash_value(audio.chromaprint_fingerprint, threshold, context) if temporary: self.delete(task) return {"result": matches} else: return {"error": "Audio not found for provided task", "task": task} def get_context_query(self, context): context_query = [] context_hash = {} for key, value in context.items(): if key != "project_media_id": if isinstance(value, list): context_clause = "(" for i,v in enumerate(value): context_clause += "context @> '[{\""+key+"\": "+json.dumps(value)+"}]'" if len(value)-1 != i: context_clause += " OR " context_hash[f"context_{key}_{i}"] = v context_clause += ")" context_query.append(context_clause) else: context_query.append("context @>'[{\""+key+"\": "+json.dumps(value)+"}]'") context_hash[f"context_{key}"] = value return str.join(" AND ", context_query), context_hash
7,601
644
46
95ba0fef43d174338ef023c953eae13b890ae3d8
4,353
py
Python
chronosphere/analysis/ublb.py
chzhong25346/Chronosphere
2db97939be3415ad508de6abe9ac79f3ee1d1eff
[ "Apache-2.0" ]
null
null
null
chronosphere/analysis/ublb.py
chzhong25346/Chronosphere
2db97939be3415ad508de6abe9ac79f3ee1d1eff
[ "Apache-2.0" ]
null
null
null
chronosphere/analysis/ublb.py
chzhong25346/Chronosphere
2db97939be3415ad508de6abe9ac79f3ee1d1eff
[ "Apache-2.0" ]
null
null
null
import logging import pandas as pd from datetime import timedelta from ..models import Index, Quote, Quote_CSI300, Ublb_cross, Rsi_predict_report from ..utils.utils import gen_id from stockstats import StockDataFrame logger = logging.getLogger('main.ublb') pd.set_option('mode.chained_assignment', None)
43.53
100
0.47875
import logging import pandas as pd from datetime import timedelta from ..models import Index, Quote, Quote_CSI300, Ublb_cross, Rsi_predict_report from ..utils.utils import gen_id from stockstats import StockDataFrame logger = logging.getLogger('main.ublb') pd.set_option('mode.chained_assignment', None) def ublb_cross_analysis(sdic): # Create UBLB Cross table s_l = sdic['learning'] Ublb_cross.__table__.create(s_l.get_bind(), checkfirst=True) for dbname, s in sdic.items(): if dbname in ('testing','tsxci','nasdaq100','sp100','csi300','eei'): logger.info("Start to process: %s" % dbname) # Get Rsi_predict_report rsi30_rpr = pd.read_sql(s_l.query(Rsi_predict_report). filter(Rsi_predict_report.index == dbname, Rsi_predict_report.target_rsi <=31).statement, s_l.bind) tickers = rsi30_rpr['symbol'].tolist() for ticker in tickers: if dbname == 'csi300': df = pd.read_sql(s.query(Quote_CSI300).\ filter(Quote_CSI300.symbol == ticker).\ statement, s.bind, index_col='date').sort_index() else: df = pd.read_sql(s.query(Quote).\ filter(Quote.symbol == ticker).\ statement, s.bind, index_col='date').sort_index() reached_date = rsi30_rpr.loc[rsi30_rpr['symbol'] == ticker]['reached_date'].iloc[-1] # Latest df = df[(df != 0).all(1)] df = df.sort_index(ascending=True).last('52w').drop(columns=['id']) df = df[-120:] latest_date = df.iloc[-1].name pre_date = df.iloc[-2].name # Bolling band diff stock = StockDataFrame.retype(df) boll_diff = round(stock['boll'].diff(),2) ub_diff = round(stock['boll_ub'].diff(),2) lb_diff = round(stock['boll_lb'].diff(),2) # Latest/Previous boll Diff info latest_boll = boll_diff[-1] latest_ub = ub_diff[-1] latest_lb = lb_diff[-1] pre_boll = boll_diff[-2] pre_ub = ub_diff[-2] pre_lb = lb_diff[-2] # Recent Rsi rsi_df = StockDataFrame.retype(df) rsi_df['rsi_14'] = rsi_df['rsi_14'] latest_rsi = rsi_df['rsi_14'].iloc[-1] try: # Define pattern ub < lb first time if ((latest_boll < 0 and pre_boll < 0 and latest_ub < 0 and latest_lb <0 and latest_ub < latest_boll and latest_ub < latest_lb and latest_lb > latest_boll and latest_lb > latest_ub) and pre_ub > pre_boll and pre_ub > pre_lb and pre_lb < pre_boll and pre_lb < pre_ub ): # Remove existing record s_l.query(Ublb_cross).filter(Ublb_cross.symbol == ticker, Ublb_cross.index == dbname).delete() s_l.commit() record = {'id': gen_id(ticker+dbname+str(reached_date)+str(latest_date)), 'date': latest_date, 'reached_date': reached_date, 'index': dbname, 'symbol': ticker, } s_l.add(Ublb_cross(**record)) s_l.commit() logger.info("Ublb Cross found - (%s, %s)" % (dbname, ticker)) # Remove record if rsi at 70+ elif latest_rsi >= 70: record = s_l.query(Ublb_cross).filter(Ublb_cross.symbol == ticker, Ublb_cross.index == dbname).first() if record: s_l.delete(record) s_l.commit() logger.info("Ublb Cross deleted - (%s, %s)" % (dbname, ticker)) except: pass
4,025
0
23
8837c89035b51cf7cab266a420e461edd6e2c565
90
py
Python
wagtailrelevancy/__init__.py
takeflight/wagtail-relevancy
3f4a9a57ccc19a8c829d67ee0088066b6c8bfc99
[ "BSD-3-Clause" ]
6
2016-01-11T03:34:51.000Z
2016-08-09T12:01:49.000Z
wagtailrelevancy/__init__.py
takeflight/wagtail-relevancy
3f4a9a57ccc19a8c829d67ee0088066b6c8bfc99
[ "BSD-3-Clause" ]
null
null
null
wagtailrelevancy/__init__.py
takeflight/wagtail-relevancy
3f4a9a57ccc19a8c829d67ee0088066b6c8bfc99
[ "BSD-3-Clause" ]
null
null
null
__version__ = '0.1.0' default_app_config = 'wagtailrelevancy.apps.WagtailRelevancyConfig'
30
67
0.822222
__version__ = '0.1.0' default_app_config = 'wagtailrelevancy.apps.WagtailRelevancyConfig'
0
0
0
d38d3934c21b6d276a3e00586b7ed8710fbe726f
7,815
py
Python
pysnmp/CISCO-BITS-CLOCK-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
11
2021-02-02T16:27:16.000Z
2021-08-31T06:22:49.000Z
pysnmp/CISCO-BITS-CLOCK-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
75
2021-02-24T17:30:31.000Z
2021-12-08T00:01:18.000Z
pysnmp/CISCO-BITS-CLOCK-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module CISCO-BITS-CLOCK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-BITS-CLOCK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:34:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") entPhysicalDescr, entPhysicalIndex = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalDescr", "entPhysicalIndex") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ModuleIdentity, Counter32, IpAddress, TimeTicks, NotificationType, Bits, Unsigned32, Gauge32, iso, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Integer32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Counter32", "IpAddress", "TimeTicks", "NotificationType", "Bits", "Unsigned32", "Gauge32", "iso", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Integer32", "Counter64") TimeStamp, TruthValue, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "TruthValue", "DisplayString", "TextualConvention") ciscoBitsClockMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 459)) ciscoBitsClockMIB.setRevisions(('2005-01-21 00:00',)) if mibBuilder.loadTexts: ciscoBitsClockMIB.setLastUpdated('200501210000Z') if mibBuilder.loadTexts: ciscoBitsClockMIB.setOrganization('Cisco Systems, Inc.') ciscoBitsClockMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 459, 0)) ciscoBitsClockMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 459, 1)) ciscoBitsClockMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 459, 2)) cBitsClkSourceTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1), ) if mibBuilder.loadTexts: cBitsClkSourceTable.setStatus('current') cBitsClkSourceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex")) if mibBuilder.loadTexts: cBitsClkSourceEntry.setStatus('current') cBitsClkSourceRoleAdmin = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("primary", 1), ("secondary", 2), ("tertiary", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cBitsClkSourceRoleAdmin.setStatus('current') cBitsClkSourceRoleCurrent = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("unavailable", 0), ("primary", 1), ("secondary", 2), ("tertiary", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cBitsClkSourceRoleCurrent.setStatus('current') cBitsClkSourceTimestamp = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 3), TimeStamp()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cBitsClkSourceTimestamp.setStatus('current') cBitsClkSourceActiveSeconds = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 4), Counter32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: cBitsClkSourceActiveSeconds.setStatus('current') cBitsClkSourceInactiveSeconds = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 5), Counter32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: cBitsClkSourceInactiveSeconds.setStatus('current') cBitsClkSourceDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 6), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: cBitsClkSourceDescription.setStatus('current') cBitsClkNotifEnabled = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cBitsClkNotifEnabled.setStatus('current') ciscoBitsClockSource = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 459, 0, 1)).setObjects(("ENTITY-MIB", "entPhysicalDescr"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceDescription"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceRoleAdmin"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceRoleCurrent")) if mibBuilder.loadTexts: ciscoBitsClockSource.setStatus('current') ciscoBitsClockFreerun = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 459, 0, 2)).setObjects(("ENTITY-MIB", "entPhysicalDescr")) if mibBuilder.loadTexts: ciscoBitsClockFreerun.setStatus('current') ciscoBitsClockHoldover = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 459, 0, 3)).setObjects(("ENTITY-MIB", "entPhysicalDescr")) if mibBuilder.loadTexts: ciscoBitsClockHoldover.setStatus('current') ciscoBitsClockMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 459, 2, 1)) ciscoBitsClockMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 459, 2, 2)) ciscoBitsClockMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 459, 2, 1, 1)).setObjects(("CISCO-BITS-CLOCK-MIB", "ciscoBitsClockSourceGroup"), ("CISCO-BITS-CLOCK-MIB", "ciscoBitsClockNotifGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoBitsClockMIBCompliance = ciscoBitsClockMIBCompliance.setStatus('current') ciscoBitsClockSourceGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 459, 2, 2, 1)).setObjects(("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceRoleAdmin"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceRoleCurrent"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceTimestamp"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceActiveSeconds"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceInactiveSeconds"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceDescription"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkNotifEnabled")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoBitsClockSourceGroup = ciscoBitsClockSourceGroup.setStatus('current') ciscoBitsClockNotifGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 459, 2, 2, 2)).setObjects(("CISCO-BITS-CLOCK-MIB", "ciscoBitsClockSource"), ("CISCO-BITS-CLOCK-MIB", "ciscoBitsClockFreerun"), ("CISCO-BITS-CLOCK-MIB", "ciscoBitsClockHoldover")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoBitsClockNotifGroup = ciscoBitsClockNotifGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-BITS-CLOCK-MIB", cBitsClkSourceRoleAdmin=cBitsClkSourceRoleAdmin, cBitsClkNotifEnabled=cBitsClkNotifEnabled, cBitsClkSourceRoleCurrent=cBitsClkSourceRoleCurrent, ciscoBitsClockFreerun=ciscoBitsClockFreerun, ciscoBitsClockNotifGroup=ciscoBitsClockNotifGroup, ciscoBitsClockMIBConform=ciscoBitsClockMIBConform, ciscoBitsClockSource=ciscoBitsClockSource, cBitsClkSourceInactiveSeconds=cBitsClkSourceInactiveSeconds, cBitsClkSourceTable=cBitsClkSourceTable, ciscoBitsClockSourceGroup=ciscoBitsClockSourceGroup, ciscoBitsClockMIBCompliances=ciscoBitsClockMIBCompliances, ciscoBitsClockMIB=ciscoBitsClockMIB, ciscoBitsClockMIBGroups=ciscoBitsClockMIBGroups, ciscoBitsClockMIBCompliance=ciscoBitsClockMIBCompliance, ciscoBitsClockHoldover=ciscoBitsClockHoldover, ciscoBitsClockMIBNotifs=ciscoBitsClockMIBNotifs, PYSNMP_MODULE_ID=ciscoBitsClockMIB, ciscoBitsClockMIBObjects=ciscoBitsClockMIBObjects, cBitsClkSourceEntry=cBitsClkSourceEntry, cBitsClkSourceDescription=cBitsClkSourceDescription, cBitsClkSourceActiveSeconds=cBitsClkSourceActiveSeconds, cBitsClkSourceTimestamp=cBitsClkSourceTimestamp)
128.114754
1,123
0.773512
# # PySNMP MIB module CISCO-BITS-CLOCK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-BITS-CLOCK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:34:03 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") entPhysicalDescr, entPhysicalIndex = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalDescr", "entPhysicalIndex") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ModuleIdentity, Counter32, IpAddress, TimeTicks, NotificationType, Bits, Unsigned32, Gauge32, iso, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Integer32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Counter32", "IpAddress", "TimeTicks", "NotificationType", "Bits", "Unsigned32", "Gauge32", "iso", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Integer32", "Counter64") TimeStamp, TruthValue, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "TruthValue", "DisplayString", "TextualConvention") ciscoBitsClockMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 459)) ciscoBitsClockMIB.setRevisions(('2005-01-21 00:00',)) if mibBuilder.loadTexts: ciscoBitsClockMIB.setLastUpdated('200501210000Z') if mibBuilder.loadTexts: ciscoBitsClockMIB.setOrganization('Cisco Systems, Inc.') ciscoBitsClockMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 459, 0)) ciscoBitsClockMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 459, 1)) ciscoBitsClockMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 459, 2)) cBitsClkSourceTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1), ) if mibBuilder.loadTexts: cBitsClkSourceTable.setStatus('current') cBitsClkSourceEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex")) if mibBuilder.loadTexts: cBitsClkSourceEntry.setStatus('current') cBitsClkSourceRoleAdmin = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("primary", 1), ("secondary", 2), ("tertiary", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cBitsClkSourceRoleAdmin.setStatus('current') cBitsClkSourceRoleCurrent = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("unavailable", 0), ("primary", 1), ("secondary", 2), ("tertiary", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cBitsClkSourceRoleCurrent.setStatus('current') cBitsClkSourceTimestamp = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 3), TimeStamp()).setMaxAccess("readwrite") if mibBuilder.loadTexts: cBitsClkSourceTimestamp.setStatus('current') cBitsClkSourceActiveSeconds = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 4), Counter32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: cBitsClkSourceActiveSeconds.setStatus('current') cBitsClkSourceInactiveSeconds = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 5), Counter32()).setUnits('seconds').setMaxAccess("readonly") if mibBuilder.loadTexts: cBitsClkSourceInactiveSeconds.setStatus('current') cBitsClkSourceDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 1, 1, 6), SnmpAdminString()).setMaxAccess("readonly") if mibBuilder.loadTexts: cBitsClkSourceDescription.setStatus('current') cBitsClkNotifEnabled = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 459, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cBitsClkNotifEnabled.setStatus('current') ciscoBitsClockSource = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 459, 0, 1)).setObjects(("ENTITY-MIB", "entPhysicalDescr"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceDescription"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceRoleAdmin"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceRoleCurrent")) if mibBuilder.loadTexts: ciscoBitsClockSource.setStatus('current') ciscoBitsClockFreerun = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 459, 0, 2)).setObjects(("ENTITY-MIB", "entPhysicalDescr")) if mibBuilder.loadTexts: ciscoBitsClockFreerun.setStatus('current') ciscoBitsClockHoldover = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 459, 0, 3)).setObjects(("ENTITY-MIB", "entPhysicalDescr")) if mibBuilder.loadTexts: ciscoBitsClockHoldover.setStatus('current') ciscoBitsClockMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 459, 2, 1)) ciscoBitsClockMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 459, 2, 2)) ciscoBitsClockMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 459, 2, 1, 1)).setObjects(("CISCO-BITS-CLOCK-MIB", "ciscoBitsClockSourceGroup"), ("CISCO-BITS-CLOCK-MIB", "ciscoBitsClockNotifGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoBitsClockMIBCompliance = ciscoBitsClockMIBCompliance.setStatus('current') ciscoBitsClockSourceGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 459, 2, 2, 1)).setObjects(("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceRoleAdmin"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceRoleCurrent"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceTimestamp"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceActiveSeconds"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceInactiveSeconds"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkSourceDescription"), ("CISCO-BITS-CLOCK-MIB", "cBitsClkNotifEnabled")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoBitsClockSourceGroup = ciscoBitsClockSourceGroup.setStatus('current') ciscoBitsClockNotifGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 459, 2, 2, 2)).setObjects(("CISCO-BITS-CLOCK-MIB", "ciscoBitsClockSource"), ("CISCO-BITS-CLOCK-MIB", "ciscoBitsClockFreerun"), ("CISCO-BITS-CLOCK-MIB", "ciscoBitsClockHoldover")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoBitsClockNotifGroup = ciscoBitsClockNotifGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-BITS-CLOCK-MIB", cBitsClkSourceRoleAdmin=cBitsClkSourceRoleAdmin, cBitsClkNotifEnabled=cBitsClkNotifEnabled, cBitsClkSourceRoleCurrent=cBitsClkSourceRoleCurrent, ciscoBitsClockFreerun=ciscoBitsClockFreerun, ciscoBitsClockNotifGroup=ciscoBitsClockNotifGroup, ciscoBitsClockMIBConform=ciscoBitsClockMIBConform, ciscoBitsClockSource=ciscoBitsClockSource, cBitsClkSourceInactiveSeconds=cBitsClkSourceInactiveSeconds, cBitsClkSourceTable=cBitsClkSourceTable, ciscoBitsClockSourceGroup=ciscoBitsClockSourceGroup, ciscoBitsClockMIBCompliances=ciscoBitsClockMIBCompliances, ciscoBitsClockMIB=ciscoBitsClockMIB, ciscoBitsClockMIBGroups=ciscoBitsClockMIBGroups, ciscoBitsClockMIBCompliance=ciscoBitsClockMIBCompliance, ciscoBitsClockHoldover=ciscoBitsClockHoldover, ciscoBitsClockMIBNotifs=ciscoBitsClockMIBNotifs, PYSNMP_MODULE_ID=ciscoBitsClockMIB, ciscoBitsClockMIBObjects=ciscoBitsClockMIBObjects, cBitsClkSourceEntry=cBitsClkSourceEntry, cBitsClkSourceDescription=cBitsClkSourceDescription, cBitsClkSourceActiveSeconds=cBitsClkSourceActiveSeconds, cBitsClkSourceTimestamp=cBitsClkSourceTimestamp)
0
0
0
d49f1553d9a98b1b441ec08f4d61a010fb516748
582
py
Python
bin/mining/sendTeamsMiningNoLootPoints.py
jgc128/crabada.py
cb50c9d4748786a6abedc822f2e1ee461d65e508
[ "MIT" ]
null
null
null
bin/mining/sendTeamsMiningNoLootPoints.py
jgc128/crabada.py
cb50c9d4748786a6abedc822f2e1ee461d65e508
[ "MIT" ]
null
null
null
bin/mining/sendTeamsMiningNoLootPoints.py
jgc128/crabada.py
cb50c9d4748786a6abedc822f2e1ee461d65e508
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 """ Crabada script to send mining all available teams for the given user. Usage: python3 -m bin.mining.sendTeamsMining <userAddress> Author: @coccoinomane (Twitter) """ from src.bot.mining.sendTeamsMining import sendTeamsMining from src.helpers.general import secondOrNone from src.models.User import User from src.common.logger import logger from sys import argv, exit userAddress = secondOrNone(argv) if not userAddress: logger.error("Specify a user address") exit(1) nSent = sendTeamsMining(User(userAddress), loot_point_filter=True)
22.384615
66
0.773196
#!/usr/bin/env python3 """ Crabada script to send mining all available teams for the given user. Usage: python3 -m bin.mining.sendTeamsMining <userAddress> Author: @coccoinomane (Twitter) """ from src.bot.mining.sendTeamsMining import sendTeamsMining from src.helpers.general import secondOrNone from src.models.User import User from src.common.logger import logger from sys import argv, exit userAddress = secondOrNone(argv) if not userAddress: logger.error("Specify a user address") exit(1) nSent = sendTeamsMining(User(userAddress), loot_point_filter=True)
0
0
0
698ec42b59e7d538b3fb96fafeb9adbd0798c637
35
py
Python
scratchpad/torch/back/__init__.py
danlkv/pywebviz
5892ef90f28dbd43c33fefbfa5a199d15322a120
[ "MIT" ]
null
null
null
scratchpad/torch/back/__init__.py
danlkv/pywebviz
5892ef90f28dbd43c33fefbfa5a199d15322a120
[ "MIT" ]
3
2019-11-24T21:03:39.000Z
2019-12-08T04:58:07.000Z
scratchpad/torch/back/__init__.py
DaniloZZZ/pywebviz
5892ef90f28dbd43c33fefbfa5a199d15322a120
[ "MIT" ]
null
null
null
from . import model as torchTensor
17.5
34
0.8
from . import model as torchTensor
0
0
0
a11b678a4820dfd9056a9ce6b6e9288239599809
1,238
py
Python
migrations/versions/e88bc62b6e4_event_tweaks.py
havanhuy1997/pmg-cms-2
21571235cf3d9552013bca29ab9af288b08e00d6
[ "Apache-2.0" ]
2
2019-06-11T20:46:43.000Z
2020-08-27T22:50:32.000Z
migrations/versions/e88bc62b6e4_event_tweaks.py
havanhuy1997/pmg-cms-2
21571235cf3d9552013bca29ab9af288b08e00d6
[ "Apache-2.0" ]
70
2017-05-26T14:04:06.000Z
2021-06-30T10:21:58.000Z
migrations/versions/e88bc62b6e4_event_tweaks.py
havanhuy1997/pmg-cms-2
21571235cf3d9552013bca29ab9af288b08e00d6
[ "Apache-2.0" ]
4
2017-08-29T10:09:30.000Z
2021-05-25T11:29:03.000Z
"""event_tweaks Revision ID: e88bc62b6e4 Revises: 4d3c2b4ceacb Create Date: 2015-03-17 14:04:09.394924 """ # revision identifiers, used by Alembic. revision = 'e88bc62b6e4' down_revision = '4d3c2b4ceacb' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql
30.195122
148
0.661551
"""event_tweaks Revision ID: e88bc62b6e4 Revises: 4d3c2b4ceacb Create Date: 2015-03-17 14:04:09.394924 """ # revision identifiers, used by Alembic. revision = 'e88bc62b6e4' down_revision = '4d3c2b4ceacb' branch_labels = None depends_on = None from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.alter_column('event_files', 'event_id', existing_type=sa.INTEGER(), nullable=False) op.alter_column('event_files', 'file_id', existing_type=sa.INTEGER(), nullable=False) op.drop_column('event_files', u'type') ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('event_files', sa.Column(u'type', postgresql.ENUM(u'related', name=u'event_file_type_enum'), autoincrement=False, nullable=False)) op.alter_column('event_files', 'file_id', existing_type=sa.INTEGER(), nullable=True) op.alter_column('event_files', 'event_id', existing_type=sa.INTEGER(), nullable=True) ### end Alembic commands ###
854
0
46
4a0e5d2b3f07b2545c2c72811134dafe9c142f43
1,363
py
Python
tests/test_json.py
ysegorov/jukoro
8be1d01b471c6091056df77ffacaee5cc8c470d0
[ "MIT" ]
null
null
null
tests/test_json.py
ysegorov/jukoro
8be1d01b471c6091056df77ffacaee5cc8c470d0
[ "MIT" ]
null
null
null
tests/test_json.py
ysegorov/jukoro
8be1d01b471c6091056df77ffacaee5cc8c470d0
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- import datetime import decimal from unittest import TestCase from jukoro import arrow from jukoro import json from jukoro import pg A = arrow.JuArrow D = decimal.Decimal
23.912281
63
0.517241
# -*- coding: utf-8 -*- import datetime import decimal from unittest import TestCase from jukoro import arrow from jukoro import json from jukoro import pg A = arrow.JuArrow D = decimal.Decimal class TestJson(TestCase): def test_arrow(self): utcnow = arrow.utcnow() now = arrow.now() a = { 'a': utcnow, 'b': now, } jsoned = json.dumps(a) b = json.loads(jsoned) self.assertEqual(utcnow, arrow.get(b['a'])) self.assertEqual(utcnow.to('local'), arrow.get(b['a'])) self.assertEqual(now, arrow.get(b['b'])) self.assertEqual(now.to('UTC'), arrow.get(b['b'])) def test_dict(self): now = datetime.datetime.now() utcnow = datetime.datetime.utcnow() a = { 'a': 12, 'b': D('1.2'), 'c': now, 'd': utcnow, } jsoned = json.dumps(a) b = json.loads(jsoned) self.assertEqual(a['a'], b['a']) self.assertIsInstance(b['b'], D) self.assertEqual(a['b'], b['b']) self.assertEqual(a['c'].isoformat(), b['c']) self.assertEqual(a['d'].isoformat(), b['d']) def test_pg(self): c = { 'e': pg.AbstractUser(123) } d = json.loads(json.dumps(c)) self.assertEqual(c['e'].entity_id, d['e'])
1,056
4
104
34d4876a4f197f9fddc9c4a61d9f7fd1c36bdc9e
106
py
Python
cdparacord/appinfo.py
fennekki/cdparacord
483682bd476631202ae135b296425bc340f57173
[ "BSD-2-Clause" ]
1
2016-12-07T08:38:53.000Z
2016-12-07T08:38:53.000Z
cdparacord/appinfo.py
fennekki/cdparacord
483682bd476631202ae135b296425bc340f57173
[ "BSD-2-Clause" ]
49
2018-02-24T15:30:35.000Z
2021-03-25T21:35:40.000Z
cdparacord/appinfo.py
fennekki/cdparacord
483682bd476631202ae135b296425bc340f57173
[ "BSD-2-Clause" ]
null
null
null
"""Information about the app.""" __version__ = '0.5.0' __url__ = 'https://github.com/fennekki/cdparacord'
26.5
50
0.707547
"""Information about the app.""" __version__ = '0.5.0' __url__ = 'https://github.com/fennekki/cdparacord'
0
0
0
5b653ff48646d4879717136503610ccb87ccf792
1,289
py
Python
download_mem.py
KenArck/WebRCP
d3feec9773c8958651f4b050c8aebc3fca4fa2f0
[ "MIT" ]
null
null
null
download_mem.py
KenArck/WebRCP
d3feec9773c8958651f4b050c8aebc3fca4fa2f0
[ "MIT" ]
null
null
null
download_mem.py
KenArck/WebRCP
d3feec9773c8958651f4b050c8aebc3fca4fa2f0
[ "MIT" ]
null
null
null
#!/usr/bin/python import serial, time, sys, fileinput #open and configure serial port ser = serial.Serial( port='/dev/ttyUSB0', baudrate=19200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout = .1 ) #first, clear out 210 buffer count = 0 while (count < 3): count +=1 ser.write("\r".encode()) time.sleep(.1) #open file for download file = open("download.mem", "w+") #send command to rc210 to start download ser.write("1SendEram\r\n".encode()) indata ="" Counter = 0 progresscounter = 0 var = 1 while var == 1: inser = str(ser.readline()) indata = inser.strip print (indata) if indata == "Complete": #check for first character of "Complete" and exit loop break Counter = Counter + 1 else: Counter = 0 ser.write("\r".encode()) file.write(indata) #LineCount -= 1 progresscounter += 1 progress = progresscounter / 44 if( progress > 100 ) : progress = 100 ser.write("OK\r\n".encode()) #print( '\rDownloading: %s (%d%%)' % ("|"*(progress/2), progress)), sys.stdout.flush() if Counter > 10 : file.close() sys.exit("RC210 did not respond. Exiting") print ("\nDownload Complete") file.close() #now for RTC sys.exit()
17.186667
81
0.626067
#!/usr/bin/python import serial, time, sys, fileinput #open and configure serial port ser = serial.Serial( port='/dev/ttyUSB0', baudrate=19200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout = .1 ) #first, clear out 210 buffer count = 0 while (count < 3): count +=1 ser.write("\r".encode()) time.sleep(.1) #open file for download file = open("download.mem", "w+") #send command to rc210 to start download ser.write("1SendEram\r\n".encode()) indata ="" Counter = 0 progresscounter = 0 var = 1 while var == 1: inser = str(ser.readline()) indata = inser.strip print (indata) if indata == "Complete": #check for first character of "Complete" and exit loop break Counter = Counter + 1 else: Counter = 0 ser.write("\r".encode()) file.write(indata) #LineCount -= 1 progresscounter += 1 progress = progresscounter / 44 if( progress > 100 ) : progress = 100 ser.write("OK\r\n".encode()) #print( '\rDownloading: %s (%d%%)' % ("|"*(progress/2), progress)), sys.stdout.flush() if Counter > 10 : file.close() sys.exit("RC210 did not respond. Exiting") print ("\nDownload Complete") file.close() #now for RTC sys.exit()
0
0
0
4adb0538bbe460de80c2fc2a9268111004a5b82a
144
py
Python
level-6/task-1/task-1-8-1.py
avedensky/python-rush-tasks
61410816dbb55cce3b518f8d76799c01cdec2aa9
[ "MIT" ]
14
2019-06-13T09:55:25.000Z
2022-03-19T15:12:36.000Z
level-6/task-1/task-1-8-1.py
avedensky/python-rush-tasks
61410816dbb55cce3b518f8d76799c01cdec2aa9
[ "MIT" ]
1
2021-09-26T16:00:51.000Z
2021-09-26T16:00:51.000Z
level-6/task-1/task-1-8-1.py
avedensky/python-rush-tasks
61410816dbb55cce3b518f8d76799c01cdec2aa9
[ "MIT" ]
4
2020-12-12T16:50:31.000Z
2022-02-08T12:16:11.000Z
#!/usr/bin/env python3 #coding: utf-8 """ pythonic way """ lst = ['aaabb', 'caca', 'dabc', 'acc', 'abbb'] res = ','.join(lst[1:-1]) print(res)
14.4
46
0.555556
#!/usr/bin/env python3 #coding: utf-8 """ pythonic way """ lst = ['aaabb', 'caca', 'dabc', 'acc', 'abbb'] res = ','.join(lst[1:-1]) print(res)
0
0
0
d89b298120322bb3f2d818e4e9f698ec1a06bc1c
655
py
Python
src/neophile/dependency/pre_commit.py
lsst-sqre/neophile
0923bd5b58851af13c09f73a05b1a2882434b437
[ "MIT" ]
null
null
null
src/neophile/dependency/pre_commit.py
lsst-sqre/neophile
0923bd5b58851af13c09f73a05b1a2882434b437
[ "MIT" ]
23
2020-07-17T23:27:44.000Z
2022-03-21T19:39:19.000Z
src/neophile/dependency/pre_commit.py
lsst-sqre/neophile
0923bd5b58851af13c09f73a05b1a2882434b437
[ "MIT" ]
null
null
null
"""A pre-commit hook dependency.""" from __future__ import annotations from dataclasses import dataclass from neophile.dependency.base import Dependency __all__ = ["PreCommitDependency"] @dataclass(frozen=True, order=True) class PreCommitDependency(Dependency): """Represents a single pre-commit dependency.""" repository: str """The URL of the GitHub repository providing this pre-commit hook.""" owner: str """The GitHub repository owner of the pre-commit hook.""" repo: str """The GitHub repository name of the pre-commit hook.""" version: str """The version of the dependency (may be a match pattern)."""
24.259259
74
0.714504
"""A pre-commit hook dependency.""" from __future__ import annotations from dataclasses import dataclass from neophile.dependency.base import Dependency __all__ = ["PreCommitDependency"] @dataclass(frozen=True, order=True) class PreCommitDependency(Dependency): """Represents a single pre-commit dependency.""" repository: str """The URL of the GitHub repository providing this pre-commit hook.""" owner: str """The GitHub repository owner of the pre-commit hook.""" repo: str """The GitHub repository name of the pre-commit hook.""" version: str """The version of the dependency (may be a match pattern)."""
0
0
0
1ccaa327ed60e19d773d59ccf22806c30fd7ccaf
16,952
py
Python
iot/nat64-dpkt.py
eric-erki/ai-smarthome
ca7316ebe72b0ad26f0b59e3186426633807cac8
[ "BSD-2-Clause" ]
28
2018-08-09T13:10:34.000Z
2022-01-07T13:39:31.000Z
iot/nat64-dpkt.py
eric-erki/ai-smarthome
ca7316ebe72b0ad26f0b59e3186426633807cac8
[ "BSD-2-Clause" ]
4
2018-08-09T13:18:12.000Z
2021-04-06T19:04:54.000Z
iot/nat64-dpkt.py
eric-erki/ai-smarthome
ca7316ebe72b0ad26f0b59e3186426633807cac8
[ "BSD-2-Clause" ]
15
2018-12-17T09:17:28.000Z
2021-03-02T11:25:05.000Z
#!/bin/python3 # # Copyright (c) 2019 Joakim Eriksson # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # # Experimental NAT64 and DNS64 using tun-interface (for the NAT64 IPv6 interface and the # regular sockets as the TCP/UDP interface. # import ipaddress, os, select, time import socket, logging, struct import dpkt # TCP State machine TCP_INIT = 1 # Same as LISTEN... more or less... TCP_SYN_RECEIVED = 2 TCP_SYN_SENT = 3 TCP_ESTABLISHED = 4 TCP_FIN_WAIT = 5 TCP_FIN_CLOSE_WAIT = 6 TYPE_HANDSHAKE_MAC_GET = 1 TYPE_HANDSHAKE_MAC_SET = 2 TYPE_RAW_IPV6 = 6 # Protocol numbers PROTO_UDP = 17 PROTO_TCP = 6 PROTO_ICMP = 58 PROTOS = {PROTO_UDP: "udp", PROTO_TCP: "tcp", PROTO_ICMP: "icmp"} MAC = b'\xca\xba\x88\x88\x00\xaa\xbb\x01' macaddr = 1 sockmap = {} adrmap = {} input = [] tuntcp = [] tun = None tunconnection = None prefix = ipaddress.ip_address("64:ff9b::0").packed log = logging.getLogger('nat64') log.setLevel(logging.DEBUG) # create log formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) log.addHandler(ch) # Remove the state for this specific socket # Tun is reception from local machine - not from native or NBR. # TunTcp from NBR or native platform. # Only for OS-X for now. # Should be easy to adapt for linux also. tun = os.open("/dev/tun12", os.O_RDWR) os.system("ifconfig tun12 inet6 64:ff9b::1/96 up") os.system("sysctl -w net.inet.ip.forwarding=1"); input = [tun] tunconnection = None tunsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 8888) tunsock.bind(server_address) tunsock.listen(1) log.info("Accepting tunctp connections over TCP on 8888.") input = input + [tunsock] try: while 1: inputready,outputready,exceptready = select.select(input,[],input) for r in inputready: if r == tun: packet = os.read(tun, 4000) recv_from_tun(packet) # Something from the tuntcp connections. elif r in tuntcp: data = r.recv(4000) if not data: log.debug(">> TUNTCP Socket shutdown - removing socket!") input.remove(r) tuntcp.remove(r) else: recv_from_tuntcp(r, data) # Something on the accept socket!? elif r == tunsock: tunconnection, client_address = tunsock.accept() log.debug("Connection from: %s", client_address) input = input + [tunconnection] tuntcp = tuntcp + [tunconnection] # Otherwise it is on a NAT64:ed socket else: st = sockmap[r] # Receive will receive and send back over tun. data = st.receive() if not data: log.debug(">> Socket shutdown - remove socket?!") for r in exceptready: print(r) except KeyboardInterrupt: log.error("Stopped by user.")
36.852174
108
0.568487
#!/bin/python3 # # Copyright (c) 2019 Joakim Eriksson # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # # # Experimental NAT64 and DNS64 using tun-interface (for the NAT64 IPv6 interface and the # regular sockets as the TCP/UDP interface. # import ipaddress, os, select, time import socket, logging, struct import dpkt # TCP State machine TCP_INIT = 1 # Same as LISTEN... more or less... TCP_SYN_RECEIVED = 2 TCP_SYN_SENT = 3 TCP_ESTABLISHED = 4 TCP_FIN_WAIT = 5 TCP_FIN_CLOSE_WAIT = 6 TYPE_HANDSHAKE_MAC_GET = 1 TYPE_HANDSHAKE_MAC_SET = 2 TYPE_RAW_IPV6 = 6 # Protocol numbers PROTO_UDP = 17 PROTO_TCP = 6 PROTO_ICMP = 58 PROTOS = {PROTO_UDP: "udp", PROTO_TCP: "tcp", PROTO_ICMP: "icmp"} MAC = b'\xca\xba\x88\x88\x00\xaa\xbb\x01' macaddr = 1 sockmap = {} adrmap = {} input = [] tuntcp = [] tun = None tunconnection = None prefix = ipaddress.ip_address("64:ff9b::0").packed log = logging.getLogger('nat64') log.setLevel(logging.DEBUG) # create log formatter and add it to the handlers formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) log.addHandler(ch) def genkey(proto, src, dest, sport, dport): return "%s:%s:%s-%s:%s"%(PROTOS[proto], src, sport, dest, dport) def get_next_mac(): global MAC, macaddr MAC = MAC[:-1] + bytes([macaddr]) macaddr = macaddr + 1 return MAC def add_socket(socket): global input if socket is not None and socket not in input: input = input + [socket] class NAT64State: def __init__(self, src, dst, sport, dport, proto): self.dst = dst self.src = src self.sport = sport self.dport = dport self.proto = proto self.maxreceive = 1200 self.key = genkey(proto, src, dst, sport, dport) class UDP64State(NAT64State): udp_port = 15000 def __init__(self, src, dst, sport, dport): super(TCP64State, self).__init__(src, dst, sport, dport, PROTO_UDP) ip4dst = ipaddress.ip_address(ipaddress.ip_address(dst).packed[-4:]) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("0.0.0.0", UDP64State.udp_port)) sock.settimeout(1.0) sock.connect((str(ip4dst), dport)) self.sock = sock UDP64State.udp_port = UDP64State.udp_port + 1 def udpip(self, data = None): udp = dpkt.udp.UDP() udp.dst = self.src udp.src = self.dst ip = dpkt.ip6.IP6() ip.src = self.dst ip.dst = self.src ip.hlim = 64 ip.nxt = PROTO_UDP if data is not None: udp.data = data ip.data = udp ip.plen = ip.data.ulen = len(ip.data) return ip def receive(self): log.debug("UDP: socket receive:", self) data, addr = self.sock.recvfrom(self.maxreceive) if not data: sock_remove(self.sock) return None ipv6 = self.udpip(data) # ipv6 = IPv6(IPv6(src = self.dst, dst = self.src)/UDP(sport=self.dport, dport=self.sport)/raw(data)) send_to_tun(ipv6) return data class TCP64State(NAT64State): sock: None tcp_port = 15000 def __init__(self, src, dst, sport, dport): super(TCP64State, self).__init__(src, dst, sport, dport, PROTO_TCP) ip4dst = ipaddress.ip_address(ipaddress.ip_address(dst).packed[-4:]) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(("0.0.0.0", TCP64State.tcp_port)) sock.settimeout(1.0) sock.connect((str(ip4dst), dport)) self.sock = sock self.state = TCP_INIT self.ack = 0 self.seq = 4711 self.window = 1200 self.mss = 1200 log.debug("TCP opening ", ip4dst, dport, sock) TCP64State.tcp_port = TCP64State.tcp_port + 1 # TCP packets are more or less always for sending back over tun. def tcp(self, flags): rep = dpkt.tcp.TCP() rep.win = 8192 rep.dport, rep.sport = self.sport, self.dport rep.flags = flags rep.seq = self.seq rep.ack = self.ack return rep def tcp_reply(self, ip, flags): # create a reply. ip.dst, ip.src = ip.src, ip.dst ip.data = self.tcp(flags) ip.plen = ip.data.ulen = len(ip.data) def tcpip(self, flags, data = None): tcp = self.tcp(flags) ip = dpkt.ip6.IP6() ip.src = self.dst ip.dst = self.src ip.hlim = 64 ip.nxt = PROTO_TCP if data is not None: tcp.data = data ip.data = tcp ip.plen = ip.data.ulen = len(ip.data) return ip # Handle TCP state - forward data from socket to tun. def update_tcp_state_totun(self, data): ip6 = self.tcpip(dpkt.tcp.TH_ACK | dpkt.tcp.TH_PUSH, data) print("IP6 :", bytes(ip6)) print("IP6: ", repr(ip6)) return ip6 # receive packet and send to tun. def receive(self): global input if self.sock is None: return None print("MSS:", self.mss) log.debug("TCP socket receive.") maxread = max(self.maxreceive, self.mss) data, addr = self.sock.recvfrom(maxread) input.remove(self.sock) if not data: log.debug("Socket closing... TCP state kept to handle TUN close.") self.sock.close() self.sock = None log.debug("TCP: FIN over socket received - sending FIN over tun.") ip6 = self.tcpip(dpkt.tcp.TH_FIN) print("FIN IP6 :", bytes(ip6)) print("FIN IP6:", repr(ip6)) self.last_to_tun = ip6 send_to_tun(bytes(ip6)) return None log.debug("NAT64 TCP to tun max: %d" % maxread) ipv6 = self.update_tcp_state_totun(data) self.last_to_tun = ipv6 send_to_tun(bytes(ipv6)) return data # Handle TCP state - TCP from ipv6 tun toward IPv4 socket def handle_tcp_state_tosock(self, ip): tcp = ip.data global tun, input log.debug("=== NAT64 TCP sock-send: %d %s."%(tcp.flags, self.sock)) if self.sock is None: log.warning("Socket already closed.") return if tcp.flags & dpkt.tcp.TH_SYN > 0: # Use Window size to control max segment? self.sock.setsockopt(socket.SOL_TCP, socket.TCP_MAXSEG, 1000) log.debug("Maxseg: %d" % self.sock.getsockopt(socket.SOL_TCP, socket.TCP_MAXSEG)) self.ack = tcp.seq + 1 # We are established... self.state = TCP_ESTABLISHED self.window = tcp.win # Get the MSS of the options opts = dpkt.tcp.parse_opts(tcp.opts) for k, v in opts: if k == dpkt.tcp.TCP_OPT_MSS: print("MSS:", v) self.mss, = struct.unpack("!H", v) print("MSS:", self.mss) log.debug("TCP State: %d SYN received." % self.mss) self.tcp_reply(ip, dpkt.tcp.TH_SYN | dpkt.tcp.TH_ACK) print("IP:", repr(ip)) send_to_tun(bytes(ip)) # sock.send(ip.load) elif tcp.flags & dpkt.tcp.TH_FIN: self.state = TCP_FIN_CLOSE_WAIT self.ack = tcp.seq + 1 self.timeout = time.time() log.debug("TCP: FIN received - sending FIN. %s" % self) self.tcp_reply(ip, dpkt.tcp.TH_FIN | dpkt.tcp.TH_ACK) print("IP:", repr(ip)) send_to_tun(bytes(ip)) # Clean out this socket? elif tcp.flags & dpkt.tcp.TH_ACK: if self.state == TCP_ESTABLISHED: if len(tcp.data) == 0: log.debug("ESTABLISHED or ACK from other side. seq: %d ack: %d" % (tcp.seq, tcp.ack)) self.seq = tcp.ack else: # ACK immediately - we assume that we get data from other side soon... log.debug("TCP: received %d seq: %d ack%d ." % (len(tcp.data), tcp.seq, tcp.ack)) self.ack = tcp.seq + len(tcp.data) # We should also handle the sanity checks for the ACK self.seq = tcp.ack self.tcp_reply(ip, dpkt.tcp.TH_ACK) print("IP:", repr(ip)) send_to_tun(bytes(ip)) add_socket(self.sock) if len(tcp.data) > 0: self.sock.send(tcp.data) # Remove the state for this specific socket def sock_remove(socket): todel = None sockmap.pop(socket) for k in adrmap: if adrmap[k] == socket: todel = k adrmap.pop(todel) if socket in input: input.remove(socket) socket.close() def send_to_tuntcp(socket, ipv6): if len(tuntcp) > 0: data = bytes(ipv6) data = struct.pack("!HH", len(data) + 4, TYPE_RAW_IPV6) + data for tunconn in tuntcp: if tunconn != socket: tunconn.send(data) def send_to_tun(ipv6): if ipv6 is not None: data = bytes(ipv6) if tun is not None: os.write(tun, data) if len(tuntcp) > 0: send_to_tuntcp(None, ipv6) def nat64_send(ip6, packet): global input, udp_port, tcp_port # NAT64 translation if ip6.dst[0:4] == prefix[0:4]: ip4dst = ipaddress.ip_address(ip6.dst[-4:]) log.debug("NAT64 dst: %s %d." % (ip4dst, ip6.nxt)) if ip6.nxt == PROTO_UDP: udp = ip6.data key = genkey(ip6.nxt, ip6.src, ip4dst, udp.sport, udp.dport) if udp.dport == 53: dns = dpkt.dns.DNS(udp.data) print("*** DNS ***", dns.opcode, dns.qd) if dns.opcode == 0 and len(dns.qd) > 0: name = dns.qd[0].name log.debug("DNS name - lookup: %s" % name) addr = socket.gethostbyname(name) dns64addr = ipaddress.ip_address(prefix[0:16-4] + ipaddress.ip_address(addr).packed) log.debug("%s => %s %s" % (name , addr, str(dns64addr))) ipaddr = dns64addr dns.op = 0 dns.qr = 1 dns.rd = 1 dns.rcode = dpkt.dns.DNS_RCODE_NOERR arr = dpkt.dns.DNS.RR() arr.cls = dpkt.dns.DNS_IN arr.type = dpkt.dns.DNS_AAAA arr.name = name arr.ttl = 3600 arr.ip6 = dns64addr.packed dns.qd = [] dns.an.append(arr) udp.sport, udp.dport = udp.dport, udp.sport udp.sum = 0 ip6.dst, ip6.src = ip6.src,ip6.dst udp.data = dns udp.ulen = len(udp) print("UDP - udplen:", len(udp), udp) ip6.data = udp ip6.plen = len(udp) print("IP6 - iplen:", len(ip6), ip6) resp = ip6 print("*** DNS Resp:", resp) log.debug(repr(resp)) send_to_tun(resp) return 0 if key not in adrmap: udpd = UDP64State(ip6.src, ip6.dst, udp.sport, udp.dport) adrmap[key] = udpd.sock sockmap[udpd.sock] = udpd log.debug("Opened sock: %s" % udpd.sock) add_socket(udpd.sock) sock = udpd.sock else: sock = adrmap[key] # sock.send(bytes(ip[UDP])) print("Sending UDP:", udp.data) sock.send(udp.data) elif ip6.nxt == PROTO_TCP: tcp = ip6.data key = genkey(ip6.nxt, ip6.src, ip4dst, tcp.sport, tcp.dport) if key not in adrmap: tcpd = TCP64State(ip6.src, ip6.dst, tcp.sport, tcp.dport) adrmap[key] = tcpd.sock sockmap[tcpd.sock] = tcpd add_socket(tcpd.sock) sock = tcpd.sock else: sock = adrmap[key] tcpd = sockmap[sock] tcpd.handle_tcp_state_tosock(ip6) # Tun is reception from local machine - not from native or NBR. def recv_from_tun(packet): ip6 = dpkt.ip6.IP6() ip6.unpack(packet) print("DPKT IPv6: SRC:", ip6.src, ip6.dst, " NH:", ip6.nxt, " data:", ip6.data) if ip6.nxt == PROTO_UDP or ip6.nxt == PROTO_TCP: log.debug(">> RECV from TUN: ") # do nat64 and send nat64_send(ip6, packet) # TunTcp from NBR or native platform. def recv_from_tuntcp(socket, packet): plen, type = struct.unpack("!HH", packet[0:4]) log.debug("Len: %d Type %d" % (plen, type)) # Assume that we got the whole packet... # In the future we should check - and wait for more if not complete. if type == TYPE_HANDSHAKE_MAC_GET: data = struct.pack("!HH", 8 + 4, TYPE_HANDSHAKE_MAC_SET) + get_next_mac() socket.send(data) elif type == TYPE_RAW_IPV6: ip = dpkt.ip6.IP6(packet[4:]) # Not matching prefix... Send to all tuntcp except "socket" to get things out to other nodes. if ip.dst[0:4] != prefix[0:4]: log.debug("Not matching prefix - send back to all. %d" % len(tuntcp)) print("IP:", repr(ip)) send_to_tuntcp(socket, packet[4:]) else: recv_from_tun(packet[4:]) # Only for OS-X for now. # Should be easy to adapt for linux also. tun = os.open("/dev/tun12", os.O_RDWR) os.system("ifconfig tun12 inet6 64:ff9b::1/96 up") os.system("sysctl -w net.inet.ip.forwarding=1"); input = [tun] tunconnection = None tunsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('localhost', 8888) tunsock.bind(server_address) tunsock.listen(1) log.info("Accepting tunctp connections over TCP on 8888.") input = input + [tunsock] try: while 1: inputready,outputready,exceptready = select.select(input,[],input) for r in inputready: if r == tun: packet = os.read(tun, 4000) recv_from_tun(packet) # Something from the tuntcp connections. elif r in tuntcp: data = r.recv(4000) if not data: log.debug(">> TUNTCP Socket shutdown - removing socket!") input.remove(r) tuntcp.remove(r) else: recv_from_tuntcp(r, data) # Something on the accept socket!? elif r == tunsock: tunconnection, client_address = tunsock.accept() log.debug("Connection from: %s", client_address) input = input + [tunconnection] tuntcp = tuntcp + [tunconnection] # Otherwise it is on a NAT64:ed socket else: st = sockmap[r] # Receive will receive and send back over tun. data = st.receive() if not data: log.debug(">> Socket shutdown - remove socket?!") for r in exceptready: print(r) except KeyboardInterrupt: log.error("Stopped by user.")
11,575
566
300
e737c7becea69fa93f8f5ebee467579a3b47506c
1,559
py
Python
setup.py
rphilipzhang/FixedEffectModel
017a6f555fff44392d33e45e26c406d02ddde109
[ "BSD-3-Clause" ]
null
null
null
setup.py
rphilipzhang/FixedEffectModel
017a6f555fff44392d33e45e26c406d02ddde109
[ "BSD-3-Clause" ]
null
null
null
setup.py
rphilipzhang/FixedEffectModel
017a6f555fff44392d33e45e26c406d02ddde109
[ "BSD-3-Clause" ]
null
null
null
from setuptools import setup, find_packages from setuptools import setup import os import re dependencies = [ 'pandas>=0.16.0', 'numpy>=1.9.2', 'scipy>=1.6.0', 'statsmodels>=0.12.2', 'networkx>=2.5', ] with open(os.path.join(os.path.dirname(__file__), "fixedeffect", "_version.py")) as file: for line in file: m = re.fullmatch("__version__ = '([^']+)'\n", line) if m: version = m.group(1) setup(name='FixedEffectModel', version=version, description='Solutions to linear model with high dimensional fixed effects.', long_description=readme(), long_description_content_type="text/markdown", author='ksecology', author_email='da_ecology@kuaishou.com', url='https://github.com/ksecology/FixedEffectModel', packages=find_packages(), install_requires=dependencies, zip_safe=False, license='MIT', python_requires='>=3.6', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Sociology', 'Topic :: Scientific/Engineering :: Information Analysis', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Operating System :: OS Independent', ] )
30.568627
89
0.604875
from setuptools import setup, find_packages from setuptools import setup import os import re def readme(): with open('README.md') as f: return f.read() dependencies = [ 'pandas>=0.16.0', 'numpy>=1.9.2', 'scipy>=1.6.0', 'statsmodels>=0.12.2', 'networkx>=2.5', ] with open(os.path.join(os.path.dirname(__file__), "fixedeffect", "_version.py")) as file: for line in file: m = re.fullmatch("__version__ = '([^']+)'\n", line) if m: version = m.group(1) setup(name='FixedEffectModel', version=version, description='Solutions to linear model with high dimensional fixed effects.', long_description=readme(), long_description_content_type="text/markdown", author='ksecology', author_email='da_ecology@kuaishou.com', url='https://github.com/ksecology/FixedEffectModel', packages=find_packages(), install_requires=dependencies, zip_safe=False, license='MIT', python_requires='>=3.6', classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: MIT License', 'Topic :: Scientific/Engineering :: Mathematics', 'Topic :: Sociology', 'Topic :: Scientific/Engineering :: Information Analysis', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Operating System :: OS Independent', ] )
49
0
23
fec798ba9bb59ea1a3fd09c421f4550be10bc182
620
py
Python
check.py
Natali-bali/git_check
2683b82fd03ddfbaf57f70b9abfa7e954c307534
[ "MIT" ]
null
null
null
check.py
Natali-bali/git_check
2683b82fd03ddfbaf57f70b9abfa7e954c307534
[ "MIT" ]
null
null
null
check.py
Natali-bali/git_check
2683b82fd03ddfbaf57f70b9abfa7e954c307534
[ "MIT" ]
null
null
null
import os import pandas as pd import matplotlib.pyplot as plt if os.path.exists("datapoints.csv"): data = pd.read_csv("datapoints.csv") else: print("File does not exist") dataY = data['y'].copy() dataX = data['x'].copy() sumx = sum1(dataX) sumy = sum1(dataY) sumxy = sum2(dataX, dataY) sumxx = sum2(dataX, dataX) resultA = (sumxy-sumx*sumy)/(sumxx - sumx**2) resultB = sumy - resultA*sumx print(resultA, resultB)
20.666667
45
0.617742
import os import pandas as pd import matplotlib.pyplot as plt if os.path.exists("datapoints.csv"): data = pd.read_csv("datapoints.csv") else: print("File does not exist") dataY = data['y'].copy() dataX = data['x'].copy() def sum1(x): sum = 0 for i in x: sum = sum + i return sum/len(x) def sum2(x,y): sum = 0 for i in range(len(x)): sum = sum + x[i]*y[i] return sum/len(x) sumx = sum1(dataX) sumy = sum1(dataY) sumxy = sum2(dataX, dataY) sumxx = sum2(dataX, dataX) resultA = (sumxy-sumx*sumy)/(sumxx - sumx**2) resultB = sumy - resultA*sumx print(resultA, resultB)
152
0
45
7b124f955bad4ce242ac0f6f2341c4c7adf1d555
1,029
py
Python
examples/src/Shapes/AccessOLEObjectFrame.py
aspose-slides/Aspose.Slides-for-Python-via-.NET
c55ad5c71f942598f1e67e22a52cbcd1cb286467
[ "MIT" ]
null
null
null
examples/src/Shapes/AccessOLEObjectFrame.py
aspose-slides/Aspose.Slides-for-Python-via-.NET
c55ad5c71f942598f1e67e22a52cbcd1cb286467
[ "MIT" ]
null
null
null
examples/src/Shapes/AccessOLEObjectFrame.py
aspose-slides/Aspose.Slides-for-Python-via-.NET
c55ad5c71f942598f1e67e22a52cbcd1cb286467
[ "MIT" ]
null
null
null
import aspose.slides as slides
35.482759
89
0.659864
import aspose.slides as slides def shapes_accessing_ole_object_frame(): dataDir = "./examples/data/" outDir = "./examples/out/" # Load the PPTX to Presentation object with slides.Presentation(dataDir + "shapes_accessing_ole_object_frame.pptx") as pres: # Access the first slide sld = pres.slides[0] # Cast the shape to OleObjectFrame oleObjectFrame = sld.shapes[0] # Read the OLE Object and write it to disk if type(oleObjectFrame) is slides.OleObjectFrame: # Get embedded file data data = oleObjectFrame.embedded_data.embedded_file_data # Get embedded file extention fileExtention = oleObjectFrame.embedded_data.embedded_file_extension # Create a path to save the extracted file extractedPath = "excelFromOLE_out" + fileExtention # Save extracted data with open(outDir + "shapes_accessing_ole_object_frame_out.xlsx", "wb") as fs: fs.write(data)
975
0
23
053ebcc69ca0c3e32127ad7b94767a442a29ee38
237
py
Python
pset_basic_data_types/basics/p1.py
mottaquikarim/pydev-psets
9749e0d216ee0a5c586d0d3013ef481cc21dee27
[ "MIT" ]
5
2019-04-08T20:05:37.000Z
2019-12-04T20:48:45.000Z
pset_basic_data_types/basics/p1.py
mottaquikarim/pydev-psets
9749e0d216ee0a5c586d0d3013ef481cc21dee27
[ "MIT" ]
8
2019-04-15T15:16:05.000Z
2022-02-12T10:33:32.000Z
pset_basic_data_types/basics/p1.py
mottaquikarim/pydev-psets
9749e0d216ee0a5c586d0d3013ef481cc21dee27
[ "MIT" ]
2
2019-04-10T00:14:42.000Z
2020-02-26T20:35:21.000Z
""" Placeholders """ # You're writing a program, and you don't know what your starting value for your 'initial' variable is yet. The program won't run if you leave it blank, but you don't want to forget you need it! Make a workaround.
33.857143
213
0.734177
""" Placeholders """ # You're writing a program, and you don't know what your starting value for your 'initial' variable is yet. The program won't run if you leave it blank, but you don't want to forget you need it! Make a workaround.
0
0
0
ef1f568460f7bcdf8ea7aae64466073bb8a1a04b
4,077
py
Python
tests/integration/management_commands/test_oscar_fork_statics.py
QueoLda/django-oscar
8dd992d82e31d26c929b3caa0e08b57e9701d097
[ "BSD-3-Clause" ]
4,639
2015-01-01T00:42:33.000Z
2022-03-29T18:32:12.000Z
tests/integration/management_commands/test_oscar_fork_statics.py
QueoLda/django-oscar
8dd992d82e31d26c929b3caa0e08b57e9701d097
[ "BSD-3-Clause" ]
2,215
2015-01-02T22:32:51.000Z
2022-03-29T12:16:23.000Z
tests/integration/management_commands/test_oscar_fork_statics.py
QueoLda/django-oscar
8dd992d82e31d26c929b3caa0e08b57e9701d097
[ "BSD-3-Clause" ]
2,187
2015-01-02T06:33:31.000Z
2022-03-31T15:32:36.000Z
import io import os import pathlib import tempfile from django.core.management import call_command from django.core.management.base import CommandError from django.test import TestCase import oscar from tests import _site
45.3
119
0.706892
import io import os import pathlib import tempfile from django.core.management import call_command from django.core.management.base import CommandError from django.test import TestCase import oscar from tests import _site class OscarForkStaticsTestCase(TestCase): def setUp(self): # Create dummy Oscar static-files directory (this exists in released # Oscar packages) self.oscar_static_dir_path = pathlib.Path(os.path.dirname(oscar.__file__), 'static') self.oscar_static_dir_path.mkdir() self.oscar_static_file_path = pathlib.Path(self.oscar_static_dir_path, 'name.css') self.oscar_static_file_path.touch(exist_ok=False) # Change to the project's base directory (where the static-files # directory should be copied to) self.project_base_dir_path = pathlib.Path(os.path.dirname(_site.__file__)) os.chdir(self.project_base_dir_path) def tearDown(self): # Delete dummy Oscar static-files directory self.oscar_static_file_path.unlink() self.oscar_static_dir_path.rmdir() def test_command_with_already_existing_directory(self): project_static_dir_path = pathlib.Path(self.project_base_dir_path, 'static') project_static_dir_path.mkdir() with self.assertRaises(CommandError) as e: call_command('oscar_fork_statics') self.assertEqual(e.exception.args[0], "The folder %s already exists - aborting!" % project_static_dir_path) project_static_dir_path.rmdir() def test_command_with_default_target_path(self): project_static_dir_path = pathlib.Path(self.project_base_dir_path, 'static') project_static_file_path = pathlib.Path(project_static_dir_path, 'name.css') out = io.StringIO() call_command('oscar_fork_statics', stdout=out) self.assertTrue(project_static_file_path.exists()) messages = out.getvalue().split('\n') self.assertEqual(messages[0], "Copying Oscar's static files to %s" % project_static_dir_path) self.assertEqual(messages[1], "You need to add %s to STATICFILES_DIRS in order for your local overrides to be " "picked up" % project_static_dir_path) project_static_file_path.unlink() project_static_dir_path.rmdir() def test_command_with_relative_target_path(self): project_static_dir_path = pathlib.Path(self.project_base_dir_path, 'relative/dir') project_static_file_path = pathlib.Path(project_static_dir_path, 'name.css') out = io.StringIO() call_command('oscar_fork_statics', target_path='relative/dir', stdout=out) self.assertTrue(project_static_file_path.exists()) messages = out.getvalue().split('\n') self.assertEqual(messages[0], "Copying Oscar's static files to %s" % project_static_dir_path) self.assertEqual(messages[1], "You need to add %s to STATICFILES_DIRS in order for your local overrides to be " "picked up" % project_static_dir_path) project_static_file_path.unlink() project_static_dir_path.rmdir() project_static_dir_path.parent.rmdir() def test_command_with_absolute_target_path(self): project_static_dir_path = pathlib.Path(tempfile.mkdtemp(), 'static') project_static_file_path = pathlib.Path(project_static_dir_path, 'name.css') out = io.StringIO() call_command('oscar_fork_statics', target_path=str(project_static_dir_path), stdout=out) self.assertTrue(project_static_file_path.exists()) messages = out.getvalue().split('\n') self.assertEqual(messages[0], "Copying Oscar's static files to %s" % project_static_dir_path) self.assertEqual(messages[1], "You need to add %s to STATICFILES_DIRS in order for your local overrides to be " "picked up" % project_static_dir_path) project_static_file_path.unlink() project_static_dir_path.rmdir() project_static_dir_path.parent.rmdir()
3,647
20
185
8d6673d38f5b42b2da78dda9142c78d85572c8de
3,520
py
Python
python_nim.py
dfdeshom/nim_log_perf
66225d5cbd65900702e0fc7e03377ae51e5889f0
[ "MIT" ]
null
null
null
python_nim.py
dfdeshom/nim_log_perf
66225d5cbd65900702e0fc7e03377ae51e5889f0
[ "MIT" ]
null
null
null
python_nim.py
dfdeshom/nim_log_perf
66225d5cbd65900702e0fc7e03377ae51e5889f0
[ "MIT" ]
null
null
null
from ctypes import * """ >>> p = parse_log_line('/plogger/ || 50.73.113.242 || - || 21/Mar/2013:13:22:13 +0000 || GET /plogger/?rand=1363872131875&idsite=deadspin.com&url=http%3A%2F%2Fdeadspin.com%2Frecommended&urlref=http%3A%2F%2Fdeadspin.com%2F&screen=1024x768%7C1024x738%7C24&data=%7B%22parsely_uuid%22%3A%22908932BF-0935-46AD-84BD-10120D5297CA%22%2C%22parsely_site_uuid%22%3A%22908932BF-0935-46AD-84BD-10120D5297CA%22%7D&title=Deadspin+-+Sports+News+without+Access%2C+Favor%2C+or+Discretion&date=Thu+Mar+21+2013+08%3A22%3A11+GMT-0500+(Central+Daylight+Time)&action=pageview HTTP/1.1 || 200 || 363 || - || Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0" || - || - || parsely_network_uuid=CrMHN1FLCYUJWgTmkT47Ag==; expires=Thu, 31-Dec-37 23:55:55 GMT; domain=track.parse.ly; path=/ || 0.000') >>> {'i': '50.73.113.242', 'r': {'title': 'Deadspin - Sports News without Access, Favor, or Discretion', 'url': 'http://deadspin.com/recommended', 'screen': '1024x768|1024x738|24', 'action': 'pageview', 'urlref': 'http://deadspin.com/', 'date': 'Thu Mar 21 2013 08:22:11 GMT-0500 (Central Daylight Time)', 'idsite': 'deadspin.com', 'data': {'parsely_site_uuid': '908932BF-0935-46AD-84BD-10120D5297CA', 'parsely_uuid': '908932BF-0935-46AD-84BD-10120D5297CA'}}, 'u': 'Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0', 't': dt.datetime(2013, 3, 21, 13, 22, 11, 875000)} == p True """ line = "/plogger/ || 191.251.123.60 || - || 31/Aug/2015:23:49:01 +0000 || GET /plogger/?rand=1441064941650&idsite=bolsademulher.com&url=http%3A%2F%2Fwww.bolsademulher.com%2Fbebe%2Fo-que-o-bebe-sente-dentro-da-barriga-quando-a-mae-faz-sexo-4-sensacoes-surpreendentes%2F%3Futm_source%3Dfacebook%26utm_medium%3Dmanual%26utm_campaign%3DBolsaFB&urlref=http%3A%2F%2Fm.facebook.com%2F&screen=360x592%7C360x592%7C32&data=%7B%22parsely_uuid%22%3A%22b5e2fcb7-966f-40f8-b41c-fca446908a56%22%2C%22parsely_site_uuid%22%3A%226e9ab165-497c-45be-9998-e029372b5a92%22%7D&sid=1&surl=http%3A%2F%2Fwww.bolsademulher.com%2Fbebe%2Fo-que-o-bebe-sente-dentro-da-barriga-quando-a-mae-faz-sexo-4-sensacoes-surpreendentes%2F%3Futm_source%3Dfacebook%26utm_medium%3Dmanual%26utm_campaign%3DBolsaFB&sref=http%3A%2F%2Fm.facebook.com%2F&sts=1441064914096&slts=0&date=Mon+Aug+31+2015+20%3A49%3A01+GMT-0300+(BRT)&action=heartbeat&inc=6 HTTP/1.1 || 200 || 236 || http://www.bolsademulher.com/bebe/o-que-o-bebe-sente-dentro-da-barriga-quando-a-mae-faz-sexo-4-sensacoes-surpreendentes/?utm_source=facebook&utm_medium=manual&utm_campaign=BolsaFB || Mozilla/5.0 (Linux; Android 4.4.4; XT1025 Build/KXC21.5-40) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/34.0.0.43.267;] || - || - || - || 0.000" main()
80
1,318
0.719034
from ctypes import * """ >>> p = parse_log_line('/plogger/ || 50.73.113.242 || - || 21/Mar/2013:13:22:13 +0000 || GET /plogger/?rand=1363872131875&idsite=deadspin.com&url=http%3A%2F%2Fdeadspin.com%2Frecommended&urlref=http%3A%2F%2Fdeadspin.com%2F&screen=1024x768%7C1024x738%7C24&data=%7B%22parsely_uuid%22%3A%22908932BF-0935-46AD-84BD-10120D5297CA%22%2C%22parsely_site_uuid%22%3A%22908932BF-0935-46AD-84BD-10120D5297CA%22%7D&title=Deadspin+-+Sports+News+without+Access%2C+Favor%2C+or+Discretion&date=Thu+Mar+21+2013+08%3A22%3A11+GMT-0500+(Central+Daylight+Time)&action=pageview HTTP/1.1 || 200 || 363 || - || Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0" || - || - || parsely_network_uuid=CrMHN1FLCYUJWgTmkT47Ag==; expires=Thu, 31-Dec-37 23:55:55 GMT; domain=track.parse.ly; path=/ || 0.000') >>> {'i': '50.73.113.242', 'r': {'title': 'Deadspin - Sports News without Access, Favor, or Discretion', 'url': 'http://deadspin.com/recommended', 'screen': '1024x768|1024x738|24', 'action': 'pageview', 'urlref': 'http://deadspin.com/', 'date': 'Thu Mar 21 2013 08:22:11 GMT-0500 (Central Daylight Time)', 'idsite': 'deadspin.com', 'data': {'parsely_site_uuid': '908932BF-0935-46AD-84BD-10120D5297CA', 'parsely_uuid': '908932BF-0935-46AD-84BD-10120D5297CA'}}, 'u': 'Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101 Firefox/19.0', 't': dt.datetime(2013, 3, 21, 13, 22, 11, 875000)} == p True """ line = "/plogger/ || 191.251.123.60 || - || 31/Aug/2015:23:49:01 +0000 || GET /plogger/?rand=1441064941650&idsite=bolsademulher.com&url=http%3A%2F%2Fwww.bolsademulher.com%2Fbebe%2Fo-que-o-bebe-sente-dentro-da-barriga-quando-a-mae-faz-sexo-4-sensacoes-surpreendentes%2F%3Futm_source%3Dfacebook%26utm_medium%3Dmanual%26utm_campaign%3DBolsaFB&urlref=http%3A%2F%2Fm.facebook.com%2F&screen=360x592%7C360x592%7C32&data=%7B%22parsely_uuid%22%3A%22b5e2fcb7-966f-40f8-b41c-fca446908a56%22%2C%22parsely_site_uuid%22%3A%226e9ab165-497c-45be-9998-e029372b5a92%22%7D&sid=1&surl=http%3A%2F%2Fwww.bolsademulher.com%2Fbebe%2Fo-que-o-bebe-sente-dentro-da-barriga-quando-a-mae-faz-sexo-4-sensacoes-surpreendentes%2F%3Futm_source%3Dfacebook%26utm_medium%3Dmanual%26utm_campaign%3DBolsaFB&sref=http%3A%2F%2Fm.facebook.com%2F&sts=1441064914096&slts=0&date=Mon+Aug+31+2015+20%3A49%3A01+GMT-0300+(BRT)&action=heartbeat&inc=6 HTTP/1.1 || 200 || 236 || http://www.bolsademulher.com/bebe/o-que-o-bebe-sente-dentro-da-barriga-quando-a-mae-faz-sexo-4-sensacoes-surpreendentes/?utm_source=facebook&utm_medium=manual&utm_campaign=BolsaFB || Mozilla/5.0 (Linux; Android 4.4.4; XT1025 Build/KXC21.5-40) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/33.0.0.0 Mobile Safari/537.36 [FB_IAB/FB4A;FBAV/34.0.0.43.267;] || - || - || - || 0.000" class TGenericSeq (Structure): _fields_ = [("len", c_int64), ("reserved", c_int64)] class NimStringDesc(Structure): pass def make_nim_string(s): _len = len(s) NimStringDesc._fields_ = [("Sup", TGenericSeq), ("data", c_char * _len)] tgs = TGenericSeq(_len, 0) nsd = NimStringDesc(tgs, s) str_pointer = POINTER(NimStringDesc) return str_pointer(nsd) def main(): lib = CDLL("/home/dfdeshom/code/nim_log_perf/liblog_parser.so") str_pointer = POINTER(NimStringDesc) lib_parse = lib.parse_log_line lib_parse.argtypes = [str_pointer] lib_parse.restype = str_pointer # for i in range(100): # res = lib_parse(e) e = make_nim_string(line) print lib_parse(e) return main()
589
85
92
e51930ab1cbcd988963bd7e470dee26c4f76502d
1,269
py
Python
day-8/test.py
PeterPrice06/advent-of-code-2021
d1af22ee2e4778372e626debca1ae9dc7f2ad47c
[ "MIT" ]
null
null
null
day-8/test.py
PeterPrice06/advent-of-code-2021
d1af22ee2e4778372e626debca1ae9dc7f2ad47c
[ "MIT" ]
null
null
null
day-8/test.py
PeterPrice06/advent-of-code-2021
d1af22ee2e4778372e626debca1ae9dc7f2ad47c
[ "MIT" ]
null
null
null
import unittest from typing import List from decoder import Decoder if __name__ == '__main__': unittest.main()
31.725
68
0.686367
import unittest from typing import List from decoder import Decoder class TestDecode(unittest.TestCase): def setUp(self) -> None: pass def test_decode_count_unique_sample(self) -> None: lines = file_read_helper('day-8/sample_input.txt') decoder = Decoder(lines) self.assertEqual(decoder.count_unique_in_output_value(), 26) def test_decode_count_unique_sample(self) -> None: lines = file_read_helper('day-8/sample_input.txt') decoder = Decoder(lines) self.assertEqual(decoder.count_unique_in_output_value(), 26) def test_decode_sum_decoded_output_sample(self) -> None: lines = file_read_helper('day-8/sample_input.txt') decoder = Decoder(lines) self.assertEqual(decoder.sum_decoded_output(), 61229) def test_decode_sum_decoded_output_puzzle(self) -> None: lines = file_read_helper('day-8/puzzle_input.txt') decoder = Decoder(lines) self.assertEqual(decoder.sum_decoded_output(), 978171) def file_read_helper(filename: str) -> List[str]: lines = [] with open(filename, 'r', encoding='UTF-8') as file: for line in file: lines.append(line.strip()) return lines if __name__ == '__main__': unittest.main()
956
15
180
f278bb3662a66ece6d5cf5324b3ba90fbf180efe
835
py
Python
service_repository/interfaces/service.py
fndmiranda/service-repository
c0ad42bd0e62b6af9e5019485a37af902a09d210
[ "MIT" ]
4
2022-02-22T23:54:35.000Z
2022-02-25T14:48:30.000Z
service_repository/interfaces/service.py
fndmiranda/service-repository
c0ad42bd0e62b6af9e5019485a37af902a09d210
[ "MIT" ]
null
null
null
service_repository/interfaces/service.py
fndmiranda/service-repository
c0ad42bd0e62b6af9e5019485a37af902a09d210
[ "MIT" ]
null
null
null
from abc import ABCMeta, abstractmethod from pydantic import BaseModel class ServiceInterface(metaclass=ABCMeta): """Class representing the service interface.""" @abstractmethod async def create(self, schema_in: BaseModel): """ Create new entity and returns the saved instance. """ raise NotImplementedError() @abstractmethod async def update(self, instance: BaseModel, schema_in: BaseModel): """Updates an entity and returns the saved instance.""" raise NotImplementedError() @abstractmethod async def get(self, **kwargs): """Get and return one instance by filter.""" raise NotImplementedError() @abstractmethod async def delete(self, **kwargs): """Delete one instance by filter.""" raise NotImplementedError()
27.833333
70
0.668263
from abc import ABCMeta, abstractmethod from pydantic import BaseModel class ServiceInterface(metaclass=ABCMeta): """Class representing the service interface.""" @abstractmethod async def create(self, schema_in: BaseModel): """ Create new entity and returns the saved instance. """ raise NotImplementedError() @abstractmethod async def update(self, instance: BaseModel, schema_in: BaseModel): """Updates an entity and returns the saved instance.""" raise NotImplementedError() @abstractmethod async def get(self, **kwargs): """Get and return one instance by filter.""" raise NotImplementedError() @abstractmethod async def delete(self, **kwargs): """Delete one instance by filter.""" raise NotImplementedError()
0
0
0
425ccd42d489c21633605a6e2026f1ca786d0378
1,882
py
Python
src/ash/gui/checkbox.py
Rolando-Zarate/ash
6672ec5d2931d39689e712fa476bbadb8733a739
[ "MIT" ]
40
2020-07-24T06:36:25.000Z
2022-03-29T11:25:37.000Z
src/ash/gui/checkbox.py
Rolando-Zarate/ash
6672ec5d2931d39689e712fa476bbadb8733a739
[ "MIT" ]
12
2020-12-22T02:56:05.000Z
2022-02-18T17:59:16.000Z
src/ash/gui/checkbox.py
Rolando-Zarate/ash
6672ec5d2931d39689e712fa476bbadb8733a739
[ "MIT" ]
3
2021-02-12T11:49:39.000Z
2021-07-23T21:17:26.000Z
# --------------------------------------------------------------------------------------------- # Copyright (c) Akash Nag. All rights reserved. # Licensed under the MIT License. See LICENSE.md in the project root for license information. # --------------------------------------------------------------------------------------------- # This module implements the CheckBox widget from ash.gui import * # when checkbox receives focus # when checkbox loses focus # returns checkbox state # draws the checkbox # when keypress occurs: space toggles checkbox state # returns the string representation: checkbox text # set the checked-status of the checkbox
26.138889
95
0.628055
# --------------------------------------------------------------------------------------------- # Copyright (c) Akash Nag. All rights reserved. # Licensed under the MIT License. See LICENSE.md in the project root for license information. # --------------------------------------------------------------------------------------------- # This module implements the CheckBox widget from ash.gui import * class CheckBox(Widget): def __init__(self, parent, y, x, text): super().__init__(WIDGET_TYPE_CHECKBOX) self.parent = parent self.y = y self.x = x self.height = 1 self.width = len(text) + 3 self.theme = gc("formfield") self.focus_theme = gc("formfield-focussed") self.text = text self.is_in_focus = False self.checked = False self.repaint() # when checkbox receives focus def focus(self): self.is_in_focus = True self.repaint() # when checkbox loses focus def blur(self): self.is_in_focus = False self.repaint() # returns checkbox state def is_checked(self): return self.checked # draws the checkbox def repaint(self): if(self.is_in_focus): curses.curs_set(False) paint_theme = self.theme if(self.is_in_focus and self.focus_theme != None): paint_theme = self.focus_theme if(self.checked): s = "\u2611 " + self.text + " " else: s = "\u2610 " + self.text + " " self.parent.addstr(self.y, self.x, s, paint_theme) # when keypress occurs: space toggles checkbox state def perform_action(self, ch): self.focus() if(KeyBindings.is_key(ch, "CHANGE_VALUE")): self.checked = not self.checked self.repaint() else: beep() # returns the string representation: checkbox text def __str__(self): return self.text # set the checked-status of the checkbox def set_value(self, checked = True): self.checked = checked def on_click(self, y, x): self.checked = not self.checked self.repaint()
980
2
231
bde00d5057eb89869a40de202d4fd01b36be6f4a
65
py
Python
src/clld/project_template/{{cookiecutter.directory_name}}/{{cookiecutter.directory_name}}/tests/conftest.py
blurks/clld
d9900f88af726eb6a4d2668f517d5af23bcc6f9d
[ "MIT" ]
32
2015-02-22T02:09:29.000Z
2022-02-18T14:40:16.000Z
src/clld/project_template/{{cookiecutter.directory_name}}/{{cookiecutter.directory_name}}/tests/conftest.py
blurks/clld
d9900f88af726eb6a4d2668f517d5af23bcc6f9d
[ "MIT" ]
199
2015-01-05T11:58:38.000Z
2022-02-22T14:34:52.000Z
src/clld/project_template/{{cookiecutter.directory_name}}/{{cookiecutter.directory_name}}/tests/conftest.py
blurks/clld
d9900f88af726eb6a4d2668f517d5af23bcc6f9d
[ "MIT" ]
18
2015-01-23T13:00:47.000Z
2022-02-21T16:32:36.000Z
from {{cookiecutter.directory_name}} import models import pytest
21.666667
50
0.830769
from {{cookiecutter.directory_name}} import models import pytest
0
0
0
fc668aaec97e29bc2f9f8b1c73a6d0392ac40431
1,137
py
Python
desafios/des115/lib/arquivo/__init__.py
Ericssm96/python
764d0d704be685db9e993c4b74d3df78da12cc6f
[ "MIT" ]
null
null
null
desafios/des115/lib/arquivo/__init__.py
Ericssm96/python
764d0d704be685db9e993c4b74d3df78da12cc6f
[ "MIT" ]
null
null
null
desafios/des115/lib/arquivo/__init__.py
Ericssm96/python
764d0d704be685db9e993c4b74d3df78da12cc6f
[ "MIT" ]
null
null
null
import optparse from des115.lib.interface import *
21.45283
59
0.531223
import optparse from des115.lib.interface import * def arquivoexiste(nome): try: a = open(nome, 'rt') a.close() except FileNotFoundError: return False else: return True def criararquivo(nome): try: a = open(nome, 'wt+') except: print('Houve um erro na criação de arquivo.') else: print(f'Arquivo {nome} criado com sucesso!') def lerarquivo(nome): try: a = open(nome, 'rt') except: print('Erro ao ler o arquivo.') else: cabecalho('PESSOAS CADASTRADAS') for linhas in a: msg = linhas.split(';') print(f'{msg[0]:-<20}{msg[1]}', end='') print('\n') finally: a.close() def cadastrar(arquivo, nome='Desconhecido', idade=0): try: a = open(arquivo, 'at') except: print('Houve um erro na abertura do arquivo.') else: try: a.write(f'{nome};{idade}\n') except: print('Erro durante a manipulação do arquivo.') else: print(f'Novo registro de {nome} adicionado.') a.close()
993
0
92
d05508d6049c08f93d847981ac32be13e69061d9
5,039
py
Python
haprestio/api_v1/fqdns.py
innofocus/haprestio
6a9bf3a3d73fb3faa7cf1e5cfc757cc360fbafde
[ "MIT" ]
null
null
null
haprestio/api_v1/fqdns.py
innofocus/haprestio
6a9bf3a3d73fb3faa7cf1e5cfc757cc360fbafde
[ "MIT" ]
null
null
null
haprestio/api_v1/fqdns.py
innofocus/haprestio
6a9bf3a3d73fb3faa7cf1e5cfc757cc360fbafde
[ "MIT" ]
null
null
null
from flask_restplus import Resource from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt_claims from . import api_v1, fqdn_ns, fqdn_m, fqdn_mr from ..data.fqdns import Fqdns, Fqdn from ..helpers.helpers import Haproxy @fqdn_ns.route('', endpoint='fqdn') @fqdn_ns.response(401, "Token has expired, bad credentials or reserved for administrators") @fqdn_ns.response(201, "Successfully created") @fqdn_ns.response(409, "Can't create already THIS present 'fqdn' fqdn") @fqdn_ns.response(406, "Error on definition content, please rewrite your definition") class Fqdns_R(Resource): """Shows a list of all Fqdns(), and lets you POST to add new fqdn""" @jwt_required @fqdn_ns.doc('list_frontends', security='apikey') @fqdn_ns.marshal_list_with(fqdn_mr) def get(self): """List all fqdn entries that you own.""" if get_jwt_claims()['roles'] == 'admin': return Fqdns().json() return Fqdns().json(get_jwt_identity()) @jwt_required @fqdn_ns.doc('Add Frontend fqdn', security='apikey') @fqdn_ns.expect(fqdn_m) @fqdn_ns.marshal_with(fqdn_mr) def post(self): """Create a new fqdn entry""" api_v1.payload.update({'owner': get_jwt_identity()}) if Fqdn(api_v1.payload['fqdn']).exists(): return { 'message': "Can't create WTF already present 'fqdn' fqdn"}, 409 f = Fqdn().create(api_v1.payload) if not f.is_publish_fail(): return f.json(), 201 else: f.destroy() f.state = "publish_failed" return f.json(), 406 @fqdn_ns.route('/<string:fqdn>', endpoint='fqdnchange') @fqdn_ns.response(400, "can't get or modify non-existent fqdn") @fqdn_ns.response(401, "Token has expired, bad credentials or reserved for administrators") @fqdn_ns.response(409, "Can't modify not present 'fqdn' fqdn") @fqdn_ns.response(200, "Operation is successful") class Fqdn_R(Resource): """Modify fqdn""" @jwt_required @fqdn_ns.doc('show fqdn', security='apikey') @fqdn_ns.marshal_with(fqdn_mr) def get(self, fqdn): """Show a fqdn entry that you own""" result = Fqdn(fqdn) if not result.exists(): fqdn_ns.abort(400, "can't get non-existent fqdn") if get_jwt_claims()['roles'] == 'admin' or get_jwt_identity() == result.owner: return result.json() @jwt_required @fqdn_ns.doc('update fqdn', security='apikey') @fqdn_ns.expect(fqdn_m) @fqdn_ns.marshal_with(fqdn_mr) def put(self, fqdn): """Modify a fqdn entry that you own""" if not Fqdn(fqdn).exists(): fqdn_ns.abort(400, "can't modify non-existent fqdn") if Fqdn(fqdn).owner != get_jwt_identity() and get_jwt_claims()['roles'] != 'admin': fqdn_ns.abort(401, "you don't own this fqdn") f = Fqdn(fqdn).update(api_v1.payload) if f.is_publish_fail(): return f.json(), 406 else: return f.json(), 201 @jwt_required @fqdn_ns.doc('remove fqdn', security='apikey') @fqdn_ns.marshal_with(fqdn_mr) # @tenant.response(204, 'fqdn deleted (set state to remove)') def delete(self, fqdn): """definitly remove a fqdn entry that you own from this service.""" if not Fqdn(fqdn).exists(): fqdn_ns.abort(400, "can't modify non-existent fqdn") if Fqdn(fqdn).owner != get_jwt_identity() and get_jwt_claims()['roles'] != 'admin': fqdn_ns.abort(401, "you don't own this fqdn") return Fqdn(fqdn).destroy().json() @fqdn_ns.route('/<string:fqdn>/hastats') @fqdn_ns.response(400, "can't get non-existent fqdn") @fqdn_ns.response(401, "Token has expired, bad credentials or reserved for administrators") @fqdn_ns.response(200, "Operation is successful") class Hastats_R(Resource): """Haproxy stats""" @jwt_required @fqdn_ns.doc("show backend's fqdn full stats", security='apikey') def get(self, fqdn): """Show backend's fqdn full stats that you own""" result = Fqdn(fqdn) if not result.exists(): fqdn_ns.abort(400, "can't get stats on non-existent fqdn") if get_jwt_claims()['roles'] == 'admin' or get_jwt_identity() == result.owner: return Haproxy().getstats(result.backend_name) @fqdn_ns.route('/<string:fqdn>/status') @fqdn_ns.response(400, "can't get non-existent fqdn") @fqdn_ns.response(401, "Token has expired, bad credentials or reserved for administrators") @fqdn_ns.response(200, "Operation is successful") class Hastatus_R(Resource): """Haproxy status""" @jwt_required @fqdn_ns.doc("show backend's fqdn short status", security='apikey') def get(self, fqdn): """Show backend's fqdn short status""" result = Fqdn(fqdn) if not result.exists(): fqdn_ns.abort(400, "can't get stats on non-existent fqdn") if get_jwt_claims()['roles'] == 'admin' or get_jwt_identity() == result.owner: return Haproxy().getstatus(result.backend_name)
40.312
91
0.652709
from flask_restplus import Resource from flask_jwt_extended import jwt_required, get_jwt_identity, get_jwt_claims from . import api_v1, fqdn_ns, fqdn_m, fqdn_mr from ..data.fqdns import Fqdns, Fqdn from ..helpers.helpers import Haproxy @fqdn_ns.route('', endpoint='fqdn') @fqdn_ns.response(401, "Token has expired, bad credentials or reserved for administrators") @fqdn_ns.response(201, "Successfully created") @fqdn_ns.response(409, "Can't create already THIS present 'fqdn' fqdn") @fqdn_ns.response(406, "Error on definition content, please rewrite your definition") class Fqdns_R(Resource): """Shows a list of all Fqdns(), and lets you POST to add new fqdn""" @jwt_required @fqdn_ns.doc('list_frontends', security='apikey') @fqdn_ns.marshal_list_with(fqdn_mr) def get(self): """List all fqdn entries that you own.""" if get_jwt_claims()['roles'] == 'admin': return Fqdns().json() return Fqdns().json(get_jwt_identity()) @jwt_required @fqdn_ns.doc('Add Frontend fqdn', security='apikey') @fqdn_ns.expect(fqdn_m) @fqdn_ns.marshal_with(fqdn_mr) def post(self): """Create a new fqdn entry""" api_v1.payload.update({'owner': get_jwt_identity()}) if Fqdn(api_v1.payload['fqdn']).exists(): return { 'message': "Can't create WTF already present 'fqdn' fqdn"}, 409 f = Fqdn().create(api_v1.payload) if not f.is_publish_fail(): return f.json(), 201 else: f.destroy() f.state = "publish_failed" return f.json(), 406 @fqdn_ns.route('/<string:fqdn>', endpoint='fqdnchange') @fqdn_ns.response(400, "can't get or modify non-existent fqdn") @fqdn_ns.response(401, "Token has expired, bad credentials or reserved for administrators") @fqdn_ns.response(409, "Can't modify not present 'fqdn' fqdn") @fqdn_ns.response(200, "Operation is successful") class Fqdn_R(Resource): """Modify fqdn""" @jwt_required @fqdn_ns.doc('show fqdn', security='apikey') @fqdn_ns.marshal_with(fqdn_mr) def get(self, fqdn): """Show a fqdn entry that you own""" result = Fqdn(fqdn) if not result.exists(): fqdn_ns.abort(400, "can't get non-existent fqdn") if get_jwt_claims()['roles'] == 'admin' or get_jwt_identity() == result.owner: return result.json() @jwt_required @fqdn_ns.doc('update fqdn', security='apikey') @fqdn_ns.expect(fqdn_m) @fqdn_ns.marshal_with(fqdn_mr) def put(self, fqdn): """Modify a fqdn entry that you own""" if not Fqdn(fqdn).exists(): fqdn_ns.abort(400, "can't modify non-existent fqdn") if Fqdn(fqdn).owner != get_jwt_identity() and get_jwt_claims()['roles'] != 'admin': fqdn_ns.abort(401, "you don't own this fqdn") f = Fqdn(fqdn).update(api_v1.payload) if f.is_publish_fail(): return f.json(), 406 else: return f.json(), 201 @jwt_required @fqdn_ns.doc('remove fqdn', security='apikey') @fqdn_ns.marshal_with(fqdn_mr) # @tenant.response(204, 'fqdn deleted (set state to remove)') def delete(self, fqdn): """definitly remove a fqdn entry that you own from this service.""" if not Fqdn(fqdn).exists(): fqdn_ns.abort(400, "can't modify non-existent fqdn") if Fqdn(fqdn).owner != get_jwt_identity() and get_jwt_claims()['roles'] != 'admin': fqdn_ns.abort(401, "you don't own this fqdn") return Fqdn(fqdn).destroy().json() @fqdn_ns.route('/<string:fqdn>/hastats') @fqdn_ns.response(400, "can't get non-existent fqdn") @fqdn_ns.response(401, "Token has expired, bad credentials or reserved for administrators") @fqdn_ns.response(200, "Operation is successful") class Hastats_R(Resource): """Haproxy stats""" @jwt_required @fqdn_ns.doc("show backend's fqdn full stats", security='apikey') def get(self, fqdn): """Show backend's fqdn full stats that you own""" result = Fqdn(fqdn) if not result.exists(): fqdn_ns.abort(400, "can't get stats on non-existent fqdn") if get_jwt_claims()['roles'] == 'admin' or get_jwt_identity() == result.owner: return Haproxy().getstats(result.backend_name) @fqdn_ns.route('/<string:fqdn>/status') @fqdn_ns.response(400, "can't get non-existent fqdn") @fqdn_ns.response(401, "Token has expired, bad credentials or reserved for administrators") @fqdn_ns.response(200, "Operation is successful") class Hastatus_R(Resource): """Haproxy status""" @jwt_required @fqdn_ns.doc("show backend's fqdn short status", security='apikey') def get(self, fqdn): """Show backend's fqdn short status""" result = Fqdn(fqdn) if not result.exists(): fqdn_ns.abort(400, "can't get stats on non-existent fqdn") if get_jwt_claims()['roles'] == 'admin' or get_jwt_identity() == result.owner: return Haproxy().getstatus(result.backend_name)
0
0
0
c257fd415c70ef05a60843b0588a4740a133c9f7
247
py
Python
wx/models/location.py
kmarekspartz/wx
1aa1d5c3fa2c4cb3304d3420e516895623a5e447
[ "MIT" ]
null
null
null
wx/models/location.py
kmarekspartz/wx
1aa1d5c3fa2c4cb3304d3420e516895623a5e447
[ "MIT" ]
null
null
null
wx/models/location.py
kmarekspartz/wx
1aa1d5c3fa2c4cb3304d3420e516895623a5e447
[ "MIT" ]
null
null
null
from peewee import DoubleField, CompositeKey from wx.app import database
20.583333
60
0.712551
from peewee import DoubleField, CompositeKey from wx.app import database class Location(database.Model): latitude = DoubleField() longitude = DoubleField() # class Meta: # primary_key = CompositeKey('latitude', 'longitude')
0
149
23
a66e6dee5ebecb5a3377454d74c3b1873a326bf3
1,029
py
Python
server.py
AlexMout/OptionPricer
3c95a3758ab9a96027d40c8d7a23c3e4482ff221
[ "MIT" ]
1
2019-08-21T16:51:59.000Z
2019-08-21T16:51:59.000Z
server.py
AlexMout/OptionPricer
3c95a3758ab9a96027d40c8d7a23c3e4482ff221
[ "MIT" ]
null
null
null
server.py
AlexMout/OptionPricer
3c95a3758ab9a96027d40c8d7a23c3e4482ff221
[ "MIT" ]
null
null
null
from flask import Flask, redirect,render_template, request import json import view_model as vm app = Flask(__name__) @app.route("/") @app.route("/get_price",methods=['POST']) if __name__ == "__main__": app.run(debug=True)
36.75
93
0.699708
from flask import Flask, redirect,render_template, request import json import view_model as vm app = Flask(__name__) @app.route("/") def main_page(): return render_template("index.html",page_title="Pricer") @app.route("/get_price",methods=['POST']) def get_price(): dict_args = {} dict_args['strategy'] = request.form.get("strategy","Vanilla") dict_args['type'] = request.form.get("type","European") dict_args['spot'] = request.form.get("spot",0) dict_args['strike'] = request.form.get("strike",0) dict_args['strike2'] = request.form.get("strike2",0) dict_args['maturity'] = request.form.get("maturity") dict_args['maturity2'] = request.form.get("maturity2",0) dict_args['volatility'] = request.form.get("volatility",0.2) dict_args['interest_rate'] = request.form.get("interest-rate",0) #The get_price() method from View_Model returns a render_template with the good html page return vm.View_Model(dict_args).get_price() if __name__ == "__main__": app.run(debug=True)
756
0
44
fc5fabe4297bec14191b579e187d61fd0988d9f1
999
py
Python
h/migrations/versions/ef3059e0396_add_staff_column_to_feature_table.py
noscripter/h
a7a4095a46683ea08dae62335bbcd53f7ab313e2
[ "MIT" ]
null
null
null
h/migrations/versions/ef3059e0396_add_staff_column_to_feature_table.py
noscripter/h
a7a4095a46683ea08dae62335bbcd53f7ab313e2
[ "MIT" ]
null
null
null
h/migrations/versions/ef3059e0396_add_staff_column_to_feature_table.py
noscripter/h
a7a4095a46683ea08dae62335bbcd53f7ab313e2
[ "MIT" ]
null
null
null
"""Add the staff columns to the feature and user tables. Revision ID: ef3059e0396 Revises: 3bf1c2289e8d Create Date: 2015-07-30 16:25:14.837823 """ # revision identifiers, used by Alembic. revision = 'ef3059e0396' down_revision = '3bf1c2289e8d' from alembic import op import sqlalchemy as sa
27.75
74
0.638639
"""Add the staff columns to the feature and user tables. Revision ID: ef3059e0396 Revises: 3bf1c2289e8d Create Date: 2015-07-30 16:25:14.837823 """ # revision identifiers, used by Alembic. revision = 'ef3059e0396' down_revision = '3bf1c2289e8d' from alembic import op import sqlalchemy as sa def upgrade(): with op.batch_alter_table('feature') as batch_op: batch_op.add_column( sa.Column('staff', sa.Boolean, nullable=False, default=False, server_default=sa.sql.expression.false())) with op.batch_alter_table('user') as batch_op: batch_op.add_column(sa.Column('staff', sa.Boolean, nullable=False, server_default=sa.sql.expression.false())) def downgrade(): with op.batch_alter_table('feature') as batch_op: batch_op.drop_column('staff') with op.batch_alter_table('user') as batch_op: batch_op.drop_column('staff')
655
0
46
4c9f9895d5041cddff5e56a84c182ada7022c5f7
4,332
py
Python
tests/utils_test.py
zhangted/tda-api
1169c87129b80c120217d420e4996a439c5903dc
[ "MIT" ]
986
2020-04-14T21:50:03.000Z
2022-03-29T19:09:31.000Z
tests/utils_test.py
zhangted/tda-api
1169c87129b80c120217d420e4996a439c5903dc
[ "MIT" ]
243
2020-04-26T14:05:34.000Z
2022-03-12T13:02:51.000Z
tests/utils_test.py
zhangted/tda-api
1169c87129b80c120217d420e4996a439c5903dc
[ "MIT" ]
286
2020-04-14T22:17:04.000Z
2022-03-27T07:30:15.000Z
from unittest.mock import MagicMock from tda.utils import AccountIdMismatchException, Utils from tda.utils import UnsuccessfulOrderException from tda.utils import EnumEnforcer from .utils import no_duplicates, MockResponse import enum import unittest
35.219512
78
0.644275
from unittest.mock import MagicMock from tda.utils import AccountIdMismatchException, Utils from tda.utils import UnsuccessfulOrderException from tda.utils import EnumEnforcer from .utils import no_duplicates, MockResponse import enum import unittest class EnumEnforcerTest(unittest.TestCase): class TestClass(EnumEnforcer): def test_enforcement(self, value): self.convert_enum(value, EnumEnforcerTest.TestEnum) class TestEnum(enum.Enum): VALUE_1 = 1 VALUE_2 = 2 def test_valid_enum(self): t = self.TestClass(enforce_enums=True) t.test_enforcement(self.TestEnum.VALUE_1) def test_invalid_enum_passed_as_string(self): t = self.TestClass(enforce_enums=True) with self.assertRaisesRegex( ValueError, 'tests.utils_test.TestEnum.VALUE_1'): t.test_enforcement('VALUE_1') def test_invalid_enum_passed_as_not_string(self): t = self.TestClass(enforce_enums=True) with self.assertRaises(ValueError): t.test_enforcement(123) class UtilsTest(unittest.TestCase): def setUp(self): self.mock_client = MagicMock() self.account_id = 10000 self.utils = Utils(self.mock_client, self.account_id) self.order_id = 1 self.maxDiff = None ########################################################################## # extract_order_id tests @no_duplicates def test_extract_order_id_order_not_ok(self): response = MockResponse({}, 403) with self.assertRaises( UnsuccessfulOrderException, msg='order not successful'): self.utils.extract_order_id(response) @no_duplicates def test_extract_order_id_no_location(self): response = MockResponse({}, 200, headers={}) self.assertIsNone(self.utils.extract_order_id(response)) @no_duplicates def test_extract_order_id_no_pattern_match(self): response = MockResponse({}, 200, headers={ 'Location': 'https://api.tdameritrade.com/v1/accounts/12345'}) self.assertIsNone(self.utils.extract_order_id(response)) @no_duplicates def test_get_order_nonmatching_account_id(self): response = MockResponse({}, 200, headers={ 'Location': 'https://api.tdameritrade.com/v1/accounts/{}/orders/456'.format( self.account_id + 1)}) with self.assertRaises( AccountIdMismatchException, msg='order request account ID != Utils.account_id'): self.utils.extract_order_id(response) @no_duplicates def test_get_order_nonmatching_account_id_str(self): self.utils = Utils(self.mock_client, str(self.account_id)) response = MockResponse({}, 200, headers={ 'Location': 'https://api.tdameritrade.com/v1/accounts/{}/orders/456'.format( self.account_id + 1)}) with self.assertRaises( AccountIdMismatchException, msg='order request account ID != Utils.account_id'): self.utils.extract_order_id(response) @no_duplicates def test_get_order_success_200(self): order_id = self.account_id + 100 response = MockResponse({}, 200, headers={ 'Location': 'https://api.tdameritrade.com/v1/accounts/{}/orders/{}'.format( self.account_id, order_id)}) self.assertEqual(order_id, self.utils.extract_order_id(response)) @no_duplicates def test_get_order_success_201(self): order_id = self.account_id + 100 response = MockResponse({}, 201, headers={ 'Location': 'https://api.tdameritrade.com/v1/accounts/{}/orders/{}'.format( self.account_id, order_id)}) self.assertEqual(order_id, self.utils.extract_order_id(response)) @no_duplicates def test_get_order_success_str_account_id(self): self.utils = Utils(self.mock_client, str(self.account_id)) order_id = self.account_id + 100 response = MockResponse({}, 200, headers={ 'Location': 'https://api.tdameritrade.com/v1/accounts/{}/orders/{}'.format( self.account_id, order_id)}) self.assertEqual(order_id, self.utils.extract_order_id(response))
3,272
760
46
18eaab80515f9d58ded2d73661955aaf052c1aef
36,651
py
Python
twistedcaldav/extensions.py
eventable/CalendarServer
384444edb1966b530bc391789afbe3fb9cd6fd3e
[ "Apache-2.0" ]
1
2017-02-18T19:22:19.000Z
2017-02-18T19:22:19.000Z
twistedcaldav/extensions.py
eventable/CalendarServer
384444edb1966b530bc391789afbe3fb9cd6fd3e
[ "Apache-2.0" ]
null
null
null
twistedcaldav/extensions.py
eventable/CalendarServer
384444edb1966b530bc391789afbe3fb9cd6fd3e
[ "Apache-2.0" ]
null
null
null
# -*- test-case-name: twistedcaldav.test.test_extensions -*- ## # Copyright (c) 2005-2015 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## from __future__ import print_function """ Extensions to web2.dav """ __all__ = [ "DAVResource", "DAVResourceWithChildrenMixin", "DAVPrincipalResource", "DAVFile", "ReadOnlyWritePropertiesResourceMixIn", "ReadOnlyResourceMixIn", "CachingPropertyStore", ] import urllib import time from itertools import cycle from twisted.internet.defer import succeed, maybeDeferred from twisted.internet.defer import inlineCallbacks, returnValue from twisted.web.template import Element, XMLFile, renderer, tags, flattenString from twisted.python.modules import getModule from txweb2 import responsecode, server from txweb2.http import HTTPError, Response, RedirectResponse from txweb2.http import StatusResponse from txweb2.http_headers import MimeType from txweb2.stream import FileStream from txweb2.static import MetaDataMixin, StaticRenderMixin from txdav.xml import element from txdav.xml.base import encodeXMLName from txdav.xml.element import dav_namespace from txweb2.dav.http import MultiStatusResponse from txweb2.dav.static import DAVFile as SuperDAVFile from txweb2.dav.resource import DAVResource as SuperDAVResource from txweb2.dav.resource import ( DAVPrincipalResource as SuperDAVPrincipalResource ) from twisted.internet.defer import gatherResults from txweb2.dav.method import prop_common from twext.python.log import Logger from twistedcaldav import customxml from twistedcaldav.customxml import calendarserver_namespace from twistedcaldav.method.report import http_REPORT from twistedcaldav.config import config from txdav.who.directory import CalendarDirectoryRecordMixin from twext.who.expression import Operand, MatchType, MatchFlags thisModule = getModule(__name__) log = Logger() class DirectoryElement(Element): """ A L{DirectoryElement} is an L{Element} for rendering the contents of a L{DirectoryRenderingMixIn} resource as HTML. """ loader = XMLFile( thisModule.filePath.sibling("directory-listing.html") ) def __init__(self, resource): """ @param resource: the L{DirectoryRenderingMixIn} resource being listed. """ super(DirectoryElement, self).__init__() self.resource = resource @renderer def resourceDetail(self, request, tag): """ Renderer which returns a distinct element for this resource's data. Subclasses should override. """ return '' @renderer def children(self, request, tag): """ Renderer which yields all child object tags as table rows. """ whenChildren = ( maybeDeferred(self.resource.listChildren) .addCallback(sorted) .addCallback( lambda names: gatherResults( [maybeDeferred(self.resource.getChild, x) for x in names] ) .addCallback(lambda children: zip(children, names)) ) ) @whenChildren.addCallback return whenChildren @renderer def main(self, request, tag): """ Main renderer; fills slots for title, etc. """ return tag.fillSlots(name=request.path) @renderer def properties(self, request, tag): """ Renderer which yields all properties as table row tags. """ whenPropertiesListed = self.resource.listProperties(request) @whenPropertiesListed.addCallback return whenPropertiesListed class DAVResource (DirectoryPrincipalPropertySearchMixIn, SuperDAVResource, DirectoryRenderingMixIn, StaticRenderMixin): """ Extended L{txweb2.dav.resource.DAVResource} implementation. Note we add StaticRenderMixin as a base class because we need all the etag etc behavior that is currently in static.py but is actually applicable to any type of resource. """ log = Logger() http_REPORT = http_REPORT class DAVResourceWithChildrenMixin (object): """ Bits needed from txweb2.static """ def putChild(self, name, child): """ Register a child with the given name with this resource. @param name: the name of the child (a URI path segment) @param child: the child to register """ self.putChildren[name] = child def getChild(self, name): """ Look up a child resource. First check C{self.putChildren}, then call C{self.makeChild} if no pre-existing children were found. @return: the child of this resource with the given name. """ if name == "": return self result = self.putChildren.get(name, None) if not result: result = self.makeChild(name) return result def makeChild(self, name): """ Called by L{DAVResourceWithChildrenMixin.getChild} to dynamically create children that have not been pre-created with C{putChild}. """ return None def listChildren(self): """ @return: a sequence of the names of all known children of this resource. """ return self.putChildren.keys() def countChildren(self): """ @return: the number of all known children of this resource. """ return len(self.putChildren.keys()) def locateChild(self, req, segments): """ See L{IResource.locateChild}. """ thisSegment = segments[0] moreSegments = segments[1:] return maybeDeferred(self.getChild, thisSegment).addCallback( lambda it: (it, moreSegments) ) class DAVResourceWithoutChildrenMixin (object): """ Bits needed from txweb2.static """ class DAVPrincipalResource (DirectoryPrincipalPropertySearchMixIn, SuperDAVPrincipalResource, DirectoryRenderingMixIn): """ Extended L{txweb2.dav.static.DAVFile} implementation. """ log = Logger() http_REPORT = http_REPORT @inlineCallbacks class DAVFile (SuperDAVFile, DirectoryRenderingMixIn): """ Extended L{txweb2.dav.static.DAVFile} implementation. """ log = Logger() class ReadOnlyWritePropertiesResourceMixIn (object): """ Read only that will allow writing of properties resource. """ readOnlyResponse = StatusResponse( responsecode.FORBIDDEN, "Resource is read only." ) http_DELETE = _forbidden http_MOVE = _forbidden http_PUT = _forbidden class ReadOnlyResourceMixIn (ReadOnlyWritePropertiesResourceMixIn): """ Read only resource. """ http_PROPPATCH = ReadOnlyWritePropertiesResourceMixIn._forbidden class CachingPropertyStore (object): """ DAV property store using a dict in memory on top of another property store implementation. """ log = Logger() def extractCalendarServerPrincipalSearchData(doc): """ Extract relevant info from a CalendarServerPrincipalSearch document @param doc: CalendarServerPrincipalSearch object to extract info from @return: A tuple containing: the list of tokens the context string the applyTo boolean the clientLimit integer the propElement containing the properties to return """ context = doc.attributes.get("context", None) applyTo = False tokens = [] clientLimit = None for child in doc.children: if child.qname() == (dav_namespace, "prop"): propElement = child elif child.qname() == ( dav_namespace, "apply-to-principal-collection-set" ): applyTo = True elif child.qname() == (calendarserver_namespace, "search-token"): tokenValue = child.toString().strip() if tokenValue: tokens.append(tokenValue) elif child.qname() == (calendarserver_namespace, "limit"): try: nresults = child.childOfType(customxml.NResults) clientLimit = int(str(nresults)) except (TypeError, ValueError,): msg = "Bad XML: unknown value for <limit> element" log.warn(msg) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg)) return tokens, context, applyTo, clientLimit, propElement def validateTokens(tokens): """ Make sure there is at least one token longer than one character @param tokens: the tokens to inspect @type tokens: iterable of utf-8 encoded strings @return: True if tokens are valid, False otherwise @rtype: boolean """ for token in tokens: if len(token) > 1: return True return False
33.967563
153
0.587051
# -*- test-case-name: twistedcaldav.test.test_extensions -*- ## # Copyright (c) 2005-2015 Apple Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## from __future__ import print_function """ Extensions to web2.dav """ __all__ = [ "DAVResource", "DAVResourceWithChildrenMixin", "DAVPrincipalResource", "DAVFile", "ReadOnlyWritePropertiesResourceMixIn", "ReadOnlyResourceMixIn", "CachingPropertyStore", ] import urllib import time from itertools import cycle from twisted.internet.defer import succeed, maybeDeferred from twisted.internet.defer import inlineCallbacks, returnValue from twisted.web.template import Element, XMLFile, renderer, tags, flattenString from twisted.python.modules import getModule from txweb2 import responsecode, server from txweb2.http import HTTPError, Response, RedirectResponse from txweb2.http import StatusResponse from txweb2.http_headers import MimeType from txweb2.stream import FileStream from txweb2.static import MetaDataMixin, StaticRenderMixin from txdav.xml import element from txdav.xml.base import encodeXMLName from txdav.xml.element import dav_namespace from txweb2.dav.http import MultiStatusResponse from txweb2.dav.static import DAVFile as SuperDAVFile from txweb2.dav.resource import DAVResource as SuperDAVResource from txweb2.dav.resource import ( DAVPrincipalResource as SuperDAVPrincipalResource ) from twisted.internet.defer import gatherResults from txweb2.dav.method import prop_common from twext.python.log import Logger from twistedcaldav import customxml from twistedcaldav.customxml import calendarserver_namespace from twistedcaldav.method.report import http_REPORT from twistedcaldav.config import config from txdav.who.directory import CalendarDirectoryRecordMixin from twext.who.expression import Operand, MatchType, MatchFlags thisModule = getModule(__name__) log = Logger() class DirectoryPrincipalPropertySearchMixIn(object): @inlineCallbacks def report_DAV__principal_property_search( self, request, principal_property_search ): """ Generate a principal-property-search REPORT. (RFC 3744, section 9.4) Overrides twisted implementation, targeting only directory-enabled searching. """ # Verify root element if not isinstance(principal_property_search, element.PrincipalPropertySearch): msg = "%s expected as root element, not %s." % (element.PrincipalPropertySearch.sname(), principal_property_search.sname()) log.warn(msg) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg)) # Should we AND (the default) or OR (if test="anyof")? testMode = principal_property_search.attributes.get("test", "allof") if testMode not in ("allof", "anyof"): msg = "Bad XML: unknown value for test attribute: %s" % (testMode,) log.warn(msg) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg)) operand = Operand.AND if testMode == "allof" else Operand.OR # Are we narrowing results down to a single CUTYPE? cuType = principal_property_search.attributes.get("type", None) if cuType not in ("INDIVIDUAL", "GROUP", "RESOURCE", "ROOM", None): msg = "Bad XML: unknown value for type attribute: %s" % (cuType,) log.warn(msg) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg)) # Only handle Depth: 0 depth = request.headers.getHeader("depth", "0") if depth != "0": log.error("Error in principal-property-search REPORT, Depth set to %s" % (depth,)) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, "Depth %s not allowed" % (depth,))) # Get any limit value from xml clientLimit = None # Get a single DAV:prop element from the REPORT request body propertiesForResource = None propElement = None propertySearches = [] applyTo = False for child in principal_property_search.children: if child.qname() == (dav_namespace, "prop"): propertiesForResource = prop_common.propertyListForResource propElement = child elif child.qname() == ( dav_namespace, "apply-to-principal-collection-set" ): applyTo = True elif child.qname() == (dav_namespace, "property-search"): props = child.childOfType(element.PropertyContainer) props.removeWhitespaceNodes() match = child.childOfType(element.Match) caseless = match.attributes.get("caseless", "yes") if caseless not in ("yes", "no"): msg = "Bad XML: unknown value for caseless attribute: %s" % (caseless,) log.warn(msg) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg)) caseless = (caseless == "yes") matchType = match.attributes.get("match-type", u"contains").encode("utf-8") if matchType not in ("starts-with", "contains", "equals"): msg = "Bad XML: unknown value for match-type attribute: %s" % (matchType,) log.warn(msg) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg)) # Convert to twext.who.expression form matchType = { "starts-with": MatchType.startsWith, "contains": MatchType.contains, "equals": MatchType.equals }.get(matchType) matchFlags = MatchFlags.caseInsensitive if caseless else MatchFlags.none # Ignore any query strings under three letters matchText = match.toString() # gives us unicode if len(matchText) >= 3: propertySearches.append((props.children, matchText, matchFlags, matchType)) elif child.qname() == (calendarserver_namespace, "limit"): try: nresults = child.childOfType(customxml.NResults) clientLimit = int(str(nresults)) except (TypeError, ValueError,): msg = "Bad XML: unknown value for <limit> element" log.warn(msg) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg)) # Run report resultsWereLimited = None resources = [] if applyTo or not hasattr(self, "directory"): for principalCollection in self.principalCollections(): uri = principalCollection.principalCollectionURL() resource = (yield request.locateResource(uri)) if resource: resources.append((resource, uri)) else: resources.append((self, request.uri)) # We need to access a directory service principalCollection = resources[0][0] if not hasattr(principalCollection, "directory"): # Use Twisted's implementation instead in this case result = (yield super(DirectoryPrincipalPropertySearchMixIn, self).report_DAV__principal_property_search(request, principal_property_search)) returnValue(result) dir = principalCollection.directory # See if we can take advantage of the directory fields = [] nonDirectorySearches = [] for props, match, matchFlags, matchType in propertySearches: nonDirectoryProps = [] for prop in props: try: fieldName, match = principalCollection.propertyToField( prop, match) except ValueError, e: raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, str(e))) if fieldName: fields.append((fieldName, match, matchFlags, matchType)) else: nonDirectoryProps.append(prop) if nonDirectoryProps: nonDirectorySearches.append(( nonDirectoryProps, match, matchFlags, matchType )) matchingResources = [] matchcount = 0 # nonDirectorySearches are ignored if fields: if cuType: recordType = CalendarDirectoryRecordMixin.fromCUType(cuType) else: recordType = None records = ( yield dir.recordsMatchingFields( fields, operand=operand, recordType=recordType, limitResults=clientLimit, timeoutSeconds=10 ) ) for record in records: resource = yield principalCollection.principalForRecord(record) if resource: matchingResources.append(resource) # We've determined this is a matching resource matchcount += 1 if clientLimit is not None and matchcount >= clientLimit: resultsWereLimited = ("client", matchcount) break if matchcount >= config.MaxPrincipalSearchReportResults: resultsWereLimited = ("server", matchcount) break # Generate the response responses = [] for resource in matchingResources: url = resource.url() yield prop_common.responseForHref( request, responses, element.HRef.fromString(url), resource, propertiesForResource, propElement ) if resultsWereLimited is not None: if resultsWereLimited[0] == "server": log.error("Too many matching resources in principal-property-search report") responses.append(element.StatusResponse( element.HRef.fromString(request.uri), element.Status.fromResponseCode( responsecode.INSUFFICIENT_STORAGE_SPACE ), element.Error(element.NumberOfMatchesWithinLimits()), element.ResponseDescription( "Results limited by %s at %d" % resultsWereLimited ), )) returnValue(MultiStatusResponse(responses)) @inlineCallbacks def report_http___calendarserver_org_ns__calendarserver_principal_search( self, request, calendarserver_principal_search ): """ Generate a calendarserver-principal-search REPORT. @param request: Request object @param calendarserver_principal_search: CalendarServerPrincipalSearch object """ # Verify root element if not isinstance(calendarserver_principal_search, customxml.CalendarServerPrincipalSearch): msg = "%s expected as root element, not %s." % (customxml.CalendarServerPrincipalSearch.sname(), calendarserver_principal_search.sname()) log.warn(msg) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg)) # Only handle Depth: 0 depth = request.headers.getHeader("depth", "0") if depth != "0": log.error("Error in calendarserver-principal-search REPORT, Depth set to %s" % (depth,)) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, "Depth %s not allowed" % (depth,))) tokens, context, applyTo, clientLimit, propElement = extractCalendarServerPrincipalSearchData(calendarserver_principal_search) if not validateTokens(tokens): raise HTTPError(StatusResponse( responsecode.FORBIDDEN, "Insufficient search token length" )) # Run report resultsWereLimited = None resources = [] if applyTo or not hasattr(self, "directory"): for principalCollection in self.principalCollections(): uri = principalCollection.principalCollectionURL() resource = (yield request.locateResource(uri)) if resource: resources.append((resource, uri)) else: resources.append((self, request.uri)) # We need to access a directory service principalCollection = resources[0][0] dir = principalCollection.directory matchingResources = [] matchcount = 0 limitResults = config.MaxPrincipalSearchReportResults if clientLimit is not None: limitResults = min(clientLimit, limitResults) records = (yield dir.recordsMatchingTokens( tokens, context=context, limitResults=limitResults, timeoutSeconds=10 )) for record in records: resource = yield principalCollection.principalForRecord(record) if resource: matchingResources.append(resource) # We've determined this is a matching resource matchcount += 1 if clientLimit is not None and matchcount >= clientLimit: resultsWereLimited = ("client", matchcount) break if matchcount >= config.MaxPrincipalSearchReportResults: resultsWereLimited = ("server", matchcount) break # Generate the response responses = [] for resource in matchingResources: url = resource.url() yield prop_common.responseForHref( request, responses, element.HRef.fromString(url), resource, prop_common.propertyListForResource, propElement ) if resultsWereLimited is not None: if resultsWereLimited[0] == "server": log.error("Too many matching resources in calendarserver-principal-search report") responses.append(element.StatusResponse( element.HRef.fromString(request.uri), element.Status.fromResponseCode( responsecode.INSUFFICIENT_STORAGE_SPACE ), element.Error(element.NumberOfMatchesWithinLimits()), element.ResponseDescription( "Results limited by %s at %d" % resultsWereLimited ), )) returnValue(MultiStatusResponse(responses)) class DirectoryElement(Element): """ A L{DirectoryElement} is an L{Element} for rendering the contents of a L{DirectoryRenderingMixIn} resource as HTML. """ loader = XMLFile( thisModule.filePath.sibling("directory-listing.html") ) def __init__(self, resource): """ @param resource: the L{DirectoryRenderingMixIn} resource being listed. """ super(DirectoryElement, self).__init__() self.resource = resource @renderer def resourceDetail(self, request, tag): """ Renderer which returns a distinct element for this resource's data. Subclasses should override. """ return '' @renderer def children(self, request, tag): """ Renderer which yields all child object tags as table rows. """ whenChildren = ( maybeDeferred(self.resource.listChildren) .addCallback(sorted) .addCallback( lambda names: gatherResults( [maybeDeferred(self.resource.getChild, x) for x in names] ) .addCallback(lambda children: zip(children, names)) ) ) @whenChildren.addCallback def gotChildren(children): for even, [child, name] in zip(cycle(["odd", "even"]), children): [url, name, size, lastModified, contentType] = map( str, self.resource.getChildDirectoryEntry( child, name, request) ) yield tag.clone().fillSlots( url=url, name=name, size=str(size), lastModified=lastModified, even=even, type=contentType, ) return whenChildren @renderer def main(self, request, tag): """ Main renderer; fills slots for title, etc. """ return tag.fillSlots(name=request.path) @renderer def properties(self, request, tag): """ Renderer which yields all properties as table row tags. """ whenPropertiesListed = self.resource.listProperties(request) @whenPropertiesListed.addCallback def gotProperties(qnames): accessDeniedValue = object() def gotError(f, name): f.trap(HTTPError) code = f.value.response.code if code == responsecode.NOT_FOUND: log.error("Property {p} was returned by listProperties() " "but does not exist for resource {r}.", p=name, r=self.resource) return (name, None) if code == responsecode.UNAUTHORIZED: return (name, accessDeniedValue) return f whenAllProperties = gatherResults([ maybeDeferred(self.resource.readProperty, qn, request) .addCallback(lambda p, iqn=qn: (p.sname(), p.toxml()) if p is not None else (encodeXMLName(*iqn), None)) .addErrback(gotError, encodeXMLName(*qn)) for qn in sorted(qnames) ]) @whenAllProperties.addCallback def gotValues(items): for even, [name, value] in zip(cycle(["odd", "even"]), items): if value is None: value = tags.i("(no value)") elif value is accessDeniedValue: value = tags.i("(access forbidden)") yield tag.clone().fillSlots( even=even, name=name, value=value, ) return whenAllProperties return whenPropertiesListed class DirectoryRenderingMixIn(object): def renderDirectory(self, request): """ Render a directory listing. """ def gotBody(output): mime_params = {"charset": "utf-8"} response = Response(200, {}, output) response.headers.setHeader( "content-type", MimeType("text", "html", mime_params) ) return response return flattenString(request, self.htmlElement()).addCallback(gotBody) def htmlElement(self): """ Create a L{DirectoryElement} or appropriate subclass for rendering this resource. """ return DirectoryElement(self) def getChildDirectoryEntry(self, child, name, request): def orNone(value, default="?", f=None): if value is None: return default elif f is not None: return f(value) else: return value url = urllib.quote(name, '/') if isinstance(child, DAVResource) and child.isCollection(): url += "/" name += "/" if isinstance(child, MetaDataMixin): size = child.contentLength() lastModified = child.lastModified() rtypes = [] fullrtype = child.resourceType() if hasattr(child, "resourceType") else None if fullrtype is not None: for rtype in fullrtype.children: rtypes.append(rtype.name) if rtypes: rtypes = "(%s)" % (", ".join(rtypes),) if child.isCollection() if hasattr(child, "isCollection") else False: contentType = rtypes else: mimeType = child.contentType() if mimeType is None: print('BAD contentType() IMPLEMENTATION', child) contentType = 'application/octet-stream' else: contentType = "%s/%s" % (mimeType.mediaType, mimeType.mediaSubtype) if rtypes: contentType += " %s" % (rtypes,) else: size = None lastModified = None contentType = None if hasattr(child, "resourceType"): rtypes = [] fullrtype = child.resourceType() for rtype in fullrtype.children: rtypes.append(rtype.name) if rtypes: contentType = "(%s)" % (", ".join(rtypes),) return ( url, name, orNone(size), orNone( lastModified, default="", f=lambda t: time.strftime("%Y-%b-%d %H:%M", time.localtime(t)) ), contentType, ) class DAVResource (DirectoryPrincipalPropertySearchMixIn, SuperDAVResource, DirectoryRenderingMixIn, StaticRenderMixin): """ Extended L{txweb2.dav.resource.DAVResource} implementation. Note we add StaticRenderMixin as a base class because we need all the etag etc behavior that is currently in static.py but is actually applicable to any type of resource. """ log = Logger() http_REPORT = http_REPORT def davComplianceClasses(self): return ("1", "access-control") # Add "2" when we have locking def render(self, request): if not self.exists(): return responsecode.NOT_FOUND if self.isCollection(): return self.renderDirectory(request) return super(DAVResource, self).render(request) def resourceType(self): # Allow live property to be overridden by dead property if self.deadProperties().contains((dav_namespace, "resourcetype")): return self.deadProperties().get((dav_namespace, "resourcetype")) return element.ResourceType(element.Collection()) if self.isCollection() else element.ResourceType() def contentType(self): return MimeType("httpd", "unix-directory") if self.isCollection() else None class DAVResourceWithChildrenMixin (object): """ Bits needed from txweb2.static """ def __init__(self, principalCollections=None): self.putChildren = {} super(DAVResourceWithChildrenMixin, self).__init__(principalCollections=principalCollections) def putChild(self, name, child): """ Register a child with the given name with this resource. @param name: the name of the child (a URI path segment) @param child: the child to register """ self.putChildren[name] = child def getChild(self, name): """ Look up a child resource. First check C{self.putChildren}, then call C{self.makeChild} if no pre-existing children were found. @return: the child of this resource with the given name. """ if name == "": return self result = self.putChildren.get(name, None) if not result: result = self.makeChild(name) return result def makeChild(self, name): """ Called by L{DAVResourceWithChildrenMixin.getChild} to dynamically create children that have not been pre-created with C{putChild}. """ return None def listChildren(self): """ @return: a sequence of the names of all known children of this resource. """ return self.putChildren.keys() def countChildren(self): """ @return: the number of all known children of this resource. """ return len(self.putChildren.keys()) def locateChild(self, req, segments): """ See L{IResource.locateChild}. """ thisSegment = segments[0] moreSegments = segments[1:] return maybeDeferred(self.getChild, thisSegment).addCallback( lambda it: (it, moreSegments) ) class DAVResourceWithoutChildrenMixin (object): """ Bits needed from txweb2.static """ def __init__(self, principalCollections=None): self.putChildren = {} super(DAVResourceWithChildrenMixin, self).__init__(principalCollections=principalCollections) def findChildren( self, depth, request, callback, privileges=None, inherited_aces=None ): return succeed(None) def locateChild(self, request, segments): return self, server.StopTraversal class DAVPrincipalResource (DirectoryPrincipalPropertySearchMixIn, SuperDAVPrincipalResource, DirectoryRenderingMixIn): """ Extended L{txweb2.dav.static.DAVFile} implementation. """ log = Logger() def liveProperties(self): return super(DAVPrincipalResource, self).liveProperties() + ( (calendarserver_namespace, "expanded-group-member-set"), (calendarserver_namespace, "expanded-group-membership"), (calendarserver_namespace, "record-type"), ) http_REPORT = http_REPORT def render(self, request): if not self.exists(): return responsecode.NOT_FOUND if self.isCollection(): return self.renderDirectory(request) return super(DAVResource, self).render(request) @inlineCallbacks def readProperty(self, property, request): if type(property) is tuple: qname = property else: qname = property.qname() namespace, name = qname if namespace == dav_namespace: if name == "resourcetype": rtype = self.resourceType() returnValue(rtype) elif namespace == calendarserver_namespace: if name == "expanded-group-member-set": principals = (yield self.expandedGroupMembers()) returnValue(customxml.ExpandedGroupMemberSet( *[element.HRef(p.principalURL()) for p in principals] )) elif name == "expanded-group-membership": principals = (yield self.expandedGroupMemberships()) returnValue(customxml.ExpandedGroupMembership( *[element.HRef(p.principalURL()) for p in principals] )) elif name == "record-type": if hasattr(self, "record"): returnValue( customxml.RecordType( self.record.service.recordTypeToOldName( self.record.recordType ) ) ) else: raise HTTPError(StatusResponse( responsecode.NOT_FOUND, "Property %s does not exist." % (qname,) )) result = (yield super(DAVPrincipalResource, self).readProperty(property, request)) returnValue(result) def groupMembers(self): return succeed(()) def expandedGroupMembers(self): return succeed(()) def groupMemberships(self): return succeed(()) def expandedGroupMemberships(self): return succeed(()) def resourceType(self): # Allow live property to be overridden by dead property if self.deadProperties().contains((dav_namespace, "resourcetype")): return self.deadProperties().get((dav_namespace, "resourcetype")) if self.isCollection(): return element.ResourceType(element.Principal(), element.Collection()) else: return element.ResourceType(element.Principal()) class DAVFile (SuperDAVFile, DirectoryRenderingMixIn): """ Extended L{txweb2.dav.static.DAVFile} implementation. """ log = Logger() def resourceType(self): # Allow live property to be overridden by dead property if self.deadProperties().contains((dav_namespace, "resourcetype")): return self.deadProperties().get((dav_namespace, "resourcetype")) if self.isCollection(): return element.ResourceType.collection #@UndefinedVariable return element.ResourceType.empty #@UndefinedVariable def render(self, request): if not self.fp.exists(): return responsecode.NOT_FOUND if self.fp.isdir(): if request.path[-1] != "/": # Redirect to include trailing '/' in URI return RedirectResponse(request.unparseURL(path=urllib.quote(urllib.unquote(request.path), safe=':/') + '/')) else: ifp = self.fp.childSearchPreauth(*self.indexNames) if ifp: # Render from the index file return self.createSimilarFile(ifp.path).render(request) return self.renderDirectory(request) try: f = self.fp.open() except IOError, e: import errno if e[0] == errno.EACCES: return responsecode.FORBIDDEN elif e[0] == errno.ENOENT: return responsecode.NOT_FOUND else: raise response = Response() response.stream = FileStream(f, 0, self.fp.getsize()) for (header, value) in ( ("content-type", self.contentType()), ("content-encoding", self.contentEncoding()), ): if value is not None: response.headers.setHeader(header, value) return response class ReadOnlyWritePropertiesResourceMixIn (object): """ Read only that will allow writing of properties resource. """ readOnlyResponse = StatusResponse( responsecode.FORBIDDEN, "Resource is read only." ) def _forbidden(self, request): return self.readOnlyResponse http_DELETE = _forbidden http_MOVE = _forbidden http_PUT = _forbidden class ReadOnlyResourceMixIn (ReadOnlyWritePropertiesResourceMixIn): """ Read only resource. """ http_PROPPATCH = ReadOnlyWritePropertiesResourceMixIn._forbidden def writeProperty(self, property, request): raise HTTPError(self.readOnlyResponse) def accessControlList( self, request, inheritance=True, expanding=False, inherited_aces=None ): # Permissions here are fixed, and are not subject to # inheritance rules, etc. return self.defaultAccessControlList() class PropertyNotFoundError (HTTPError): def __init__(self, qname): HTTPError.__init__( self, StatusResponse( responsecode.NOT_FOUND, "No such property: %s" % encodeXMLName(*qname) ) ) class CachingPropertyStore (object): """ DAV property store using a dict in memory on top of another property store implementation. """ log = Logger() def __init__(self, propertyStore): self.propertyStore = propertyStore self.resource = propertyStore.resource def get(self, qname, uid=None): # self.log.debug("Get: %r, %r" % (self.resource.fp.path, qname)) cache = self._cache() cachedQname = qname + (uid,) if cachedQname in cache: property = cache.get(cachedQname, None) if property is None: self.log.debug("Cache miss: %r, %r, %r" % (self, self.resource.fp.path, qname)) try: property = self.propertyStore.get(qname, uid) except HTTPError: del cache[cachedQname] raise PropertyNotFoundError(qname) cache[cachedQname] = property return property else: raise PropertyNotFoundError(qname) def set(self, property, uid=None): # self.log.debug("Set: %r, %r" % (self.resource.fp.path, property)) cache = self._cache() cachedQname = property.qname() + (uid,) cache[cachedQname] = None self.propertyStore.set(property, uid) cache[cachedQname] = property def contains(self, qname, uid=None): # self.log.debug("Contains: %r, %r" % (self.resource.fp.path, qname)) cachedQname = qname + (uid,) try: cache = self._cache() except HTTPError, e: if e.response.code == responsecode.NOT_FOUND: return False else: raise if cachedQname in cache: # self.log.debug("Contains cache hit: %r, %r, %r" % (self, self.resource.fp.path, qname)) return True else: return False def delete(self, qname, uid=None): # self.log.debug("Delete: %r, %r" % (self.resource.fp.path, qname)) cachedQname = qname + (uid,) if self._data is not None and cachedQname in self._data: del self._data[cachedQname] self.propertyStore.delete(qname, uid) def list(self, uid=None, filterByUID=True): # self.log.debug("List: %r" % (self.resource.fp.path,)) keys = self._cache().iterkeys() if filterByUID: return [ (namespace, name) for namespace, name, propuid in keys if propuid == uid ] else: return keys def _cache(self): if not hasattr(self, "_data"): # self.log.debug("Cache init: %r" % (self.resource.fp.path,)) self._data = dict( (name, None) for name in self.propertyStore.list(filterByUID=False) ) return self._data def extractCalendarServerPrincipalSearchData(doc): """ Extract relevant info from a CalendarServerPrincipalSearch document @param doc: CalendarServerPrincipalSearch object to extract info from @return: A tuple containing: the list of tokens the context string the applyTo boolean the clientLimit integer the propElement containing the properties to return """ context = doc.attributes.get("context", None) applyTo = False tokens = [] clientLimit = None for child in doc.children: if child.qname() == (dav_namespace, "prop"): propElement = child elif child.qname() == ( dav_namespace, "apply-to-principal-collection-set" ): applyTo = True elif child.qname() == (calendarserver_namespace, "search-token"): tokenValue = child.toString().strip() if tokenValue: tokens.append(tokenValue) elif child.qname() == (calendarserver_namespace, "limit"): try: nresults = child.childOfType(customxml.NResults) clientLimit = int(str(nresults)) except (TypeError, ValueError,): msg = "Bad XML: unknown value for <limit> element" log.warn(msg) raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, msg)) return tokens, context, applyTo, clientLimit, propElement def validateTokens(tokens): """ Make sure there is at least one token longer than one character @param tokens: the tokens to inspect @type tokens: iterable of utf-8 encoded strings @return: True if tokens are valid, False otherwise @rtype: boolean """ for token in tokens: if len(token) > 1: return True return False
12,989
13,301
910
1ec186044470a12f22d40759ef34223c5f8b558c
1,428
py
Python
apps/product/urls.py
asmuratbek/oobamarket
1053976a13ea84b9aabfcbbcbcffd79549ce9538
[ "MIT" ]
null
null
null
apps/product/urls.py
asmuratbek/oobamarket
1053976a13ea84b9aabfcbbcbcffd79549ce9538
[ "MIT" ]
7
2020-06-05T23:36:01.000Z
2022-01-13T01:42:07.000Z
apps/product/urls.py
asmuratbek/oobamarket
1053976a13ea84b9aabfcbbcbcffd79549ce9538
[ "MIT" ]
null
null
null
from django.conf.urls import url, include from .views import ProductCreateView, ProductUpdateView, ProductIndexCreateView, upload_images, \ remove_uploaded_image, ProductDeleteView, change_publish_status, upload_images_product_update, \ delete_product_images, add_product_review, ProductListView, update_product_review, ProductDetailView, delete_product urlpatterns = [ url(r'^$', ProductDetailView.as_view(), name='product_detail'), url(r'^all/$', ProductListView.as_view(), name='product_list'), url(r'^(?P<slug>[\w-]+)/add-product/$', ProductCreateView.as_view(), name='add_product'), url(r'^(?P<slug>[\w-]+)/update-product/$', ProductUpdateView.as_view(), name='update_product'), url(r'^(?P<slug>[\w-]+)/upload-product-images/$', upload_images_product_update, name='upload_product_images'), url(r'^(?P<slug>[\w-]+)/delete-product/$', delete_product, name='delete_product'), url(r'^add-product/$', ProductIndexCreateView.as_view(), name='add_product_index'), url(r'^delete-product-images/$', delete_product_images, name='delete_product_images'), url(r'^upload/images/$', upload_images, name='upload_images'), url(r'^remove/images/$', remove_uploaded_image, name='remove_images'), url(r'^(?P<slug>[\w-]+)/add-review/$', add_product_review, name='add_review'), url(r'^(?P<slug>[\w-]+)/update-review/(?P<pk>[0-9]+)/$$', update_product_review, name='update_review'), ]
62.086957
120
0.716387
from django.conf.urls import url, include from .views import ProductCreateView, ProductUpdateView, ProductIndexCreateView, upload_images, \ remove_uploaded_image, ProductDeleteView, change_publish_status, upload_images_product_update, \ delete_product_images, add_product_review, ProductListView, update_product_review, ProductDetailView, delete_product urlpatterns = [ url(r'^$', ProductDetailView.as_view(), name='product_detail'), url(r'^all/$', ProductListView.as_view(), name='product_list'), url(r'^(?P<slug>[\w-]+)/add-product/$', ProductCreateView.as_view(), name='add_product'), url(r'^(?P<slug>[\w-]+)/update-product/$', ProductUpdateView.as_view(), name='update_product'), url(r'^(?P<slug>[\w-]+)/upload-product-images/$', upload_images_product_update, name='upload_product_images'), url(r'^(?P<slug>[\w-]+)/delete-product/$', delete_product, name='delete_product'), url(r'^add-product/$', ProductIndexCreateView.as_view(), name='add_product_index'), url(r'^delete-product-images/$', delete_product_images, name='delete_product_images'), url(r'^upload/images/$', upload_images, name='upload_images'), url(r'^remove/images/$', remove_uploaded_image, name='remove_images'), url(r'^(?P<slug>[\w-]+)/add-review/$', add_product_review, name='add_review'), url(r'^(?P<slug>[\w-]+)/update-review/(?P<pk>[0-9]+)/$$', update_product_review, name='update_review'), ]
0
0
0
c45f7fea9fc7283439b8d96051094b0a4149e1ec
1,133
py
Python
account/acct.py
dahanhan/Ad-Insertion-Sample
12019c70a95f1d83d792e7e03d1dd5f732630558
[ "BSD-3-Clause" ]
82
2019-04-07T04:27:47.000Z
2022-02-04T07:35:58.000Z
account/acct.py
dahanhan/Ad-Insertion-Sample
12019c70a95f1d83d792e7e03d1dd5f732630558
[ "BSD-3-Clause" ]
43
2019-04-04T22:03:02.000Z
2020-08-25T10:11:44.000Z
account/acct.py
dahanhan/Ad-Insertion-Sample
12019c70a95f1d83d792e7e03d1dd5f732630558
[ "BSD-3-Clause" ]
54
2019-04-04T23:27:05.000Z
2022-01-30T14:27:16.000Z
#!/usr/bin/python3 from tornado import web import random
33.323529
199
0.533098
#!/usr/bin/python3 from tornado import web import random class AcctHandler(web.RequestHandler): def __init__(self, app, request, **kwargs): super(AcctHandler, self).__init__(app, request, **kwargs) self._users={ "guest": { "subscription": "basic", "ad-preference": "any", }, "default": { "subscription": "universal", "ad-preference": "any", }, } random.seed() for name in ["sophia","emma","isabella","olivia","ava","emily","abigail","mia","madison","elizabeth","sophia","emma","isabella","olivia","ava","emily","abigail","mia","madison","elizabeth"]: self._users[name]={ "subscription": "universal", "ad-preference": ["sports","family"][int(random.random())%2], } def check_origin(self, origin): return True def get(self): name = str(self.get_argument("name")).lower() if name not in self._users: name="default" self.set_status(200,"OK") self.write(self._users[name])
955
17
103
d11f0cf6415d468e14983474a46033013201acd7
504
py
Python
src/clientsubscription/urls.py
kaizer88/moltrandashboad
590b3426ecc3a80aa31a08eb07bed224d0c2562d
[ "MIT" ]
null
null
null
src/clientsubscription/urls.py
kaizer88/moltrandashboad
590b3426ecc3a80aa31a08eb07bed224d0c2562d
[ "MIT" ]
4
2021-04-08T22:01:45.000Z
2021-09-22T19:50:53.000Z
src/clientsubscription/urls.py
kaizer88/moltrandashboad
590b3426ecc3a80aa31a08eb07bed224d0c2562d
[ "MIT" ]
null
null
null
from django.urls import path from .views import clients, edit_client, edit_client_plan urlpatterns = [ path('clients', clients, name='clients'), path('add_client', edit_client, name='add_client'), path('add_client_plan', edit_client_plan, name='add_client_plan'), path('edit_client/<id>', edit_client, name='edit_client'), # path('add_client_plan', edit_client_plan, name='add_client_plan'), path('update_subscription/<id>', edit_client_plan, name='update_subscription'), ]
29.647059
83
0.728175
from django.urls import path from .views import clients, edit_client, edit_client_plan urlpatterns = [ path('clients', clients, name='clients'), path('add_client', edit_client, name='add_client'), path('add_client_plan', edit_client_plan, name='add_client_plan'), path('edit_client/<id>', edit_client, name='edit_client'), # path('add_client_plan', edit_client_plan, name='add_client_plan'), path('update_subscription/<id>', edit_client_plan, name='update_subscription'), ]
0
0
0
1374c32f5067399da6487fb75c2e6f20e0f54694
2,522
py
Python
policy/stale_issue_policy.py
kskewes-sf/spinnakerbot
32a7ad75a0c12e09498d24fe0cc8dd1b810bd6f7
[ "Apache-2.0" ]
6
2020-03-18T10:33:53.000Z
2021-05-02T01:58:10.000Z
policy/stale_issue_policy.py
kskewes-sf/spinnakerbot
32a7ad75a0c12e09498d24fe0cc8dd1b810bd6f7
[ "Apache-2.0" ]
8
2020-03-28T23:01:00.000Z
2020-12-01T06:52:00.000Z
policy/stale_issue_policy.py
kskewes-sf/spinnakerbot
32a7ad75a0c12e09498d24fe0cc8dd1b810bd6f7
[ "Apache-2.0" ]
10
2020-02-05T16:24:28.000Z
2022-03-17T21:37:36.000Z
from datetime import datetime import github.Issue from gh import HasLabel, AddLabel from .policy import Policy StaleIssuePolicy()
37.088235
104
0.593973
from datetime import datetime import github.Issue from gh import HasLabel, AddLabel from .policy import Policy class StaleIssuePolicy(Policy): def __init__(self): super().__init__() self.stale_days = self.config.get('stale_days') self.ignore_lifecycle_label = self.config.get('ignore_lifecycle_label', 'no-lifecycle') self.beginner_friendly_label = self.config.get('beginner_friendly_label', 'beginner friendly') self.count = 0 if not self.stale_days: self.stale_days = 45 def applies(self, o: github.Issue.Issue): return o.html_url.split('/')[-2] == 'issues' def apply(self, g, o: github.Issue.Issue): days_since_created = None days_since_updated = None now = datetime.now() if o.state == 'closed': return if o.created_at is not None: days_since_created = (now - o.created_at).days else: return if days_since_created < self.stale_days: return if o.updated_at is not None: days_since_updated = (now - o.updated_at).days else: return if days_since_updated < self.stale_days: return if HasLabel(o, self.ignore_lifecycle_label) or HasLabel(o, self.beginner_friendly_label): return if HasLabel(o, 'to-be-closed'): o.create_comment("This issue is tagged as 'to-be-closed' and hasn't been updated " + " in {} days, ".format(days_since_updated) + "so we are closing it. You can always reopen this issue if needed.") o.edit(state='closed') elif HasLabel(o, 'stale'): o.create_comment("This issue is tagged as 'stale' and hasn't been updated " + " in {} days, ".format(days_since_updated) + "so we are tagging it as 'to-be-closed'. It will be closed " + "in {} days unless updates are made. ".format(self.stale_days) + "If you want to remove this label, comment:\n\n" + "> @spinnakerbot remove-label to-be-closed") AddLabel(g, o, 'to-be-closed') else: o.create_comment("This issue hasn't been updated in {} days, ".format(days_since_updated) + "so we are tagging it as 'stale'. If you want to remove this label, comment:\n\n" + "> @spinnakerbot remove-label stale") AddLabel(g, o, 'stale') StaleIssuePolicy()
2,275
10
103
8e6e30b241b821e6cd24440aa8eac536f1de48b0
385
py
Python
cogbot/cogs/robo_mod/conditions/author_is_not_self.py
Arcensoth/cogbot
ef9d935ae8c8fbe00fb9370c75e0e6d9189141d0
[ "MIT" ]
8
2016-12-26T14:10:38.000Z
2021-01-02T03:50:05.000Z
cogbot/cogs/robo_mod/conditions/author_is_not_self.py
Arcensoth/cogbot
ef9d935ae8c8fbe00fb9370c75e0e6d9189141d0
[ "MIT" ]
28
2016-12-12T04:06:53.000Z
2020-04-23T06:18:55.000Z
cogbot/cogs/robo_mod/conditions/author_is_not_self.py
Arcensoth/cogbot
ef9d935ae8c8fbe00fb9370c75e0e6d9189141d0
[ "MIT" ]
9
2017-06-03T00:33:57.000Z
2020-10-29T18:16:02.000Z
from cogbot.cogs.robo_mod.robo_mod_condition import RoboModCondition from cogbot.cogs.robo_mod.robo_mod_trigger import RoboModTrigger
35
68
0.771429
from cogbot.cogs.robo_mod.robo_mod_condition import RoboModCondition from cogbot.cogs.robo_mod.robo_mod_trigger import RoboModTrigger class AuthorIsNotSelfCondition(RoboModCondition): async def update(self, state: "RoboModServerState", data: dict): pass async def check(self, trigger: RoboModTrigger) -> bool: return trigger.bot.user.id != trigger.author.id
146
28
76
f677cf2975804dbb775573b4329825da1295a53d
3,794
py
Python
rkqc/tools/gui/ui/PLAFile.py
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
158
2016-07-21T10:45:05.000Z
2022-03-25T00:56:20.000Z
rkqc/tools/gui/ui/PLAFile.py
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
35
2016-07-25T01:23:07.000Z
2021-09-27T16:05:50.000Z
rkqc/tools/gui/ui/PLAFile.py
clairechingching/ScaffCC
737ae90f85d9fe79819d66219747d27efa4fa5b9
[ "BSD-2-Clause" ]
62
2016-08-29T17:28:11.000Z
2021-12-29T17:55:58.000Z
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'PLAFile.ui' # # Created: Fri Jun 10 09:11:23 2011 # by: PyQt4 UI code generator 4.8.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s from core.SpecificationTable import SpecificationTable
49.921053
129
0.718239
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'PLAFile.ui' # # Created: Fri Jun 10 09:11:23 2011 # by: PyQt4 UI code generator 4.8.3 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_PLAFile(object): def setupUi(self, PLAFile): PLAFile.setObjectName(_fromUtf8("PLAFile")) PLAFile.resize(549, 469) PLAFile.setWindowTitle(_fromUtf8("")) self.horizontalLayout = QtGui.QHBoxLayout(PLAFile) self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout")) self.splitter = QtGui.QSplitter(PLAFile) self.splitter.setOrientation(QtCore.Qt.Horizontal) self.splitter.setObjectName(_fromUtf8("splitter")) self.filename = SpecificationTable(self.splitter) self.filename.setObjectName(_fromUtf8("filename")) self.filename.setColumnCount(0) self.filename.setRowCount(0) self.widget = QtGui.QWidget(self.splitter) self.widget.setObjectName(_fromUtf8("widget")) self.verticalLayout = QtGui.QVBoxLayout(self.widget) self.verticalLayout.setMargin(0) self.verticalLayout.setObjectName(_fromUtf8("verticalLayout")) self.groupBox = QtGui.QGroupBox(self.widget) self.groupBox.setObjectName(_fromUtf8("groupBox")) self.formLayout = QtGui.QFormLayout(self.groupBox) self.formLayout.setObjectName(_fromUtf8("formLayout")) self.label = QtGui.QLabel(self.groupBox) self.label.setObjectName(_fromUtf8("label")) self.formLayout.setWidget(0, QtGui.QFormLayout.LabelRole, self.label) self.numInputs = QtGui.QLabel(self.groupBox) self.numInputs.setText(_fromUtf8("")) self.numInputs.setObjectName(_fromUtf8("numInputs")) self.formLayout.setWidget(0, QtGui.QFormLayout.FieldRole, self.numInputs) self.label_2 = QtGui.QLabel(self.groupBox) self.label_2.setObjectName(_fromUtf8("label_2")) self.formLayout.setWidget(1, QtGui.QFormLayout.LabelRole, self.label_2) self.numOutputs = QtGui.QLabel(self.groupBox) self.numOutputs.setText(_fromUtf8("")) self.numOutputs.setObjectName(_fromUtf8("numOutputs")) self.formLayout.setWidget(1, QtGui.QFormLayout.FieldRole, self.numOutputs) self.label_3 = QtGui.QLabel(self.groupBox) self.label_3.setObjectName(_fromUtf8("label_3")) self.formLayout.setWidget(2, QtGui.QFormLayout.LabelRole, self.label_3) self.numCubes = QtGui.QLabel(self.groupBox) self.numCubes.setText(_fromUtf8("")) self.numCubes.setObjectName(_fromUtf8("numCubes")) self.formLayout.setWidget(2, QtGui.QFormLayout.FieldRole, self.numCubes) self.verticalLayout.addWidget(self.groupBox) spacerItem = QtGui.QSpacerItem(20, 356, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding) self.verticalLayout.addItem(spacerItem) self.horizontalLayout.addWidget(self.splitter) self.retranslateUi(PLAFile) QtCore.QMetaObject.connectSlotsByName(PLAFile) def retranslateUi(self, PLAFile): self.groupBox.setTitle(QtGui.QApplication.translate("PLAFile", "Information", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("PLAFile", "Number of Inputs:", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("PLAFile", "Number of Outputs:", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("PLAFile", "Number of Cubes:", None, QtGui.QApplication.UnicodeUTF8)) from core.SpecificationTable import SpecificationTable
3,301
4
76
1ad9a1e9d74f0a233755e761f044ec5a30b35931
1,492
py
Python
idVaildator/core/tests.py
aboueleyes/id-validator
29ecf517516921f92e9eee85b6f97078a8334509
[ "MIT" ]
6
2022-03-17T21:18:52.000Z
2022-03-18T15:57:35.000Z
idVaildator/core/tests.py
aboueleyes/id-validator
29ecf517516921f92e9eee85b6f97078a8334509
[ "MIT" ]
2
2022-03-17T20:49:27.000Z
2022-03-17T22:37:57.000Z
idVaildator/core/tests.py
aboueleyes/id-validator
29ecf517516921f92e9eee85b6f97078a8334509
[ "MIT" ]
null
null
null
import datetime import unittest from .EgyptianNationalId import EgyptianNationalId VALID_ID = "30103211203135" if __name__ == "__main__": unittest.main()
28.692308
66
0.656836
import datetime import unittest from .EgyptianNationalId import EgyptianNationalId VALID_ID = "30103211203135" class TestNationalId(unittest.TestCase): def setUp(self) -> None: self.id = EgyptianNationalId(VALID_ID) def test_validaty(self): id_2 = "abc123" id_3 = "301031120135" id_4 = "4010311203135" id_5 = "30103214403135" with self.assertRaises(ValueError): EgyptianNationalId(id_2) with self.assertRaises(ValueError): EgyptianNationalId(id_3) with self.assertRaises(ValueError): EgyptianNationalId(id_4) with self.assertRaises(ValueError): EgyptianNationalId(id_5) self.assertEqual(self.id.is_valid(), True) def test_gender(self): id_female = EgyptianNationalId("29501023201922") self.assertEqual(self.id.fields["gender"], "Male") self.assertEqual(id_female.fields["gender"], "Female") def test_governarate(self): self.assertEqual(self.id.fields["governrate"], "Dakahlia") def test_birthday(self): self.assertEqual(self.id.fields["birthDate"], datetime.datetime(2001, 3, 21).date()) def test_century(self): self.assertTrue(2002 in self.id.birth_century_range) def test_century_old(self): id = EgyptianNationalId("20103211203134") self.assertTrue(id.fields["birthDate"].year, 1901) if __name__ == "__main__": unittest.main()
1,098
19
212
14651715e8f22cb30846c42b99b85c2b58ee6a19
1,333
py
Python
train.py
tom-doerr/Hindsight-Goal-Generation
3abd832bcd484da62dcbc72296f9435a3d55397d
[ "MIT" ]
20
2019-09-25T21:20:59.000Z
2021-12-08T08:32:01.000Z
train.py
tom-doerr/Hindsight-Goal-Generation
3abd832bcd484da62dcbc72296f9435a3d55397d
[ "MIT" ]
2
2020-01-09T02:52:56.000Z
2021-05-14T13:23:18.000Z
train.py
tom-doerr/Hindsight-Goal-Generation
3abd832bcd484da62dcbc72296f9435a3d55397d
[ "MIT" ]
10
2019-12-19T15:37:15.000Z
2022-03-24T17:21:41.000Z
import numpy as np import time from common import get_args,experiment_setup if __name__=='__main__': args = get_args() env, env_test, agent, buffer, learner, tester = experiment_setup(args) args.logger.summary_init(agent.graph, agent.sess) # Progress info args.logger.add_item('Epoch') args.logger.add_item('Cycle') args.logger.add_item('Episodes@green') args.logger.add_item('Timesteps') args.logger.add_item('TimeCost(sec)') # Algorithm info for key in agent.train_info.keys(): args.logger.add_item(key, 'scalar') # Test info for key in tester.info: args.logger.add_item(key, 'scalar') args.logger.summary_setup() for epoch in range(args.epochs): for cycle in range(args.cycles): args.logger.tabular_clear() args.logger.summary_clear() start_time = time.time() learner.learn(args, env, env_test, agent, buffer) tester.cycle_summary() args.logger.add_record('Epoch', str(epoch)+'/'+str(args.epochs)) args.logger.add_record('Cycle', str(cycle)+'/'+str(args.cycles)) args.logger.add_record('Episodes', buffer.counter) args.logger.add_record('Timesteps', buffer.steps_counter) args.logger.add_record('TimeCost(sec)', time.time()-start_time) args.logger.tabular_show(args.tag) args.logger.summary_show(buffer.counter) tester.epoch_summary() tester.final_summary()
27.204082
71
0.736684
import numpy as np import time from common import get_args,experiment_setup if __name__=='__main__': args = get_args() env, env_test, agent, buffer, learner, tester = experiment_setup(args) args.logger.summary_init(agent.graph, agent.sess) # Progress info args.logger.add_item('Epoch') args.logger.add_item('Cycle') args.logger.add_item('Episodes@green') args.logger.add_item('Timesteps') args.logger.add_item('TimeCost(sec)') # Algorithm info for key in agent.train_info.keys(): args.logger.add_item(key, 'scalar') # Test info for key in tester.info: args.logger.add_item(key, 'scalar') args.logger.summary_setup() for epoch in range(args.epochs): for cycle in range(args.cycles): args.logger.tabular_clear() args.logger.summary_clear() start_time = time.time() learner.learn(args, env, env_test, agent, buffer) tester.cycle_summary() args.logger.add_record('Epoch', str(epoch)+'/'+str(args.epochs)) args.logger.add_record('Cycle', str(cycle)+'/'+str(args.cycles)) args.logger.add_record('Episodes', buffer.counter) args.logger.add_record('Timesteps', buffer.steps_counter) args.logger.add_record('TimeCost(sec)', time.time()-start_time) args.logger.tabular_show(args.tag) args.logger.summary_show(buffer.counter) tester.epoch_summary() tester.final_summary()
0
0
0
a25da8c4cf788af26bbd8f7f6206a46740a73edc
398
py
Python
lecture5.py
sterbinsky/APSpyLecture5
6319017ab1287dc8e29cfe7fd7ef02675fbebba0
[ "Apache-2.0" ]
null
null
null
lecture5.py
sterbinsky/APSpyLecture5
6319017ab1287dc8e29cfe7fd7ef02675fbebba0
[ "Apache-2.0" ]
null
null
null
lecture5.py
sterbinsky/APSpyLecture5
6319017ab1287dc8e29cfe7fd7ef02675fbebba0
[ "Apache-2.0" ]
null
null
null
''' Python code used in APS 2016 Python lecture 5 ''' import h5py import lecture5_lib f = h5py.File('writer_1_3.hdf5', 'r') x = f['/Scan/data/two_theta'] y = f['/Scan/data/counts'] print 'file:', f.filename print 'peak position:', lecture5_lib.peak_position(x, y) print 'center-of-mass:', lecture5_lib.center_of_mass(x, y) print 'FWHM:', lecture5_lib.fwhm(x, y) f.close() def dummy(): ''' '''
20.947368
58
0.683417
''' Python code used in APS 2016 Python lecture 5 ''' import h5py import lecture5_lib f = h5py.File('writer_1_3.hdf5', 'r') x = f['/Scan/data/two_theta'] y = f['/Scan/data/counts'] print 'file:', f.filename print 'peak position:', lecture5_lib.peak_position(x, y) print 'center-of-mass:', lecture5_lib.center_of_mass(x, y) print 'FWHM:', lecture5_lib.fwhm(x, y) f.close() def dummy(): ''' '''
0
0
0
2e248422e9305b21ac686ef4537042f773eec2b5
546
py
Python
007/test_list_user.py
joeryan/100pythondays2019
1d2ae8a75b6614d8aec40dfb8b6bc1268578c049
[ "MIT" ]
null
null
null
007/test_list_user.py
joeryan/100pythondays2019
1d2ae8a75b6614d8aec40dfb8b6bc1268578c049
[ "MIT" ]
null
null
null
007/test_list_user.py
joeryan/100pythondays2019
1d2ae8a75b6614d8aec40dfb8b6bc1268578c049
[ "MIT" ]
null
null
null
import json import pytest import requests @pytest.mark.parametrize("userid, firstname", [(1,"George"),(2,"Janet")])
32.117647
73
0.714286
import json import pytest import requests @pytest.mark.parametrize("userid, firstname", [(1,"George"),(2,"Janet")]) def test_list_valid_user(supply_url, userid, firstname): url = supply_url + "/users/" + str(userid) resp = requests.get(url) json_resp = json.loads(resp.text) assert json_resp['data']['id'] == userid, resp.text assert json_resp['data']['first_name'] == firstname, resp.text def test_list_invalid_user(supply_url): url = supply_url + "/users/50" resp = requests.get(url) assert resp.status_code == 404, resp.text
384
0
45
4ae604f13ca9a87e0ca10ccf04abacaf47194f98
7,231
py
Python
priceprobi/geocoding/geocoder.py
ujjwaln/priceprobi
73acaca303590ebb3eaa01452c7343e5d72cf836
[ "Apache-2.0" ]
null
null
null
priceprobi/geocoding/geocoder.py
ujjwaln/priceprobi
73acaca303590ebb3eaa01452c7343e5d72cf836
[ "Apache-2.0" ]
null
null
null
priceprobi/geocoding/geocoder.py
ujjwaln/priceprobi
73acaca303590ebb3eaa01452c7343e5d72cf836
[ "Apache-2.0" ]
null
null
null
__author__ = "ujjwal" import os import json import requests import urllib import xmltodict from priceprobi.utils import get_env from priceprobi.config import get_config from priceprobi.db.mongo_helper import MongoHelper from priceprobi.config import NOMINATIM, CSIS from priceprobi import logger if __name__ == "__main__": config = get_config(get_env()) geocoder = Geocoder(config=config) geocoder.check_mandi_locations() geocoder.create_batch_geocodes()
39.086486
113
0.511824
__author__ = "ujjwal" import os import json import requests import urllib import xmltodict from priceprobi.utils import get_env from priceprobi.config import get_config from priceprobi.db.mongo_helper import MongoHelper from priceprobi.config import NOMINATIM, CSIS from priceprobi import logger def scrape_cics_data(): states_url = "http://india.csis.u-tokyo.ac.jp/api/getStateList" st_req = requests.get(states_url) states = json.loads(st_req.text) data = [] for s in states: districts_url = "http://india.csis.u-tokyo.ac.jp/api/getDistrictList?p=%s" % s['id'] dis_req = requests.get(districts_url) districts = json.loads(dis_req.text) s["districts"] = [] for d in districts: subdistricts_url = "http://india.csis.u-tokyo.ac.jp/api/getSubDistrictList?p=%s" % d['id'] subdis_req = requests.get(subdistricts_url) sub_districts = json.loads(subdis_req.text) d["sub_districts"] = sub_districts s["districts"].append(d) data.append(s) with open(CSIS["scraped_file_name"], 'w') as of: of.write(json.dumps(data)) class Geocoder(object): def __init__(self, config): self.mongo_helper = MongoHelper(config=config) if not os.path.exists(CSIS["scraped_file_name"]): scrape_cics_data() if os.path.exists(CSIS["scraped_file_name"]): with open(CSIS["scraped_file_name"], 'r') as sf: data = sf.read() self.states = json.loads(data) else: raise Exception("Could not download CSIS file") def __nominatim_geocode(self, state, district, market): query = "%s, %s, %s" % (market, district, state) params = { "format": "json", "q": query } req = requests.get(NOMINATIM["api_url"], params=params) logger.debug("nm request for %s %s %s" % (state, district, market)) resp = req.json() return resp def __cics_geocode(self, state, district, market): f_str_state = "" f_str_district = "" for st in self.states: if st['name'].lower() == state.lower(): state_id = st['id'] f_str_state = '"state":"' + state_id + '"' for di in st['districts']: if di['name'].lower() == district.lower(): district_id = di['id'] f_str_district = ', "district":"' + district_id + '"' break f_param = "{" + f_str_state + f_str_district + "}" data = urllib.urlencode({"q": market, "f": f_param}) req = requests.post("http://india.csis.u-tokyo.ac.jp/geocode-cgi/census_ajax_json.cgi", data=data) logger.debug("cics request for %s %s %s" % (state, district, market)) xmldict = xmltodict.parse(req.text) if "markers" in xmldict: results = xmldict["markers"] if results and "marker" in results: return results["marker"] return None def check_mandi_locations(self): logger.debug("Check mandi locations") mandi_prices = self.mongo_helper.db["mandi_prices"] mandi_locations = self.mongo_helper.db["mandi_locations"] cursor = mandi_prices.find() for mp in cursor: state = (mp["state"]).lower() district = (mp["district"]).lower() market = (mp["market"]).lower() query = {"state": state, "district": district, "market": market} doc = mandi_locations.find_one(query) if doc is None: doc = { "state": state, "district": district, "market": market } doc["_id"] = mandi_locations.insert(doc) if not "cics_geocode" in doc: cics_data = self.__cics_geocode(state, district, market) if cics_data and len(cics_data) > 0: mandi_locations.update({"_id": doc["_id"]}, {"$set": {"cics_geocode": cics_data}}) if not "nm_geocode" in doc: nm_data = self.__nominatim_geocode(state, district, market) if nm_data and len(nm_data) > 0: mandi_locations.update({"_id": doc["_id"]}, {"$set": {"nm_geocode": nm_data}}) logger.debug("Inserted new mandi location for %s %s %s" % (state, district, market)) def create_batch_geocodes(self): mandi_prices = self.mongo_helper.db["mandi_prices"] mandi_locations = self.mongo_helper.db["mandi_locations"] cursor = mandi_prices.find() for mp in cursor: state = (mp["state"]).lower() district = (mp["district"]).lower() market = (mp["market"]).lower() query = {"state": state, "district": district, "market": market} logger.info("geocoding mandi %s" % mp["_id"]) ml = mandi_locations.find_one(query) if ml is None: logger.warn("no mandi location for mandi %s, %s, %s, %s" % (mp["_id"], state, district, market)) else: #if not "cics_loc" in mp: if "cics_geocode" in ml: if isinstance(ml["cics_geocode"], list): score = -1 nm_max = None for cg in ml["cics_geocode"]: if int(cg["@score"]) > score: nm_max = cg score = int(cg["@score"]) if nm_max: cics_loc = { "type": "Point", "coordinates": [float(nm_max["@lng"]), float(nm_max["@lat"])] } mandi_prices.update({"_id": mp["_id"]}, {"$set": {"cics_loc": cics_loc}}) if isinstance(ml["cics_geocode"], dict): cics_loc = { "type": "Point", "coordinates": [float(ml["cics_geocode"]["@lng"]), float(ml["cics_geocode"]["@lat"])] } mandi_prices.update({"_id": mp["_id"]}, {"$set": {"cics_loc": cics_loc}}) #if not "nm_loc" in mp: if "nm_geocode" in ml: score = -1 nm_max = None for nm in ml["nm_geocode"]: if ("importance" in nm) and (float(nm["importance"]) > score): nm_max = nm score = float(nm["importance"]) if nm_max: nm_loc = { "type": "Point", "coordinates": [nm_max["lon"], nm_max["lat"]] } mandi_prices.update({"_id": mp["_id"]}, {"$set": {"nm_loc": nm_loc}}) if __name__ == "__main__": config = get_config(get_env()) geocoder = Geocoder(config=config) geocoder.check_mandi_locations() geocoder.create_batch_geocodes()
6,574
2
181
9b786af279c83d145ff4e00615157b0533f35625
203
py
Python
api/admin.py
ilovedarknet/BookShoping
315d2b9996acb3dc1a0743c29728f1d3affd848d
[ "BSD-3-Clause" ]
null
null
null
api/admin.py
ilovedarknet/BookShoping
315d2b9996acb3dc1a0743c29728f1d3affd848d
[ "BSD-3-Clause" ]
null
null
null
api/admin.py
ilovedarknet/BookShoping
315d2b9996acb3dc1a0743c29728f1d3affd848d
[ "BSD-3-Clause" ]
null
null
null
from django.contrib import admin from .models import * admin.site.register(Book) admin.site.register(Booking) admin.site.register(Achievement) admin.site.register(AboutUs) admin.site.register(Card)
15.615385
32
0.79803
from django.contrib import admin from .models import * admin.site.register(Book) admin.site.register(Booking) admin.site.register(Achievement) admin.site.register(AboutUs) admin.site.register(Card)
0
0
0
a6b85a9fa5b6a9d33c01490e4df617306ecdb1a1
818
py
Python
Algorithms/014_SPLC.py
ChaoticMarauder/Project_Rosalind
6c70cd32908f3b11285e8505c3b43f1ea222decb
[ "MIT" ]
null
null
null
Algorithms/014_SPLC.py
ChaoticMarauder/Project_Rosalind
6c70cd32908f3b11285e8505c3b43f1ea222decb
[ "MIT" ]
null
null
null
Algorithms/014_SPLC.py
ChaoticMarauder/Project_Rosalind
6c70cd32908f3b11285e8505c3b43f1ea222decb
[ "MIT" ]
null
null
null
from rosalind import parse_fasta from rosalind import translate from rosalind import transcribe if(__name__=='__main__'): main()
22.108108
65
0.655257
from rosalind import parse_fasta from rosalind import translate from rosalind import transcribe def rna_splicing(dna, intron_list): for intron in intron_list: dna=dna.replace(intron,'') spliced_rna = ''.join(transcribe(dna)) return spliced_rna def main(): file_name='datasets/rosalind_splc.txt' seq_dict = parse_fasta(file_name) list_seq=[] for key in seq_dict: list_seq.append(seq_dict[key]) dna=list_seq[0] intron_list=list_seq[1:] spliced_rna=rna_splicing(dna, intron_list) protein, start_codon, end_codon=translate(spliced_rna) print(protein) with open('solutions/rosalind_splc.txt', 'w') as output_file: output_file.write(protein) if(__name__=='__main__'): main()
631
0
46
6cdd182dff528ad72ef2041ff1abe444851d12e2
2,658
py
Python
setup.py
JGoutin/compilertools
f4375238937384a0400cfc618d3b18fc6e7233a9
[ "BSD-2-Clause" ]
10
2017-09-07T18:53:26.000Z
2021-02-22T22:05:30.000Z
setup.py
JGoutin/compilertools
f4375238937384a0400cfc618d3b18fc6e7233a9
[ "BSD-2-Clause" ]
2
2018-08-16T08:42:09.000Z
2019-01-11T20:20:21.000Z
setup.py
JGoutin/compilertools
f4375238937384a0400cfc618d3b18fc6e7233a9
[ "BSD-2-Clause" ]
2
2018-05-11T07:44:56.000Z
2018-05-28T13:08:41.000Z
#! /usr/bin/env python3 """Setup script run "./setup.py --help-commands" for help. """ from datetime import datetime from os.path import abspath, dirname, join PACKAGE_INFO = dict( name="compilertools", description="A library for helping optimizing Python extensions compilation.", long_description_content_type="text/markdown; charset=UTF-8", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Topic :: Software Development :: Build Tools", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: CPython", ], keywords="compiler distutils setuptools build_ext wheels setup build", author="J.Goutin", url="https://github.com/JGoutin/compilertools", project_urls={ "Documentation": "http://compilertools.readthedocs.io/", "Download": "https://pypi.org/project/compilertools", }, license="BSD", zip_safe=True, python_requires=">=3.6", setup_requires=["setuptools"], tests_require=["pytest-cov", "pytest-flake8", "pytest-black"], command_options={}, ) SETUP_DIR = abspath(dirname(__file__)) with open(join(SETUP_DIR, "compilertools/_version.py")) as file: for line in file: if line.rstrip().startswith("__version__"): PACKAGE_INFO["version"] = line.split("=", 1)[1].strip(" \"'\n") break with open(join(SETUP_DIR, "readme.md")) as file: PACKAGE_INFO["long_description"] = file.read() PACKAGE_INFO["command_options"]["build_sphinx"] = { "project": ("setup.py", PACKAGE_INFO["name"].capitalize()), "version": ("setup.py", PACKAGE_INFO["version"]), "release": ("setup.py", PACKAGE_INFO["version"]), "copyright": ( "setup.py", "2017-%s, %s" % (datetime.now().year, PACKAGE_INFO["author"]), ), } if __name__ == "__main__": from os import chdir from sys import argv from setuptools import setup, find_packages if {"pytest", "test", "ptr"}.intersection(argv): PACKAGE_INFO["setup_requires"].append("pytest-runner") elif "build_sphinx" in argv: PACKAGE_INFO["setup_requires"] += ["sphinx", "sphinx_rtd_theme"] chdir(SETUP_DIR) setup(packages=find_packages(exclude=["tests", "doc"]), **PACKAGE_INFO)
34.973684
82
0.640331
#! /usr/bin/env python3 """Setup script run "./setup.py --help-commands" for help. """ from datetime import datetime from os.path import abspath, dirname, join PACKAGE_INFO = dict( name="compilertools", description="A library for helping optimizing Python extensions compilation.", long_description_content_type="text/markdown; charset=UTF-8", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Topic :: Software Development :: Build Tools", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: Implementation :: CPython", ], keywords="compiler distutils setuptools build_ext wheels setup build", author="J.Goutin", url="https://github.com/JGoutin/compilertools", project_urls={ "Documentation": "http://compilertools.readthedocs.io/", "Download": "https://pypi.org/project/compilertools", }, license="BSD", zip_safe=True, python_requires=">=3.6", setup_requires=["setuptools"], tests_require=["pytest-cov", "pytest-flake8", "pytest-black"], command_options={}, ) SETUP_DIR = abspath(dirname(__file__)) with open(join(SETUP_DIR, "compilertools/_version.py")) as file: for line in file: if line.rstrip().startswith("__version__"): PACKAGE_INFO["version"] = line.split("=", 1)[1].strip(" \"'\n") break with open(join(SETUP_DIR, "readme.md")) as file: PACKAGE_INFO["long_description"] = file.read() PACKAGE_INFO["command_options"]["build_sphinx"] = { "project": ("setup.py", PACKAGE_INFO["name"].capitalize()), "version": ("setup.py", PACKAGE_INFO["version"]), "release": ("setup.py", PACKAGE_INFO["version"]), "copyright": ( "setup.py", "2017-%s, %s" % (datetime.now().year, PACKAGE_INFO["author"]), ), } if __name__ == "__main__": from os import chdir from sys import argv from setuptools import setup, find_packages if {"pytest", "test", "ptr"}.intersection(argv): PACKAGE_INFO["setup_requires"].append("pytest-runner") elif "build_sphinx" in argv: PACKAGE_INFO["setup_requires"] += ["sphinx", "sphinx_rtd_theme"] chdir(SETUP_DIR) setup(packages=find_packages(exclude=["tests", "doc"]), **PACKAGE_INFO)
0
0
0
493df341c71de6258d096663ce60490db7df8986
6,047
py
Python
help_func.py
GiladGH/pointcleannet
1c7f8f00c2062923063de2f796d96e444476d698
[ "MIT" ]
null
null
null
help_func.py
GiladGH/pointcleannet
1c7f8f00c2062923063de2f796d96e444476d698
[ "MIT" ]
null
null
null
help_func.py
GiladGH/pointcleannet
1c7f8f00c2062923063de2f796d96e444476d698
[ "MIT" ]
null
null
null
import os import h5py import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm def load_h5_data_label(h5_filename): """ load the data from the hdf5 files """ f = h5py.File(h5_filename) data = f['data'][:] labels = f['label'][:] # normal = f['normal'][:] return (data, labels) def pointnet_to_cleanpoint(data_dir, samples, labels): """ read pointnet dataset point cloud and transfer it to pcpnet dataset format """ shape_names_dir = os.path.join(data_dir, 'shape_names.txt') with open(shape_names_dir) as f: label_names = f.readlines() # save in the pcp data set format new_dir = os.path.join(data_dir, '../modelNetDataset') if not os.path.exists(new_dir): os.mkdir(new_dir) for i, _ in enumerate(samples, 0): sample = samples[i, :, :] # save clean sample num = 0 filename = os.path.join(new_dir, label_names[labels[i][0]].strip() + '_{:d}_{:02d}.xyz'.format(labels[i][0], num)) while os.path.exists(filename): num = num + 1 filename = os.path.join(new_dir, label_names[labels[i][0]].strip() + '_{:d}_{:02d}.xyz'.format(labels[i][0], num)) if num > 10: continue with open(filename, 'w') as f: f.write('\n'.join([' '.join(map(str, x)) for x in sample])) f.close() # save noisy sample - white noise std 0.25% filename_1 = os.path.splitext(filename)[0] noisy_sample = sample + np.random.normal(scale=0.0025, size=sample.shape) filename_1 = filename_1 + '_2.50e-03.xyz' with open(filename_1, 'w') as f: f.write('\n'.join([' '.join(map(str, x)) for x in noisy_sample])) f.close() # save noisy sample - white noise std 1% filename_2 = os.path.splitext(filename)[0] noisy_sample = sample + np.random.normal(scale=0.01, size=sample.shape) filename_2 = filename_2 + '_1.00e-02.xyz' with open(filename_2, 'w') as f: f.write('\n'.join([' '.join(map(str, x)) for x in noisy_sample])) f.close() # save noisy sample - white noise std 2.5% filename_3 = os.path.splitext(filename)[0] noisy_sample = sample + np.random.normal(scale=0.025, size=sample.shape) filename_3 = filename_3 + '_2.50e-02.xyz' with open(filename_3, 'w') as f: f.write('\n'.join([' '.join(map(str, x)) for x in noisy_sample])) f.close() # for each file create clean copy for GT filename = os.path.splitext(filename)[0] + '.clean_xyz' filename_1 = os.path.splitext(filename_1)[0] + '.clean_xyz' filename_2 = os.path.splitext(filename_2)[0] + '.clean_xyz' filename_3 = os.path.splitext(filename_3)[0] + '.clean_xyz' with open(filename, 'w') as f, open(filename_1, 'w') as f1, open(filename_2, 'w') as f2, open(filename_3, 'w') as f3: f.write('\n'.join([' '.join(map(str, x)) for x in sample])) f1.write('\n'.join([' '.join(map(str, x)) for x in sample])) f2.write('\n'.join([' '.join(map(str, x)) for x in sample])) f3.write('\n'.join([' '.join(map(str, x)) for x in sample])) f.close() f1.close() f2.close() f3.close() return def visualize_point_cloud(pc, output_filename='null', fig_num=0, color=np.array([1])): """ points is a Nx3 numpy array """ fig = plt.figure(fig_num) ax = fig.add_subplot(111, projection='3d') if color[0] == 1: color = pc[:, 2] ax.scatter(pc[:, 0], pc[:, 1], pc[:, 2], c=color, s=5, marker='.', depthshade=True) # ax.set_xlabel('x') # ax.set_ylabel('y') # ax.set_zlabel('z') ax.axis('on') # plt.savefig(output_filename) def prep_training_set_file(data_dir): """ prep trainingset.txt and validationset.txt files """ trainset_file = os.path.join(data_dir, 'trainingset.txt') valiset_file = os.path.join(data_dir, 'validationset.txt') with open(trainset_file, 'w') as f1, open(valiset_file, 'w') as f2: for path, subdirs, files in os.walk(data_dir): for file in files: file = os.path.splitext(file)[0] if file != 'trainingset' and file != 'validationset': if int(file.split('_')[2]) <= 8: f1.write(file + '\n') else: f2.write(file + '\n') f1.close() f2.close() if __name__ == '__main__': clean = np.loadtxt('data/modelNetDataset/airplane_0_09_1.00e-02.clean_xyz') pc1 = np.loadtxt('results/airplane_0_09_1.00e-02_0.xyz') pc2 = np.loadtxt('results/airplane_0_09_1.00e-02_1.xyz') err1 = np.sum(np.square(pc1 - clean), axis=1) err2 = np.sum(np.square(pc2 - clean), axis=1) visualize_point_cloud(pc1, fig_num=1) visualize_point_cloud(pc2, fig_num=2) visualize_point_cloud(pc1, fig_num=3, color=err1) visualize_point_cloud(pc2, fig_num=4, color=err2) plt.show() # samples, labels = load_dataset() # in_dir = os.path.join(os.getcwd(), 'data/modelnet40_ply_hdf5_2048') # pointnet_to_cleanpoint(in_dir, samples, labels) # prep_training_set_file(os.path.join(os.getcwd(), 'data/modelNetDataset'))
39.266234
127
0.587729
import os import h5py import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm def load_h5_data_label(h5_filename): """ load the data from the hdf5 files """ f = h5py.File(h5_filename) data = f['data'][:] labels = f['label'][:] # normal = f['normal'][:] return (data, labels) def load_dataset(train_files='train_files.txt'): with open('data/modelnet40_ply_hdf5_2048/train_files.txt') as f: files = [line.strip() for line in f.readlines()] h5_filename = os.path.join(os.getcwd(), files[0]) data, labels = load_h5_data_label(h5_filename) for filename in files[1:]: h5_filename = os.path.join(os.getcwd(), filename) new_data, new_labels = load_h5_data_label(h5_filename) np.concatenate((data, new_data)) np.concatenate((labels, new_labels)) return data, labels def pointnet_to_cleanpoint(data_dir, samples, labels): """ read pointnet dataset point cloud and transfer it to pcpnet dataset format """ shape_names_dir = os.path.join(data_dir, 'shape_names.txt') with open(shape_names_dir) as f: label_names = f.readlines() # save in the pcp data set format new_dir = os.path.join(data_dir, '../modelNetDataset') if not os.path.exists(new_dir): os.mkdir(new_dir) for i, _ in enumerate(samples, 0): sample = samples[i, :, :] # save clean sample num = 0 filename = os.path.join(new_dir, label_names[labels[i][0]].strip() + '_{:d}_{:02d}.xyz'.format(labels[i][0], num)) while os.path.exists(filename): num = num + 1 filename = os.path.join(new_dir, label_names[labels[i][0]].strip() + '_{:d}_{:02d}.xyz'.format(labels[i][0], num)) if num > 10: continue with open(filename, 'w') as f: f.write('\n'.join([' '.join(map(str, x)) for x in sample])) f.close() # save noisy sample - white noise std 0.25% filename_1 = os.path.splitext(filename)[0] noisy_sample = sample + np.random.normal(scale=0.0025, size=sample.shape) filename_1 = filename_1 + '_2.50e-03.xyz' with open(filename_1, 'w') as f: f.write('\n'.join([' '.join(map(str, x)) for x in noisy_sample])) f.close() # save noisy sample - white noise std 1% filename_2 = os.path.splitext(filename)[0] noisy_sample = sample + np.random.normal(scale=0.01, size=sample.shape) filename_2 = filename_2 + '_1.00e-02.xyz' with open(filename_2, 'w') as f: f.write('\n'.join([' '.join(map(str, x)) for x in noisy_sample])) f.close() # save noisy sample - white noise std 2.5% filename_3 = os.path.splitext(filename)[0] noisy_sample = sample + np.random.normal(scale=0.025, size=sample.shape) filename_3 = filename_3 + '_2.50e-02.xyz' with open(filename_3, 'w') as f: f.write('\n'.join([' '.join(map(str, x)) for x in noisy_sample])) f.close() # for each file create clean copy for GT filename = os.path.splitext(filename)[0] + '.clean_xyz' filename_1 = os.path.splitext(filename_1)[0] + '.clean_xyz' filename_2 = os.path.splitext(filename_2)[0] + '.clean_xyz' filename_3 = os.path.splitext(filename_3)[0] + '.clean_xyz' with open(filename, 'w') as f, open(filename_1, 'w') as f1, open(filename_2, 'w') as f2, open(filename_3, 'w') as f3: f.write('\n'.join([' '.join(map(str, x)) for x in sample])) f1.write('\n'.join([' '.join(map(str, x)) for x in sample])) f2.write('\n'.join([' '.join(map(str, x)) for x in sample])) f3.write('\n'.join([' '.join(map(str, x)) for x in sample])) f.close() f1.close() f2.close() f3.close() return def visualize_point_cloud(pc, output_filename='null', fig_num=0, color=np.array([1])): """ points is a Nx3 numpy array """ fig = plt.figure(fig_num) ax = fig.add_subplot(111, projection='3d') if color[0] == 1: color = pc[:, 2] ax.scatter(pc[:, 0], pc[:, 1], pc[:, 2], c=color, s=5, marker='.', depthshade=True) # ax.set_xlabel('x') # ax.set_ylabel('y') # ax.set_zlabel('z') ax.axis('on') # plt.savefig(output_filename) def prep_training_set_file(data_dir): """ prep trainingset.txt and validationset.txt files """ trainset_file = os.path.join(data_dir, 'trainingset.txt') valiset_file = os.path.join(data_dir, 'validationset.txt') with open(trainset_file, 'w') as f1, open(valiset_file, 'w') as f2: for path, subdirs, files in os.walk(data_dir): for file in files: file = os.path.splitext(file)[0] if file != 'trainingset' and file != 'validationset': if int(file.split('_')[2]) <= 8: f1.write(file + '\n') else: f2.write(file + '\n') f1.close() f2.close() if __name__ == '__main__': clean = np.loadtxt('data/modelNetDataset/airplane_0_09_1.00e-02.clean_xyz') pc1 = np.loadtxt('results/airplane_0_09_1.00e-02_0.xyz') pc2 = np.loadtxt('results/airplane_0_09_1.00e-02_1.xyz') err1 = np.sum(np.square(pc1 - clean), axis=1) err2 = np.sum(np.square(pc2 - clean), axis=1) visualize_point_cloud(pc1, fig_num=1) visualize_point_cloud(pc2, fig_num=2) visualize_point_cloud(pc1, fig_num=3, color=err1) visualize_point_cloud(pc2, fig_num=4, color=err2) plt.show() # samples, labels = load_dataset() # in_dir = os.path.join(os.getcwd(), 'data/modelnet40_ply_hdf5_2048') # pointnet_to_cleanpoint(in_dir, samples, labels) # prep_training_set_file(os.path.join(os.getcwd(), 'data/modelNetDataset'))
534
0
25
ab6875a1e5f03d7dfe00c29b4051c4828e6cf04b
5,842
py
Python
canvas.py
zach-king/GlyphyType
dd930730af4396ad7d5ac12d5011a35a1f5ab9bc
[ "MIT" ]
null
null
null
canvas.py
zach-king/GlyphyType
dd930730af4396ad7d5ac12d5011a35a1f5ab9bc
[ "MIT" ]
null
null
null
canvas.py
zach-king/GlyphyType
dd930730af4396ad7d5ac12d5011a35a1f5ab9bc
[ "MIT" ]
null
null
null
''' File: canvas.py Description: Implements the custom GlyphyType canvas widget for drawing characters/glyphs. ''' from PyQt4.QtCore import * from PyQt4.QtGui import * from tools import brush, line
31.240642
119
0.60647
''' File: canvas.py Description: Implements the custom GlyphyType canvas widget for drawing characters/glyphs. ''' from PyQt4.QtCore import * from PyQt4.QtGui import * from tools import brush, line class Canvas(QWidget): def __init__(self, parent=None): super(Canvas, self).__init__(parent) self.setAttribute(Qt.WA_StaticContents) self.modified = False self.isDrawing = False self.penWidth = 3 self.penColor = Qt.black self.currentTool = brush.Brush(self) imageSize = QSize(500, 500) self.image = QImage(imageSize, QImage.Format_RGB32) self.lastPoint = QPoint() self.paths = [] self.parent = parent self.painter = QPainter() def openImage(self, fileName): loadedImage = QImage() if not loadedImage.load(fileName): return False w = loadedImage.width() h = loadedImage.height() self.mainWindow.resize(w, h) self.image = loadedImage self.modified = False self.update() return True def saveImage(self, fileName, fileFormat): visibleImage = self.image self.resizeImage(visibleImage, self.size()) if visibleImage.save(fileName, fileFormat): self.modified = False return True else: return False def setPenColor(self, newColor): self.penColor = newColor def setPenWidth(self, newWidth): self.penWidth = newWidth def clearImage(self): self.image.fill(qRgb(255, 255, 255)) self.modified = True self.update() def clearCanvas(self): self.clearImage() self.paths = [] def mousePressEvent(self, event): self.currentTool.mousePress(event) def mouseMoveEvent(self, event): self.currentTool.mouseMove(event) def mouseReleaseEvent(self, event): self.currentTool.mouseRelease(event) def paintEvent(self, event): self.painter.begin(self) self.painter.drawImage(event.rect(), self.image) self.painter.end() def resizeEvent(self, event): self.resizeImage(self.image, event.size()) super(Canvas, self).resizeEvent(event) def drawLineTo(self, endPoint): self.painter.begin(self.image) self.painter.setPen(QPen(self.penColor, self.penWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) self.painter.drawLine(self.lastPoint, endPoint) self.modified = True self.update() self.lastPoint = QPoint(endPoint) self.painter.end() def drawLine(self, startPoint, endPoint): self.painter.begin(self.image) self.painter.setPen(QPen(self.penColor, self.penWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) # print('Drawing segment from ({}, {}) to ({}, {})'.format(startPoint.x, startPoint.y, endPoint.x, endPoint.y)) self.painter.drawLine(startPoint, endPoint) self.modified = True self.update() self.painter.end() def drawRectangle(self, origin, width, height): self.painter.begin(self.image) self.painter.setPen(QPen(self.penColor, self.penWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) self.painter.drawRect(QRect(origin, QSize(width, height))) self.modified = True self.update() self.painter.end() def drawTriangle(self, origin, base_width, height): self.painter.begin(self.image) self.painter.setPen(QPen(self.penColor, self.penWidth, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)) self.modified = True def addPath(self, list_of_vertices): self.paths.append(list_of_vertices) def resizeImage(self, image, newSize): if image.size() == newSize: return # this resizes the canvas without resampling the image newImage = QImage(newSize, QImage.Format_RGB32) newImage.fill(qRgb(255, 255, 255)) painter = QPainter(newImage) painter.drawImage(QPoint(0, 0), image) self.image = newImage def print_(self): printer = QPrinter(QPrinter.HighResolution) printDialog = QPrintDialog(printer, self) if printDialog.exec_() == QDialog.Accepted: painter = QPainter(printer) rect = painter.viewport() size = self.image.size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self.image.rect()) painter.drawImage(0, 0, self.image) painter.end() def isModified(self): return self.modified def penColor(self): return self.penColor def penWidth(self): return self.penWidth def DrawPaths(self): '''Draws the paths stored in self. Only lines currently.''' # self.drawLine(QPoint(393, 23), QPoint(691, 23)) # self.drawLine(QPoint(691, 23), QPoint(691, 419)) # self.drawLine(QPoint(691, 419), QPoint(393, 419)) # self.drawLine(QPoint(393, 419), QPoint(393, 23)) # self.painter.end() # return for path in self.paths: startPoint = self.ParsePoint(path[0]) origin = startPoint endPoint = None for point in path[1:]: endPoint = self.ParsePoint(point) self.drawLine(startPoint, endPoint) startPoint = endPoint endPoint = origin self.drawLine(startPoint, endPoint) def ParsePoint(self, tup): point = QPoint() point.x = tup[0] point.y = tup[1] # print('Parsed QPoint ({}, {})'.format(point.x, point.y)) return point
4,196
1,392
23
cf852852484ccf979e059170505d800849d97458
1,807
py
Python
app/doll/models/doll.py
Younlab/GFS-Backend
06bd2d14bc1e3226a458089fb99496516273f296
[ "MIT" ]
2
2019-03-03T10:59:55.000Z
2019-03-03T11:00:07.000Z
app/doll/models/doll.py
Younlab/GFS-Backend
06bd2d14bc1e3226a458089fb99496516273f296
[ "MIT" ]
null
null
null
app/doll/models/doll.py
Younlab/GFS-Backend
06bd2d14bc1e3226a458089fb99496516273f296
[ "MIT" ]
null
null
null
from django.contrib.postgres.fields import ArrayField from django.db import models __all__ = ( 'Doll', 'Status', )
28.234375
67
0.667405
from django.contrib.postgres.fields import ArrayField from django.db import models __all__ = ( 'Doll', 'Status', ) class Doll(models.Model): id = models.PositiveIntegerField(unique=True, primary_key=True) code_name = models.CharField(max_length=50) rank = models.PositiveSmallIntegerField() type = models.CharField(max_length=10) build_time = models.PositiveIntegerField() grow = models.PositiveIntegerField() image = models.ImageField(upload_to='doll_image') image_d = models.ImageField(upload_to='doll_image_d') obtain = ArrayField( ArrayField( models.PositiveSmallIntegerField() ), ) slot_01 = ArrayField( ArrayField( models.CharField(max_length=20, blank=True, null=True), ), ) slot_02 = ArrayField( ArrayField( models.CharField(max_length=20, blank=True, null=True), ), ) slot_03 = ArrayField( ArrayField( models.CharField(max_length=20, blank=True, null=True), ), ) def __str__(self): return self.code_name class Status(models.Model): doll = models.ForeignKey( 'Doll', on_delete=models.CASCADE, ) hp = models.PositiveIntegerField() pow = models.PositiveIntegerField() hit = models.PositiveIntegerField() dodge = models.PositiveIntegerField() rate = models.PositiveIntegerField() armor_piercing = models.PositiveIntegerField() critical_harm_rate = models.PositiveIntegerField() critical_percent = models.PositiveIntegerField() bullet = models.PositiveIntegerField() speed = models.PositiveIntegerField() night_view = models.PositiveIntegerField() armor = models.PositiveIntegerField() class Meta: ordering = ['id']
27
1,608
46
d5644bcae84f74922c59509dd07adf55a2df2457
1,762
py
Python
check_version_increase.py
elbuco1/fen2png
c64263cb5c53eeb33d2d311328256ffe4f1ac1a2
[ "MIT" ]
2
2021-12-01T03:28:52.000Z
2022-01-29T19:58:38.000Z
check_version_increase.py
elbuco1/fen2png
c64263cb5c53eeb33d2d311328256ffe4f1ac1a2
[ "MIT" ]
1
2021-12-01T03:28:21.000Z
2021-12-01T03:28:21.000Z
check_version_increase.py
elbuco1/fen2png
c64263cb5c53eeb33d2d311328256ffe4f1ac1a2
[ "MIT" ]
null
null
null
#!/usr/bin/env python import argparse import os import re import json def version_increased(former_version, current_version): """Check that version in the package is greater than version_master and that only one int has increased of 1. Args: version_master (str): former version """ current_version_int = int("".join(current_version.split("."))) former_version_int = int("".join(former_version.split("."))) assert current_version_int > former_version_int, f"New version ({current_version}) should be greater than former version ({former_version})." version = [int(e) for e in current_version.split(".")] version_former = [int(e) for e in former_version.split(".")] diffs = [] for new, old in zip(version, version_former): diffs.append(max(0, new - old)) assert sum( diffs) == 1, f"Only one digit should be increased by one in version. Got {diffs}." print("Version increased validation passed!") if __name__ == "__main__": main()
30.912281
146
0.692963
#!/usr/bin/env python import argparse import os import re import json def version_increased(former_version, current_version): """Check that version in the package is greater than version_master and that only one int has increased of 1. Args: version_master (str): former version """ current_version_int = int("".join(current_version.split("."))) former_version_int = int("".join(former_version.split("."))) assert current_version_int > former_version_int, f"New version ({current_version}) should be greater than former version ({former_version})." version = [int(e) for e in current_version.split(".")] version_former = [int(e) for e in former_version.split(".")] diffs = [] for new, old in zip(version, version_former): diffs.append(max(0, new - old)) assert sum( diffs) == 1, f"Only one digit should be increased by one in version. Got {diffs}." print("Version increased validation passed!") def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() version_increased_parser = subparsers.add_parser( 'version_increased', help="Validate that version is greater than former version") version_increased_parser.add_argument( '-f', '--former_version', type=str, required=True, help='Pass the content of VERSION file in master last commit.') version_increased_parser.add_argument( '-c', '--current_version', type=str, required=True, help='Pass the content of VERSION file in current commit.') version_increased_parser.set_defaults(func=version_increased) # parse args = parser.parse_args() func = vars(args).pop("func") func(**vars(args)) if __name__ == "__main__": main()
715
0
23
5b7977666f84d8a4ea7e54aea41d21726f3c0d64
261
py
Python
utils.py
lmeaou/teal
e1c0502390cdaa9c62cef04f4c2b94344100666d
[ "MIT" ]
null
null
null
utils.py
lmeaou/teal
e1c0502390cdaa9c62cef04f4c2b94344100666d
[ "MIT" ]
null
null
null
utils.py
lmeaou/teal
e1c0502390cdaa9c62cef04f4c2b94344100666d
[ "MIT" ]
null
null
null
import json import os from os import path
23.727273
49
0.62069
import json import os from os import path def get_key_from_db(uuid, key): data_path = "database/data-" + uuid + ".json" if path.exists(data_path): f = open(data_path, "r") data = json.load(f) return data[key] return "nodata"
197
0
23
dcd65afe1b7d373194d0df45e4433ca60003a021
324
py
Python
testing/urls.py
Joshijax/covidapp
cae6f6fde5c936af2615ff79b6d883f31825a7ee
[ "MIT" ]
null
null
null
testing/urls.py
Joshijax/covidapp
cae6f6fde5c936af2615ff79b6d883f31825a7ee
[ "MIT" ]
null
null
null
testing/urls.py
Joshijax/covidapp
cae6f6fde5c936af2615ff79b6d883f31825a7ee
[ "MIT" ]
null
null
null
# -*- encoding: utf-8 -*- """ License: MIT Copyright (c) 2019 - present AppSeed.us """ from django.contrib import admin from django.urls import path, include # add this from testing import views urlpatterns = [ path('', views.index, name='tester'), path('/take', views.tester, name='tester1'), # add this ]
20.25
49
0.654321
# -*- encoding: utf-8 -*- """ License: MIT Copyright (c) 2019 - present AppSeed.us """ from django.contrib import admin from django.urls import path, include # add this from testing import views urlpatterns = [ path('', views.index, name='tester'), path('/take', views.tester, name='tester1'), # add this ]
0
0
0
313b0c39616ef4195670de4e815f8d591baba29d
173
py
Python
c3i/app/views.py
addinall/python-C3I
be72f026fb7c6b5084404876cd1296d3c3cb9b85
[ "Unlicense" ]
null
null
null
c3i/app/views.py
addinall/python-C3I
be72f026fb7c6b5084404876cd1296d3c3cb9b85
[ "Unlicense" ]
null
null
null
c3i/app/views.py
addinall/python-C3I
be72f026fb7c6b5084404876cd1296d3c3cb9b85
[ "Unlicense" ]
null
null
null
# from django.shortcuts import render from django.http import HttpResponse
21.625
74
0.780347
# from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse("Hello world - You are in the Python version of C3I")
73
0
23
2bebc284726ac0538aa8d5cd151421d4848b75ef
4,684
py
Python
data_utils.py
lyeoni/gpt-pytorch
c3ef84edaf5b4c34034e333228bd425da55d2483
[ "MIT" ]
49
2020-03-17T08:15:49.000Z
2022-03-23T08:42:16.000Z
data_utils.py
lyeoni/gpt-pytorch
c3ef84edaf5b4c34034e333228bd425da55d2483
[ "MIT" ]
2
2020-07-01T08:29:59.000Z
2020-08-17T18:53:48.000Z
data_utils.py
lyeoni/gpt-pytorch
c3ef84edaf5b4c34034e333228bd425da55d2483
[ "MIT" ]
4
2021-01-14T14:13:48.000Z
2021-07-06T12:55:53.000Z
from typing import Iterable, Union, List from pathlib import Path import json import torch import torch.distributed as dist from torch.utils.data import TensorDataset class PretrainInputExample: """A single example for unsupervised pre-training. """ class ClsInputExample: """A single example for supervised fine-tuning (classification). """ class PretrainInputFeatures: """A single set of features of pre-training data. """ class ClsInputFeatures: """A single set of features of fine-tuning data (classification). """
39.361345
152
0.648591
from typing import Iterable, Union, List from pathlib import Path import json import torch import torch.distributed as dist from torch.utils.data import TensorDataset class PretrainInputExample: """A single example for unsupervised pre-training. """ def __init__(self, text: str): self.text = text class ClsInputExample: """A single example for supervised fine-tuning (classification). """ def __init__(self, text: str, label: str): self.text = text self.label = label class PretrainInputFeatures: """A single set of features of pre-training data. """ def __init__(self, input_ids: List[int]): self.input_ids = input_ids class ClsInputFeatures: """A single set of features of fine-tuning data (classification). """ def __init__(self, input_ids: List[int], label_id: int): self.input_ids = input_ids self.label_id = label_id def convert_examples_to_features(examples, tokenizer, args, mode): bos_token = tokenizer.bos_token eos_token = tokenizer.eos_token pad_token = tokenizer.pad_token # Build label dict(vocab) with examples if args.finetune: if mode == 'train': labels = sorted(list(set([example.label for example in examples]))) label_dict = {label: i for i, label in enumerate(labels)} with open(args.cached_label_dict, 'w') as file: json.dump(label_dict, file, indent=4) elif mode == 'test': with open(args.cached_label_dict, 'r') as file: label_dict = json.load(file) # Create features features = [] for i, example in enumerate(examples): tokens = tokenizer.tokenize(example.text) tokens = [bos_token] + tokens[:args.max_seq_len-2] + [eos_token] # BOS, EOS tokens += [pad_token] * (args.max_seq_len - len(tokens)) input_ids = tokenizer.convert_tokens_to_ids(tokens) if args.finetune: label_id = label_dict.get(example.label) if args.pretrain: feature = PretrainInputFeatures(input_ids) elif args.finetune: feature = ClsInputFeatures(input_ids, label_id) features.append(feature) return features def create_examples(args, tokenizer, mode='train'): if args.local_rank not in [-1, 0]: # Make sure only the first process in distributed training process the dataset, and the others will use the cache dist.barrier() # Load data features from cache or dataset file assert mode in ('train', 'test') cached_features_file = Path('cached_features_{}_{}_{}'.format('pretrain' if args.pretrain else 'finetune', mode, args.max_seq_len)) if cached_features_file.exists(): print('Loading features from cached file', cached_features_file) features = torch.load(cached_features_file) else: corpus_path = args.train_corpus if mode=='train' else args.test_corpus with open(corpus_path, 'r', encoding='utf-8') as reader: corpus = reader.readlines() # Create examples if args.pretrain: corpus = list(map(lambda x: x.strip(), corpus)) corpus = list(filter(lambda x: len(x) > 0, corpus)) examples = [PretrainInputExample(text) for text in corpus] elif args.finetune: corpus = list(map(lambda x: x.split('\t'), corpus)) corpus = list(map(lambda x: list(map(lambda y: y.strip(), x)), corpus)) corpus = list(map(lambda x: list(filter(lambda y: len(y) > 0, x)), corpus)) examples = [ClsInputExample(text, label) for label, text in corpus] # Convert examples to features features = convert_examples_to_features(examples, tokenizer, args, mode) print('Saving features into cached file', cached_features_file) torch.save(features, cached_features_file) if args.local_rank == 0: # Make sure only the first process in distributed training process the dataset, and the others will use the cache dist.barrier() # Create dataset with features if args.pretrain: all_input_ids = torch.tensor([feature.input_ids for feature in features], dtype=torch.long) dataset = TensorDataset(all_input_ids) elif args.finetune: all_input_ids = torch.tensor([feature.input_ids for feature in features], dtype=torch.long) all_label_ids = torch.tensor([feature.label_id for feature in features], dtype=torch.long) dataset = TensorDataset(all_input_ids, all_label_ids) return dataset
3,979
0
150
58d550b93e451cd67d33f0ac2c26d92b3d42faae
2,140
py
Python
networking_generic_switch/tests/unit/test_config.py
ChameleonCloud/networking-generic-switch
98ddec1f11eab5197f1443207b13a16f364e5f10
[ "Apache-2.0" ]
null
null
null
networking_generic_switch/tests/unit/test_config.py
ChameleonCloud/networking-generic-switch
98ddec1f11eab5197f1443207b13a16f364e5f10
[ "Apache-2.0" ]
4
2018-11-21T17:54:37.000Z
2021-10-04T14:40:40.000Z
networking_generic_switch/tests/unit/test_config.py
ChameleonCloud/networking-generic-switch
98ddec1f11eab5197f1443207b13a16f364e5f10
[ "Apache-2.0" ]
null
null
null
# Copyright 2016 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures import mock from oslo_config import fixture as config_fixture import six from networking_generic_switch import config fake_config = """ [genericswitch:foo] device_type = foo_device spam = eggs [genericswitch:bar] device_type = bar_device ham = vikings """
34.516129
78
0.647664
# Copyright 2016 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import fixtures import mock from oslo_config import fixture as config_fixture import six from networking_generic_switch import config fake_config = """ [genericswitch:foo] device_type = foo_device spam = eggs [genericswitch:bar] device_type = bar_device ham = vikings """ class TestConfig(fixtures.TestWithFixtures): def setUp(self): super(TestConfig, self).setUp() self.cfg = self.useFixture(config_fixture.Config()) self._patch_open() self.cfg.conf(args=["--config-file=/some/config/path"]) def _patch_open(self): m = mock.mock_open(read_data=fake_config) # NOTE(pas-ha) mocks and iterators work differently in Py2 and Py3 # http://bugs.python.org/issue21258 if six.PY3: m.return_value.__iter__ = lambda self: self m.return_value.__next__ = lambda self: next(iter(self.readline, '')) else: m.return_value.__iter__ = lambda self: iter(self.readline, '') patcher = mock.patch('oslo_config.cfg.open', m) patcher.start() self.addCleanup(patcher.stop) def test_get_devices(self): device_list = config.get_devices() self.assertEqual(set(device_list), set(['foo', 'bar'])) self.assertEqual({"device_type": "foo_device", "spam": "eggs"}, device_list['foo']) self.assertEqual({"device_type": "bar_device", "ham": "vikings"}, device_list['bar'])
1,130
23
103
eaea90e08e9efbbcbd75fc8b2ce4c80958a2e515
206
py
Python
src/product_data_types/apps.py
evis-market/web-interface-backend
f8930ff1c009ad18e522ab29680b4bcd50a6020e
[ "MIT" ]
2
2021-08-30T22:58:32.000Z
2021-12-12T10:47:52.000Z
src/product_data_types/apps.py
evis-market/web-interface-backend
f8930ff1c009ad18e522ab29680b4bcd50a6020e
[ "MIT" ]
null
null
null
src/product_data_types/apps.py
evis-market/web-interface-backend
f8930ff1c009ad18e522ab29680b4bcd50a6020e
[ "MIT" ]
1
2021-08-22T19:12:44.000Z
2021-08-22T19:12:44.000Z
from django.apps import AppConfig
25.75
56
0.771845
from django.apps import AppConfig class ProductDataTypesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'product_data_types' verbose_name = 'Product data types'
0
148
23
7fa4fe2358baef5d84f26905903f3f8b4bb6d5f4
12,163
py
Python
venv/lib/python3.8/site-packages/xdis/load.py
yuta-komura/vishnu
67173b674d5f4f3be189474103612447ef69ab44
[ "MIT" ]
1
2021-05-20T19:33:37.000Z
2021-05-20T19:33:37.000Z
S4/S4 Decompiler/xdis/load.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
4
2020-10-03T20:37:55.000Z
2020-10-04T23:11:38.000Z
S4/S4 Decompiler/xdis/load.py
NeonOcean/Environment
ca658cf66e8fd6866c22a4a0136d415705b36d26
[ "CC-BY-4.0" ]
null
null
null
# Copyright (c) 2015-2020 by Rocky Bernstein # 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. import marshal, py_compile, sys, tempfile, time from struct import unpack, pack import os.path as osp import xdis.unmarshal from xdis.version_info import PYTHON3, PYTHON_VERSION from xdis.magics import ( IS_PYPY3, PYTHON_MAGIC_INT, int2magic, magic_int2float, magic2int, magicint2version, versions, ) from xdis.dropbox.decrypt25 import fix_dropbox_pyc def load_file(filename, out=sys.stdout): """ load a Python source file and compile it to byte-code _load_file(filename: string): code_object filename: name of file containing Python source code (normally a .py) code_object: code_object compiled from this source code This function does NOT write any file! """ fp = open(filename, "rb") try: source = fp.read() try: if PYTHON_VERSION < 2.6: co = compile(source, filename, "exec") else: co = compile(source, filename, "exec", dont_inherit=True) except SyntaxError: out.write(">>Syntax error in %s\n" % filename) raise finally: fp.close() return co def load_module(filename, code_objects=None, fast_load=False, get_code=True): """load a module without importing it. Parameters: filename: name of file containing Python byte-code object (normally a .pyc) code_objects: list of additional code_object from this file. This might be a types.CodeType or one of the portable xdis code types, e.g. Code38, Code3, Code2, etc. This can be empty get_code: bool. Parsing the code object takes a bit of parsing time, but sometimes all you want is the module info, time string, code size, python version, etc. For that, set `get_code` to `False`. Return values are as follows: float_version: float; the floating-point version number for the given magic_int, e.g. 2.7 or 3.4 timestamp: int; the seconds since EPOCH of the time of the bytecode creation, or None if no timestamp was stored magic_int: int, a more specific than version number. The actual byte code version of the code object co : code object ispypy : True if this was a PyPy code object source_size: The size of the source code mod 2**32, if that was stored in the bytecode. None otherwise. sip_hash : the SIP Hash for the file (only in Python 3.7 or greater), if the file was created with a SIP hash or None otherwise. Note that if the sip_hash is not none, then the timestamp and source_size will be invalid. """ # Some sanity checks if not osp.exists(filename): raise ImportError("File name: '%s' doesn't exist" % filename) elif not osp.isfile(filename): raise ImportError("File name: '%s' isn't a file" % filename) elif osp.getsize(filename) < 50: raise ImportError( "File name: '%s (%d bytes)' is too short to be a valid pyc file" % (filename, osp.getsize(filename)) ) with open(filename, "rb") as fp: return load_module_from_file_object( fp, filename=filename, code_objects=code_objects, fast_load=fast_load, get_code=get_code, ) def load_module_from_file_object( fp, filename="<unknown>", code_objects=None, fast_load=False, get_code=True ): """load a module from a file object without importing it. See :func:load_module for a list of return values. """ if code_objects is None: code_objects = {} timestamp = 0 try: magic = fp.read(4) magic_int = magic2int(magic) # For reasons I don't understand, PyPy 3.2 stores a magic # of '0'... The two values below are for Python 2.x and 3.x respectively if magic[0:1] in ["0", b"0"]: magic = int2magic(3180 + 7) try: # FIXME: use the internal routine below float_version = magic_int2float(magic_int) except KeyError: if magic_int in (2657, 22138): raise ImportError("This smells like Pyston which is not supported.") if len(magic) >= 2: raise ImportError( "Unknown magic number %s in %s" % (ord(magic[0:1]) + 256 * ord(magic[1:2]), filename) ) else: raise ImportError("Bad magic number: '%s'" % magic) if magic_int in ( 3010, 3020, 3030, 3040, 3050, 3060, 3061, 3071, 3361, 3091, 3101, 3103, 3141, 3270, 3280, 3290, 3300, 3320, 3330, 3371, 62071, 62071, 62081, 62091, 62092, 62111, ): raise ImportError( "%s is interim Python %s (%d) bytecode which is " "not supported.\nFinal released versions are " "supported." % (filename, versions[magic], magic2int(magic)) ) elif magic_int == 62135: fp.seek(0) return fix_dropbox_pyc(fp) elif magic_int == 62215: raise ImportError( "%s is a dropbox-hacked Python %s (bytecode %d).\n" "See https://github.com/kholia/dedrop for how to " "decrypt." % (filename, versions[magic], magic2int(magic)) ) try: # print version my_magic_int = PYTHON_MAGIC_INT magic_int = magic2int(magic) version = magic_int2float(magic_int) timestamp = None source_size = None sip_hash = None ts = fp.read(4) if version >= 3.7: # PEP 552. https://www.python.org/dev/peps/pep-0552/ pep_bits = ts[-1] if PYTHON_VERSION <= 2.7: pep_bits = ord(pep_bits) if (pep_bits & 1) or magic_int == 3393: # 3393 is 3.7.0beta3 # SipHash sip_hash = unpack("<Q", fp.read(8))[0] else: # Uses older-style timestamp and size timestamp = unpack("<I", fp.read(4))[0] # pep552_bits source_size = unpack("<I", fp.read(4))[0] # size mod 2**32 pass else: timestamp = unpack("<I", ts)[0] # Note: a higher magic number doesn't necessarily mean a later # release. At Python 3.0 the magic number decreased # significantly. Hence the range below. Also note inclusion of # the size info, occurred within a Python major/minor # release. Hence the test on the magic value rather than # PYTHON_VERSION, although PYTHON_VERSION would probably work. if ( (3200 <= magic_int < 20121) and version >= 1.5 or magic_int in IS_PYPY3 ): source_size = unpack("<I", fp.read(4))[0] # size mod 2**32 if get_code: if my_magic_int == magic_int: bytecode = fp.read() co = marshal.loads(bytecode) elif fast_load: co = xdis.marsh.load(fp, magicint2version[magic_int]) else: co = xdis.unmarshal.load_code(fp, magic_int, code_objects) pass else: co = None except: kind, msg = sys.exc_info()[0:2] import traceback traceback.print_exc() raise ImportError( "Ill-formed bytecode file %s\n%s; %s" % (filename, kind, msg) ) finally: fp.close() return ( float_version, timestamp, magic_int, co, is_pypy(magic_int), source_size, sip_hash, ) def write_bytecode_file(bytecode_path, code, magic_int, filesize=0): """Write bytecode file _bytecode_path_, with code for having Python magic_int (i.e. bytecode associated with some version of Python) """ fp = open(bytecode_path, "wb") try: if PYTHON3: fp.write(pack("<Hcc", magic_int, b"\r", b"\n")) else: fp.write(pack("<Hcc", magic_int, "\r", "\n")) fp.write(pack("<I", int(time.time()))) if 3000 <= magic_int < 20121: # In Python 3 you need to write out the size mod 2**32 here fp.write(pack("<I", filesize)) fp.write(marshal.dumps(code)) finally: fp.close() if __name__ == "__main__": co = load_file(__file__) obj_path = check_object_path(__file__) version, timestamp, magic_int, co2, pypy, source_size, sip_hash = load_module( obj_path ) print("version", version, "magic int", magic_int, "is_pypy", pypy) if timestamp is not None: import datetime print(datetime.datetime.fromtimestamp(timestamp)) if source_size is not None: print("source size mod 2**32: %d" % source_size) if sip_hash is not None: print("Sip Hash: 0x%x" % sip_hash) assert co == co2
33.880223
107
0.553317
# Copyright (c) 2015-2020 by Rocky Bernstein # 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. import marshal, py_compile, sys, tempfile, time from struct import unpack, pack import os.path as osp import xdis.unmarshal from xdis.version_info import PYTHON3, PYTHON_VERSION from xdis.magics import ( IS_PYPY3, PYTHON_MAGIC_INT, int2magic, magic_int2float, magic2int, magicint2version, versions, ) from xdis.dropbox.decrypt25 import fix_dropbox_pyc def is_python_source(path): try: data = open(path, "r").read() except UnicodeDecodeError: for encoding in ("utf-8", "utf-16", "latin-1", "iso-8859-15"): try: data = open(path, "r", encoding=encoding).read() except UnicodeDecodeError: pass else: break except: return False try: compile(data, path, "exec") except: return False return True def is_bytecode_extension(path): return path.endswith(".pyc") or path.endswith(".pyo") def check_object_path(path): if not is_bytecode_extension(path) and is_python_source(path): try: import importlib bytecode_path = importlib.util.cache_from_source(path, optimization="") if osp.exists(bytecode_path): return bytecode_path except: try: import imp imp.cache_from_source(path, debug_override=False) except: pass pass basename = osp.basename(path)[0:-3] if PYTHON3: spath = path else: spath = path.decode("utf-8") path = tempfile.mkstemp(prefix=basename + "-", suffix=".pyc", text=False)[1] py_compile.compile(spath, cfile=path, doraise=True) if not is_bytecode_extension(path): raise ValueError( "path %s must point to a Python source that can be compiled, or Python bytecode (.pyc, .pyo)\n" % path ) return path def is_pypy(magic_int): return magic_int in ((62211 + 7, 3180 + 7) + IS_PYPY3) def load_file(filename, out=sys.stdout): """ load a Python source file and compile it to byte-code _load_file(filename: string): code_object filename: name of file containing Python source code (normally a .py) code_object: code_object compiled from this source code This function does NOT write any file! """ fp = open(filename, "rb") try: source = fp.read() try: if PYTHON_VERSION < 2.6: co = compile(source, filename, "exec") else: co = compile(source, filename, "exec", dont_inherit=True) except SyntaxError: out.write(">>Syntax error in %s\n" % filename) raise finally: fp.close() return co def load_module(filename, code_objects=None, fast_load=False, get_code=True): """load a module without importing it. Parameters: filename: name of file containing Python byte-code object (normally a .pyc) code_objects: list of additional code_object from this file. This might be a types.CodeType or one of the portable xdis code types, e.g. Code38, Code3, Code2, etc. This can be empty get_code: bool. Parsing the code object takes a bit of parsing time, but sometimes all you want is the module info, time string, code size, python version, etc. For that, set `get_code` to `False`. Return values are as follows: float_version: float; the floating-point version number for the given magic_int, e.g. 2.7 or 3.4 timestamp: int; the seconds since EPOCH of the time of the bytecode creation, or None if no timestamp was stored magic_int: int, a more specific than version number. The actual byte code version of the code object co : code object ispypy : True if this was a PyPy code object source_size: The size of the source code mod 2**32, if that was stored in the bytecode. None otherwise. sip_hash : the SIP Hash for the file (only in Python 3.7 or greater), if the file was created with a SIP hash or None otherwise. Note that if the sip_hash is not none, then the timestamp and source_size will be invalid. """ # Some sanity checks if not osp.exists(filename): raise ImportError("File name: '%s' doesn't exist" % filename) elif not osp.isfile(filename): raise ImportError("File name: '%s' isn't a file" % filename) elif osp.getsize(filename) < 50: raise ImportError( "File name: '%s (%d bytes)' is too short to be a valid pyc file" % (filename, osp.getsize(filename)) ) with open(filename, "rb") as fp: return load_module_from_file_object( fp, filename=filename, code_objects=code_objects, fast_load=fast_load, get_code=get_code, ) def load_module_from_file_object( fp, filename="<unknown>", code_objects=None, fast_load=False, get_code=True ): """load a module from a file object without importing it. See :func:load_module for a list of return values. """ if code_objects is None: code_objects = {} timestamp = 0 try: magic = fp.read(4) magic_int = magic2int(magic) # For reasons I don't understand, PyPy 3.2 stores a magic # of '0'... The two values below are for Python 2.x and 3.x respectively if magic[0:1] in ["0", b"0"]: magic = int2magic(3180 + 7) try: # FIXME: use the internal routine below float_version = magic_int2float(magic_int) except KeyError: if magic_int in (2657, 22138): raise ImportError("This smells like Pyston which is not supported.") if len(magic) >= 2: raise ImportError( "Unknown magic number %s in %s" % (ord(magic[0:1]) + 256 * ord(magic[1:2]), filename) ) else: raise ImportError("Bad magic number: '%s'" % magic) if magic_int in ( 3010, 3020, 3030, 3040, 3050, 3060, 3061, 3071, 3361, 3091, 3101, 3103, 3141, 3270, 3280, 3290, 3300, 3320, 3330, 3371, 62071, 62071, 62081, 62091, 62092, 62111, ): raise ImportError( "%s is interim Python %s (%d) bytecode which is " "not supported.\nFinal released versions are " "supported." % (filename, versions[magic], magic2int(magic)) ) elif magic_int == 62135: fp.seek(0) return fix_dropbox_pyc(fp) elif magic_int == 62215: raise ImportError( "%s is a dropbox-hacked Python %s (bytecode %d).\n" "See https://github.com/kholia/dedrop for how to " "decrypt." % (filename, versions[magic], magic2int(magic)) ) try: # print version my_magic_int = PYTHON_MAGIC_INT magic_int = magic2int(magic) version = magic_int2float(magic_int) timestamp = None source_size = None sip_hash = None ts = fp.read(4) if version >= 3.7: # PEP 552. https://www.python.org/dev/peps/pep-0552/ pep_bits = ts[-1] if PYTHON_VERSION <= 2.7: pep_bits = ord(pep_bits) if (pep_bits & 1) or magic_int == 3393: # 3393 is 3.7.0beta3 # SipHash sip_hash = unpack("<Q", fp.read(8))[0] else: # Uses older-style timestamp and size timestamp = unpack("<I", fp.read(4))[0] # pep552_bits source_size = unpack("<I", fp.read(4))[0] # size mod 2**32 pass else: timestamp = unpack("<I", ts)[0] # Note: a higher magic number doesn't necessarily mean a later # release. At Python 3.0 the magic number decreased # significantly. Hence the range below. Also note inclusion of # the size info, occurred within a Python major/minor # release. Hence the test on the magic value rather than # PYTHON_VERSION, although PYTHON_VERSION would probably work. if ( (3200 <= magic_int < 20121) and version >= 1.5 or magic_int in IS_PYPY3 ): source_size = unpack("<I", fp.read(4))[0] # size mod 2**32 if get_code: if my_magic_int == magic_int: bytecode = fp.read() co = marshal.loads(bytecode) elif fast_load: co = xdis.marsh.load(fp, magicint2version[magic_int]) else: co = xdis.unmarshal.load_code(fp, magic_int, code_objects) pass else: co = None except: kind, msg = sys.exc_info()[0:2] import traceback traceback.print_exc() raise ImportError( "Ill-formed bytecode file %s\n%s; %s" % (filename, kind, msg) ) finally: fp.close() return ( float_version, timestamp, magic_int, co, is_pypy(magic_int), source_size, sip_hash, ) def write_bytecode_file(bytecode_path, code, magic_int, filesize=0): """Write bytecode file _bytecode_path_, with code for having Python magic_int (i.e. bytecode associated with some version of Python) """ fp = open(bytecode_path, "wb") try: if PYTHON3: fp.write(pack("<Hcc", magic_int, b"\r", b"\n")) else: fp.write(pack("<Hcc", magic_int, "\r", "\n")) fp.write(pack("<I", int(time.time()))) if 3000 <= magic_int < 20121: # In Python 3 you need to write out the size mod 2**32 here fp.write(pack("<I", filesize)) fp.write(marshal.dumps(code)) finally: fp.close() if __name__ == "__main__": co = load_file(__file__) obj_path = check_object_path(__file__) version, timestamp, magic_int, co2, pypy, source_size, sip_hash = load_module( obj_path ) print("version", version, "magic int", magic_int, "is_pypy", pypy) if timestamp is not None: import datetime print(datetime.datetime.fromtimestamp(timestamp)) if source_size is not None: print("source size mod 2**32: %d" % source_size) if sip_hash is not None: print("Sip Hash: 0x%x" % sip_hash) assert co == co2
1,569
0
92
be4aedc2ea1f5dae400358c5df45de6791875da8
452
py
Python
envergo/evaluations/migrations/0016_request_parcels.py
MTES-MCT/envergo
8bb6e4ffa15a39edda51b39401db6cc12e73ad0a
[ "MIT" ]
null
null
null
envergo/evaluations/migrations/0016_request_parcels.py
MTES-MCT/envergo
8bb6e4ffa15a39edda51b39401db6cc12e73ad0a
[ "MIT" ]
6
2021-07-12T14:33:18.000Z
2022-02-14T10:36:09.000Z
envergo/evaluations/migrations/0016_request_parcels.py
MTES-MCT/envergo
8bb6e4ffa15a39edda51b39401db6cc12e73ad0a
[ "MIT" ]
null
null
null
# Generated by Django 3.2.6 on 2021-08-26 14:49 from django.db import migrations, models
22.6
86
0.599558
# Generated by Django 3.2.6 on 2021-08-26 14:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('geodata', '0001_initial'), ('evaluations', '0015_request'), ] operations = [ migrations.AddField( model_name='request', name='parcels', field=models.ManyToManyField(to='geodata.Parcel', verbose_name='Parcels'), ), ]
0
338
23
d1621eaaee2261fef168153ab19e0c022183ce72
830
py
Python
self_attention/word2vec.py
huangqianfei0916/Attention_classification
a60460771cce640737523d0ea3b9ef22f1c1bcb9
[ "MIT" ]
2
2021-03-21T02:10:10.000Z
2021-04-09T09:38:43.000Z
self_attention/word2vec.py
huangqianfei0916/Attention_classification
a60460771cce640737523d0ea3b9ef22f1c1bcb9
[ "MIT" ]
null
null
null
self_attention/word2vec.py
huangqianfei0916/Attention_classification
a60460771cce640737523d0ea3b9ef22f1c1bcb9
[ "MIT" ]
3
2020-07-29T05:32:16.000Z
2022-03-26T07:40:42.000Z
from gensim.models import word2vec import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-word', required=True,help="word file") parser.add_argument('-iter', default=3) parser.add_argument('-sg', default=0) parser.add_argument('-hs', default=1) parser.add_argument('-window', default=3) parser.add_argument('-size', default=100) opt = parser.parse_args() print(opt) tomodel(opt.word,opt.iter,opt.sg,opt.hs,opt.window,opt.size) print("end..................")
31.923077
105
0.691566
from gensim.models import word2vec def tomodel(train_word, iter1, sg, hs, window, size): sentences = word2vec.LineSentence(train_word) model = word2vec.Word2Vec(sentences, iter=iter1, sg=sg, hs=hs, min_count=1, window=window, size=size) model.wv.save_word2vec_format("word2vec.model", binary=False) import argparse if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-word', required=True,help="word file") parser.add_argument('-iter', default=3) parser.add_argument('-sg', default=0) parser.add_argument('-hs', default=1) parser.add_argument('-window', default=3) parser.add_argument('-size', default=100) opt = parser.parse_args() print(opt) tomodel(opt.word,opt.iter,opt.sg,opt.hs,opt.window,opt.size) print("end..................")
254
0
23
f905e161591e69fe8cae246049f2bea69e1749a6
10,794
py
Python
shells/backends/azure_tf_backend/src/driver.py
oleksandr-r-q/CloudShell-Terraform-Shell
8d331cf8eebeae794e4e73a3c70af8064bafa434
[ "Apache-2.0" ]
4
2021-11-26T05:41:05.000Z
2022-03-11T20:01:40.000Z
shells/backends/azure_tf_backend/src/driver.py
oleksandr-r-q/CloudShell-Terraform-Shell
8d331cf8eebeae794e4e73a3c70af8064bafa434
[ "Apache-2.0" ]
10
2021-07-14T05:19:54.000Z
2021-11-02T05:37:48.000Z
shells/backends/azure_tf_backend/src/driver.py
oleksandr-r-q/CloudShell-Terraform-Shell
8d331cf8eebeae794e4e73a3c70af8064bafa434
[ "Apache-2.0" ]
1
2021-11-01T07:46:59.000Z
2021-11-01T07:46:59.000Z
import json from azure.core.exceptions import ClientAuthenticationError from cloudshell.shell.core.resource_driver_interface import ResourceDriverInterface from cloudshell.shell.core.driver_context import AutoLoadDetails from cloudshell.shell.core.session.cloudshell_session import CloudShellSessionContext from cloudshell.shell.core.session.logging_session import LoggingSessionContext from constants import AZURE2G_MODEL, AZURE_MODELS from data_model import AzureTfBackend from azure.storage.blob import BlobServiceClient from msrestazure.azure_active_directory import ServicePrincipalCredentials from azure.mgmt.storage import StorageManagementClient
51.894231
118
0.693163
import json from azure.core.exceptions import ClientAuthenticationError from cloudshell.shell.core.resource_driver_interface import ResourceDriverInterface from cloudshell.shell.core.driver_context import AutoLoadDetails from cloudshell.shell.core.session.cloudshell_session import CloudShellSessionContext from cloudshell.shell.core.session.logging_session import LoggingSessionContext from constants import AZURE2G_MODEL, AZURE_MODELS from data_model import AzureTfBackend from azure.storage.blob import BlobServiceClient from msrestazure.azure_active_directory import ServicePrincipalCredentials from azure.mgmt.storage import StorageManagementClient class AzureTfBackendDriver (ResourceDriverInterface): def __init__(self): """ ctor must be without arguments, it is created with reflection at run time """ self._backend_secret_vars = {} pass def initialize(self, context): """ Initialize the driver session, this function is called everytime a new instance of the driver is created This is a good place to load and cache the driver configuration, initiate sessions etc. :param InitCommandContext context: the context the command runs on """ pass def cleanup(self): """ Destroy the driver session, this function is called everytime a driver instance is destroyed This is a good place to close any open sessions, finish writing to log files """ pass # <editor-fold desc="Discovery"> def get_inventory(self, context): """ Discovers the resource structure and attributes. :param AutoLoadCommandContext context: the context the command runs on :return Attribute and sub-resource information for the Shell resource you can return an AutoLoadDetails object :rtype: AutoLoadDetails """ # See below some example code demonstrating how to return the resource structure and attributes # In real life, this code will be preceded by SNMP/other calls to the resource details and will not be static # run 'shellfoundry generate' in order to create classes that represent your data model self._get_validated_blob_svc_client(context) return AutoLoadDetails([], []) def _get_validated_blob_svc_client(self, context): with LoggingSessionContext(context) as logger: azure_backend_resource = AzureTfBackend.create_from_context(context) credential = self._get_cloud_credential(context, azure_backend_resource, logger) blob_svc_container_client = self._get_container_client(logger, azure_backend_resource, credential) self._validate_container(logger, blob_svc_container_client) return blob_svc_container_client def _validate_container(self, logger, blob_svc_container_client): try: # The following command will yield an exception in case container does not exist blob_svc_container_client.get_container_properties() except ClientAuthenticationError as e: self._handle_exception_logging( logger, "Was not able to Authenticate in order to validate azure backend storage" ) def _get_cloud_credential(self, context, azure_backend_resource, logger): try: api = CloudShellSessionContext(context).get_api() if api.DecryptPassword(azure_backend_resource.access_key).Value: if azure_backend_resource.cloud_provider: self._handle_exception_logging(logger, "Only one method of authentication should be filled") credentials = api.DecryptPassword(azure_backend_resource.access_key).Value else: if azure_backend_resource.cloud_provider: clp_details = self._validate_clp(api, azure_backend_resource, logger) account_keys = self._get_storage_keys(api, azure_backend_resource, clp_details) if not account_keys.keys: self._handle_exception_logging(logger, "Unable to find access key for the storage account") credentials = account_keys.keys[0].value else: self._handle_exception_logging(logger, "Inputs for Cloud Backend Access missing") except Exception as e: self._handle_exception_logging(logger, "Inputs for Cloud Backend Access missing or incorrect") return credentials def _get_container_client(self, logger, azure_backend_resource, credential): try: blob_svc_client = BlobServiceClient( account_url=f"https://{azure_backend_resource.storage_account_name}.blob.core.windows.net/", credential=credential ) blob_svc_container_client = blob_svc_client.get_container_client(azure_backend_resource.container_name) # The following command will yield an exception in case container does not exist blob_svc_container_client.get_container_properties() except ClientAuthenticationError as e: self._handle_exception_logging( logger, "Was not able to Authenticate in order to validate azure backend storage" ) return blob_svc_container_client def _get_storage_keys(self, api, azure_backend_resource, clp_details): azure_model_prefix = "" if clp_details.ResourceModelName == AZURE2G_MODEL: azure_model_prefix = AZURE2G_MODEL + "." self._fill_backend_sercret_vars_data(api, azure_model_prefix, clp_details.ResourceAttributes) credentials = ServicePrincipalCredentials( tenant=self._backend_secret_vars["tenant_id"], client_id=self._backend_secret_vars["client_id"], secret=self._backend_secret_vars["client_secret"] ) storage_client = StorageManagementClient( credentials=credentials, subscription_id=self._backend_secret_vars["subscription_id"] ) account_keys = storage_client.storage_accounts.list_keys( azure_backend_resource.resource_group, azure_backend_resource.storage_account_name ) return account_keys def _handle_exception_logging(self, logger, msg): logger.exception(msg) raise ValueError(msg) def get_backend_data(self, context, tf_state_unique_name: str) -> str: with LoggingSessionContext(context) as logger: azure_backend_resource = AzureTfBackend.create_from_context(context) tf_state_file_string = self._generate_state_file_string(azure_backend_resource, tf_state_unique_name) backend_data = {"tf_state_file_string": tf_state_file_string} try: api = CloudShellSessionContext(context).get_api() if api.DecryptPassword(azure_backend_resource.access_key).Value != '': dec_access_key = api.DecryptPassword(azure_backend_resource.access_key).Value # self._backend_secret_vars = {"access_key": dec_access_key} else: if azure_backend_resource.cloud_provider: clp_details = self._validate_clp(api, azure_backend_resource, logger) azure_model_prefix = "" if clp_details.ResourceModelName == AZURE2G_MODEL: azure_model_prefix = AZURE2G_MODEL + "." # self._backend_secret_vars = {"access_key": self._get_cloud_credential()} self._fill_backend_sercret_vars_data(api, azure_model_prefix, clp_details.ResourceAttributes) else: self._handle_exception_logging(logger, "Inputs for Cloud Backend Access missing") self._backend_secret_vars = \ {"access_key": self._get_cloud_credential(context, azure_backend_resource, logger)} except Exception as e: self._handle_exception_logging(logger, "Inputs for Cloud Backend Access missing or incorrect") logger.info(f"Returning backend data for creating provider file :\n{backend_data}") response = json.dumps({"backend_data": backend_data, "backend_secret_vars": self._backend_secret_vars}) return response def delete_tfstate_file(self, context, tf_state_unique_name: str): container_client = self._get_validated_blob_svc_client(context) blobs = list(container_client.list_blobs(name_starts_with=tf_state_unique_name)) for blob in blobs: if blob["name"] == tf_state_unique_name: container_client.delete_blob(blob) return raise ValueError(f"{tf_state_unique_name} file was not removed from backend provider") def _generate_state_file_string(self, azure_backend_resource, tf_state_unique_name): tf_state_file_string = f'terraform {{\n\ \tbackend "azurerm" {{\n\ \t\tstorage_account_name = "{azure_backend_resource.storage_account_name}"\n\ \t\tcontainer_name = "{azure_backend_resource.container_name}"\n\ \t\tkey = "{tf_state_unique_name}"\n\ \t}}\n\ }}' return tf_state_file_string def _validate_clp(self, api, azure_backend_resource, logger): clp_resource_name = azure_backend_resource.cloud_provider clp_details = api.GetResourceDetails(clp_resource_name) clp_res_model = clp_details.ResourceModelName clpr_res_fam = clp_details.ResourceFamilyName if (clpr_res_fam != 'Cloud Provider' and clpr_res_fam != 'CS_CloudProvider') or \ clp_res_model not in AZURE_MODELS: logger.error(f"Cloud Provider does not have the expected type: {clpr_res_fam}") raise ValueError(f"Cloud Provider does not have the expected type:{clpr_res_fam}") return clp_details def _fill_backend_sercret_vars_data(self, api, azure_model_prefix, clp_resource_attributes): self._backend_secret_vars = {} for attr in clp_resource_attributes: if attr.Name == azure_model_prefix + "Azure Subscription ID": self._backend_secret_vars["subscription_id"] = attr.Value if attr.Name == azure_model_prefix + "Azure Tenant ID": self._backend_secret_vars["tenant_id"] = attr.Value if attr.Name == azure_model_prefix + "Azure Application ID": self._backend_secret_vars["client_id"] = attr.Value if attr.Name == azure_model_prefix + "Azure Application Key": dec_client_secret = api.DecryptPassword(attr.Value).Value self._backend_secret_vars["client_secret"] = dec_client_secret
8,197
1,915
23
44b0ca69529138fdd86fa4389670400d93e53eb5
4,372
py
Python
tests/test_grow_tree.py
stephleighton/placentagen
968685955fce7ca5503a85713113f62c1e5c74a4
[ "Apache-2.0" ]
2
2019-06-11T21:35:54.000Z
2022-03-10T01:53:43.000Z
tests/test_grow_tree.py
stephleighton/placentagen
968685955fce7ca5503a85713113f62c1e5c74a4
[ "Apache-2.0" ]
31
2018-03-14T01:43:19.000Z
2020-07-23T21:23:27.000Z
tests/test_grow_tree.py
stephleighton/placentagen
968685955fce7ca5503a85713113f62c1e5c74a4
[ "Apache-2.0" ]
6
2018-04-29T23:42:48.000Z
2021-09-14T01:33:53.000Z
from unittest import TestCase import numpy as np import unittest import placentagen import os if __name__ == '__main__': unittest.main()
45.541667
113
0.522187
from unittest import TestCase import numpy as np import unittest import placentagen import os class Test_create_trees(TestCase): def test_umilical_node(self): thickness = (3.0 * 1 / (4.0 * np.pi)) ** (1.0 / 3.0) * 2.0 data_input = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) datapoints = placentagen.umbilical_seed_geometry(1.0, thickness, 1.0, 0.0, 0.0, 0.1, 20.0, data_input) self.assertTrue(datapoints['nodes'][5][3], 0.61833222) def test_umilical_node(self): thickness = (3.0 * 1 / (4.0 * np.pi)) ** (1.0 / 3.0) * 2.0 data_input = np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]) datapoints = placentagen.umbilical_seed_geometry(1.0, thickness, 1.0, 0.0, 0.0, 0.1, 20.0, data_input) self.assertTrue(datapoints['elems'][2][2], 4) class Test_grow_trees(TestCase): def test_grow_node(self): seed_geom = {} seed_geom['nodes'] = [[0, 0, 1, 0], [1, 0, .1, 0], [2, -0.1, 0.1, 0], [3, 0.1, 0.1, 0]] seed_geom['elems'] = [[0, 0, 1], [1, 1, 2], [2, 1, 3]] seed_geom['elem_up'] = [[0, 0, 0], [1, 0, 0], [1, 0, 0]] seed_geom['elem_down'] = [[2, 1, 2], [0, 0, 0], [0, 0, 0]] data = [[-0.1, 0.0, 0.0], [0.1, 0.0, 0.0], [0.0, 0.0, 0.3], [0.1, 0.1, 0.1], [-0.2, -0.2, -0.2]] chorion_geom = placentagen.grow_chorionic_surface(90 * np.pi / 180, 45 * np.pi / 180, 0.5, 0.1, 1, 1, 1, 1, data, seed_geom, 'surface') self.assertTrue(chorion_geom['nodes'][6][3], 0.48527182) def test_grow_node_alt(self): seed_geom = {} seed_geom['nodes'] = [[0, 0, 1, 0], [1, 0, .1, 0], [2, -0.1, 0.1, 0], [3, 0.1, 0.1, 0]] seed_geom['elems'] = [[0, 0, 1], [1, 1, 2], [2, 1, 3]] seed_geom['elem_up'] = [[0, 0, 0], [1, 0, 0], [1, 0, 0]] seed_geom['elem_down'] = [[2, 1, 2], [0, 0, 0], [0, 0, 0]] data = placentagen.uniform_data_on_ellipsoid(5,1,1,1,0) geom = placentagen.grow_large_tree(90 * np.pi / 180, 45 * np.pi / 180, 0.5, 0.1, 1, 1, 1, 1, data, seed_geom,1) self.assertTrue(geom['nodes'][6][3], 0.22301891) class Test_refine_trees(TestCase): def test_refine_node(self): from_elem = 0 initial_geom = {} initial_geom['nodes'] = [[0, 0.0, 0.0, 0.0], [1, 0.0, 0.0, 1.0]] initial_geom['elems'] = [[0, 0, 1]] initial_geom['elem_up'] = [[0, 0, 0]] initial_geom['elem_down'] = [[0, 0, 0]] project={} project['status']=[] refined_geom = placentagen.refine_1D(initial_geom, from_elem,project) self.assertTrue(refined_geom['nodes'][1][3], 0.5) def test_refine_cnct(self): from_elem = 0 initial_geom = {} initial_geom['nodes'] = [[0, 0.0, 0.0, 0.0], [1, 0.0, 0.0, 1.0]] initial_geom['elems'] = [[0, 0, 1]] initial_geom['elem_up'] = [[0, 0, 0]] initial_geom['elem_down'] = [[0, 0, 0]] project={} project['status']=[] refined_geom = placentagen.refine_1D(initial_geom, from_elem,project) self.assertTrue(refined_geom['elem_up'][1][0], 1) def test_refine_node_from(self): from_elem = 1 initial_geom = {} initial_geom['nodes'] = [[0, 0.0, 0.0, 0.0], [1, 0.0, 0.0, 1.0], [2, 1.0, 0.0, 1.0], [3, -1.0, 0.0, 1.0]] initial_geom['elems'] = [[0, 0, 1], [1, 1, 2], [1, 1, 3]] initial_geom['elem_up'] = [[0, 0, 0], [1, 0, 0], [1, 0, 0]] initial_geom['elem_down'] = [[2, 1, 2], [0, 0, 0], [0, 0, 0]] project={} project['status']=[] refined_geom = placentagen.refine_1D(initial_geom, from_elem,project) self.assertTrue(refined_geom['nodes'][2][1], 0.5) class Test_add_villi(TestCase): def test_add_villi(self): from_elem = 0 initial_geom = {} initial_geom['nodes'] = [[0, 0.0, 0.0, 0.0], [1, 0.0, 0.5, 0.0], [2, 0.0, 1.0, 0.0]] initial_geom['elems'] = [[0, 0, 1], [1, 1, 2]] initial_geom['elem_up'] = [[0, 0, 0], [1, 0, 0]] initial_geom['elem_down'] = [[1, 1, 0], [0, 0, 0]] chorion_and_stem = placentagen.add_stem_villi(initial_geom, from_elem, 0.2, False, 'test.txt') self.assertTrue(chorion_and_stem['nodes'][3][3], -0.2) if __name__ == '__main__': unittest.main()
3,877
47
304
1b959ecde2bf0e549c10dc649b1fc3831d79b54e
2,104
py
Python
main.py
MostafaAbuelnoor/Facial-Recognitoin
43c02c8479120aa67a05699c3ba806338398e07c
[ "MIT" ]
1
2021-05-26T08:20:14.000Z
2021-05-26T08:20:14.000Z
main.py
MostafaAbuelnoor/Facial-Recognitoin
43c02c8479120aa67a05699c3ba806338398e07c
[ "MIT" ]
null
null
null
main.py
MostafaAbuelnoor/Facial-Recognitoin
43c02c8479120aa67a05699c3ba806338398e07c
[ "MIT" ]
1
2022-03-07T07:22:08.000Z
2022-03-07T07:22:08.000Z
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' ##This is used to suppress the warnings given by tensorflow import tensorflow as tf #Comment the above lines if there's an error and the code isn't working as expected from deepface import DeepFace import pandas as pd # Add photos to the photos folder in order to analyse them or do facial recognition on them ############################### Face recognition # This function looks at a photo (Argument 1) and sees if the person is in another photo in a database (Argument 2) ############################### Face analysis # This function analyzes the face in the picture(Argument) and gives out the estimated age, gender, race and emotion ############################### Face verification # This function returns whether or not two pictures(Both arguments) contain the same person ############################### Real time face analysis # This function will give a real time analysis (Age, gender, emotion) of your face by opening the # webcamera and compares it to pictures in the database specified in the argument # Note: My webcamera is not working properly so I am not sure if this works as intended or not. if __name__ == "__main__": main()
40.461538
147
0.687738
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' ##This is used to suppress the warnings given by tensorflow import tensorflow as tf #Comment the above lines if there's an error and the code isn't working as expected from deepface import DeepFace import pandas as pd # Add photos to the photos folder in order to analyse them or do facial recognition on them def main(): faceRecognise("photos/will.jpg", "photos") faceAnalysis("photos/mostafa.jpg") faceVerify("photos/jackie.jpg", "photos/angelina.jpg") faceStream("photos") ############################### Face recognition # This function looks at a photo (Argument 1) and sees if the person is in another photo in a database (Argument 2) def faceRecognise(pic, database): df = DeepFace.find(img_path = pic, db_path = database) #Storing the results in a panda dataframe to be analysed print(df.head()) ############################### Face analysis # This function analyzes the face in the picture(Argument) and gives out the estimated age, gender, race and emotion def faceAnalysis(pic): obj = DeepFace.analyze(pic, actions = ['age', 'gender', 'race', 'emotion']) # Analysing the picture and storing the results to be printed later print("Age: ",obj["age"]) print("Race: ", obj["dominant_race"]) print("Emotion: ", obj["dominant_emotion"]) print("Gender: ", obj["gender"]) ############################### Face verification # This function returns whether or not two pictures(Both arguments) contain the same person def faceVerify(pic1, pic2): result = DeepFace.verify(pic1, pic2) # Comparing the two pictures print("Same person: ", result["verified"]) ############################### Real time face analysis # This function will give a real time analysis (Age, gender, emotion) of your face by opening the # webcamera and compares it to pictures in the database specified in the argument # Note: My webcamera is not working properly so I am not sure if this works as intended or not. def faceStream(database): DeepFace.stream(database) if __name__ == "__main__": main()
775
0
111
fba9a66135210ef0d62d9141e920c64ff6e57ae8
2,130
py
Python
aries_cloudagent/messaging/federatedlearningmessage/messages/federatedlearningmessage.py
harshkasyap/PyAriesFL
dd78dcebc771971abfee301b80cdd5d246c14840
[ "Apache-2.0" ]
7
2020-07-07T15:44:41.000Z
2022-03-26T21:20:41.000Z
aries_cloudagent/messaging/federatedlearningmessage/messages/federatedlearningmessage.py
totemprotocol/aries-fl
dd78dcebc771971abfee301b80cdd5d246c14840
[ "Apache-2.0" ]
null
null
null
aries_cloudagent/messaging/federatedlearningmessage/messages/federatedlearningmessage.py
totemprotocol/aries-fl
dd78dcebc771971abfee301b80cdd5d246c14840
[ "Apache-2.0" ]
2
2020-08-11T10:02:03.000Z
2021-12-12T12:19:21.000Z
"""Basic message.""" from datetime import datetime from typing import Union from marshmallow import fields from ...agent_message import AgentMessage, AgentMessageSchema from ...util import datetime_now, datetime_to_str from ...valid import INDY_ISO8601_DATETIME from ..message_types import FEDERATEDLEARNING_MESSAGE HANDLER_CLASS = ( "aries_cloudagent.messaging.federatedlearningmessage." + "handlers.basicmessage_handler.FederatedLearningMessageHandler" ) class FederatedLearningMessage(AgentMessage): """Class defining the structure of a federated learning message.""" class Meta: """Federated learning message metadata class.""" handler_class = HANDLER_CLASS message_type = FEDERATEDLEARNING_MESSAGE schema_class = "FederatedLearningMessageSchema" def __init__( self, *, sent_time: Union[str, datetime] = None, content: str = None, localization: str = None, **kwargs ): """ Initialize federated learning message object. Args: sent_time: Time message was sent content: message content localization: localization """ super(FederatedLearningMessage, self).__init__(**kwargs) if not sent_time: sent_time = datetime_now() self.sent_time = datetime_to_str(sent_time) self.content = content self.localization = localization class FederatedLearningMessageSchema(AgentMessageSchema): """FederatedLearning message schema class.""" class Meta: """FederatedLearning message schema metadata.""" model_class = FederatedLearningMessage localization = fields.Str( required=False, description="Localization", example="en-CA", data_key="l10n", ) sent_time = fields.Str( required=False, description="Time message was sent, ISO8601 with space date/time separator", **INDY_ISO8601_DATETIME ) content = fields.Str( required=True, description="Message content", example="Hello", )
26.962025
84
0.667606
"""Basic message.""" from datetime import datetime from typing import Union from marshmallow import fields from ...agent_message import AgentMessage, AgentMessageSchema from ...util import datetime_now, datetime_to_str from ...valid import INDY_ISO8601_DATETIME from ..message_types import FEDERATEDLEARNING_MESSAGE HANDLER_CLASS = ( "aries_cloudagent.messaging.federatedlearningmessage." + "handlers.basicmessage_handler.FederatedLearningMessageHandler" ) class FederatedLearningMessage(AgentMessage): """Class defining the structure of a federated learning message.""" class Meta: """Federated learning message metadata class.""" handler_class = HANDLER_CLASS message_type = FEDERATEDLEARNING_MESSAGE schema_class = "FederatedLearningMessageSchema" def __init__( self, *, sent_time: Union[str, datetime] = None, content: str = None, localization: str = None, **kwargs ): """ Initialize federated learning message object. Args: sent_time: Time message was sent content: message content localization: localization """ super(FederatedLearningMessage, self).__init__(**kwargs) if not sent_time: sent_time = datetime_now() self.sent_time = datetime_to_str(sent_time) self.content = content self.localization = localization class FederatedLearningMessageSchema(AgentMessageSchema): """FederatedLearning message schema class.""" class Meta: """FederatedLearning message schema metadata.""" model_class = FederatedLearningMessage localization = fields.Str( required=False, description="Localization", example="en-CA", data_key="l10n", ) sent_time = fields.Str( required=False, description="Time message was sent, ISO8601 with space date/time separator", **INDY_ISO8601_DATETIME ) content = fields.Str( required=True, description="Message content", example="Hello", )
0
0
0
fe951ac780dbde2cba39609a3d5e778c7cb3b4f3
626
py
Python
cms/home/migrations/0007_auto_20201125_1247.py
rkhleics/nhs-ei.website
9968916a5c442a2b33003f8a48b238df53ebded0
[ "MIT" ]
1
2021-02-04T13:20:31.000Z
2021-02-04T13:20:31.000Z
cms/home/migrations/0007_auto_20201125_1247.py
rkhleics/nhs-ei.website
9968916a5c442a2b33003f8a48b238df53ebded0
[ "MIT" ]
77
2020-11-29T23:10:16.000Z
2022-03-23T11:47:51.000Z
cms/home/migrations/0007_auto_20201125_1247.py
rkhleics/nhs-ei.website
9968916a5c442a2b33003f8a48b238df53ebded0
[ "MIT" ]
3
2021-03-19T09:23:59.000Z
2021-08-31T21:49:36.000Z
# Generated by Django 3.1.2 on 2020-11-25 12:47 from django.db import migrations, models import wagtail.core.fields
25.04
64
0.618211
# Generated by Django 3.1.2 on 2020-11-25 12:47 from django.db import migrations, models import wagtail.core.fields class Migration(migrations.Migration): dependencies = [ ('home', '0006_auto_20201125_1244'), ] operations = [ migrations.AddField( model_name='homepage', name='all_publications_sub_title', field=wagtail.core.fields.RichTextField(blank=True), ), migrations.AddField( model_name='homepage', name='all_publications_title', field=models.CharField(blank=True, max_length=100), ), ]
0
485
23
38e317f3795b434b14359446540d077599e83168
1,476
py
Python
ex_kerasApi.py
DLVIsualizer/dlvis-flask
e1e22028b2d57fb894d105bd716437a3de8e4e7f
[ "MIT" ]
null
null
null
ex_kerasApi.py
DLVIsualizer/dlvis-flask
e1e22028b2d57fb894d105bd716437a3de8e4e7f
[ "MIT" ]
13
2020-01-28T22:20:14.000Z
2022-03-11T23:20:14.000Z
ex_kerasApi.py
DLVIsualizer/dlvis-flask
e1e22028b2d57fb894d105bd716437a3de8e4e7f
[ "MIT" ]
null
null
null
# import the necessary packages from keras.applications import ResNet50 from keras.applications import MobileNet import matplotlib.pyplot as plt import numpy as np import cv2 import dlv if __name__ == "__main__": test = np.random.rand(500,300) cv2.imshow('img',test) cv2.waitKey(0) resnet50Model = MobileNet(weights="imagenet") dlvModel = dlv.Model(resnet50Model) dlvModel.addInputData('dog.jpg') dlvModel.getFeaturesFromFetchedList() result = dlvModel._indata_FeatureMap_Dict['dog.jpg']._featureMapList[0] result = np.moveaxis(result, -1, 0) filter0 = result[0] # filter0 = filter0.astype(np.uint8) cv2.imshow('image',filter0) cv2.waitKey(0) print('tmp') # # if __name__ == "__main__": # resnet50Model = MobileNet(weights="imagenet") # dlvModel = dlv.Model(resnet50Model) # dlvModel.addInputData('dog.jpg') # dlvModel.addInputData('cat.jpg') # dlvModel.getFeaturesFromFetchedList() # # # Prepare pyplot # # w = 112 # h = 112 # # # fig = plt.figure(figsize=(64, len(dlvModel._indata_FeatureMap_Dict['cat.jpg']._featureMapList))) # fig = plt.figure(figsize=(64, 1)) # # columns = 1 # rows = 64 # # for j in range(0, columns): # conv_j_result = dlvModel._indata_FeatureMap_Dict['cat.jpg']._featureMapList[j] # # for i in range(0, rows ): # subplot = fig.add_subplot(j+1, 64, j*64 + i + 1) # subplot.set_xticks([]) # subplot.set_yticks([]) # image = conv_j_result[:, :, i] # subplot.imshow(image) # plt.show()
22.707692
101
0.695122
# import the necessary packages from keras.applications import ResNet50 from keras.applications import MobileNet import matplotlib.pyplot as plt import numpy as np import cv2 import dlv if __name__ == "__main__": test = np.random.rand(500,300) cv2.imshow('img',test) cv2.waitKey(0) resnet50Model = MobileNet(weights="imagenet") dlvModel = dlv.Model(resnet50Model) dlvModel.addInputData('dog.jpg') dlvModel.getFeaturesFromFetchedList() result = dlvModel._indata_FeatureMap_Dict['dog.jpg']._featureMapList[0] result = np.moveaxis(result, -1, 0) filter0 = result[0] # filter0 = filter0.astype(np.uint8) cv2.imshow('image',filter0) cv2.waitKey(0) print('tmp') # # if __name__ == "__main__": # resnet50Model = MobileNet(weights="imagenet") # dlvModel = dlv.Model(resnet50Model) # dlvModel.addInputData('dog.jpg') # dlvModel.addInputData('cat.jpg') # dlvModel.getFeaturesFromFetchedList() # # # Prepare pyplot # # w = 112 # h = 112 # # # fig = plt.figure(figsize=(64, len(dlvModel._indata_FeatureMap_Dict['cat.jpg']._featureMapList))) # fig = plt.figure(figsize=(64, 1)) # # columns = 1 # rows = 64 # # for j in range(0, columns): # conv_j_result = dlvModel._indata_FeatureMap_Dict['cat.jpg']._featureMapList[j] # # for i in range(0, rows ): # subplot = fig.add_subplot(j+1, 64, j*64 + i + 1) # subplot.set_xticks([]) # subplot.set_yticks([]) # image = conv_j_result[:, :, i] # subplot.imshow(image) # plt.show()
0
0
0
e3d984eaea5180d35af66b9d17a7e46e5fca15cc
5,642
py
Python
python/onos/uenib/__init__.py
ray-milkey/onos-api
1df48546bba93fc475a080fdb29983c2e36da3c4
[ "Apache-2.0" ]
null
null
null
python/onos/uenib/__init__.py
ray-milkey/onos-api
1df48546bba93fc475a080fdb29983c2e36da3c4
[ "Apache-2.0" ]
null
null
null
python/onos/uenib/__init__.py
ray-milkey/onos-api
1df48546bba93fc475a080fdb29983c2e36da3c4
[ "Apache-2.0" ]
null
null
null
# Generated by the protocol buffer compiler. DO NOT EDIT! # sources: onos/uenib/ran.proto, onos/uenib/uenib.proto # plugin: python-betterproto from dataclasses import dataclass from typing import AsyncIterator, Dict, List import betterproto import grpclib @dataclass(eq=False, repr=False) class CellConnection(betterproto.Message): """CellConnection represents UE cell connection.""" id: str = betterproto.string_field(1) signal_strength: float = betterproto.double_field(2) @dataclass(eq=False, repr=False) class CellInfo(betterproto.Message): """CellInfo provides data on serving cell and candidate cells.""" serving_cell: "CellConnection" = betterproto.message_field(1) candidate_cells: List["CellConnection"] = betterproto.message_field(2) @dataclass(eq=False, repr=False) class Event(betterproto.Message): """CellConnection represents UE cell connection.""" type: "EventType" = betterproto.enum_field(1) ue: "Ue" = betterproto.message_field(2) @dataclass(eq=False, repr=False) class CreateUeRequest(betterproto.Message): """CellInfo provides data on serving cell and candidate cells.""" ue: "Ue" = betterproto.message_field(1) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) @dataclass(eq=False, repr=False) import betterproto.lib.google.protobuf as betterproto_lib_google_protobuf
25.645455
86
0.684864
# Generated by the protocol buffer compiler. DO NOT EDIT! # sources: onos/uenib/ran.proto, onos/uenib/uenib.proto # plugin: python-betterproto from dataclasses import dataclass from typing import AsyncIterator, Dict, List import betterproto import grpclib class EventType(betterproto.Enum): NONE = 0 ADDED = 1 UPDATED = 2 REMOVED = 3 @dataclass(eq=False, repr=False) class CellConnection(betterproto.Message): """CellConnection represents UE cell connection.""" id: str = betterproto.string_field(1) signal_strength: float = betterproto.double_field(2) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class CellInfo(betterproto.Message): """CellInfo provides data on serving cell and candidate cells.""" serving_cell: "CellConnection" = betterproto.message_field(1) candidate_cells: List["CellConnection"] = betterproto.message_field(2) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class Event(betterproto.Message): """CellConnection represents UE cell connection.""" type: "EventType" = betterproto.enum_field(1) ue: "Ue" = betterproto.message_field(2) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class CreateUeRequest(betterproto.Message): """CellInfo provides data on serving cell and candidate cells.""" ue: "Ue" = betterproto.message_field(1) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class CreateUeResponse(betterproto.Message): pass def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class GetUeRequest(betterproto.Message): id: str = betterproto.string_field(1) aspect_types: List[str] = betterproto.string_field(2) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class GetUeResponse(betterproto.Message): ue: "Ue" = betterproto.message_field(1) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class UpdateUeRequest(betterproto.Message): ue: "Ue" = betterproto.message_field(1) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class UpdateUeResponse(betterproto.Message): pass def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class DeleteUeRequest(betterproto.Message): id: str = betterproto.string_field(1) aspect_types: List[str] = betterproto.string_field(2) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class DeleteUeResponse(betterproto.Message): pass def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class ListUeRequest(betterproto.Message): aspect_types: List[str] = betterproto.string_field(1) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class ListUeResponse(betterproto.Message): ue: "Ue" = betterproto.message_field(1) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class WatchUeRequest(betterproto.Message): noreplay: bool = betterproto.bool_field(2) aspect_types: List[str] = betterproto.string_field(3) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class WatchUeResponse(betterproto.Message): event: "Event" = betterproto.message_field(1) def __post_init__(self) -> None: super().__post_init__() @dataclass(eq=False, repr=False) class Ue(betterproto.Message): id: str = betterproto.string_field(1) aspects: Dict[str, "betterproto_lib_google_protobuf.Any"] = betterproto.map_field( 2, betterproto.TYPE_STRING, betterproto.TYPE_MESSAGE ) def __post_init__(self) -> None: super().__post_init__() class UeServiceStub(betterproto.ServiceStub): async def create_ue(self) -> "CreateUeResponse": request = CreateUeRequest() return await self._unary_unary( "/onos.uenib.UEService/CreateUE", request, CreateUeResponse ) async def get_ue(self) -> "GetUeResponse": request = GetUeRequest() return await self._unary_unary( "/onos.uenib.UEService/GetUE", request, GetUeResponse ) async def update_ue(self) -> "UpdateUeResponse": request = UpdateUeRequest() return await self._unary_unary( "/onos.uenib.UEService/UpdateUE", request, UpdateUeResponse ) async def delete_ue(self) -> "DeleteUeResponse": request = DeleteUeRequest() return await self._unary_unary( "/onos.uenib.UEService/DeleteUE", request, DeleteUeResponse ) async def list_u_es(self) -> AsyncIterator["ListUeResponse"]: request = ListUeRequest() async for response in self._unary_stream( "/onos.uenib.UEService/ListUEs", request, ListUeResponse, ): yield response async def watch_u_es(self) -> AsyncIterator["WatchUeResponse"]: request = WatchUeRequest() async for response in self._unary_stream( "/onos.uenib.UEService/WatchUEs", request, WatchUeResponse, ): yield response import betterproto.lib.google.protobuf as betterproto_lib_google_protobuf
1,942
1,433
579