code stringlengths 4 4.48k | docstring stringlengths 1 6.45k | _id stringlengths 24 24 |
|---|---|---|
class Shubert01(Benchmark): <NEW_LINE> <INDENT> def __init__(self, dimensions=2): <NEW_LINE> <INDENT> Benchmark.__init__(self, dimensions) <NEW_LINE> self.bounds = zip([-10.0] * self.dimensions, [10.0] * self.dimensions) <NEW_LINE> self.global_optimum = [-7.0835, 4.8580] <NEW_LINE> self.fglob = -186.7309 <NEW_LINE> <DEDENT> def evaluator(self, x, *args): <NEW_LINE> <INDENT> self.fun_evals += 1 <NEW_LINE> s1 = s2 = 0.0 <NEW_LINE> for i in range(1, 6): <NEW_LINE> <INDENT> s1 = s1+i*cos((i+1)*x[0]+i) <NEW_LINE> s2 = s2+i*cos((i+1)*x[1]+i) <NEW_LINE> <DEDENT> y = s1*s2 <NEW_LINE> return y | Shubert 1 test objective function.
This class defines the Shubert 1 global optimization problem. This
is a multimodal minimization problem defined as follows:
.. math::
f_{\text{Shubert01}}(\mathbf{x}) = \left( \sum\limits_{i=1}^{5} i\cos[(i+1)x_1 + i] \right) \left( \sum\limits_{i=1}^{5} i\cos[(i+1)x_2 + i] \right)
Here, :math:`n` represents the number of dimensions and :math:`x_i \in [-10, 10]` for :math:`i=1,...,n`.
.. figure:: figures/Shubert01.png
:alt: Shubert 1 function
:align: center
**Two-dimensional Shubert 1 function**
*Global optimum*: :math:`f(x_i) = -186.7309` for :math:`\mathbf{x} = [-7.0835, 4.8580]` (and many others). | 62598faf009cb60464d0153e |
class Document(ABase): <NEW_LINE> <INDENT> __tablename__ = 'document' <NEW_LINE> id = Column(Integer, primary_key=True) <NEW_LINE> person_id = Column(Integer, ForeignKey('person.id'), nullable=False, index=True) <NEW_LINE> doc_type = Column(Integer, nullable=False) <NEW_LINE> doc_no = Column(String(50), nullable=False) <NEW_LINE> valid_from = Column(Date, nullable=False) <NEW_LINE> valid_until = Column(Date, nullable=False) <NEW_LINE> @property <NEW_LINE> def doc_type_name(self): <NEW_LINE> <INDENT> if self.doc_type == 1: <NEW_LINE> <INDENT> return 'ID card' <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return 'Passport' | Identity document of a person | 62598faf66673b3332c303ea |
class RecipeTypesValidationView(APIView): <NEW_LINE> <INDENT> renderer_classes = (JSONRenderer, BrowsableAPIRenderer) <NEW_LINE> def post(self, request): <NEW_LINE> <INDENT> name = rest_util.parse_string(request, u'name') <NEW_LINE> version = rest_util.parse_string(request, u'version') <NEW_LINE> description = rest_util.parse_string(request, u'description', '') <NEW_LINE> definition = rest_util.parse_dict(request, u'definition') <NEW_LINE> try: <NEW_LINE> <INDENT> recipe_def = RecipeDefinition(definition) <NEW_LINE> warnings = RecipeType.objects.validate_recipe_type(name, version, description, recipe_def) <NEW_LINE> <DEDENT> except InvalidDefinition as ex: <NEW_LINE> <INDENT> logger.exception('Unable to validate new recipe type: %s', name) <NEW_LINE> raise BadParameter(unicode(ex)) <NEW_LINE> <DEDENT> results = [{'id': w.key, 'details': w.details} for w in warnings] <NEW_LINE> return Response({u'warnings': results}, status=status.HTTP_200_OK) | This view is the endpoint for validating a new recipe type before attempting to actually create it
| 62598faf4a966d76dd5eeef5 |
class LangStore(txt.TxtFile): <NEW_LINE> <INDENT> UnitClass = LangUnit <NEW_LINE> Name = "Mozilla .lang" <NEW_LINE> Extensions = ['lang'] <NEW_LINE> def __init__(self, inputfile=None, flavour=None, encoding="utf-8", mark_active=False): <NEW_LINE> <INDENT> self.is_active = False <NEW_LINE> self.mark_active = mark_active <NEW_LINE> super(LangStore, self).__init__(inputfile, flavour, encoding) <NEW_LINE> <DEDENT> def parse(self, lines): <NEW_LINE> <INDENT> readyTrans = False <NEW_LINE> comment = "" <NEW_LINE> if not isinstance(lines, list): <NEW_LINE> <INDENT> lines = lines.split("\n") <NEW_LINE> <DEDENT> for lineoffset, line in enumerate(lines): <NEW_LINE> <INDENT> line = line.decode(self.encoding).rstrip("\n").rstrip("\r") <NEW_LINE> if lineoffset == 0 and line == "## active ##": <NEW_LINE> <INDENT> self.is_active = True <NEW_LINE> continue <NEW_LINE> <DEDENT> if len(line) == 0 and not readyTrans: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> if readyTrans: <NEW_LINE> <INDENT> if line != u.source: <NEW_LINE> <INDENT> u.target = line.replace(" {ok}", "") <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> u.target = "" <NEW_LINE> <DEDENT> readyTrans = False <NEW_LINE> continue <NEW_LINE> <DEDENT> if line.startswith('#') and not line.startswith('##'): <NEW_LINE> <INDENT> comment += line[1:].strip() + "\n" <NEW_LINE> <DEDENT> if line.startswith(';'): <NEW_LINE> <INDENT> u = self.addsourceunit(line[1:]) <NEW_LINE> readyTrans = True <NEW_LINE> u.addlocation("%s:%d" % (self.filename, lineoffset + 1)) <NEW_LINE> if comment is not None: <NEW_LINE> <INDENT> u.addnote(comment[:-1], 'developer') <NEW_LINE> comment = "" <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> def serialize(self): <NEW_LINE> <INDENT> ret_string = b"" <NEW_LINE> if self.is_active or self.mark_active: <NEW_LINE> <INDENT> ret_string += b"## active ##\n" <NEW_LINE> <DEDENT> ret_string += u"\n\n\n".join([six.text_type(unit) for unit in self.units]).encode('utf-8') <NEW_LINE> ret_string += b"\n" <NEW_LINE> return ret_string | We extend TxtFile, since that has a lot of useful stuff for encoding | 62598faf30dc7b766599f86b |
class TiebaSpider(): <NEW_LINE> <INDENT> def __init__(self, keywords, page_num): <NEW_LINE> <INDENT> self.keywords = keywords <NEW_LINE> self.page_num = page_num <NEW_LINE> <DEDENT> def get_page_list(self): <NEW_LINE> <INDENT> return [i*50 for i in range(self.page_num)] <NEW_LINE> <DEDENT> def reuest_url(self, page_n, current): <NEW_LINE> <INDENT> url = "http://tieba.baidu.com/f?kw={}&ie=utf-8&pn={}".format(self.keywords, page_n) <NEW_LINE> headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"} <NEW_LINE> resp = requests.get(url, headers=headers) <NEW_LINE> content = resp.content.decode() <NEW_LINE> filename = os.path.join(os.path.dirname(__file__), "bieba/{}吧第{}页.html".format(self.keywords, current)) <NEW_LINE> print(filename) <NEW_LINE> with open(filename, "w", encoding="utf-8") as f: <NEW_LINE> <INDENT> f.write(content) <NEW_LINE> <DEDENT> <DEDENT> def run(self): <NEW_LINE> <INDENT> if os.path.exists(os.path.join(os.path.dirname(__file__), "bieba")) == False: <NEW_LINE> <INDENT> os.mkdir(os.path.join(os.path.dirname(__file__), "bieba")) <NEW_LINE> <DEDENT> page_list = self.get_page_list() <NEW_LINE> for i in page_list: <NEW_LINE> <INDENT> index = page_list.index(i) + 1 <NEW_LINE> self.reuest_url(i, index) | 百度贴吧采集类 | 62598faf99fddb7c1ca62df8 |
class GeoPoint(Choreography): <NEW_LINE> <INDENT> def __init__(self, temboo_session): <NEW_LINE> <INDENT> Choreography.__init__(self, temboo_session, '/Library/Parse/GeoPoints/GeoPoint') <NEW_LINE> <DEDENT> def new_input_set(self): <NEW_LINE> <INDENT> return GeoPointInputSet() <NEW_LINE> <DEDENT> def _make_result_set(self, result, path): <NEW_LINE> <INDENT> return GeoPointResultSet(result, path) <NEW_LINE> <DEDENT> def _make_execution(self, session, exec_id, path): <NEW_LINE> <INDENT> return GeoPointChoreographyExecution(session, exec_id, path) | Create a new instance of the GeoPoint Choreography. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied. | 62598faf7d847024c075c3e0 |
class Encoding(object): <NEW_LINE> <INDENT> __slots__ = ('encoding',) <NEW_LINE> def __init__(self, filename): <NEW_LINE> <INDENT> with open(filename, 'rb') as file: <NEW_LINE> <INDENT> _log.debug('Parsing TeX encoding %s', filename) <NEW_LINE> self.encoding = self._parse(file) <NEW_LINE> _log.debug('Result: %s', self.encoding) <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> yield from self.encoding <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def _parse(file): <NEW_LINE> <INDENT> result = [] <NEW_LINE> lines = (line.split(b'%', 1)[0].strip() for line in file) <NEW_LINE> data = b''.join(lines) <NEW_LINE> beginning = data.find(b'[') <NEW_LINE> if beginning < 0: <NEW_LINE> <INDENT> raise ValueError("Cannot locate beginning of encoding in {}" .format(file)) <NEW_LINE> <DEDENT> data = data[beginning:] <NEW_LINE> end = data.find(b']') <NEW_LINE> if end < 0: <NEW_LINE> <INDENT> raise ValueError("Cannot locate end of encoding in {}" .format(file)) <NEW_LINE> <DEDENT> data = data[:end] <NEW_LINE> return re.findall(br'/([^][{}<>\s]+)', data) | Parses a \*.enc file referenced from a psfonts.map style file.
The format this class understands is a very limited subset of
PostScript.
Usage (subject to change)::
for name in Encoding(filename):
whatever(name)
Parameters
----------
filename : string or bytestring
Attributes
----------
encoding : list
List of character names | 62598fafbe8e80087fbbf082 |
class BoolMixin(object): <NEW_LINE> <INDENT> def __add__(self, other): <NEW_LINE> <INDENT> q = self._clone() <NEW_LINE> if isinstance(other, self.__class__): <NEW_LINE> <INDENT> q.must += other.must <NEW_LINE> q.should += other.should <NEW_LINE> q.must_not += other.must_not <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> q.must.append(other) <NEW_LINE> <DEDENT> return q <NEW_LINE> <DEDENT> __radd__ = __add__ <NEW_LINE> def __or__(self, other): <NEW_LINE> <INDENT> if not (self.must or self.must_not): <NEW_LINE> <INDENT> q = self._clone() <NEW_LINE> q.should.append(other) <NEW_LINE> return q <NEW_LINE> <DEDENT> elif isinstance(other, self.__class__) and not (other.must or other.must_not): <NEW_LINE> <INDENT> q = other._clone() <NEW_LINE> q.should.append(self) <NEW_LINE> return q <NEW_LINE> <DEDENT> return self.__class__(should=[self, other]) <NEW_LINE> <DEDENT> __ror__ = __or__ <NEW_LINE> def __invert__(self): <NEW_LINE> <INDENT> if not (self.must or self.should) and len(self.must_not) == 1: <NEW_LINE> <INDENT> return self.must_not[0]._clone() <NEW_LINE> <DEDENT> elif not self.should: <NEW_LINE> <INDENT> q = self._clone() <NEW_LINE> q.must, q.must_not = q.must_not, q.must <NEW_LINE> return q <NEW_LINE> <DEDENT> return super(BoolMixin, self).__invert__() | Mixin containing all the operator overrides for Bool queries and filters.
Except for and where should behavior differs | 62598faf7047854f4633f3f8 |
class Solution: <NEW_LINE> <INDENT> def removeElement(self, A, elem): <NEW_LINE> <INDENT> current = 0 <NEW_LINE> for index in xrange(len(A)): <NEW_LINE> <INDENT> if A[index] != elem: <NEW_LINE> <INDENT> A[current] = A[index] <NEW_LINE> current += 1 <NEW_LINE> <DEDENT> <DEDENT> return current | @param A: A list of integers
@param elem: An integer
@return: The new length after remove | 62598faf7d847024c075c3e1 |
class Engine(object): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> def initialize(self, control, state, conf=None): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def reconfigure(self, control, newconf): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def decide(self, control, state): <NEW_LINE> <INDENT> raise NotImplementedError | This is the superclass for any implementation of the state object that
is passed to the decision engine. The state object is a way for the
engine to find out relevant information that has been collected by the
EPU Controller.
The abc (abstract base class) module is not present in Python 2.5 but
Engine should be treated as such. It is not meant to be instantiated
directly.
@note See the decision engine implementer's guide for more information. | 62598faf851cf427c66b82da |
class Node(object): <NEW_LINE> <INDENT> def __init__(self, data='start', children=None): <NEW_LINE> <INDENT> self.data = data <NEW_LINE> self.children = [] <NEW_LINE> if children is not None: <NEW_LINE> <INDENT> for child in children: <NEW_LINE> <INDENT> self.children.append(child) | Class used for pieces tree.
- For each node a list of children is created.
- Each child is also an instance of the Node class.
- Each node instance contains data which is which is referenced by the .data variable. | 62598fafdd821e528d6d8f53 |
class SDKPackage(MetaPackage): <NEW_LINE> <INDENT> root_env_var = 'CERBERO_SDK_ROOT_%(arch)s' <NEW_LINE> osx_framework_library = None <NEW_LINE> def __init__(self, config, store): <NEW_LINE> <INDENT> MetaPackage.__init__(self, config, store) <NEW_LINE> <DEDENT> def get_root_env_var(self): <NEW_LINE> <INDENT> return (self.root_env_var % {'arch': self.config.target_arch}).upper() | Creates an installer for SDK's.
On Windows the installer will add a new enviroment variable set in
root_env_var as well as a new key in the registry so that other installers
depending on the SDK could use them to set their environment easily and
check wether the requirements are met in the pre-installation step.
On OS X, the installer will create the tipical bundle structure used for
OS X Frameworks, creating the 'Versions' and 'Current' directories for
versionning as well as 'Headers' and 'Libraries' linking to the current
version of the framework.
On Linux everything just works without extra hacks ;)
@cvar root_env_var: name of the environment variable with the prefix
@type root_env_var: str
@cvar osx_framework_library: (name, path) of the lib used for the Framework
@type osx_framework_library: tuple | 62598faf3d592f4c4edbaedf |
class Workbook(TimeStampedModel): <NEW_LINE> <INDENT> workbook_title = models.CharField(max_length=128, unique=False) <NEW_LINE> workbook_description = models.CharField(max_length=512, unique=False) <NEW_LINE> workbook_notes = models.TextField(blank=True) <NEW_LINE> user = models.ForeignKey(User, on_delete=models.CASCADE) <NEW_LINE> def __str__(self): <NEW_LINE> <INDENT> return f"{str(self.pk)}: {self.workbook_title}" <NEW_LINE> <DEDENT> def workbook_samples(self): <NEW_LINE> <INDENT> return WorkbookSample.objects.filter(workbook=self.id) <NEW_LINE> <DEDENT> class Meta: <NEW_LINE> <INDENT> verbose_name = 'Workbook' <NEW_LINE> verbose_name_plural = 'Workbooks' | Base Workbook model for representing a group of samples | 62598fafa17c0f6771d5c254 |
class TwoLayerNet(object): <NEW_LINE> <INDENT> def __init__(self, input_dim=3*32*32, hidden_dim=100, num_classes=10, weight_scale=1e-3, reg=0.0): <NEW_LINE> <INDENT> self.params = {} <NEW_LINE> self.reg = reg <NEW_LINE> self.params['W1'] = np.random.randn(input_dim, hidden_dim) * weight_scale <NEW_LINE> self.params['b1'] = np.zeros(hidden_dim) <NEW_LINE> self.params['W2'] = np.random.randn(hidden_dim, num_classes) * weight_scale <NEW_LINE> self.params['b2'] = np.zeros(num_classes) <NEW_LINE> pass <NEW_LINE> <DEDENT> def loss(self, X, y=None): <NEW_LINE> <INDENT> scores = None <NEW_LINE> num_train = X.shape[0] <NEW_LINE> num_class = self.params['b1'].shape[0] <NEW_LINE> num_hidden_dim = self.params['W1'].shape[0] <NEW_LINE> caches = {} <NEW_LINE> W1 = self.params['W1'] <NEW_LINE> b1 = self.params['b1'] <NEW_LINE> scores, caches[0] = affine_relu_forward(X, W1, b1) <NEW_LINE> W2 = self.params['W2'] <NEW_LINE> b2 = self.params['b2'] <NEW_LINE> scores, caches[1] = affine_relu_forward(scores, W2, b2) <NEW_LINE> pass <NEW_LINE> if y is None: <NEW_LINE> <INDENT> return scores <NEW_LINE> <DEDENT> loss, grads = 0, {} <NEW_LINE> loss, dout = softmax_loss(scores, y) <NEW_LINE> dx, dW2, db2 = affine_relu_backward(dout, caches[1]) <NEW_LINE> dx, dW1, db1 = affine_relu_backward(dx, caches[0]) <NEW_LINE> grads['W1'] = dW1 + self.reg * W1 <NEW_LINE> grads['W2'] = dW2 + self.reg * W2 <NEW_LINE> grads['b1'] = db1 <NEW_LINE> grads['b2'] = db2 <NEW_LINE> loss += 0.5 * self.reg * (np.sum(W1 ** 2) + np.sum(W2 ** 2)) <NEW_LINE> pass <NEW_LINE> return loss, grads | A two-layer fully-connected neural network with ReLU nonlinearity and
softmax loss that uses a modular layer design. We assume an input dimension
of D, a hidden dimension of H, and perform classification over C classes.
The architecure should be affine - relu - affine - softmax.
Note that this class does not implement gradient descent; instead, it
will interact with a separate Solver object that is responsible for running
optimization.
The learnable parameters of the model are stored in the dictionary
self.params that maps parameter names to numpy arrays. | 62598faf091ae35668704c3e |
class getFamilyInfosByUserId_result(object): <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.LIST, 'success', (TType.STRUCT, (FamilyInfo, FamilyInfo.thrift_spec), False), None, ), (1, TType.STRUCT, 'ex', (XKCommon.ttypes.HealthServiceException, XKCommon.ttypes.HealthServiceException.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, ex=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.ex = ex <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: <NEW_LINE> <INDENT> iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.LIST: <NEW_LINE> <INDENT> self.success = [] <NEW_LINE> (_etype122, _size119) = iprot.readListBegin() <NEW_LINE> for _i123 in range(_size119): <NEW_LINE> <INDENT> _elem124 = FamilyInfo() <NEW_LINE> _elem124.read(iprot) <NEW_LINE> self.success.append(_elem124) <NEW_LINE> <DEDENT> iprot.readListEnd() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.ex = XKCommon.ttypes.HealthServiceException() <NEW_LINE> self.ex.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot._fast_encode is not None and self.thrift_spec is not None: <NEW_LINE> <INDENT> oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('getFamilyInfosByUserId_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.LIST, 0) <NEW_LINE> oprot.writeListBegin(TType.STRUCT, len(self.success)) <NEW_LINE> for iter125 in self.success: <NEW_LINE> <INDENT> iter125.write(oprot) <NEW_LINE> <DEDENT> oprot.writeListEnd() <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.ex is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('ex', TType.STRUCT, 1) <NEW_LINE> self.ex.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.items()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- ex | 62598faf498bea3a75a57b3f |
class ReferenceAPIClient(APIClient): <NEW_LINE> <INDENT> def getCategories(self): <NEW_LINE> <INDENT> request = "reference/categories" <NEW_LINE> response = self.sendRequest(request) <NEW_LINE> if (response is None) or (response['status'] != 200): <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> results = json.loads(response['contents']) <NEW_LINE> categories = [] <NEW_LINE> for cat in results: <NEW_LINE> <INDENT> category = self._parseCategory(cat) <NEW_LINE> categories.append(category) <NEW_LINE> <DEDENT> return categories <NEW_LINE> <DEDENT> def _parseCategory(self, data): <NEW_LINE> <INDENT> category = Category(**data) <NEW_LINE> return category <NEW_LINE> <DEDENT> def _parseLocation(self, data): <NEW_LINE> <INDENT> location = Location() <NEW_LINE> if "latitude" in data: location.latitude = data['latitude'] <NEW_LINE> if "longitude" in data: location.longitude = data['longitude'] <NEW_LINE> if "accuracy" in data: location.accuracy = data['accuracy'] <NEW_LINE> if "countryCode" in data: location.countryCode = data['countryCode'] <NEW_LINE> if "regionCode" in data: location.regionCode = data['regionCode'] <NEW_LINE> if "stateCode" in data: location.stateCode = data['stateCode'] <NEW_LINE> if "metroCode" in data: location.stateCode = data['metroCode'] <NEW_LINE> if "countyCode" in data: location.stateCode = data['countyCode'] <NEW_LINE> if "cityCode" in data: location.stateCode = data['cityCode'] <NEW_LINE> if "localityCode" in data: location.localityCode = data['localityCode'] <NEW_LINE> if "zipCode" in data: location.zipCode = data['zipCode'] <NEW_LINE> return location | A client for the 3taps Reference API.
| 62598faf30bbd72246469988 |
class NamedTupleReader(UnicodeDictReader): <NEW_LINE> <INDENT> def __init__(self, f, **kw): <NEW_LINE> <INDENT> self._cls = None <NEW_LINE> UnicodeDictReader.__init__(self, f, **kw) <NEW_LINE> <DEDENT> @property <NEW_LINE> def cls(self): <NEW_LINE> <INDENT> if self._cls is None: <NEW_LINE> <INDENT> self._cls = namedtuple('Row', list(map(normalize_name, self.fieldnames))) <NEW_LINE> <DEDENT> return self._cls <NEW_LINE> <DEDENT> def item(self, row): <NEW_LINE> <INDENT> d = UnicodeDictReader.item(self, row) <NEW_LINE> for name in self.fieldnames: <NEW_LINE> <INDENT> d.setdefault(name, None) <NEW_LINE> <DEDENT> return self.cls( **{normalize_name(k): v for k, v in d.items() if k in self.fieldnames}) | Read namedtuple objects from a csv file. | 62598faf66673b3332c303ec |
class SignatureType(object): <NEW_LINE> <INDENT> REGEX_URL = 'REGEX_URL' <NEW_LINE> SNORT = 'SNORT' <NEW_LINE> SURICATA = 'SURICATA' <NEW_LINE> YARA = 'YARA' | Vocabulary for the Threat Indicator Signature Threat Type. | 62598faf97e22403b383af2d |
class asci_sink(gr.sync_block): <NEW_LINE> <INDENT> def __init__(self, vlen, filename): <NEW_LINE> <INDENT> self.vlen = vlen <NEW_LINE> self.filename = filename <NEW_LINE> gr.sync_block.__init__(self, name="asci_sink", in_sig=[(numpy.float32, self.vlen)], out_sig=[]) <NEW_LINE> <DEDENT> def work(self, input_items, output_items): <NEW_LINE> <INDENT> in0 = input_items[0] <NEW_LINE> numpy.savetxt(self.filename, in0) <NEW_LINE> return 0 | docstring for block asci_sink | 62598faf55399d3f05626543 |
class future_is_full_result(object): <NEW_LINE> <INDENT> thrift_spec = ( (0, TType.BOOL, 'success', None, None, ), (1, TType.STRUCT, 'e', (ClientException, ClientException.thrift_spec), None, ), ) <NEW_LINE> def __init__(self, success=None, e=None,): <NEW_LINE> <INDENT> self.success = success <NEW_LINE> self.e = e <NEW_LINE> <DEDENT> def read(self, iprot): <NEW_LINE> <INDENT> if iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) <NEW_LINE> return <NEW_LINE> <DEDENT> iprot.readStructBegin() <NEW_LINE> while True: <NEW_LINE> <INDENT> (fname, ftype, fid) = iprot.readFieldBegin() <NEW_LINE> if ftype == TType.STOP: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if fid == 0: <NEW_LINE> <INDENT> if ftype == TType.BOOL: <NEW_LINE> <INDENT> self.success = iprot.readBool() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> elif fid == 1: <NEW_LINE> <INDENT> if ftype == TType.STRUCT: <NEW_LINE> <INDENT> self.e = ClientException() <NEW_LINE> self.e.read(iprot) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> iprot.skip(ftype) <NEW_LINE> <DEDENT> iprot.readFieldEnd() <NEW_LINE> <DEDENT> iprot.readStructEnd() <NEW_LINE> <DEDENT> def write(self, oprot): <NEW_LINE> <INDENT> if oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None: <NEW_LINE> <INDENT> oprot.trans.write(fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) <NEW_LINE> return <NEW_LINE> <DEDENT> oprot.writeStructBegin('future_is_full_result') <NEW_LINE> if self.success is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('success', TType.BOOL, 0) <NEW_LINE> oprot.writeBool(self.success) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> if self.e is not None: <NEW_LINE> <INDENT> oprot.writeFieldBegin('e', TType.STRUCT, 1) <NEW_LINE> self.e.write(oprot) <NEW_LINE> oprot.writeFieldEnd() <NEW_LINE> <DEDENT> oprot.writeFieldStop() <NEW_LINE> oprot.writeStructEnd() <NEW_LINE> <DEDENT> def validate(self): <NEW_LINE> <INDENT> return <NEW_LINE> <DEDENT> def __hash__(self): <NEW_LINE> <INDENT> value = 17 <NEW_LINE> value = (value * 31) ^ hash(self.success) <NEW_LINE> value = (value * 31) ^ hash(self.e) <NEW_LINE> return value <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> L = ['%s=%r' % (key, value) for key, value in self.__dict__.iteritems()] <NEW_LINE> return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) <NEW_LINE> <DEDENT> def __eq__(self, other): <NEW_LINE> <INDENT> return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ <NEW_LINE> <DEDENT> def __ne__(self, other): <NEW_LINE> <INDENT> return not (self == other) | Attributes:
- success
- e | 62598faf5166f23b2e2433f9 |
class DefaultFormatter(): <NEW_LINE> <INDENT> use_color = False <NEW_LINE> def display(self, content): <NEW_LINE> <INDENT> return pformat(content) | Class to display a variable beautifully | 62598faf4a966d76dd5eeef7 |
class Redshift(object): <NEW_LINE> <INDENT> def __init__(self, config): <NEW_LINE> <INDENT> self.config = config <NEW_LINE> self.connection = psycopg2.connect( dbname=config["dbname"], user=config["user"], password=config["password"], host=config["host"], port=config["port"], sslmode="require", ) <NEW_LINE> self.connection.set_session(autocommit=False) <NEW_LINE> self.cursor = self.connection.cursor() <NEW_LINE> <DEDENT> def execute(self, query, data=None): <NEW_LINE> <INDENT> self.cursor.execute(query, data) <NEW_LINE> logger.info(self.cursor.statusmessage) <NEW_LINE> <DEDENT> def commit(self): <NEW_LINE> <INDENT> self.connection.commit() <NEW_LINE> <DEDENT> def rollback(self): <NEW_LINE> <INDENT> self.connection.rollback() <NEW_LINE> <DEDENT> def __enter__(self): <NEW_LINE> <INDENT> self.connection.__enter__() <NEW_LINE> self.cursor.__enter__() <NEW_LINE> return self <NEW_LINE> <DEDENT> def __exit__(self, exception_type, exception_value, traceback): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.cursor.__exit__(exception_type, exception_value, traceback) <NEW_LINE> <DEDENT> finally: <NEW_LINE> <INDENT> self.connection.__exit__(exception_type, exception_value, traceback) | Redshift psycopg2 interface. | 62598faf99fddb7c1ca62df9 |
class GaussianEncoderBase(EncoderBase): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(GaussianEncoderBase, self).__init__() <NEW_LINE> <DEDENT> def freeze(self): <NEW_LINE> <INDENT> for param in self.parameters(): <NEW_LINE> <INDENT> param.requires_grad = False <NEW_LINE> <DEDENT> <DEDENT> def forward(self, x): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> def encode_stats(self, x): <NEW_LINE> <INDENT> return self.forward(x) <NEW_LINE> <DEDENT> def sample(self, input, nsamples): <NEW_LINE> <INDENT> mu, logvar = self.forward(input) <NEW_LINE> z = self.reparameterize(mu, logvar, nsamples) <NEW_LINE> return z, (mu, logvar) <NEW_LINE> <DEDENT> def encode(self, input, nsamples): <NEW_LINE> <INDENT> mu, logvar = self.forward(input) <NEW_LINE> z = self.reparameterize(mu, logvar, nsamples) <NEW_LINE> KL = 0.5 * (mu.pow(2) + logvar.exp() - logvar - 1).sum(dim=1) <NEW_LINE> return z, KL <NEW_LINE> <DEDENT> def reparameterize(self, mu, logvar, nsamples=1): <NEW_LINE> <INDENT> batch_size, nz = mu.size() <NEW_LINE> std = logvar.mul(0.5).exp() <NEW_LINE> mu_expd = mu.unsqueeze(1).expand(batch_size, nsamples, nz) <NEW_LINE> std_expd = std.unsqueeze(1).expand(batch_size, nsamples, nz) <NEW_LINE> eps = torch.zeros_like(std_expd).normal_() <NEW_LINE> return mu_expd + torch.mul(eps, std_expd) <NEW_LINE> <DEDENT> def eval_inference_dist(self, x, z, param=None): <NEW_LINE> <INDENT> nz = z.size(2) <NEW_LINE> if not param: <NEW_LINE> <INDENT> mu, logvar = self.forward(x) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mu, logvar = param <NEW_LINE> <DEDENT> mu, logvar = mu.unsqueeze(1), logvar.unsqueeze(1) <NEW_LINE> var = logvar.exp() <NEW_LINE> dev = z - mu <NEW_LINE> log_density = -0.5 * ((dev ** 2) / var).sum(dim=-1) - 0.5 * (nz * math.log(2 * math.pi) + logvar.sum(-1)) <NEW_LINE> return log_density <NEW_LINE> <DEDENT> def calc_mi(self, x): <NEW_LINE> <INDENT> mu, logvar = self.forward(x) <NEW_LINE> x_batch, nz = mu.size() <NEW_LINE> neg_entropy = (-0.5 * nz * math.log(2 * math.pi)- 0.5 * (1 + logvar).sum(-1)).mean() <NEW_LINE> z_samples = self.reparameterize(mu, logvar, 1) <NEW_LINE> mu, logvar = mu.unsqueeze(0), logvar.unsqueeze(0) <NEW_LINE> var = logvar.exp() <NEW_LINE> dev = z_samples - mu <NEW_LINE> log_density = -0.5 * ((dev ** 2) / var).sum(dim=-1) - 0.5 * (nz * math.log(2 * math.pi) + logvar.sum(-1)) <NEW_LINE> log_qz = log_sum_exp(log_density, dim=1) - math.log(x_batch) <NEW_LINE> return (neg_entropy - log_qz.mean(-1)).item() | docstring for EncoderBase | 62598faf0c0af96317c563a1 |
class LayerAllNodesGeojsonList(generics.RetrieveAPIView): <NEW_LINE> <INDENT> model = Layer <NEW_LINE> def get(self, request, *args, **kwargs): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> slug_value = self.kwargs.get('slug', None) <NEW_LINE> layer = Layer.objects.get(slug=slug_value) <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> raise Http404(_('Layer not found')) <NEW_LINE> <DEDENT> node = layer.node_set.all() <NEW_LINE> dj = Django.Django(geodjango="coords", properties=['name', 'description']) <NEW_LINE> geojson = GeoJSON.GeoJSON() <NEW_LINE> string = geojson.encode(dj.decode(node)) <NEW_LINE> return Response(json.loads(string)) | ### GET
Retrieve list of nodes of the specified layer in GeoJSON format. | 62598faf8a43f66fc4bf219a |
class ObjectType(enum.Enum): <NEW_LINE> <INDENT> FIRMWARE = 0b00 <NEW_LINE> CONFIGURATION_PARAMETERS_BLOCK = 0b01 | Object type | 62598faf4e4d562566372446 |
class BuildHttp(Build): <NEW_LINE> <INDENT> def __init__(self, ref): <NEW_LINE> <INDENT> super(BuildHttp, self).__init__(ref=ref, type='http') <NEW_LINE> self.auth = ('user', 'pass') <NEW_LINE> self.http_verify = False <NEW_LINE> self.timeout = None <NEW_LINE> <DEDENT> def _load(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> get = requests.get(self._ref, verify=self.http_verify, auth=self.auth, timeout=self.timeout) <NEW_LINE> <DEDENT> except requests.exceptions.RequestException as err: <NEW_LINE> <INDENT> raise NotFoundError(err) <NEW_LINE> <DEDENT> return get.content <NEW_LINE> <DEDENT> def is_exists(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return self._load() is not None <NEW_LINE> <DEDENT> except NotFoundError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> def get_file(self): <NEW_LINE> <INDENT> content = self._load() <NEW_LINE> if not content: <NEW_LINE> <INDENT> return None <NEW_LINE> <DEDENT> filename = "temporary_file.bin" <NEW_LINE> with open(filename, "wb") as file_name: <NEW_LINE> <INDENT> file_name.write(content) <NEW_LINE> <DEDENT> return filename | Build as a Http link | 62598fafa8370b77170f03fb |
class RotateNative2Celestial(_SkyRotation): <NEW_LINE> <INDENT> n_inputs = 2 <NEW_LINE> n_outputs = 2 <NEW_LINE> @property <NEW_LINE> def input_units(self): <NEW_LINE> <INDENT> return {'phi_N': u.deg, 'theta_N': u.deg} <NEW_LINE> <DEDENT> @property <NEW_LINE> def return_units(self): <NEW_LINE> <INDENT> return {'alpha_C': u.deg, 'delta_C': u.deg} <NEW_LINE> <DEDENT> def __init__(self, lon, lat, lon_pole, **kwargs): <NEW_LINE> <INDENT> super().__init__(lon, lat, lon_pole, **kwargs) <NEW_LINE> self.inputs = ('phi_N', 'theta_N') <NEW_LINE> self.outputs = ('alpha_C', 'delta_C') <NEW_LINE> <DEDENT> def evaluate(self, phi_N, theta_N, lon, lat, lon_pole): <NEW_LINE> <INDENT> if isinstance(lon, u.Quantity): <NEW_LINE> <INDENT> lon = lon.value <NEW_LINE> lat = lat.value <NEW_LINE> lon_pole = lon_pole.value <NEW_LINE> <DEDENT> phi = lon_pole - np.pi / 2 <NEW_LINE> theta = - (np.pi / 2 - lat) <NEW_LINE> psi = -(np.pi / 2 + lon) <NEW_LINE> alpha_C, delta_C = super()._evaluate(phi_N, theta_N, phi, theta, psi) <NEW_LINE> return alpha_C, delta_C <NEW_LINE> <DEDENT> @property <NEW_LINE> def inverse(self): <NEW_LINE> <INDENT> return RotateCelestial2Native(self.lon, self.lat, self.lon_pole) | Transform from Native to Celestial Spherical Coordinates.
Parameters
----------
lon : float or or `~astropy.units.Quantity`
Celestial longitude of the fiducial point.
lat : float or or `~astropy.units.Quantity`
Celestial latitude of the fiducial point.
lon_pole : float or or `~astropy.units.Quantity`
Longitude of the celestial pole in the native system.
Notes
-----
If ``lon``, ``lat`` and ``lon_pole`` are numerical values they
should be in units of deg. Inputs are angles on the native sphere.
Outputs are angles on the celestial sphere. | 62598faf66656f66f7d5a410 |
class OverdueReportTable(ModelSQL, ModelView): <NEW_LINE> <INDENT> __name__ = 'overdue.report.table' <NEW_LINE> name = fields.Char('Name') | Overdue Report Table | 62598faf6e29344779b0067c |
class SubjectCodeDoesntExist(twc.Validator): <NEW_LINE> <INDENT> msgs = { 'exists': twc._("Subject code already exists."), 'parseerr': twc._("Error parsing session and subject code") } <NEW_LINE> def validate_python(self, value, state): <NEW_LINE> <INDENT> super(SubjectCodeDoesntExist, self).validate_python(value, state) <NEW_LINE> session_id = value['id'] <NEW_LINE> subject_id = int(value['subject']['id']) <NEW_LINE> subject_code = value['subject']['code'] <NEW_LINE> session = Session.query.filter_by(id=session_id).first() <NEW_LINE> if not session: <NEW_LINE> <INDENT> raise twc.ValidationError('parseerr', self) <NEW_LINE> <DEDENT> subject = Subject.query.filter_by(code=subject_code).filter_by(experiment=session.experiment).first() <NEW_LINE> if subject and subject.id != subject_id: <NEW_LINE> <INDENT> raise twc.ValidationError('exists', self) | Confirm a subject code doesn't exist.
`id`
Name of the sibling field this must match | 62598faffff4ab517ebcd805 |
class Solution: <NEW_LINE> <INDENT> @printTime() <NEW_LINE> def snakesAndLadders(self, board: List[List[int]]) -> int: <NEW_LINE> <INDENT> N = len(board) <NEW_LINE> N2 = N * N <NEW_LINE> step = 0 <NEW_LINE> visit = [False for _ in range(N2)] <NEW_LINE> cur = set() <NEW_LINE> cur.add(0) <NEW_LINE> def getValue(index): <NEW_LINE> <INDENT> row = N - 1 - (index // N) <NEW_LINE> if (index // N) % 2 == 0: <NEW_LINE> <INDENT> column = index % N <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> column = N - 1 - (index % N) <NEW_LINE> <DEDENT> return board[row][column] <NEW_LINE> <DEDENT> while len(cur): <NEW_LINE> <INDENT> if cur.__contains__(N2 - 1): <NEW_LINE> <INDENT> return step <NEW_LINE> <DEDENT> temp = set() <NEW_LINE> for c in cur: <NEW_LINE> <INDENT> visit[c] = True <NEW_LINE> <DEDENT> for c in cur: <NEW_LINE> <INDENT> for x in range(1, 7): <NEW_LINE> <INDENT> if c + x >= N2: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> value = getValue(c + x) <NEW_LINE> if value != -1: <NEW_LINE> <INDENT> if not visit[value - 1]: <NEW_LINE> <INDENT> temp.add(value - 1) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if not visit[c + x]: <NEW_LINE> <INDENT> temp.add(c + x) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> cur = temp <NEW_LINE> step += 1 <NEW_LINE> <DEDENT> return -1 | BFS | 62598fafaad79263cf42e7f3 |
class ParseResult(object): <NEW_LINE> <INDENT> type = "Unknown" <NEW_LINE> subtype = "Unknown" <NEW_LINE> confidence = 0 <NEW_LINE> result_value = None <NEW_LINE> data = {} <NEW_LINE> def __init__( self, p_type="Unknown", subtype="Unknown", confidence=0, value=None, additional_data=None ): <NEW_LINE> <INDENT> if additional_data is None: <NEW_LINE> <INDENT> additional_data = {} <NEW_LINE> <DEDENT> self.type = p_type <NEW_LINE> self.subtype = subtype <NEW_LINE> self.confidence = confidence <NEW_LINE> self.result_value = value <NEW_LINE> self.data = additional_data | Represents a single result from the parsing process | 62598fafe5267d203ee6b92a |
class ChangeType(object): <NEW_LINE> <INDENT> def __init__(self, name): <NEW_LINE> <INDENT> object.__init__(self) <NEW_LINE> self.__name = name <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self.__name | Describes the type of change performed. Should be considered an enum. | 62598faf5fcc89381b26615c |
class itkMeshToVTKPolyDataMD3S(ITKCommonBasePython.itkObject): <NEW_LINE> <INDENT> thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag') <NEW_LINE> def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined") <NEW_LINE> __repr__ = _swig_repr <NEW_LINE> def __New_orig__(): <NEW_LINE> <INDENT> return _itkMeshToVTKPolyDataPython.itkMeshToVTKPolyDataMD3S___New_orig__() <NEW_LINE> <DEDENT> __New_orig__ = staticmethod(__New_orig__) <NEW_LINE> def SetInput(self, *args): <NEW_LINE> <INDENT> return _itkMeshToVTKPolyDataPython.itkMeshToVTKPolyDataMD3S_SetInput(self, *args) <NEW_LINE> <DEDENT> def GetInput(self): <NEW_LINE> <INDENT> return _itkMeshToVTKPolyDataPython.itkMeshToVTKPolyDataMD3S_GetInput(self) <NEW_LINE> <DEDENT> def GetOutput(self): <NEW_LINE> <INDENT> return _itkMeshToVTKPolyDataPython.itkMeshToVTKPolyDataMD3S_GetOutput(self) <NEW_LINE> <DEDENT> def Update(self): <NEW_LINE> <INDENT> return _itkMeshToVTKPolyDataPython.itkMeshToVTKPolyDataMD3S_Update(self) <NEW_LINE> <DEDENT> __swig_destroy__ = _itkMeshToVTKPolyDataPython.delete_itkMeshToVTKPolyDataMD3S <NEW_LINE> def cast(*args): <NEW_LINE> <INDENT> return _itkMeshToVTKPolyDataPython.itkMeshToVTKPolyDataMD3S_cast(*args) <NEW_LINE> <DEDENT> cast = staticmethod(cast) <NEW_LINE> def GetPointer(self): <NEW_LINE> <INDENT> return _itkMeshToVTKPolyDataPython.itkMeshToVTKPolyDataMD3S_GetPointer(self) <NEW_LINE> <DEDENT> def New(*args, **kargs): <NEW_LINE> <INDENT> obj = itkMeshToVTKPolyDataMD3S.__New_orig__() <NEW_LINE> import itkTemplate <NEW_LINE> itkTemplate.New(obj, *args, **kargs) <NEW_LINE> return obj <NEW_LINE> <DEDENT> New = staticmethod(New) | Proxy of C++ itkMeshToVTKPolyDataMD3S class | 62598faf3d592f4c4edbaee1 |
class Gamble(Vector): <NEW_LINE> <INDENT> def __init__(self, data={}): <NEW_LINE> <INDENT> if isinstance(data, Mapping): <NEW_LINE> <INDENT> Vector.__init__(self, data) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> Vector.__init__(self, {component: 1 for component in data}) <NEW_LINE> <DEDENT> <DEDENT> def __add__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Gamble): <NEW_LINE> <INDENT> return Vector.__add__(self, other) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> other = _make_rational(other) <NEW_LINE> return type(self)({arg: value + other for arg, value in self.iteritems()}) <NEW_LINE> <DEDENT> <DEDENT> __radd__ = __add__ <NEW_LINE> __rsub__ = lambda self, other: -(self - other) <NEW_LINE> def __mul__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Gamble): <NEW_LINE> <INDENT> return type(self)({x: self[x] * other[x] for x in self._domain_joiner(other)}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return Vector.__mul__(self, other) <NEW_LINE> <DEDENT> <DEDENT> def __xor__(self, other): <NEW_LINE> <INDENT> if isinstance(other, Set): <NEW_LINE> <INDENT> return type(self)({(x, y): self[x] for x in self for y in other}) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> raise TypeError("the argument must be a Set") <NEW_LINE> <DEDENT> <DEDENT> def bounds(self): <NEW_LINE> <INDENT> values = self.range() <NEW_LINE> if values != frozenset(): <NEW_LINE> <INDENT> return (min(values), max(values)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return (0, 0) <NEW_LINE> <DEDENT> <DEDENT> def scaled_shifted(self): <NEW_LINE> <INDENT> minval, maxval = self.bounds() <NEW_LINE> shift = minval <NEW_LINE> scale = maxval - minval <NEW_LINE> return (self - shift) if scale == 0 else (self - shift) / scale <NEW_LINE> <DEDENT> def norm(self): <NEW_LINE> <INDENT> minval, maxval = self.bounds() <NEW_LINE> return max(-minval, maxval) <NEW_LINE> <DEDENT> def normalized(self): <NEW_LINE> <INDENT> norm = self.norm() <NEW_LINE> return None if norm == 0 else self / norm | Gambles map states to utility payoffs
This class derives from :class:`~murasyp.vectors.Vector`, so its methods
apply here as well.
What has changed:
* There is a new constructor. If `data` is not a
:class:`~collections.Mapping`, but is a :class:`~collections.Iterable`
:class:`~collections.Hashable` :class:`~collections.Container`, then its
so-called indicator function is generated.
>>> Gamble('abc')
Gamble({'a': 1, 'c': 1, 'b': 1})
>>> Gamble({'abc'})
Gamble({'abc': 1})
* Pointwise multiplication and scalar addition & subtraction
have been added.
>>> f = Gamble({'a': 1.1, 'b': '-1/2', 'c': 0})
>>> g = Gamble({'b': '.6', 'c': -2, 'd': 0.0})
>>> f * g
Gamble({'a': 0, 'c': 0, 'b': '-3/10', 'd': 0})
>>> -3 - f
Gamble({'a': '-41/10', 'c': -3, 'b': '-5/2'})
* A gamble's domain can be cylindrically extended to the cartesian product
of its domain and a specified :class:`~collections.Set`.
>>> Gamble({'a': 0, 'b': -1}) ^ {'c', 'd'}
Gamble({('b', 'c'): -1, ('a', 'd'): 0, ('a', 'c'): 0, ('b', 'd'): -1}) | 62598faf99cbb53fe6830ef9 |
class BacteriumAPI(object): <NEW_LINE> <INDENT> def __init__(self, function='bacterium/'): <NEW_LINE> <INDENT> self.function = function <NEW_LINE> <DEDENT> def get_all(self): <NEW_LINE> <INDENT> result_get = GetRest(function = self.function).performRequest() <NEW_LINE> return result_get <NEW_LINE> <DEDENT> def set_bacterium(self, jsonData): <NEW_LINE> <INDENT> jsonData = json.dumps(jsonData) <NEW_LINE> result_post = PostRest(function = self.function, dataDict = jsonData).performRequest() <NEW_LINE> return result_post <NEW_LINE> <DEDENT> def get_by_id(self, id_bacterium:int): <NEW_LINE> <INDENT> self.function += str(id_bacterium) + '/' <NEW_LINE> result_get = GetRest(function = self.function).performRequest() <NEW_LINE> return result_get <NEW_LINE> <DEDENT> def setBacteriumExistsByAcc(self, acc_value): <NEW_LINE> <INDENT> self.function += 'accnumber/' + acc_value + '/exists/' <NEW_LINE> result_get = GetRest(function = self.function).performRequest() <NEW_LINE> return result_get <NEW_LINE> <DEDENT> def getBacteriumByAcc(self, acc_value): <NEW_LINE> <INDENT> self.function += 'accnumber/' + acc_value + '/' <NEW_LINE> result_get = GetRest(function = self.function).performRequest() <NEW_LINE> return result_get | This class manage the requests for the Bacteria objects into the restAPI
:param function: the name of the function to access in the rest API
:type function: string | 62598faf91f36d47f2230eb7 |
class TestRouterMap(TestRouterMapControllers): <NEW_LINE> <INDENT> @property <NEW_LINE> def subject(self): <NEW_LINE> <INDENT> return self.router.add | router.add aliases router.map_controllers | 62598faf4428ac0f6e658546 |
class IntermediateLayerGetter(nn.ModuleDict): <NEW_LINE> <INDENT> _version = 2 <NEW_LINE> __annotations__ = { "return_layers": Dict[str, str], } <NEW_LINE> def __init__(self, model, return_layers): <NEW_LINE> <INDENT> if not set(return_layers).issubset([name for name, _ in model.named_children()]): <NEW_LINE> <INDENT> raise ValueError("return_layers are not present in model") <NEW_LINE> <DEDENT> orig_return_layers = return_layers <NEW_LINE> return_layers = {str(k): str(v) for k, v in return_layers.items()} <NEW_LINE> layers = OrderedDict() <NEW_LINE> for name, module in model.named_children(): <NEW_LINE> <INDENT> layers[name] = module <NEW_LINE> if name in return_layers: <NEW_LINE> <INDENT> del return_layers[name] <NEW_LINE> <DEDENT> if not return_layers: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> <DEDENT> super(IntermediateLayerGetter, self).__init__(layers) <NEW_LINE> self.return_layers = orig_return_layers <NEW_LINE> <DEDENT> def forward(self, x, layer=None, edge_out=None): <NEW_LINE> <INDENT> if layer is None: <NEW_LINE> <INDENT> out = OrderedDict() <NEW_LINE> for name, module in self.items(): <NEW_LINE> <INDENT> x = module(x) <NEW_LINE> if name in self.return_layers: <NEW_LINE> <INDENT> out_name = self.return_layers[name] <NEW_LINE> out[out_name] = x <NEW_LINE> <DEDENT> <DEDENT> return out <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> if edge_out is None: <NEW_LINE> <INDENT> out = OrderedDict() <NEW_LINE> for name, module in self.items(): <NEW_LINE> <INDENT> x = module(x) <NEW_LINE> if name in self.return_layers: <NEW_LINE> <INDENT> out_name = self.return_layers[name] <NEW_LINE> out[out_name] = x <NEW_LINE> if name == layer: <NEW_LINE> <INDENT> return out <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return out <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> out = edge_out <NEW_LINE> flag = False <NEW_LINE> for name, module in self.items(): <NEW_LINE> <INDENT> if flag == True: <NEW_LINE> <INDENT> x = module(x) <NEW_LINE> if name in self.return_layers: <NEW_LINE> <INDENT> out_name = self.return_layers[name] <NEW_LINE> out[out_name] = x <NEW_LINE> <DEDENT> <DEDENT> if name == layer: <NEW_LINE> <INDENT> flag = True <NEW_LINE> <DEDENT> <DEDENT> return out | Module wrapper that returns intermediate layers from a model
It has a strong assumption that the modules have been registered
into the model in the same order as they are used.
This means that one should **not** reuse the same nn.Module
twice in the forward if you want this to work.
Additionally, it is only able to query submodules that are directly
assigned to the model. So if `model` is passed, `model.feature1` can
be returned, but not `model.feature1.layer2`.
Arguments:
model (nn.Module): model on which we will extract the features
return_layers (Dict[name, new_name]): a dict containing the names
of the modules for which the activations will be returned as
the key of the dict, and the value of the dict is the name
of the returned activation (which the user can specify).
Examples::
>>> m = torchvision.models.resnet18(pretrained=True)
>>> # extract layer1 and layer3, giving as names `feat1` and feat2`
>>> new_m = torchvision.models._utils.IntermediateLayerGetter(m,
>>> {'layer1': 'feat1', 'layer3': 'feat2'})
>>> out = new_m(torch.rand(1, 3, 224, 224))
>>> print([(k, v.shape) for k, v in out.items()])
>>> [('feat1', torch.Size([1, 64, 56, 56])),
>>> ('feat2', torch.Size([1, 256, 14, 14]))] | 62598faf4e4d562566372447 |
class GaugeRobustErrgenTable(WorkspaceTable): <NEW_LINE> <INDENT> def __init__(self, ws, gateset, targetGateset, confidenceRegionInfo=None, genType="logGTi"): <NEW_LINE> <INDENT> super(GaugeRobustErrgenTable,self).__init__(ws, self._create, gateset, targetGateset, confidenceRegionInfo, genType) <NEW_LINE> <DEDENT> def _create(self, gateset, targetGateset, confidenceRegionInfo, genType): <NEW_LINE> <INDENT> gateLabels = list(gateset.gates.keys()) <NEW_LINE> colHeadings = ['Error rates', 'Value'] <NEW_LINE> table = _ReportTable(colHeadings, (None,)*len(colHeadings), confidenceRegionInfo=confidenceRegionInfo) <NEW_LINE> assert(genType == "logGTi"), "Only `genType == \"logGTI\"` is supported when `gaugeRobust` is True" <NEW_LINE> syntheticIdleStrs = [] <NEW_LINE> maxPower = 4; maxLen = 6; Id = _np.identity(targetGateset.dim,'d') <NEW_LINE> baseStrs = _cnst.list_all_gatestrings_without_powers_and_cycles(list(gateset.gates.keys()), maxLen) <NEW_LINE> for s in baseStrs: <NEW_LINE> <INDENT> for i in range(1,maxPower): <NEW_LINE> <INDENT> if len(s**i) > 1 and _np.linalg.norm(targetGateset.product( s**i ) - Id) < 1e-6: <NEW_LINE> <INDENT> syntheticIdleStrs.append( s**i ); break <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> print("Using synthetic idles: \n",'\n'.join([str(gstr) for gstr in syntheticIdleStrs])) <NEW_LINE> gaugeRobust_info = _ev(_reportables.Robust_LogGTi_and_projections( gateset, targetGateset, syntheticIdleStrs), confidenceRegionInfo) <NEW_LINE> for linear_combo_lbl, val in gaugeRobust_info.items(): <NEW_LINE> <INDENT> row_data = [linear_combo_lbl, val] <NEW_LINE> row_formatters = [None, 'Normal'] <NEW_LINE> table.addrow(row_data, row_formatters) <NEW_LINE> <DEDENT> table.finish() <NEW_LINE> return table | Table displaying the first-order gauge invariant ("gauge robust")
linear combinations of standard error generator coefficients for
the gates in a gate set. | 62598fafcc0a2c111447b033 |
class TestUtil(Tester): <NEW_LINE> <INDENT> def test_add_calibration_exposures(self): <NEW_LINE> <INDENT> config = desisurvey.config.Configuration() <NEW_LINE> tiles = desisurvey.tiles.get_tiles() <NEW_LINE> tileID = tiles.tileID[0] <NEW_LINE> exposures = surveysim.exposures.ExposureList() <NEW_LINE> exposures.add(58849., 1., tileID, 1., 1., 1., 1.1, 0.9, 1.0) <NEW_LINE> exposures.add(58850., 1., tileID, 1., 1., 1., 1.1, 0.9, 1.0) <NEW_LINE> for mode in 'obj', 'recarray', 'table': <NEW_LINE> <INDENT> if mode == 'obj': <NEW_LINE> <INDENT> input = exposures <NEW_LINE> <DEDENT> elif mode == 'recarray': <NEW_LINE> <INDENT> input = exposures._exposures[:exposures.nexp] <NEW_LINE> <DEDENT> elif mode == 'table': <NEW_LINE> <INDENT> exposures.save('exposures.fits') <NEW_LINE> input = astropy.table.Table.read( config.get_path('exposures.fits'), hdu='EXPOSURES') <NEW_LINE> <DEDENT> output = add_calibration_exposures(input) <NEW_LINE> self.assertEqual(len(output), 14) <NEW_LINE> self.assertEqual('EXPID', output.colnames[0]) <NEW_LINE> self.assertTrue(np.all(output['EXPID'] == np.arange(14, dtype=np.int32))) <NEW_LINE> self.assertTrue(np.all(np.diff(output['MJD']) >= 0)) <NEW_LINE> self.assertTrue(np.all(np.diff(output['EXPID']) == 1)) <NEW_LINE> <DEDENT> bad_exposures = surveysim.exposures.ExposureList() <NEW_LINE> bad_exposures.add(58851., 1., tileID, 1., 1., 1., 1.1, 0.9, 1.0) <NEW_LINE> bad_exposures.add(58850., 1., tileID, 1., 1., 1., 1.1, 0.9, 1.0) <NEW_LINE> with self.assertRaises(ValueError): <NEW_LINE> <INDENT> output = add_calibration_exposures(bad_exposures) | Test surveysim.util.
| 62598faff7d966606f748006 |
class Container(Segment): <NEW_LINE> <INDENT> def __defaults__(self): <NEW_LINE> <INDENT> self.segments = Process() <NEW_LINE> self.state = State.Container() <NEW_LINE> <DEDENT> def append_segment(self,segment): <NEW_LINE> <INDENT> self.segments.append(segment) <NEW_LINE> return | A container for the segment
Assumptions:
None
Source:
None | 62598fafd58c6744b42dc2e8 |
class Checks(upgradecheck.UpgradeCommands): <NEW_LINE> <INDENT> def _check_placeholder(self): <NEW_LINE> <INDENT> return upgradecheck.Result(upgradecheck.Code.SUCCESS) <NEW_LINE> <DEDENT> _upgrade_checks = ( (_('Placeholder'), _check_placeholder), (_('Policy File JSON to YAML Migration'), (common_checks.check_policy_json, {'conf': cfg.CONF})), ) | Various upgrade checks should be added as separate methods in this class
and added to _upgrade_checks tuple. | 62598faf56ac1b37e630220d |
class PSS_SigScheme: <NEW_LINE> <INDENT> def __init__(self, key, mgfunc, saltLen): <NEW_LINE> <INDENT> self._key = key <NEW_LINE> self._saltLen = saltLen <NEW_LINE> self._mgfunc = mgfunc <NEW_LINE> <DEDENT> def can_sign(self): <NEW_LINE> <INDENT> return self._key.has_private() <NEW_LINE> <DEDENT> def sign(self, mhash): <NEW_LINE> <INDENT> randfunc = self._key._randfunc <NEW_LINE> if self._saltLen == None: <NEW_LINE> <INDENT> sLen = mhash.digest_size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sLen = self._saltLen <NEW_LINE> <DEDENT> if self._mgfunc: <NEW_LINE> <INDENT> mgf = self._mgfunc <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mgf = lambda x,y: MGF1(x,y,mhash) <NEW_LINE> <DEDENT> modBits = Crypto.Util.number.size(self._key.n) <NEW_LINE> k = ceil_div(modBits,8) <NEW_LINE> em = EMSA_PSS_ENCODE(mhash, modBits-1, randfunc, mgf, sLen) <NEW_LINE> m = self._key.decrypt(em) <NEW_LINE> S = bchr(0x00)*(k-len(m)) + m <NEW_LINE> return S <NEW_LINE> <DEDENT> def verify(self, mhash, S): <NEW_LINE> <INDENT> if self._saltLen == None: <NEW_LINE> <INDENT> sLen = mhash.digest_size <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> sLen = self._saltLen <NEW_LINE> <DEDENT> if self._mgfunc: <NEW_LINE> <INDENT> mgf = self._mgfunc <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mgf = lambda x,y: MGF1(x,y,mhash) <NEW_LINE> <DEDENT> modBits = Crypto.Util.number.size(self._key.n) <NEW_LINE> k = ceil_div(modBits,8) <NEW_LINE> if len(S) != k: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> em = self._key.encrypt(S, 0)[0] <NEW_LINE> emLen = ceil_div(modBits-1,8) <NEW_LINE> em = bchr(0x00)*(emLen-len(em)) + em <NEW_LINE> try: <NEW_LINE> <INDENT> result = EMSA_PSS_VERIFY(mhash, em, modBits-1, mgf, sLen) <NEW_LINE> <DEDENT> except ValueError: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> return result | This signature scheme can perform PKCS#1 PSS RSA signature or verification. | 62598faf4a966d76dd5eeef8 |
class PreciseBNHook(Hook): <NEW_LINE> <INDENT> def __init__(self, dataloader, num_iters=200, interval=1): <NEW_LINE> <INDENT> if not isinstance(dataloader, DataLoader): <NEW_LINE> <INDENT> raise TypeError('dataloader must be a pytorch DataLoader, but got' f' {type(dataloader)}') <NEW_LINE> <DEDENT> self.dataloader = dataloader <NEW_LINE> self.interval = interval <NEW_LINE> self.num_iters = num_iters <NEW_LINE> <DEDENT> def after_train_epoch(self, runner): <NEW_LINE> <INDENT> if self.every_n_epochs(runner, self.interval): <NEW_LINE> <INDENT> time.sleep(2.) <NEW_LINE> print_log( f'Running Precise BN for {self.num_iters} iterations', logger=runner.logger) <NEW_LINE> update_bn_stats( runner.model, self.dataloader, self.num_iters, logger=runner.logger) <NEW_LINE> print_log('BN stats updated', logger=runner.logger) <NEW_LINE> time.sleep(2.) | Precise BN hook.
Attributes:
dataloader (DataLoader): A PyTorch dataloader.
num_iters (int): Number of iterations to update the bn stats.
Default: 200.
interval (int): Perform precise bn interval (by epochs). Default: 1. | 62598faf851cf427c66b82dd |
class MachineLearning(Prisoner): <NEW_LINE> <INDENT> def __init__(self, name, agent=False): <NEW_LINE> <INDENT> super(MachineLearning, self).__init__(name) <NEW_LINE> self.agent = agent if agent else QLearning(2) <NEW_LINE> self.last_action = None <NEW_LINE> <DEDENT> def punish(self, state, action, reward, new_state): <NEW_LINE> <INDENT> action = ACTIONS.index(action) <NEW_LINE> if self.last_action: <NEW_LINE> <INDENT> self.agent.learn(state=state, action=action, reward=reward, new_state=new_state) <NEW_LINE> <DEDENT> self.last_action = True <NEW_LINE> <DEDENT> def strategy(self, state, **context): <NEW_LINE> <INDENT> action = ACTIONS[self.agent.choose(state=state)] <NEW_LINE> self.actions.append(action) <NEW_LINE> return action | implement the simplest ML algorithm possible
Non iterative version of the game
It should learn that he should always defect | 62598faf3539df3088ecc2d4 |
class ValidationFailedError(KaitaiStructError): <NEW_LINE> <INDENT> def __init__(self, msg, io, src_path): <NEW_LINE> <INDENT> super(ValidationFailedError, self).__init__("at pos %d: validation failed: %s" % (io.pos(), msg), src_path) <NEW_LINE> self.io = io | Common ancestor for all validation failures. Stores pointer to
KaitaiStream IO object which was involved in an error. | 62598faf7d847024c075c3e4 |
class ListParameter(MessageParameter): <NEW_LINE> <INDENT> type = tuple <NEW_LINE> def __init__(self, iparam, iname="item", length=None): <NEW_LINE> <INDENT> MessageParameter.__init__(self) <NEW_LINE> if not isinstance(iparam, MessageParameter): <NEW_LINE> <INDENT> raise ParameterError("Invalid parameter type: %s", iparam) <NEW_LINE> <DEDENT> self._iname = iname <NEW_LINE> self._iparam = iparam <NEW_LINE> self._length = length <NEW_LINE> <DEDENT> def validate(self, value): <NEW_LINE> <INDENT> if not isinstance(value, tuple) and not isinstance(value, list): <NEW_LINE> <INDENT> raise ParameterError(value=value) <NEW_LINE> <DEDENT> if self._length is not None and len(value) != self._length: <NEW_LINE> <INDENT> raise ParameterError("Invalid list length: %d" % len(value)) <NEW_LINE> <DEDENT> for item in value: <NEW_LINE> <INDENT> self._iparam.validate(item) <NEW_LINE> <DEDENT> <DEDENT> def marshal(self, element, value): <NEW_LINE> <INDENT> for item in value: <NEW_LINE> <INDENT> self._iparam.marshal(etree.SubElement(element, self._iname), item) <NEW_LINE> <DEDENT> <DEDENT> def unmarshal(self, element): <NEW_LINE> <INDENT> value = [] <NEW_LINE> for item in element.getchildren(): <NEW_LINE> <INDENT> if item.tag != self._iname: <NEW_LINE> <INDENT> raise ParameterError("Invalid list item name: %s" % item.tag) <NEW_LINE> <DEDENT> value.append(self._iparam.unmarshal(item)) <NEW_LINE> <DEDENT> return self.type(value) | A class of list or tuple message parameters. | 62598faf4e4d562566372448 |
class IPublicPage(Interface): <NEW_LINE> <INDENT> pass | Only needed for schema compatibility. This interface should be deleted once
Axiom gains the ability to remove interfaces from existing stores. | 62598fafa8370b77170f03fd |
class Assignment(base.Assignment): <NEW_LINE> <INDENT> implements(ICourseBuilderPortlet) <NEW_LINE> title = _(u'Course Builder Portlet') | Assignment | 62598fafb7558d589546364c |
class StochasticVariableBoundsAnnotation(PySP_Annotation): <NEW_LINE> <INDENT> _ctypes = (Var,) <NEW_LINE> _ctypes_data = (_VarData,) <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> super(StochasticVariableBoundsAnnotation, self).__init__() <NEW_LINE> self._default = (True, True) <NEW_LINE> <DEDENT> def _declare_impl(self, component, lb=True, ub=True): <NEW_LINE> <INDENT> assert lb or ub <NEW_LINE> assert (lb is True) or (lb is False) <NEW_LINE> assert (ub is True) or (ub is False) <NEW_LINE> self._data[component] = (lb, ub) | This annotation is used to identify variable
bounds that are stochastic.
When calling declare, at most one of the keywords 'lb' or
'ub' can be set to False to disable the annotation for
one of the variable bounds. | 62598faf66656f66f7d5a412 |
class DrinkAction(): <NEW_LINE> <INDENT> def __init__(self, character, potion, effect_factory): <NEW_LINE> <INDENT> self.character = character <NEW_LINE> self.potion = potion <NEW_LINE> self.effect_factory = effect_factory <NEW_LINE> <DEDENT> def execute(self): <NEW_LINE> <INDENT> if not self.is_legal(): <NEW_LINE> <INDENT> return Left(self.character) <NEW_LINE> <DEDENT> self.character.identify_item(self.potion) <NEW_LINE> drink_effects = self.potion.get_effect_handles('on drink') <NEW_LINE> if len(drink_effects) > 0: <NEW_LINE> <INDENT> for effect_spec in drink_effects: <NEW_LINE> <INDENT> effect = self.effect_factory(effect_spec.effect, target=self.character) <NEW_LINE> if effect.duration == 0: <NEW_LINE> <INDENT> effect.trigger() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> self.character.add_effect(effect) <NEW_LINE> <DEDENT> effect_spec.charges = effect_spec.charges - 1 <NEW_LINE> <DEDENT> if self.potion.maximum_charges_left < 1: <NEW_LINE> <INDENT> self.character.inventory.remove(self.potion) <NEW_LINE> <DEDENT> <DEDENT> return Right(self.character) <NEW_LINE> <DEDENT> def is_legal(self): <NEW_LINE> <INDENT> return True | Action for drinking | 62598faf4527f215b58e9ef7 |
class GroupsCoursesList(SecureAPIView): <NEW_LINE> <INDENT> def post(self, request, group_id): <NEW_LINE> <INDENT> response_data = {} <NEW_LINE> try: <NEW_LINE> <INDENT> existing_group = Group.objects.get(id=group_id) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return Response({}, status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> course_id = request.DATA['course_id'] <NEW_LINE> base_uri = generate_base_uri(request) <NEW_LINE> response_data['uri'] = '{}/{}'.format(base_uri, course_id) <NEW_LINE> existing_course, course_key, course_content = get_course(request, request.user, course_id) <NEW_LINE> if not existing_course: <NEW_LINE> <INDENT> return Response({}, status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> existing_relationship = CourseGroupRelationship.objects.get(course_id=course_id, group=existing_group) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> existing_relationship = None <NEW_LINE> <DEDENT> if existing_relationship is None: <NEW_LINE> <INDENT> new_relationship = CourseGroupRelationship.objects.create(course_id=course_id, group=existing_group) <NEW_LINE> response_data['group_id'] = str(new_relationship.group_id) <NEW_LINE> response_data['course_id'] = str(new_relationship.course_id) <NEW_LINE> response_status = status.HTTP_201_CREATED <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> response_data['message'] = "Relationship already exists." <NEW_LINE> response_status = status.HTTP_409_CONFLICT <NEW_LINE> <DEDENT> return Response(response_data, status=response_status) <NEW_LINE> <DEDENT> def get(self, request, group_id): <NEW_LINE> <INDENT> response_data = {} <NEW_LINE> try: <NEW_LINE> <INDENT> existing_group = Group.objects.get(id=group_id) <NEW_LINE> <DEDENT> except ObjectDoesNotExist: <NEW_LINE> <INDENT> return Response({}, status.HTTP_404_NOT_FOUND) <NEW_LINE> <DEDENT> members = CourseGroupRelationship.objects.filter(group=existing_group) <NEW_LINE> response_data = [] <NEW_LINE> for member in members: <NEW_LINE> <INDENT> course, course_key, course_content = get_course(request, request.user, member.course_id) <NEW_LINE> course_data = { 'course_id': member.course_id, 'display_name': course.display_name } <NEW_LINE> response_data.append(course_data) <NEW_LINE> <DEDENT> response_status = status.HTTP_200_OK <NEW_LINE> return Response(response_data, status=response_status) | ### The GroupsCoursesList view allows clients to interact with the set of Courses related to the specified Group
- URI: ```/api/groups/{group_id}/courses/```
- GET: Returns a JSON representation (array) of the set of related Course entities
- POST: Provides the ability to append to the related Course entity set
* course_id: __required__, The name of the Course being added
- POST Example:
{
"course_id" : "edx/demo/course",
}
### Use Cases/Notes:
* Create a Group of Courses to model cases such as an academic program or topical series
* Once a Course Group exists, you can additionally link to Users and other Groups (see GroupsUsersList, GroupsGroupsList) | 62598fafbe383301e025381b |
class SCSGateSwitch(SwitchDevice): <NEW_LINE> <INDENT> def __init__(self, scs_id, name, logger): <NEW_LINE> <INDENT> self._name = name <NEW_LINE> self._scs_id = scs_id <NEW_LINE> self._toggled = False <NEW_LINE> self._logger = logger <NEW_LINE> <DEDENT> @property <NEW_LINE> def scs_id(self): <NEW_LINE> <INDENT> return self._scs_id <NEW_LINE> <DEDENT> @property <NEW_LINE> def should_poll(self): <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> @property <NEW_LINE> def name(self): <NEW_LINE> <INDENT> return self._name <NEW_LINE> <DEDENT> @property <NEW_LINE> def is_on(self): <NEW_LINE> <INDENT> return self._toggled <NEW_LINE> <DEDENT> def turn_on(self, **kwargs): <NEW_LINE> <INDENT> from scsgate.tasks import ToggleStatusTask <NEW_LINE> scsgate.SCSGATE.append_task( ToggleStatusTask(target=self._scs_id, toggled=True)) <NEW_LINE> self._toggled = True <NEW_LINE> self.schedule_update_ha_state() <NEW_LINE> <DEDENT> def turn_off(self, **kwargs): <NEW_LINE> <INDENT> from scsgate.tasks import ToggleStatusTask <NEW_LINE> scsgate.SCSGATE.append_task( ToggleStatusTask(target=self._scs_id, toggled=False)) <NEW_LINE> self._toggled = False <NEW_LINE> self.schedule_update_ha_state() <NEW_LINE> <DEDENT> def process_event(self, message): <NEW_LINE> <INDENT> if self._toggled == message.toggled: <NEW_LINE> <INDENT> self._logger.info( "Switch %s, ignoring message %s because state already active", self._scs_id, message) <NEW_LINE> return <NEW_LINE> <DEDENT> self._toggled = message.toggled <NEW_LINE> self.update_ha_state() <NEW_LINE> command = "off" <NEW_LINE> if self._toggled: <NEW_LINE> <INDENT> command = "on" <NEW_LINE> <DEDENT> self.hass.bus.fire( 'button_pressed', { ATTR_ENTITY_ID: self._scs_id, ATTR_STATE: command} ) | Representation of a SCSGate switch. | 62598fafbf627c535bcb14c1 |
@attr.s(repr=False) <NEW_LINE> class Link(models__common.Signable): <NEW_LINE> <INDENT> _type = attr.ib("Link", init=False) <NEW_LINE> name = attr.ib("") <NEW_LINE> materials = attr.ib({}) <NEW_LINE> products = attr.ib({}) <NEW_LINE> byproducts = attr.ib({}) <NEW_LINE> command = attr.ib("") <NEW_LINE> return_value = attr.ib(None) <NEW_LINE> def dump(self, filename=False): <NEW_LINE> <INDENT> super(Link, self).dump(filename or "%s.link" % self.name) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def read_from_file(filename): <NEW_LINE> <INDENT> with open(filename, 'r') as fp: <NEW_LINE> <INDENT> return Link.read(json.load(fp)) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def read(data): <NEW_LINE> <INDENT> if data.get("_type"): <NEW_LINE> <INDENT> data.pop(u"_type") <NEW_LINE> <DEDENT> return Link(**data) | A link is the metadata representation of a supply chain step performed
by a functionary.
Links are recorded, signed and stored to a file when a functionary wraps
a command with toto-run.
Links also contain materials and products which are hashes of the file before
the command was executed and after the command was executed.
<Attributes>
name:
a unique name used to identify the related step in the layout
materials and products:
a dictionary in the format of
{ <relative file path> : {
{<hash algorithm> : <hash of the file>}
},... }
byproducts:
a dictionary in the format of
{
"stdout": <standard output of the executed command>
"stderr": <standard error of the executed command>
}
command:
the command that was wrapped by toto-run
return_value:
the return value of the executed command
| 62598faf4428ac0f6e658548 |
class Workflow(Resource): <NEW_LINE> <INDENT> def __init__(self, transport, wf_url): <NEW_LINE> <INDENT> super(Workflow, self).__init__(transport, wf_url) <NEW_LINE> <DEDENT> def is_running(self): <NEW_LINE> <INDENT> status = self.properties['status'] <NEW_LINE> return status not in ('SUCCESSFUL', 'FAILED', ) <NEW_LINE> <DEDENT> def abort(self): <NEW_LINE> <INDENT> url = self.properties['_links']['action:abort']['href'] <NEW_LINE> return self.transport.post(url=url, json={}) <NEW_LINE> <DEDENT> def resume(self, params={}): <NEW_LINE> <INDENT> url = self.properties['_links']['action:resume']['href'] <NEW_LINE> return self.transport.post(url=url, json={}) <NEW_LINE> <DEDENT> def get_files(self): <NEW_LINE> <INDENT> return self.transport.get(url=self.links['files']) <NEW_LINE> <DEDENT> def get_jobs(self, offset=0, num=None): <NEW_LINE> <INDENT> j_url = _build_full_url(self.links['jobs'], offset, num, []) <NEW_LINE> return [Job(self.transport, url) for url in self.transport.get(url=j_url)['jobs']] <NEW_LINE> <DEDENT> def stat(self, path): <NEW_LINE> <INDENT> physical_location = self.get_files()[path] <NEW_LINE> storage_url, name = physical_location.split("/files/",1) <NEW_LINE> return Storage(self.transport, storage_url).stat(name) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ('Workflow: %s submitted: %s running: %s' % (self.resource_url, self.properties['submissionTime'], self.is_running())) <NEW_LINE> <DEDENT> __str__ = __repr__ | wrapper around a UNICORE workflow | 62598faf38b623060ffa90be |
class TwoRings(Structure): <NEW_LINE> <INDENT> __name_prefix__ = "TWORING" <NEW_LINE> ring1 = DefinitionProperty(restriction = RestrictType(RingResonator)) <NEW_LINE> ring2 = DefinitionProperty(restriction = RestrictType(RingResonator)) <NEW_LINE> def get_transformations(self): <NEW_LINE> <INDENT> t1 = Translation((0.0, self.ring1.ring_radius + 5.0)) <NEW_LINE> t2 = VMirror() + Translation((0.0, -self.ring2.ring_radius - 5.0)) <NEW_LINE> return (t1, t2) <NEW_LINE> <DEDENT> def define_elements(self, elems): <NEW_LINE> <INDENT> t1, t2 = self.get_transformations() <NEW_LINE> elems += SRef(reference = self.ring1, transformation = t1) <NEW_LINE> elems += SRef(reference = self.ring2, transformation = t2) <NEW_LINE> return elems <NEW_LINE> <DEDENT> def define_ports(self, prts): <NEW_LINE> <INDENT> t1, t2 = self.get_transformations() <NEW_LINE> prts += self.ring1.ports.transform_copy(t1) <NEW_LINE> prts += self.ring2.ports.transform_copy(t2) <NEW_LINE> return prts | structure with two rings defined by the user, which are stacked
vertically, with the bottom one flipped. | 62598faf236d856c2adc944f |
class HandleRefManager(models.Manager): <NEW_LINE> <INDENT> @property <NEW_LINE> def tag(self): <NEW_LINE> <INDENT> return self.prop("tag") <NEW_LINE> <DEDENT> def prop(self, key): <NEW_LINE> <INDENT> return getattr(self.model._handleref, key) <NEW_LINE> <DEDENT> def get_queryset(self): <NEW_LINE> <INDENT> return HandleRefQuerySet(self.model, using=self._db) <NEW_LINE> <DEDENT> def last_change(self, **kwargs): <NEW_LINE> <INDENT> return self.get_queryset().last_change(**kwargs) <NEW_LINE> <DEDENT> def since(self, **kwargs): <NEW_LINE> <INDENT> return self.get_queryset().since(**kwargs) <NEW_LINE> <DEDENT> def undeleted(self): <NEW_LINE> <INDENT> return self.get_queryset().undeleted() | Custom manager to provide handleref querying | 62598faf3317a56b869be55c |
class EthernetMACAddress(object): <NEW_LINE> <INDENT> _STRUCT_ = construct.Array(6, construct.Byte) <NEW_LINE> _MAC_RE_ = re.compile( r'^([0-9A-Fa-f]{2})([:-])' r'([0-9A-Fa-f]{2})\2' r'([0-9A-Fa-f]{2})\2' r'([0-9A-Fa-f]{2})\2' r'([0-9A-Fa-f]{2})\2' r'([0-9A-Fa-f]{2})$' ) <NEW_LINE> def __init__(self, address): <NEW_LINE> <INDENT> if isinstance(address, str): <NEW_LINE> <INDENT> address = self.fromstr(address) <NEW_LINE> <DEDENT> address = tobytes(address) <NEW_LINE> if len(address) != 6: <NEW_LINE> <INDENT> raise ValueError('address must be 6 bytes long') <NEW_LINE> <DEDENT> self._address = address <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def fromstr(cls, mac): <NEW_LINE> <INDENT> match = cls._MAC_RE_.match(mac) <NEW_LINE> if match is None: <NEW_LINE> <INDENT> raise ValueError('%r does not match pattern' % mac) <NEW_LINE> <DEDENT> (mac1, _, mac2, mac3, mac4, mac5, mac6) = match.groups() <NEW_LINE> return cls(bytes([ int(mac1, base=16), int(mac2, base=16), int(mac3, base=16), int(mac4, base=16), int(mac5, base=16), int(mac6, base=16) ])) <NEW_LINE> <DEDENT> @property <NEW_LINE> def islocal(self): <NEW_LINE> <INDENT> return self._address[0] & (1 << 1) <NEW_LINE> <DEDENT> @property <NEW_LINE> def ismulticast(self): <NEW_LINE> <INDENT> return self._address[0] & (1 << 0) <NEW_LINE> <DEDENT> def __str__(self): <NEW_LINE> <INDENT> return ':'.join(['%02x' % b for b in self._address]) <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return '%s(%r)' % (self.__class__.__name__, self._address) <NEW_LINE> <DEDENT> def __bytes__(self): <NEW_LINE> <INDENT> return self._address | A representation of a MAC (EUI-48) address. | 62598faff7d966606f748008 |
class LicenseContentAdjuster(object): <NEW_LINE> <INDENT> def __init__(self, source_path): <NEW_LINE> <INDENT> super().__init__() <NEW_LINE> self._source_path = source_path <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def create_from_resource_query(source_path, _): <NEW_LINE> <INDENT> return LicenseContentAdjuster(source_path) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def needs_adjustment(content_type): <NEW_LINE> <INDENT> return content_type in _CONTENT_TYPE_DISPATCH.keys() <NEW_LINE> <DEDENT> def render_async(self, content_type, content_bytes, version, query, cache, cancellable, callback): <NEW_LINE> <INDENT> render_license_content_async(content_type, content_bytes, version, query, self._source_path, cache, cancellable, callback) | An implementation of Adjuster for License Content routes. | 62598fafbaa26c4b54d4f2d7 |
class Host: <NEW_LINE> <INDENT> def __init__(self, host_url, auth): <NEW_LINE> <INDENT> self.host_url = host_url <NEW_LINE> self.rancher_auth = auth <NEW_LINE> self.hostname = None <NEW_LINE> self.initilize() <NEW_LINE> <DEDENT> def initilize(self): <NEW_LINE> <INDENT> host_props = r.get(self.host_url, auth=self.rancher_auth).json() <NEW_LINE> if self.host_url: <NEW_LINE> <INDENT> self.hostname = host_props['hostname'] <NEW_LINE> <DEDENT> <DEDENT> def evacuate(self): <NEW_LINE> <INDENT> host_props = r.get(self.host_url, auth=self.rancher_auth).json() <NEW_LINE> evacuate_url = host_props['actions']['evacuate'] <NEW_LINE> resp = r.post(evacuate_url, auth=self.rancher_auth) <NEW_LINE> return resp <NEW_LINE> <DEDENT> def deactivate(self): <NEW_LINE> <INDENT> host_props = r.get(self.host_url, auth=self.rancher_auth).json() <NEW_LINE> deactivate_url = host_props['actions']['deactivate'] <NEW_LINE> resp = r.post(deactivate_url, auth=self.rancher_auth) <NEW_LINE> return resp <NEW_LINE> <DEDENT> def activate(self): <NEW_LINE> <INDENT> self_props = r.get(self.host_url, auth=self.rancher_auth).json() <NEW_LINE> activate_url = self_props['actions'].get('activate') <NEW_LINE> if not activate_url: <NEW_LINE> <INDENT> logging.info("Action unavailable: activate") <NEW_LINE> return <NEW_LINE> <DEDENT> resp = r.post(activate_url, auth=self.rancher_auth) <NEW_LINE> return resp <NEW_LINE> <DEDENT> def remove(self): <NEW_LINE> <INDENT> host_props = r.get(self.host_url, auth=self.rancher_auth).json() <NEW_LINE> remove_url = host_props['actions'].get('remove') <NEW_LINE> if not remove_url: <NEW_LINE> <INDENT> logging.info("Action unavailable: remove") <NEW_LINE> return <NEW_LINE> <DEDENT> resp = r.post(remove_url, auth=self.rancher_auth) <NEW_LINE> return resp <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return self.hostname | Class models Hosts in Rancher | 62598faf097d151d1a2c104e |
class MILLIAMPERE( Unit ): <NEW_LINE> <INDENT> standard= AMPERE <NEW_LINE> name= "mA" <NEW_LINE> factor= 1.0E3 | millimpere | 62598faf60cbc95b06364373 |
class ParticipationSetting(models.Model): <NEW_LINE> <INDENT> name = models.CharField(default="Participation Settings", max_length="30", editable=False, help_text="The settings label.") <NEW_LINE> points_50_percent = models.IntegerField( default=5, help_text="The point amount for 50 percent participation." ) <NEW_LINE> points_75_percent = models.IntegerField( default=5, help_text="The point amount for 75 percent participation." ) <NEW_LINE> points_100_percent = models.IntegerField( default=10, help_text="The point amount for 100 percent participation." ) <NEW_LINE> admin_tool_tip = "Points for different participation levels" | participation settings models. | 62598faf30bbd7224646998a |
class Player(messages.Enum): <NEW_LINE> <INDENT> LEFT = 0 <NEW_LINE> RIGHT = 1 | two player game side | 62598fafd486a94d0ba2bff2 |
class CRAN(JSONHoster): <NEW_LINE> <INDENT> async def get_versions_from_json(self, data, _, orig_version): <NEW_LINE> <INDENT> res = [] <NEW_LINE> versions = list(set((str(data["latest"]), self.vals["version"], orig_version))) <NEW_LINE> for vers in versions: <NEW_LINE> <INDENT> if vers not in data['versions']: <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> vdata = data['versions'][vers] <NEW_LINE> depends = { "r-" + pkg.lower() if pkg != 'R' else 'r-base': spec.replace(" ", "").replace("\n", "").replace("*", "") for pkg, spec in chain(vdata.get('Depends', {}).items(), vdata.get('Imports', {}).items(), vdata.get('LinkingTo', {}).items()) } <NEW_LINE> version = { 'link': '', 'version': vers, 'depends': {'host': depends, 'run': depends}, } <NEW_LINE> res.append(version) <NEW_LINE> <DEDENT> return res <NEW_LINE> <DEDENT> package_pattern = r"(?P<package>[\w.]+)" <NEW_LINE> url_pattern = (r"r-project\.org/src/contrib" r"(/Archive)?/{package}(?(1)/{package}|)" r"_{version}{ext}") <NEW_LINE> releases_formats = ["https://crandb.r-pkg.org/{package}/all"] | R packages hosted on r-project.org (CRAN) | 62598faf67a9b606de545ff0 |
@unittest.skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in lms') <NEW_LINE> class GetAwardedCertificateProgramsTestCase(TestCase): <NEW_LINE> <INDENT> def make_credential_result(self, **kwargs): <NEW_LINE> <INDENT> result = { 'id': 1, 'username': 'dummy-username', 'credential': { 'credential_id': None, 'program_id': None, }, 'status': 'dummy-status', 'uuid': 'dummy-uuid', 'certificate_url': 'http://credentials.edx.org/credentials/dummy-uuid/' } <NEW_LINE> result.update(**kwargs) <NEW_LINE> return result <NEW_LINE> <DEDENT> @mock.patch(TASKS_MODULE + '.get_user_credentials') <NEW_LINE> def test_get_awarded_certificate_programs(self, mock_get_user_credentials): <NEW_LINE> <INDENT> student = UserFactory(username='test-username') <NEW_LINE> mock_get_user_credentials.return_value = [ self.make_credential_result(status='awarded', credential={'program_id': 1}), self.make_credential_result(status='awarded', credential={'course_id': 2}), self.make_credential_result(status='revoked', credential={'program_id': 3}), ] <NEW_LINE> result = tasks.get_awarded_certificate_programs(student) <NEW_LINE> self.assertEqual(mock_get_user_credentials.call_args[0], (student, )) <NEW_LINE> self.assertEqual(result, [1]) | Test the get_awarded_certificate_programs function | 62598faf55399d3f05626547 |
class precipitation(basetype): <NEW_LINE> <INDENT> known_units = ['IN', 'CM', 'MM'] <NEW_LINE> def value(self, units): <NEW_LINE> <INDENT> if units.upper() not in precipitation.known_units: <NEW_LINE> <INDENT> raise UnitsError("unrecognized precipitation unit: %s known: %s" % ( units, precipitation.known_units)) <NEW_LINE> <DEDENT> if units.upper() == self._units: <NEW_LINE> <INDENT> return self._value <NEW_LINE> <DEDENT> if self._units == 'IN': <NEW_LINE> <INDENT> mm = self._value * 25.4 <NEW_LINE> <DEDENT> elif self._units == 'CM': <NEW_LINE> <INDENT> mm = self._value * 10.0 <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> mm = self._value <NEW_LINE> <DEDENT> if units == 'MM': <NEW_LINE> <INDENT> return mm <NEW_LINE> <DEDENT> elif units == 'CM': <NEW_LINE> <INDENT> return mm * 10.0 <NEW_LINE> <DEDENT> elif units == 'IN': <NEW_LINE> <INDENT> return mm / 25.4 | Precipitation | 62598faf851cf427c66b82df |
class KeyboardTestCase(TestCase, LoaderModuleMockMixin): <NEW_LINE> <INDENT> def setup_loader_modules(self): <NEW_LINE> <INDENT> return {keyboard: {}} <NEW_LINE> <DEDENT> def test_system(self): <NEW_LINE> <INDENT> name = 'salt' <NEW_LINE> ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} <NEW_LINE> mock = MagicMock(side_effect=[name, '', '', '']) <NEW_LINE> mock_t = MagicMock(side_effect=[True, False]) <NEW_LINE> with patch.dict(keyboard.__salt__, {'keyboard.get_sys': mock, 'keyboard.set_sys': mock_t}): <NEW_LINE> <INDENT> comt = ('System layout {0} already set'.format(name)) <NEW_LINE> ret.update({'comment': comt}) <NEW_LINE> self.assertDictEqual(keyboard.system(name), ret) <NEW_LINE> with patch.dict(keyboard.__opts__, {'test': True}): <NEW_LINE> <INDENT> comt = ('System layout {0} needs to be set'.format(name)) <NEW_LINE> ret.update({'comment': comt, 'result': None}) <NEW_LINE> self.assertDictEqual(keyboard.system(name), ret) <NEW_LINE> <DEDENT> with patch.dict(keyboard.__opts__, {'test': False}): <NEW_LINE> <INDENT> comt = ('Set system keyboard layout {0}'.format(name)) <NEW_LINE> ret.update({'comment': comt, 'result': True, 'changes': {'layout': name}}) <NEW_LINE> self.assertDictEqual(keyboard.system(name), ret) <NEW_LINE> comt = ('Failed to set system keyboard layout') <NEW_LINE> ret.update({'comment': comt, 'result': False, 'changes': {}}) <NEW_LINE> self.assertDictEqual(keyboard.system(name), ret) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def test_xorg(self): <NEW_LINE> <INDENT> name = 'salt' <NEW_LINE> ret = {'name': name, 'result': True, 'comment': '', 'changes': {}} <NEW_LINE> mock = MagicMock(side_effect=[name, '', '', '']) <NEW_LINE> mock_t = MagicMock(side_effect=[True, False]) <NEW_LINE> with patch.dict(keyboard.__salt__, {'keyboard.get_x': mock, 'keyboard.set_x': mock_t}): <NEW_LINE> <INDENT> comt = ('XOrg layout {0} already set'.format(name)) <NEW_LINE> ret.update({'comment': comt}) <NEW_LINE> self.assertDictEqual(keyboard.xorg(name), ret) <NEW_LINE> with patch.dict(keyboard.__opts__, {'test': True}): <NEW_LINE> <INDENT> comt = ('XOrg layout {0} needs to be set'.format(name)) <NEW_LINE> ret.update({'comment': comt, 'result': None}) <NEW_LINE> self.assertDictEqual(keyboard.xorg(name), ret) <NEW_LINE> <DEDENT> with patch.dict(keyboard.__opts__, {'test': False}): <NEW_LINE> <INDENT> comt = ('Set XOrg keyboard layout {0}'.format(name)) <NEW_LINE> ret.update({'comment': comt, 'result': True, 'changes': {'layout': name}}) <NEW_LINE> self.assertDictEqual(keyboard.xorg(name), ret) <NEW_LINE> comt = ('Failed to set XOrg keyboard layout') <NEW_LINE> ret.update({'comment': comt, 'result': False, 'changes': {}}) <NEW_LINE> self.assertDictEqual(keyboard.xorg(name), ret) | Test cases for salt.states.keyboard | 62598faf85dfad0860cbfa85 |
class Tree: <NEW_LINE> <INDENT> def __init__(self, root, parent=None): <NEW_LINE> <INDENT> self.root = root <NEW_LINE> self.subtrees = [] <NEW_LINE> self.parent = parent <NEW_LINE> <DEDENT> def is_empty(self): <NEW_LINE> <INDENT> return self.root is None <NEW_LINE> <DEDENT> def add_subtree(self, new_tree): <NEW_LINE> <INDENT> if self.is_empty(): <NEW_LINE> <INDENT> raise ValueError() <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> new_tree.parent = self <NEW_LINE> self.subtrees.append(new_tree) | A recursive tree data structure, modified by keeping track of each node`s parent.
This version of tree is created specifically for the purposes of controller, it assumes that
values of the tree are tuples with the puzzle state and a string representation of a move.
Also, all of its attributes are public, as they need to be accessed in controller.
=== Public Attributes ===
@type root: o(Puzzle, str | None) | None | None
The item stored at the tree's root, or None if the tree is empty.
@type subtrees: list[Tree]
A list of all subtrees of the tree
@type parent: Tree | None
The parent tree of the current subtree or None, if tree is the root tree. | 62598fafa05bb46b3848a88f |
class TestRequest(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.req = Manager() <NEW_LINE> <DEDENT> @mock.patch('onion_py.manager.requests') <NEW_LINE> def test_without_parameters(self, mock_requests): <NEW_LINE> <INDENT> mock_requests.get.return_value = FakeResponse(200) <NEW_LINE> self.req.query('details') <NEW_LINE> mock_requests.get.assert_called_with( self.req.OOO_URL + 'details', params={}) <NEW_LINE> <DEDENT> @mock.patch('onion_py.manager.requests') <NEW_LINE> def test_with_parameters(self, mock_requests): <NEW_LINE> <INDENT> mock_requests.get.return_value = FakeResponse(200) <NEW_LINE> self.req.query( 'details', type='relay', running='true') <NEW_LINE> mock_requests.get.assert_called_with( self.req.OOO_URL + 'details', params={'type': 'relay', 'running': 'true'}) | Test case for the Manager object | 62598faf1b99ca400228f542 |
@ENTITY_ADAPTERS.register(camera.DOMAIN) <NEW_LINE> class CameraCapabilities(AlexaEntity): <NEW_LINE> <INDENT> def default_display_categories(self): <NEW_LINE> <INDENT> return [DisplayCategory.CAMERA] <NEW_LINE> <DEDENT> def interfaces(self): <NEW_LINE> <INDENT> if self._check_requirements(): <NEW_LINE> <INDENT> supported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0) <NEW_LINE> if supported & camera.SUPPORT_STREAM: <NEW_LINE> <INDENT> yield AlexaCameraStreamController(self.entity) <NEW_LINE> <DEDENT> <DEDENT> yield AlexaEndpointHealth(self.hass, self.entity) <NEW_LINE> yield Alexa(self.hass) <NEW_LINE> <DEDENT> def _check_requirements(self): <NEW_LINE> <INDENT> if "stream" not in self.hass.config.components: <NEW_LINE> <INDENT> _LOGGER.debug( "%s requires stream component for AlexaCameraStreamController", self.entity_id, ) <NEW_LINE> return False <NEW_LINE> <DEDENT> url = urlparse(network.async_get_external_url(self.hass)) <NEW_LINE> if url.scheme != "https": <NEW_LINE> <INDENT> _LOGGER.debug( "%s requires HTTPS for AlexaCameraStreamController", self.entity_id ) <NEW_LINE> return False <NEW_LINE> <DEDENT> return True | Class to represent Camera capabilities. | 62598fafaad79263cf42e7f7 |
class Parameter(object): <NEW_LINE> <INDENT> @classmethod <NEW_LINE> def bstr(cls, arg): <NEW_LINE> <INDENT> if is_unicode(arg): <NEW_LINE> <INDENT> return arg.encode('latin1') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return arg <NEW_LINE> <DEDENT> <DEDENT> @classmethod <NEW_LINE> def bparameters(cls, parameters): <NEW_LINE> <INDENT> result = {} <NEW_LINE> warn = False <NEW_LINE> for k, v in dict_items(parameters): <NEW_LINE> <INDENT> if not is_text(k): <NEW_LINE> <INDENT> warn = True <NEW_LINE> k = k.decode('ascii') <NEW_LINE> <DEDENT> n, v = v <NEW_LINE> if not is_text(n): <NEW_LINE> <INDENT> warn = True <NEW_LINE> n = n.decode('ascii') <NEW_LINE> <DEDENT> if is_unicode(v): <NEW_LINE> <INDENT> v = v.encode('iso-8859-1') <NEW_LINE> <DEDENT> result[k] = (n, v) <NEW_LINE> <DEDENT> if warn: <NEW_LINE> <INDENT> logging.warn("Parameter names should be character strings: %s" % repr(parameters)) <NEW_LINE> <DEDENT> return result <NEW_LINE> <DEDENT> def to_bytes(self): <NEW_LINE> <INDENT> raise NotImplementedError <NEW_LINE> <DEDENT> if py2: <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return self.to_bytes() <NEW_LINE> <DEDENT> def __unicode__(self): <NEW_LINE> <INDENT> return self.to_bytes().decode('iso-8859-1') <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> def __str__(self): <NEW_LINE> <INDENT> return self.to_bytes().decode('iso-8859-1') <NEW_LINE> <DEDENT> def __bytes__(self): <NEW_LINE> <INDENT> return self.to_bytes() | Abstract base class for HTTP Parameters
Provides conversion to strings based on the :meth:`to_bytes` method.
In Python 2, also provides conversion to the unicode string type.
In Python 3, implements __bytes__ to enable use of bytes(parameter)
which becomes portable as in Python 2 __str__ is mapped to to_bytes
too.
The HTTP grammar and the parsers and classes that implement it all
use binary strings but usage of byte values outside those of the US
ASCII codepoints is discouraged and unlikely to be portable between
systems.
When required, Pyslet converts to character strings using the
ISO-8859-1 codec. This ensures that the conversions never generate
unicode decoding erros and is consistent with the text of RFC2616.
As the purpose of these modules is to provide a way to use HTTP
constructs in other contexts too, parameters use *character* strings
where possible. Therefore, if an attribute must represent a token
then it is converted to a character string and *must* therefore be
compared using character strings and not binary strings. For
example, see the type and subtype attributes of :class:`MediaType`.
Similarly where tokens are passed as arguments to constructors these
must also be character strings.
Where an attribute may be, or may contain, a value that would be
represented as a quoted string in the protocol then it is stored as
a binary string. You need to take particular care with parameter
lists as the parameter names are tokens so are character strings but
the parameter values are binary strings. The distinction is lost in
Python 2 but the following code snippet will behave unexpectedly in
Python 3 so for future compatibility it is better to make usage
explicit now::
Python 2.7
>>> from pyslet.http.params import MediaType
>>> t = MediaType.from_str("text/plain; charset=utf-8")
>>> "Yes" if t["charset"] == 'utf-8' else "No"
'Yes'
>>> "Yes" if t["charset"] == b'utf-8' else "No"
'Yes'
Python 3.5
>>> from pyslet.http.params import MediaType
>>> t = MediaType.from_str("text/plain; charset=utf-8")
>>> "Yes" if t["charset"] == 'utf-8' else "No"
'No'
>>> "Yes" if t["charset"] == b'utf-8' else "No"
'Yes'
Such values *may* be set using character strings, in which case
ISO-8859-1 is used to encode them. | 62598faf379a373c97d99038 |
class Trading(Ebay): <NEW_LINE> <INDENT> def __init__(self, **kwargs): <NEW_LINE> <INDENT> super(Trading, self).__init__(**kwargs) <NEW_LINE> env_file = 'envs.yml' <NEW_LINE> if self.sandbox: <NEW_LINE> <INDENT> domain = 'api.sandbox.ebay.com' <NEW_LINE> certid = kwargs.get('certid', getenv('EBAY_SB_CERT_ID')) <NEW_LINE> token = kwargs.get('token', getenv('EBAY_SB_TOKEN')) <NEW_LINE> token = (token or getenv_from_file('EBAY_SB_TOKEN', env_file)) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> domain = 'api.ebay.com' <NEW_LINE> certid = kwargs.get('certid', getenv('EBAY_LIVE_CERT_ID')) <NEW_LINE> token = kwargs.get('token', getenv('EBAY_LIVE_TOKEN')) <NEW_LINE> token = (token or getenv_from_file('EBAY_LIVE_TOKEN', env_file)) <NEW_LINE> <DEDENT> new = { 'siteid': self.global_ids[self.kwargs['country']]['countryid'], 'domain': domain, 'certid': certid, 'token': token, 'version': '861', 'compatibility': '861', } <NEW_LINE> self.kwargs.update(new) <NEW_LINE> self.api = trading(**self.kwargs) <NEW_LINE> <DEDENT> def get_item(self, item_id): <NEW_LINE> <INDENT> data = {'DetailLevel': 'ItemReturnAttributes', 'ItemID': item_id} <NEW_LINE> return self.execute('GetItem', data) <NEW_LINE> <DEDENT> def get_categories(self): <NEW_LINE> <INDENT> data = {'DetailLevel': 'ReturnAll', 'LevelLimit': 1} <NEW_LINE> response = self.execute('GetCategories', data) <NEW_LINE> return Andand(response) <NEW_LINE> <DEDENT> def get_hierarchy(self, category_id, **kwargs): <NEW_LINE> <INDENT> data = { 'CategoryParent': category_id, 'DetailLevel': kwargs.get('detail_level', 'ReturnAll'), } <NEW_LINE> response = self.execute('GetCategories', data) <NEW_LINE> return Andand(response) <NEW_LINE> <DEDENT> def parse(self, response): <NEW_LINE> <INDENT> if response and hasattr(response, 'update'): <NEW_LINE> <INDENT> response = [response] <NEW_LINE> <DEDENT> return [ { 'id': r['CategoryID'], 'category': r['CategoryName'], 'level': r['CategoryLevel'], 'parent_id': r['CategoryParentID'], 'country': self.kwargs['country'], } for r in response] <NEW_LINE> <DEDENT> def make_lookup(self, results): <NEW_LINE> <INDENT> return {r['category'].lower(): r for r in results} | An Ebay Trading API object | 62598fafaad79263cf42e7f8 |
class Command(BaseCommand): <NEW_LINE> <INDENT> def add_arguments(self, parser): <NEW_LINE> <INDENT> parser.add_argument( '--path', action='store', dest='path', required=True, help='Import files located in the path into django-filer' ) <NEW_LINE> parser.add_argument( '--folder', action='store', dest='base_folder', default=False, help='Specify the destination folder in which the directory structure should be imported' ) <NEW_LINE> <DEDENT> def handle(self, *args, **options): <NEW_LINE> <INDENT> file_importer = FileImporter(**options) <NEW_LINE> file_importer.walker() | Import directory structure into the filer ::
manage.py --path=/tmp/assets/images
manage.py --path=/tmp/assets/news --folder=images | 62598faf4428ac0f6e65854a |
class AccountInvoice(models.Model): <NEW_LINE> <INDENT> _inherit = 'account.invoice' <NEW_LINE> credit_policy_id = fields.Many2one( 'credit.control.policy', string='Credit Control Policy', help="The Credit Control Policy used for this " "invoice. If nothing is defined, it will " "use the account setting or the partner " "setting.", readonly=True, copy=False, groups="account_credit_control.group_account_credit_control_manager," "account_credit_control.group_account_credit_control_user," "account_credit_control.group_account_credit_control_info", ) <NEW_LINE> credit_control_line_ids = fields.One2many( 'credit.control.line', 'invoice_id', string='Credit Lines', readonly=True, copy=False, ) <NEW_LINE> @api.multi <NEW_LINE> def action_cancel(self): <NEW_LINE> <INDENT> cc_line_obj = self.env['credit.control.line'] <NEW_LINE> for invoice in self: <NEW_LINE> <INDENT> nondraft_domain = [('invoice_id', '=', invoice.id), ('state', '!=', 'draft')] <NEW_LINE> cc_nondraft_lines = cc_line_obj.search(nondraft_domain) <NEW_LINE> if cc_nondraft_lines: <NEW_LINE> <INDENT> raise UserError( _('You cannot cancel this invoice.\n' 'A payment reminder has already been ' 'sent to the customer.\n' 'You must create a credit note and ' 'issue a new invoice.') ) <NEW_LINE> <DEDENT> draft_domain = [('invoice_id', '=', invoice.id), ('state', '=', 'draft')] <NEW_LINE> cc_draft_line = cc_line_obj.search(draft_domain) <NEW_LINE> cc_draft_line.unlink() <NEW_LINE> <DEDENT> return super(AccountInvoice, self).action_cancel() | Check on cancelling of an invoice | 62598faf7b180e01f3e49062 |
class CustomDispatcher(Dispatcher): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(CustomDispatcher, self).__init__(["SMALL", "BIG"]) <NEW_LINE> <DEDENT> def dispatch(self, image, polygon): <NEW_LINE> <INDENT> return "BIG" if polygon.area > 1000 else "SMALL" | Dispatch 'BIG' if area is larger 1000, otherwise 'SMALL' | 62598faf460517430c432070 |
class MutableDefaultArgumentValues(object): <NEW_LINE> <INDENT> name = 'mutabledefaults' <NEW_LINE> version = '1.0.0' <NEW_LINE> def __init__(self, tree, filename): <NEW_LINE> <INDENT> self.tree = tree <NEW_LINE> self.filename = filename <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def add_options(cls, parser): <NEW_LINE> <INDENT> parser.add_option('--allow-type', action='append', type='string', dest='allowed_types') <NEW_LINE> parser.config_options.append('allowed-types') <NEW_LINE> <DEDENT> @classmethod <NEW_LINE> def parse_options(cls, options): <NEW_LINE> <INDENT> cls.allowed_types = options.allowed_types if options.allowed_types else [] <NEW_LINE> <DEDENT> def run(self): <NEW_LINE> <INDENT> for node in ast.walk(self.tree): <NEW_LINE> <INDENT> if isinstance(node, ast.FunctionDef): <NEW_LINE> <INDENT> for default in node.args.defaults: <NEW_LINE> <INDENT> if isinstance(default, ast.Dict) or isinstance(default, ast.List): <NEW_LINE> <INDENT> yield ( default.lineno, default.col_offset, 'FS10 Mutable type as default argument: %s' % type(default).__name__, type(self) ) <NEW_LINE> continue <NEW_LINE> <DEDENT> elif (isinstance(default, ast.Name) or isinstance(default, ast.Num) or isinstance(default, ast.Str) or isinstance(default, ast.Tuple)): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif (isinstance(default, ast.BinOp) or isinstance(default, ast.Attribute)): <NEW_LINE> <INDENT> continue <NEW_LINE> <DEDENT> elif isinstance(default, ast.Call): <NEW_LINE> <INDENT> if default.func.id == 'set': <NEW_LINE> <INDENT> yield ( default.lineno, default.col_offset, 'FS10 Mutable type as default argument: %s' % 'Set', type(self) ) <NEW_LINE> continue <NEW_LINE> <DEDENT> <DEDENT> if type(default).__name__ not in self.allowed_types: <NEW_LINE> <INDENT> yield ( default.lineno, default.col_offset, 'FS11 Unrecognized type as default argument: %s' % type(default).__name__, type(self) ) | It's 100% perfect, but it will catch the most common cases of using a mutable type as a
default argument value. | 62598faf16aa5153ce400527 |
class MirrorError(BaseException): <NEW_LINE> <INDENT> pass | Raised if the distance from child A to child B is not the same as the
distance from child B to child A. | 62598faf38b623060ffa90c0 |
class WindfieldMap(FilledContourMapFigure): <NEW_LINE> <INDENT> def plot(self, data, xgrid, ygrid, title, lvls, cbarlab, map_kwargs): <NEW_LINE> <INDENT> self.add(data, xgrid, ygrid, title, lvls, cbarlab, map_kwargs) <NEW_LINE> self.cmap = sns.light_palette("orange", as_cmap=True) <NEW_LINE> super(WindfieldMap, self).plot() | Plot a wind field using filled contours. Only presents the magnitude of
the wind field, not the direction. | 62598fafbaa26c4b54d4f2d9 |
class MoleculeDepictor(Resource): <NEW_LINE> <INDENT> def __init__(self): <NEW_LINE> <INDENT> super(MoleculeDepictor, self).__init__() <NEW_LINE> <DEDENT> def get(self, fmt): <NEW_LINE> <INDENT> args = depictor_arg_parser.parse_args() <NEW_LINE> try: <NEW_LINE> <INDENT> mol = read_molecule_from_string(args['val'], fmt, bool(args['gz']), bool(args['reparse'])) <NEW_LINE> return self.__render_image(mol, args) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> if args['debug']: <NEW_LINE> <INDENT> return Response(json.dumps({"error": str(ex)}), status=400, mimetype='application/json') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return render_error_image(args['width'], args['height'], str(ex)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def post(self, fmt): <NEW_LINE> <INDENT> args = depictor_arg_parser.parse_args() <NEW_LINE> try: <NEW_LINE> <INDENT> mol = read_molecule_from_string(request.data.decode("utf-8"), fmt, bool(args['gz']), bool(args['reparse'])) <NEW_LINE> return self.__render_image(mol, args) <NEW_LINE> <DEDENT> except Exception as ex: <NEW_LINE> <INDENT> if args['debug']: <NEW_LINE> <INDENT> return Response(json.dumps({"error": str(ex)}), status=400, mimetype='application/json') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> return render_error_image(args['width'], args['height'], str(ex)) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def __render_image(self, mol, args): <NEW_LINE> <INDENT> width = args['width'] <NEW_LINE> height = args['height'] <NEW_LINE> title = args['title'] <NEW_LINE> use_molecule_title = bool(args['keeptitle']) <NEW_LINE> bond_scaling = bool(args['scalebonds']) <NEW_LINE> image_format = args['format'] <NEW_LINE> image_mimetype = get_image_mime_type(image_format) <NEW_LINE> highlight_style = get_highlight_style(args['highlightstyle']) <NEW_LINE> title_location = get_title_location(args['titleloc']) <NEW_LINE> highlight = args['highlight'] <NEW_LINE> background = get_color_from_rgba(args['background']) <NEW_LINE> color = get_color_from_rgba(args['highlightcolor']) <NEW_LINE> if not image_mimetype: <NEW_LINE> <INDENT> raise Exception("Invalid MIME type") <NEW_LINE> <DEDENT> if not highlight_style: <NEW_LINE> <INDENT> highlight_style = OEHighlightStyle_Default <NEW_LINE> <DEDENT> if not title_location: <NEW_LINE> <INDENT> title_location = OETitleLocation_Top <NEW_LINE> <DEDENT> image = OEImage(width, height) <NEW_LINE> OEPrepareDepiction(mol, False, True) <NEW_LINE> opts = OE2DMolDisplayOptions(image.GetWidth(), image.GetHeight(), OEScale_AutoScale) <NEW_LINE> if title: <NEW_LINE> <INDENT> mol.SetTitle(title) <NEW_LINE> opts.SetTitleLocation(title_location) <NEW_LINE> <DEDENT> elif not use_molecule_title: <NEW_LINE> <INDENT> mol.SetTitle("") <NEW_LINE> opts.SetTitleLocation(OETitleLocation_Hidden) <NEW_LINE> <DEDENT> opts.SetBondWidthScaling(bond_scaling) <NEW_LINE> opts.SetBackgroundColor(background) <NEW_LINE> disp = OE2DMolDisplay(mol, opts) <NEW_LINE> if highlight: <NEW_LINE> <INDENT> for querySmiles in highlight: <NEW_LINE> <INDENT> subs = OESubSearch(querySmiles) <NEW_LINE> for match in subs.Match(mol, True): <NEW_LINE> <INDENT> OEAddHighlighting(disp, color, highlight_style, match) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> OERenderMolecule(image, disp) <NEW_LINE> img_content = OEWriteImageToString(image_format, image) <NEW_LINE> return Response(img_content, mimetype=image_mimetype) | Render a small molecule in 2D | 62598faf4428ac0f6e65854b |
class Logging(object): <NEW_LINE> <INDENT> COLORS = { LOG_ERROR: "red", LOG_WARN: "yellow", LOG_INFO: "blue", LOG_DEBUG: "green", LOG_CACHE: "cyan", LOG_DATA: "magenta", } <NEW_LINE> MAPPING = { 0: LOG_WARN, 1: LOG_INFO, 2: LOG_DEBUG, 3: LOG_CACHE, 4: LOG_DATA, 5: LOG_ALL, } <NEW_LINE> LEVELS = "CRITICAL DEBUG ERROR FATAL INFO NOTSET WARN WARNING".split() <NEW_LINE> _level = LOG_WARN <NEW_LINE> _loggers = dict() <NEW_LINE> def __init__(self, name='did'): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> self.logger = Logging._loggers[name] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> self.logger = self._create_logger(name=name) <NEW_LINE> Logging._loggers[name] = self.logger <NEW_LINE> self.set() <NEW_LINE> <DEDENT> <DEDENT> class ColoredFormatter(logging.Formatter): <NEW_LINE> <INDENT> def format(self, record): <NEW_LINE> <INDENT> if record.levelno == LOG_ALL: <NEW_LINE> <INDENT> levelname = "ALL" <NEW_LINE> <DEDENT> elif record.levelno == LOG_DATA: <NEW_LINE> <INDENT> levelname = "DATA" <NEW_LINE> <DEDENT> elif record.levelno == LOG_CACHE: <NEW_LINE> <INDENT> levelname = "CACHE" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> levelname = record.levelname <NEW_LINE> <DEDENT> try: <NEW_LINE> <INDENT> colour = Logging.COLORS[record.levelno] <NEW_LINE> <DEDENT> except KeyError: <NEW_LINE> <INDENT> colour = "black" <NEW_LINE> <DEDENT> if Coloring().enabled(): <NEW_LINE> <INDENT> level = color(" " + levelname + " ", "lightwhite", colour) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> level = "[{0}]".format(levelname) <NEW_LINE> <DEDENT> return u"{0} {1}".format(level, record.getMessage()) <NEW_LINE> <DEDENT> <DEDENT> @staticmethod <NEW_LINE> def _create_logger(name='did', level=None): <NEW_LINE> <INDENT> logger = logging.getLogger(name) <NEW_LINE> handler = logging.StreamHandler() <NEW_LINE> handler.setFormatter(Logging.ColoredFormatter()) <NEW_LINE> logger.addHandler(handler) <NEW_LINE> for level in Logging.LEVELS: <NEW_LINE> <INDENT> setattr(logger, level, getattr(logging, level)) <NEW_LINE> <DEDENT> logger.DATA = LOG_DATA <NEW_LINE> logger.CACHE = LOG_CACHE <NEW_LINE> logger.ALL = LOG_ALL <NEW_LINE> logger.cache = lambda message: logger.log(LOG_CACHE, message) <NEW_LINE> logger.data = lambda message: logger.log(LOG_DATA, message) <NEW_LINE> logger.all = lambda message: logger.log(LOG_ALL, message) <NEW_LINE> return logger <NEW_LINE> <DEDENT> def set(self, level=None): <NEW_LINE> <INDENT> if level is not None: <NEW_LINE> <INDENT> Logging._level = level <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> Logging._level = Logging.MAPPING[int(os.environ["DEBUG"])] <NEW_LINE> <DEDENT> except StandardError: <NEW_LINE> <INDENT> Logging._level = logging.WARN <NEW_LINE> <DEDENT> <DEDENT> self.logger.setLevel(Logging._level) <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> return self.logger.level | Logging Configuration | 62598faf30bbd7224646998b |
class LinearGradientBrush(AbstractGradientBrush): <NEW_LINE> <INDENT> def __init__(self, x1, y1, x2, y2, stops, spreadMethod="pad", transforms=None, units="userSpaceOnUse"): <NEW_LINE> <INDENT> self.x1 = x1 <NEW_LINE> self.y1 = y1 <NEW_LINE> self.x2 = x2 <NEW_LINE> self.y2 = y2 <NEW_LINE> self.stops = stops <NEW_LINE> self.spreadMethod = spreadMethod <NEW_LINE> if transforms is None: <NEW_LINE> <INDENT> transforms = [] <NEW_LINE> <DEDENT> self.transforms = transforms <NEW_LINE> self.units = units <NEW_LINE> <DEDENT> def __repr__(self): <NEW_LINE> <INDENT> return ( "LinearGradientBrush(%r,%r, %r,%r, %r, spreadMethod=%r, " "transforms=%r, units=%r)" % ( self.x1, self.y1, self.x2, self.y2, self.stops, self.spreadMethod, self.transforms, self.units, ) ) <NEW_LINE> <DEDENT> def set_on_gc(self, gc, bbox=None): <NEW_LINE> <INDENT> if self.transforms is not None: <NEW_LINE> <INDENT> for func, f_args in self.transforms: <NEW_LINE> <INDENT> if isinstance(f_args, tuple): <NEW_LINE> <INDENT> func(gc, *f_args) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> func(gc, f_args) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> x1 = self.x1 <NEW_LINE> x2 = self.x2 <NEW_LINE> y1 = self.y1 <NEW_LINE> y2 = self.y2 <NEW_LINE> if sys.platform == "darwin": <NEW_LINE> <INDENT> if self.spreadMethod != "pad": <NEW_LINE> <INDENT> warnings.warn( "spreadMethod %r is not supported. Using 'pad'" % self.spreadMethod ) <NEW_LINE> <DEDENT> if bbox is not None: <NEW_LINE> <INDENT> gc.clip_to_rect(*bbox) <NEW_LINE> <DEDENT> <DEDENT> else: <NEW_LINE> <INDENT> if self.units == "objectBoundingBox" and bbox is not None: <NEW_LINE> <INDENT> x1 = (bbox[2] + bbox[0]) * x1 <NEW_LINE> y1 = (bbox[3] + bbox[1]) * y1 <NEW_LINE> x2 = (bbox[2] + bbox[0]) * x2 <NEW_LINE> y2 = (bbox[3] + bbox[1]) * y2 <NEW_LINE> self.bbox_transform(gc, bbox) <NEW_LINE> <DEDENT> <DEDENT> stops = np.transpose(self.stops) <NEW_LINE> gc.linear_gradient( x1, y1, x2, y2, stops, self.spreadMethod, self.units ) | A Brush representing a linear gradient.
| 62598fafcc40096d6161a1ec |
class MultiSubjectSlot(SlotManager, SubjectSlot): <NEW_LINE> <INDENT> def __init__(self, subject = None, listener = None, event = None, extra_kws = None, extra_args = None, *a, **k): <NEW_LINE> <INDENT> self._original_listener = listener <NEW_LINE> self._slot_subject = None <NEW_LINE> self._nested_slot = None <NEW_LINE> super(MultiSubjectSlot, self).__init__(event=event[0], listener=self._event_fired, subject=subject, extra_kws=extra_kws, extra_args=extra_args) <NEW_LINE> if len(event) > 1: <NEW_LINE> <INDENT> self._nested_slot = self.register_disconnectable(MultiSubjectSlot(event=event[1:], listener=listener, subject=subject, extra_kws=extra_kws, extra_args=extra_args)) <NEW_LINE> self._update_nested_subject() <NEW_LINE> <DEDENT> <DEDENT> def _get_subject(self): <NEW_LINE> <INDENT> return super(MultiSubjectSlot, self)._get_subject() <NEW_LINE> <DEDENT> def _set_subject(self, subject): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> super(MultiSubjectSlot, self)._set_subject(subject) <NEW_LINE> <DEDENT> except SubjectSlotError: <NEW_LINE> <INDENT> if self._nested_slot == None: <NEW_LINE> <INDENT> raise <NEW_LINE> <DEDENT> <DEDENT> finally: <NEW_LINE> <INDENT> self._slot_subject = subject <NEW_LINE> self._update_nested_subject() <NEW_LINE> <DEDENT> <DEDENT> subject = property(_get_subject, _set_subject) <NEW_LINE> def _event_fired(self, *a, **k): <NEW_LINE> <INDENT> self._update_nested_subject() <NEW_LINE> self._original_listener(*a, **k) <NEW_LINE> <DEDENT> def _update_nested_subject(self): <NEW_LINE> <INDENT> if self._nested_slot != None: <NEW_LINE> <INDENT> self._nested_slot.subject = getattr(self._slot_subject, self._event) if self._slot_subject != None else None | A subject slot that takes a string describing the path to the event to listen to.
It will make sure that any changes to the elements of this path notify the given
listener and will follow the changing subjects. | 62598faf56b00c62f0fb28db |
class SerializeToJsonError(Error): <NEW_LINE> <INDENT> pass | Thrown if serialization to JSON fails. | 62598faff548e778e596b5ca |
class Primes: <NEW_LINE> <INDENT> __cached_primes = [2, 3] <NEW_LINE> __cached_until = 3 <NEW_LINE> def __init__(self, maximum=0): <NEW_LINE> <INDENT> self.max = maximum <NEW_LINE> if maximum > Primes.__cached_until: <NEW_LINE> <INDENT> Primes.__build_cache(maximum) <NEW_LINE> <DEDENT> <DEDENT> def __iter__(self): <NEW_LINE> <INDENT> self.index = -1 <NEW_LINE> return self <NEW_LINE> <DEDENT> def __next__(self): <NEW_LINE> <INDENT> self.index += 1 <NEW_LINE> if self.index >= len(Primes.__cached_primes): <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> if Primes.__cached_primes[self.index] > self.max: <NEW_LINE> <INDENT> raise StopIteration <NEW_LINE> <DEDENT> return Primes.__cached_primes[self.index] <NEW_LINE> <DEDENT> def __getitem__(self, index): <NEW_LINE> <INDENT> return Primes.prime_at(index) <NEW_LINE> <DEDENT> def __contains__(self, n): <NEW_LINE> <INDENT> return Primes.is_prime(Primes.is_prime(n)) <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def isqrt(n): <NEW_LINE> <INDENT> x = n <NEW_LINE> y = (2 ** ((n.bit_length() + 1) // 2)) - 1 <NEW_LINE> while y < x: <NEW_LINE> <INDENT> x = y <NEW_LINE> y = (x + n // x) // 2 <NEW_LINE> <DEDENT> return x <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_perfect_square(n): <NEW_LINE> <INDENT> sqrt = Primes.isqrt(n) <NEW_LINE> return n == sqrt * sqrt <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def prime_at(index): <NEW_LINE> <INDENT> if index >= len(Primes.__cached_primes): <NEW_LINE> <INDENT> Primes.__cache_next(1 + index - len(Primes.__cached_primes)) <NEW_LINE> <DEDENT> return Primes.__cached_primes[index] <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def is_prime(n): <NEW_LINE> <INDENT> until = Primes.isqrt(n) + 1 <NEW_LINE> if n > Primes.__cached_until: <NEW_LINE> <INDENT> Primes.__build_cache(until) <NEW_LINE> <DEDENT> for prime in Primes.__cached_primes: <NEW_LINE> <INDENT> if n % prime == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> if prime > until: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __is_prime(n): <NEW_LINE> <INDENT> start_from = Primes.__cached_primes[-1] + 2 <NEW_LINE> until = int(n**0.5) + 1 <NEW_LINE> for prime in Primes.__cached_primes: <NEW_LINE> <INDENT> if prime > until: <NEW_LINE> <INDENT> break <NEW_LINE> <DEDENT> if n % prime == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> for i in range(start_from, until, 2): <NEW_LINE> <INDENT> if n % i == 0: <NEW_LINE> <INDENT> return False <NEW_LINE> <DEDENT> <DEDENT> return True <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __build_cache(until): <NEW_LINE> <INDENT> start_from = Primes.__cached_primes[-1] + 2 <NEW_LINE> for i in range(start_from, until + 1, 2): <NEW_LINE> <INDENT> if Primes.__is_prime(i): <NEW_LINE> <INDENT> Primes.__cached_primes.append(i) <NEW_LINE> <DEDENT> <DEDENT> Primes.__cached_until = until <NEW_LINE> <DEDENT> @staticmethod <NEW_LINE> def __cache_next(n): <NEW_LINE> <INDENT> i = Primes.__cached_primes[-1] <NEW_LINE> while n > 0: <NEW_LINE> <INDENT> i += 2 <NEW_LINE> if Primes.__is_prime(i): <NEW_LINE> <INDENT> Primes.__cached_primes.append(i) <NEW_LINE> Primes.__cached_until = i <NEW_LINE> n -= 1 | Iterator that yields prime numbers using a cache system.
To initialize the static cache, call the constructor with a maximum prime | 62598faf3346ee7daa33765a |
class EncryptionVersionType(with_metaclass(_CaseInsensitiveEnumMeta, str, Enum)): <NEW_LINE> <INDENT> FIXED = "Fixed" <NEW_LINE> AUTO_DETECTED = "AutoDetected" | Property of the key if user provided or auto detected
| 62598faf10dbd63aa1c70bd9 |
class Provider(object): <NEW_LINE> <INDENT> PROTO_TCP = 'TCP' <NEW_LINE> PROTO_UDP = 'UDP' <NEW_LINE> def __init__(self, service, domain, protocol=None, refresh_delta=None): <NEW_LINE> <INDENT> self._service = service <NEW_LINE> self._domain = domain <NEW_LINE> self._protocol = self.PROTO_UDP if protocol is None else protocol <NEW_LINE> self._refresh_delta = (timedelta(minutes=1) if refresh_delta is None else refresh_delta) <NEW_LINE> self._last_refresh_at = datetime.fromtimestamp(0) <NEW_LINE> self._addr = None <NEW_LINE> <DEDENT> def _refresh_addr(self): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> srvs = srvlookup.lookup(self._service, self._protocol, self._domain) <NEW_LINE> <DEDENT> except srvlookup.SRVQueryFailure: <NEW_LINE> <INDENT> logger.debug('SRV query failed') <NEW_LINE> return <NEW_LINE> <DEDENT> assert len(srvs) > 0 <NEW_LINE> srv = srvs[0] <NEW_LINE> self._addr = (srv.host, srv.port) <NEW_LINE> self._last_refresh_at = datetime.now() <NEW_LINE> <DEDENT> def get(self): <NEW_LINE> <INDENT> if (datetime.now() - self._last_refresh_at) > self._refresh_delta: <NEW_LINE> <INDENT> self._refresh_addr() <NEW_LINE> <DEDENT> return self._addr | socket.AF_INET addresses provider based on SRV records
https://en.wikipedia.org/wiki/SRV_record | 62598faf283ffb24f3cf38b2 |
class Step(object): <NEW_LINE> <INDENT> def __init__(self, step_kind, step_name, additional_properties=None): <NEW_LINE> <INDENT> self.step_kind = step_kind <NEW_LINE> self.step_name = step_name <NEW_LINE> self.proto = dataflow.Step(kind=step_kind, name=step_name) <NEW_LINE> self.proto.properties = {} <NEW_LINE> self._additional_properties = [] <NEW_LINE> if additional_properties is not None: <NEW_LINE> <INDENT> for (n, v, t) in additional_properties: <NEW_LINE> <INDENT> self.add_property(n, v, t) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> def add_property(self, name, value, with_type=False): <NEW_LINE> <INDENT> self._additional_properties.append((name, value, with_type)) <NEW_LINE> self.proto.properties.additionalProperties.append( dataflow.Step.PropertiesValue.AdditionalProperty( key=name, value=to_json_value(value, with_type=with_type))) <NEW_LINE> <DEDENT> def _get_outputs(self): <NEW_LINE> <INDENT> outputs = [] <NEW_LINE> for p in self.proto.properties.additionalProperties: <NEW_LINE> <INDENT> if p.key == PropertyNames.OUTPUT_INFO: <NEW_LINE> <INDENT> for entry in p.value.array_value.entries: <NEW_LINE> <INDENT> for entry_prop in entry.object_value.properties: <NEW_LINE> <INDENT> if entry_prop.key == PropertyNames.OUTPUT_NAME: <NEW_LINE> <INDENT> outputs.append(entry_prop.value.string_value) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> <DEDENT> <DEDENT> return outputs <NEW_LINE> <DEDENT> def __reduce__(self): <NEW_LINE> <INDENT> return (Step, (self.step_kind, self.step_name, self._additional_properties)) <NEW_LINE> <DEDENT> def get_output(self, tag=None): <NEW_LINE> <INDENT> outputs = self._get_outputs() <NEW_LINE> if tag is None: <NEW_LINE> <INDENT> return outputs[0] <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> name = '%s_%s' % (PropertyNames.OUT, tag) <NEW_LINE> if name not in outputs: <NEW_LINE> <INDENT> raise ValueError( 'Cannot find named output: %s in %s.' % (name, outputs)) <NEW_LINE> <DEDENT> return name | Wrapper for a dataflow Step protobuf. | 62598faf4a966d76dd5eeefd |
class StatusResource(BaseResource): <NEW_LINE> <INDENT> @policy.ApiEnforcer(policy.GET_SITE_STATUSES) <NEW_LINE> def on_get(self, req, resp, **kwargs): <NEW_LINE> <INDENT> status_filters = req.get_param(name='filters') or None <NEW_LINE> if status_filters: <NEW_LINE> <INDENT> fltrs = status_filters.split(',') <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> fltrs = None <NEW_LINE> <DEDENT> helper = StatusHelper(req.context) <NEW_LINE> resp.body = self.to_json(helper.get_site_statuses(fltrs)) <NEW_LINE> resp.status = falcon.HTTP_200 | The status resource handles the retrieval of Drydock provisioning
node status and power state | 62598faf1b99ca400228f543 |
class sale_order_line(osv.osv): <NEW_LINE> <INDENT> _inherit = 'sale.order.line' <NEW_LINE> def _weight_net(self, cr, uid, ids, field_name, arg, context): <NEW_LINE> <INDENT> result = {} <NEW_LINE> for line in self.browse(cr, uid, ids, context=context): <NEW_LINE> <INDENT> result[line.id] = 0.0 <NEW_LINE> if line.product_id: <NEW_LINE> <INDENT> if line.product_id.weight_net: <NEW_LINE> <INDENT> result[line.id] += (line.product_id.weight_net * line.product_uom_qty / line.product_uom.factor) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> result[line.id] += (line.th_weight * line.product_uom_qty / line.product_uom.factor) <NEW_LINE> <DEDENT> <DEDENT> <DEDENT> return result <NEW_LINE> <DEDENT> _columns = { 'weight_net': fields.function(_weight_net, method=True, readonly=True, string='Net Weight', help="The net weight", store={ 'sale.order.line': (lambda self, cr, uid, ids, c={}: ids, ['product_uom_qty', 'product_id'], -11), }, ), } | Add the net weight to the object "Sale Order Line". | 62598faf66656f66f7d5a416 |
class Restaurant(): <NEW_LINE> <INDENT> def __init__(self, restaurant_name, cuisine_type): <NEW_LINE> <INDENT> self.restaurant_name = restaurant_name <NEW_LINE> self.cuisine_type = cuisine_type <NEW_LINE> <DEDENT> def describe_restaurant(self): <NEW_LINE> <INDENT> string1 = f"Welcome to {self.restaurant_name} serving the best" <NEW_LINE> string2 = f" {self.cuisine_type} in town!" <NEW_LINE> return string1 + string2 <NEW_LINE> <DEDENT> def open_restaurant(self): <NEW_LINE> <INDENT> print(f"{self.restaurant_name} is now open.") | Class Used to Represent a Restaurant | 62598faf442bda511e95c47e |
class BowtieIndex(Html): <NEW_LINE> <INDENT> MetadataElement(name="base_name", desc="base name for this index set", default='galaxy_generated_bowtie_index', set_in_upload=True, readonly=True) <NEW_LINE> MetadataElement(name="sequence_space", desc="sequence_space for this index set", default='unknown', set_in_upload=True, readonly=True) <NEW_LINE> composite_type = 'auto_primary_file' <NEW_LINE> def generate_primary_file(self, dataset=None): <NEW_LINE> <INDENT> return '<html><head></head><body>AutoGenerated Primary File for Composite Dataset</body></html>' <NEW_LINE> <DEDENT> def regenerate_primary_file(self, dataset): <NEW_LINE> <INDENT> bn = dataset.metadata.base_name <NEW_LINE> flist = os.listdir(dataset.extra_files_path) <NEW_LINE> rval = [f'<html><head><title>Files for Composite Dataset {bn}</title></head><p/>Comprises the following files:<p/><ul>'] <NEW_LINE> for fname in flist: <NEW_LINE> <INDENT> sfname = os.path.split(fname)[-1] <NEW_LINE> rval.append(f'<li><a href="{sfname}">{sfname}</a>') <NEW_LINE> <DEDENT> rval.append('</ul></html>') <NEW_LINE> with open(dataset.file_name, 'w') as f: <NEW_LINE> <INDENT> f.write("\n".join(rval)) <NEW_LINE> f.write('\n') <NEW_LINE> <DEDENT> <DEDENT> def set_peek(self, dataset, is_multi_byte=False): <NEW_LINE> <INDENT> if not dataset.dataset.purged: <NEW_LINE> <INDENT> dataset.peek = f"Bowtie index file ({dataset.metadata.sequence_space})" <NEW_LINE> dataset.blurb = f"{dataset.metadata.sequence_space} space" <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> dataset.peek = 'file does not exist' <NEW_LINE> dataset.blurb = 'file purged from disk' <NEW_LINE> <DEDENT> <DEDENT> def display_peek(self, dataset): <NEW_LINE> <INDENT> try: <NEW_LINE> <INDENT> return dataset.peek <NEW_LINE> <DEDENT> except Exception: <NEW_LINE> <INDENT> return "Bowtie index file" | base class for BowtieIndex
is subclassed by BowtieColorIndex and BowtieBaseIndex | 62598fafac7a0e7691f7252f |
class GpioPhysicalSensor(PhysicalSensor): <NEW_LINE> <INDENT> def __init__(self, broker, gpio_pin=None, **kwargs): <NEW_LINE> <INDENT> super(GpioPhysicalSensor, self).__init__(broker, **kwargs) <NEW_LINE> self._pin = gpio_pin <NEW_LINE> self._GPIO = None <NEW_LINE> <DEDENT> def on_start(self): <NEW_LINE> <INDENT> if self._GPIO is None: <NEW_LINE> <INDENT> import RPi.GPIO as GPIO <NEW_LINE> self._GPIO = GPIO <NEW_LINE> <DEDENT> self._GPIO.setmode(GPIO.BCM) <NEW_LINE> self._GPIO.setup(self._pin, GPIO.IN) <NEW_LINE> super(GpioPhysicalSensor, self).on_start() <NEW_LINE> <DEDENT> def read_raw(self): <NEW_LINE> <INDENT> input_value = self._GPIO.input(self._pin) <NEW_LINE> return input_value | This class is specifically designed for use with GPIO sensors attached to a Raspberry Pi. | 62598fafe5267d203ee6b930 |
class MinimaxPlayer(IsolationPlayer): <NEW_LINE> <INDENT> def get_move(self, game, time_left): <NEW_LINE> <INDENT> self.time_left = time_left <NEW_LINE> best_move = (-1, -1) <NEW_LINE> try: <NEW_LINE> <INDENT> return self.minimax(game, self.search_depth) <NEW_LINE> <DEDENT> except SearchTimeout: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> return best_move <NEW_LINE> <DEDENT> def minimax(self, game, depth): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> def terminal_test(game, depth): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> if depth == 0 or len(game.get_legal_moves()) == 0: <NEW_LINE> <INDENT> return True <NEW_LINE> <DEDENT> return False <NEW_LINE> <DEDENT> def min_value(game, depth): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> if terminal_test(game, depth): <NEW_LINE> <INDENT> return self.score(game, self) <NEW_LINE> <DEDENT> min_value = float('inf') <NEW_LINE> for move in game.get_legal_moves(): <NEW_LINE> <INDENT> min_value = min(min_value, max_value(game.forecast_move(move), depth - 1)) <NEW_LINE> <DEDENT> return min_value <NEW_LINE> <DEDENT> def max_value(game, depth): <NEW_LINE> <INDENT> if self.time_left() < self.TIMER_THRESHOLD: <NEW_LINE> <INDENT> raise SearchTimeout() <NEW_LINE> <DEDENT> if terminal_test(game, depth): <NEW_LINE> <INDENT> return self.score(game, self) <NEW_LINE> <DEDENT> max_value = float('-inf') <NEW_LINE> for move in game.get_legal_moves(): <NEW_LINE> <INDENT> max_value = max(max_value, min_value(game.forecast_move(move), depth - 1)) <NEW_LINE> <DEDENT> return max_value <NEW_LINE> <DEDENT> best_move = (-1, -1) <NEW_LINE> best_score = float('-inf') <NEW_LINE> for move in game.get_legal_moves(): <NEW_LINE> <INDENT> current_score = min_value(game.forecast_move(move), depth - 1) <NEW_LINE> if current_score >= best_score: <NEW_LINE> <INDENT> best_score, best_move = current_score, move <NEW_LINE> <DEDENT> <DEDENT> return best_move | Game-playing agent that chooses a move using depth-limited minimax
search. You must finish and test this player to make sure it properly uses
minimax to return a good move before the search time limit expires. | 62598faf2ae34c7f260ab108 |
class VerticalScrolledFrame(Frame): <NEW_LINE> <INDENT> def __init__(self, parent, bg, *args, **kw): <NEW_LINE> <INDENT> Frame.__init__(self, parent, *args, **kw) <NEW_LINE> vscrollbar = Scrollbar(self, orient=VERTICAL) <NEW_LINE> canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set,bg=bg) <NEW_LINE> vscrollbar.config(command=canvas.yview) <NEW_LINE> canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) <NEW_LINE> canvas.xview_moveto(0) <NEW_LINE> canvas.yview_moveto(0) <NEW_LINE> self.interior = interior = Frame(canvas,bg=bg) <NEW_LINE> interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) <NEW_LINE> a = Frame(self.interior,height=10,bg=dynamicBackground()) <NEW_LINE> a.pack() <NEW_LINE> def canvasscroll(event): <NEW_LINE> <INDENT> canvas.yview('scroll',int(-1*(event.delta/120)), "units") <NEW_LINE> <DEDENT> def _configure_canvas(event): <NEW_LINE> <INDENT> a.configure(height=10) <NEW_LINE> a.update() <NEW_LINE> mylist = interior.winfo_children() <NEW_LINE> for i in mylist: <NEW_LINE> <INDENT> lasty=i.winfo_height()+i.winfo_y() <NEW_LINE> <DEDENT> a.configure(height=lasty+150) <NEW_LINE> if interior.winfo_reqwidth() != canvas.winfo_width(): <NEW_LINE> <INDENT> canvas.itemconfigure(interior_id, width=canvas.winfo_width()) <NEW_LINE> <DEDENT> if canvas.winfo_height()<lasty: <NEW_LINE> <INDENT> vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) <NEW_LINE> canvas.config(scrollregion=(0,0,0,lasty)) <NEW_LINE> canvas.bind_all("<MouseWheel>", canvasscroll) <NEW_LINE> <DEDENT> else: <NEW_LINE> <INDENT> canvas.unbind_all("<MouseWheel>") <NEW_LINE> try: <NEW_LINE> <INDENT> vscrollbar.pack_forget() <NEW_LINE> <DEDENT> except: <NEW_LINE> <INDENT> pass <NEW_LINE> <DEDENT> canvas.config(scrollregion=(0,0,0,0)) <NEW_LINE> <DEDENT> <DEDENT> canvas.bind('<Configure>', _configure_canvas) | A pure Tkinter scrollable frame that actually works!
* Use the 'interior' attribute to place widgets inside the scrollable frame
* Construct and pack/place/grid normally
* This frame only allows vertical scrolling | 62598faf99cbb53fe6830eff |
class SchemaDoesNotExist(WWModeException): <NEW_LINE> <INDENT> pass | Exception to be raised when file with schema does not found | 62598faf7047854f4633f401 |
class Task(): <NEW_LINE> <INDENT> def __init__(self, init_pose=None, init_velocities=None, init_angle_velocities=None, runtime=5., target_pos=None): <NEW_LINE> <INDENT> self.sim = PhysicsSim(init_pose, init_velocities, init_angle_velocities, runtime) <NEW_LINE> self.action_repeat = 3 <NEW_LINE> self.state_size = self.action_repeat * 6 <NEW_LINE> self.action_low = 0 <NEW_LINE> self.action_high = 900 <NEW_LINE> self.action_size = 4 <NEW_LINE> self.target_pos = target_pos if target_pos is not None else np.array([0., 0., 10.]) <NEW_LINE> try: <NEW_LINE> <INDENT> self.norm=[1.0 if (target_pos[i] - init_pose[i]) == 0 else np.linalg.norm([init_pose[i], target_pos[i]]) for i in range(3)] <NEW_LINE> self.norm_target = self.target_pos / self.norm <NEW_LINE> <DEDENT> except TypeError: <NEW_LINE> <INDENT> self.norm = [1.0, 1.0, 1.0] <NEW_LINE> <DEDENT> <DEDENT> def get_reward(self): <NEW_LINE> <INDENT> reward = 1.-.3*(abs(self.sim.pose[:3] - self.target_pos)).sum() <NEW_LINE> return reward <NEW_LINE> <DEDENT> def get_reward_2(self): <NEW_LINE> <INDENT> def dist_reward(xyz): <NEW_LINE> <INDENT> normalized = xyz / self.norm <NEW_LINE> diff = abs(normalized - self.norm_target) <NEW_LINE> if (diff < 0.03).all(): <NEW_LINE> <INDENT> return 1.0 <NEW_LINE> <DEDENT> av_diff = sum(diff) / 3.0 <NEW_LINE> return max(1 - av_diff**0.4, -1.0) <NEW_LINE> <DEDENT> def velocity_reward_exp(zv): <NEW_LINE> <INDENT> return 0.01 * np.exp(zv) <NEW_LINE> <DEDENT> if self.sim.pose[2] < 0: <NEW_LINE> <INDENT> return -1.0 <NEW_LINE> <DEDENT> reward = dist_reward(self.sim.pose[:3]) <NEW_LINE> if self.sim.v[2] > 0: <NEW_LINE> <INDENT> reward += velocity_reward_exp(self.sim.v[2]) <NEW_LINE> <DEDENT> if self.sim.v[2] < 0: <NEW_LINE> <INDENT> reward -= 0.1 <NEW_LINE> <DEDENT> return min(reward, 1.0) <NEW_LINE> <DEDENT> def step(self, rotor_speeds, opt=False): <NEW_LINE> <INDENT> reward = 0 <NEW_LINE> pose_all = [] <NEW_LINE> for _ in range(self.action_repeat): <NEW_LINE> <INDENT> done = self.sim.next_timestep(rotor_speeds) <NEW_LINE> reward += self.get_reward() if not opt else self.get_reward_2() <NEW_LINE> pose_all.append(self.sim.pose) <NEW_LINE> <DEDENT> next_state = np.concatenate(pose_all) <NEW_LINE> return next_state, reward, done <NEW_LINE> <DEDENT> def reset(self): <NEW_LINE> <INDENT> self.sim.reset() <NEW_LINE> state = np.concatenate([self.sim.pose] * self.action_repeat) <NEW_LINE> return state | Task (environment) that defines the goal and provides feedback to the agent. | 62598faf01c39578d7f12da6 |
class UserLoginForm(forms.Form): <NEW_LINE> <INDENT> username = forms.CharField(label='Usuario') <NEW_LINE> password = forms.CharField(label='Contraseña', widget=forms.PasswordInput) | Used by the user to enter login credentials | 62598faf16aa5153ce400529 |
class ProcessMonitoredQueue(MonitoredQueueBase, ProcessProxy): <NEW_LINE> <INDENT> pass | Run zmq.monitored_queue in a background thread.
See MonitoredQueue and Proxy for details. | 62598faffff4ab517ebcd80c |
class TestCache(unittest.TestCase): <NEW_LINE> <INDENT> def setUp(self): <NEW_LINE> <INDENT> self.mock_logger = MagicMock() <NEW_LINE> self.mock_resolver = MagicMock() <NEW_LINE> self.mock_cache = MagicMock() <NEW_LINE> patch("se_dns.dnsutil.logging.getLogger", return_value=self.mock_logger).start() <NEW_LINE> patch("se_dns.dnsutil.dns.resolver.Resolver", return_value=self.mock_resolver).start() <NEW_LINE> patch("se_dns.dnsutil.dns.resolver.Cache", return_value=self.mock_cache).start() <NEW_LINE> self.mock_rdtype = patch("se_dns.dnsutil.dns.rdatatype.from_text").start() <NEW_LINE> self.mock_rdclass = patch("se_dns.dnsutil.dns.rdataclass.from_text").start() <NEW_LINE> <DEDENT> def tearDown(self): <NEW_LINE> <INDENT> patch.stopall() <NEW_LINE> <DEDENT> def test_init(self): <NEW_LINE> <INDENT> tested_obj = dnsutil.Cache("dnsserver") <NEW_LINE> self.assertEqual(tested_obj.queryObj.nameservers, ["dnsserver"]) <NEW_LINE> self.assertEqual(tested_obj.queryObj.lifetime, 10) <NEW_LINE> self.mock_logger.warn.assert_not_called() <NEW_LINE> <DEDENT> def test_lookup_use_cache(self): <NEW_LINE> <INDENT> reply = MagicMock() <NEW_LINE> items = [MagicMock(to_text=lambda: 1)] <NEW_LINE> reply.response.answer = [ MagicMock(to_rdataset=lambda: MagicMock(items=items)) ] <NEW_LINE> self.mock_cache.get.return_value = reply <NEW_LINE> tested_obj = dnsutil.Cache("dnsserver") <NEW_LINE> result = tested_obj.lookup("test.question") <NEW_LINE> self.assertEqual(result, [1]) <NEW_LINE> tested_obj.queryObj.query.assert_not_called() <NEW_LINE> <DEDENT> def test_lookup_no_cache(self): <NEW_LINE> <INDENT> self.mock_cache.get.return_value = None <NEW_LINE> cache_line = ( "test.question", self.mock_rdtype.return_value, self.mock_rdclass.return_value ) <NEW_LINE> tested_obj = dnsutil.Cache("dnsserver") <NEW_LINE> tested_obj.lookup("test.question") <NEW_LINE> query_func = tested_obj.queryObj.query <NEW_LINE> query_func.assert_called_with(*cache_line) <NEW_LINE> tested_obj.queryObj.cache.put.assert_called_with(cache_line, query_func.return_value) <NEW_LINE> <DEDENT> def test_lookup_cache_failure(self): <NEW_LINE> <INDENT> question = "test.question" <NEW_LINE> side_effects = [ dnsutil.dns.resolver.NXDOMAIN, dnsutil.dns.exception.Timeout, dnsutil.dns.resolver.NoAnswer, IndexError, dnsutil.struct.error ] <NEW_LINE> for side_effect in side_effects: <NEW_LINE> <INDENT> tested_obj = dnsutil.Cache('dnsserver') <NEW_LINE> tested_obj.queryObj.cache.get = MagicMock(return_value=None) <NEW_LINE> tested_obj.queryObj.query.side_effect = [side_effect, MagicMock()] <NEW_LINE> result = tested_obj.lookup(question) <NEW_LINE> self.assertEqual(result, []) <NEW_LINE> result = tested_obj.lookup(question) <NEW_LINE> self.assertEqual(result, []) <NEW_LINE> tested_obj.queryObj.cache.get.assert_called_once() | Tests for the dnsutil.Cache class. | 62598faf8e7ae83300ee90c9 |
class SupplyCreatedTracker(object): <NEW_LINE> <INDENT> name = 'SupplyCreatedTracker' <NEW_LINE> def __init__(self): <NEW_LINE> <INDENT> self._supply_created = defaultdict(int) <NEW_LINE> self._workers_created = defaultdict(int) <NEW_LINE> self._army_created = defaultdict(int) <NEW_LINE> <DEDENT> def _add_to_workers(self,event,replay): <NEW_LINE> <INDENT> self._workers_created[event.unit.owner.pid] += event.unit.supply <NEW_LINE> supp = SupplyCount(util.convert_to_realtime_r(replay,event.second), self._workers_created[event.unit.owner.pid], event.unit.supply, event.unit.is_worker) <NEW_LINE> replay.player[event.unit.owner.pid].metrics.workers_created.append(supp) <NEW_LINE> <DEDENT> def _add_to_army(self,event,replay): <NEW_LINE> <INDENT> self._army_created[event.unit.owner.pid] += event.unit.supply <NEW_LINE> supp = SupplyCount(util.convert_to_realtime_r(replay,event.second), self._army_created[event.unit.owner.pid], event.unit.supply, event.unit.is_worker) <NEW_LINE> replay.player[event.unit.owner.pid].metrics.army_created.append(supp) <NEW_LINE> <DEDENT> def _add_to_supply(self,event,replay): <NEW_LINE> <INDENT> self._supply_created[event.unit.owner.pid] += event.unit.supply <NEW_LINE> supp = SupplyCount(util.convert_to_realtime_r(replay,event.second), self._supply_created[event.unit.owner.pid], event.unit.supply, event.unit.is_worker) <NEW_LINE> replay.player[event.unit.owner.pid].metrics.supply_created.append(supp) <NEW_LINE> <DEDENT> def handleInitGame(self,event,replay): <NEW_LINE> <INDENT> for player in replay.players: <NEW_LINE> <INDENT> player.metrics = Sc2MetricAnalyzer() <NEW_LINE> self._supply_created[player.pid] = 0 <NEW_LINE> self._workers_created[player.pid] = 0 <NEW_LINE> self._army_created[player.pid] = 0 <NEW_LINE> <DEDENT> <DEDENT> def handleUnitBornEvent(self,event,replay): <NEW_LINE> <INDENT> if event.unit.is_worker: <NEW_LINE> <INDENT> self._add_to_supply(event,replay) <NEW_LINE> self._add_to_workers(event,replay) <NEW_LINE> <DEDENT> elif (event.unit.is_army and not event.unit.hallucinated and event.unit.name != "Archon"): <NEW_LINE> <INDENT> self._add_to_supply(event,replay) <NEW_LINE> self._add_to_army(event,replay) <NEW_LINE> <DEDENT> <DEDENT> def handleUnitInitEvent(self,event,replay): <NEW_LINE> <INDENT> if (event.unit.is_army and not event.unit.hallucinated and event.unit.name != "Archon"): <NEW_LINE> <INDENT> self._add_to_supply(event,replay) <NEW_LINE> self._add_to_army(event,replay) | Builds ``player.metrics.army_created``, ``player.metrics.workers_created``, and
``player.metrics.supply_created`` arrays made of :class:`~metrics.metric_containers.SupplyCount`.
The ``metrics`` being of the type :class:`~metrics.sc2metric.Sc2MetricAnalyzer`. The supplies
are tracked whenever a unit is created. The unit's supply and a cumulative supply count of the
army, workers, and total supply are tracked for the corresponding second. | 62598faf7b25080760ed74d6 |
class KernelCenterer(BaseEstimator, TransformerMixin): <NEW_LINE> <INDENT> def fit(self, K, y=None): <NEW_LINE> <INDENT> K = array2d(K) <NEW_LINE> n_samples = K.shape[0] <NEW_LINE> self.K_fit_rows_ = np.sum(K, axis=0) / n_samples <NEW_LINE> self.K_fit_all_ = self.K_fit_rows_.sum() / n_samples <NEW_LINE> return self <NEW_LINE> <DEDENT> def transform(self, K, y=None, copy=True): <NEW_LINE> <INDENT> K = array2d(K) <NEW_LINE> if copy: <NEW_LINE> <INDENT> K = K.copy() <NEW_LINE> <DEDENT> K_pred_cols = (np.sum(K, axis=1) / self.K_fit_rows_.shape[0])[:, np.newaxis] <NEW_LINE> K -= self.K_fit_rows_ <NEW_LINE> K -= K_pred_cols <NEW_LINE> K += self.K_fit_all_ <NEW_LINE> return K | Center a kernel matrix
Let K(x_i, x_j) be a kernel defined by K(x_i, x_j) = phi(x_i)^T phi(x_j),
where phi(x) is a function mapping x to a hilbert space. KernelCenterer is
a class to center (i.e., normalize to have zero-mean) the data without
explicitly computing phi(x). It is equivalent equivalent to centering
phi(x) with sklearn.preprocessing.StandardScaler(with_std=False). | 62598faf9c8ee82313040185 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.