prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>wiener.py<|end_file_name|><|fim▁begin|># Copyright 2015 Matthew J. Aburn # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. See <http://www.gnu.org/licenses/>. r""" Simulation of standard multiple stochastic integrals, both Ito and Stratonovich I_{ij}(t) = \int_{0}^{t}\int_{0}^{s} dW_i(u) dW_j(s) (Ito) J_{ij}(t) = \int_{0}^{t}\int_{0}^{s} \circ dW_i(u) \circ dW_j(s) (Stratonovich) These multiple integrals I and J are important building blocks that will be used by most of the higher-order algorithms that integrate multi-dimensional SODEs. We first implement the method of Kloeden, Platen and Wright (1992) to approximate the integrals by the first n terms from the series expansion of a Brownian bridge process. By default using n=5. Finally we implement the method of Wiktorsson (2001) which improves on the previous method by also approximating the tail-sum distribution by a multivariate normal distribution. References: P. Kloeden, E. Platen and I. Wright (1992) The approximation of multiple stochastic integrals M. Wiktorsson (2001) Joint Characteristic Function and Simultaneous Simulation of Iterated Ito Integrals for Multiple Independent Brownian Motions """ import numpy as np numpy_version = list(map(int, np.version.short_version.split('.'))) if numpy_version >= [1,10,0]: broadcast_to = np.broadcast_to else: from ._broadcast import broadcast_to def deltaW(N, m, h): """Generate sequence of Wiener increments for m independent Wiener processes W_j(t) j=0..m-1 for each of N time intervals of length h. Returns: dW (array of shape (N, m)): The [n, j] element has the value W_j((n+1)*h) - W_j(n*h) """ return np.random.normal(0.0, np.sqrt(h), (N, m)) def _t(a):<|fim▁hole|> def _dot(a, b): r""" for rank 3 arrays a and b, return \sum_k a_ij^k . b_ik^l (no sum on i) i.e. This is just normal matrix multiplication at each point on first axis """ return np.einsum('ijk,ikl->ijl', a, b) def _Aterm(N, h, m, k, dW): """kth term in the sum of Wiktorsson2001 equation (2.2)""" sqrt2h = np.sqrt(2.0/h) Xk = np.random.normal(0.0, 1.0, (N, m, 1)) Yk = np.random.normal(0.0, 1.0, (N, m, 1)) term1 = _dot(Xk, _t(Yk + sqrt2h*dW)) term2 = _dot(Yk + sqrt2h*dW, _t(Xk)) return (term1 - term2)/k def Ikpw(dW, h, n=5): """matrix I approximating repeated Ito integrals for each of N time intervals, based on the method of Kloeden, Platen and Wright (1992). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using sdeint.deltaW()) h (float): the time step size n (int, optional): how many terms to take in the series expansion Returns: (A, I) where A: array of shape (N, m, m) giving the Levy areas that were used. I: array of shape (N, m, m) giving an m x m matrix of repeated Ito integral values for each of the N time intervals. """ N = dW.shape[0] m = dW.shape[1] if dW.ndim < 3: dW = dW.reshape((N, -1, 1)) # change to array of shape (N, m, 1) if dW.shape[2] != 1 or dW.ndim > 3: raise(ValueError) A = _Aterm(N, h, m, 1, dW) for k in range(2, n+1): A += _Aterm(N, h, m, k, dW) A = (h/(2.0*np.pi))*A I = 0.5*(_dot(dW, _t(dW)) - np.diag(h*np.ones(m))) + A dW = dW.reshape((N, -1)) # change back to shape (N, m) return (A, I) def Jkpw(dW, h, n=5): """matrix J approximating repeated Stratonovich integrals for each of N time intervals, based on the method of Kloeden, Platen and Wright (1992). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using sdeint.deltaW()) h (float): the time step size n (int, optional): how many terms to take in the series expansion Returns: (A, J) where A: array of shape (N, m, m) giving the Levy areas that were used. J: array of shape (N, m, m) giving an m x m matrix of repeated Stratonovich integral values for each of the N time intervals. """ m = dW.shape[1] A, I = Ikpw(dW, h, n) J = I + 0.5*h*np.eye(m).reshape((1, m, m)) return (A, J) # The code below this point implements the method of Wiktorsson2001. def _vec(A): """ Linear operator _vec() from Wiktorsson2001 p478 Args: A: a rank 3 array of shape N x m x n, giving a matrix A[j] for each interval of time j in 0..N-1 Returns: array of shape N x mn x 1, made by stacking the columns of matrix A[j] on top of each other, for each j in 0..N-1 """ N, m, n = A.shape return A.reshape((N, m*n, 1), order='F') def _unvec(vecA, m=None): """inverse of _vec() operator""" N = vecA.shape[0] if m is None: m = np.sqrt(vecA.shape[1] + 0.25).astype(np.int64) return vecA.reshape((N, m, -1), order='F') def _kp(a, b): """Special case Kronecker tensor product of a[i] and b[i] at each time interval i for i = 0 .. N-1 It is specialized for the case where both a and b are shape N x m x 1 """ if a.shape != b.shape or a.shape[-1] != 1: raise(ValueError) N = a.shape[0] # take the outer product over the last two axes, then reshape: return np.einsum('ijk,ilk->ijkl', a, b).reshape(N, -1, 1) def _kp2(A, B): """Special case Kronecker tensor product of A[i] and B[i] at each time interval i for i = 0 .. N-1 Specialized for the case A and B rank 3 with A.shape[0]==B.shape[0] """ N = A.shape[0] if B.shape[0] != N: raise(ValueError) newshape1 = A.shape[1]*B.shape[1] return np.einsum('ijk,ilm->ijlkm', A, B).reshape(N, newshape1, -1) def _P(m): """Returns m^2 x m^2 permutation matrix that swaps rows i and j where j = 1 + m((i - 1) mod m) + (i - 1) div m, for i = 1 .. m^2 """ P = np.zeros((m**2,m**2), dtype=np.int64) for i in range(1, m**2 + 1): j = 1 + m*((i - 1) % m) + (i - 1)//m P[i-1, j-1] = 1 return P def _K(m): """ matrix K_m from Wiktorsson2001 """ M = m*(m - 1)//2 K = np.zeros((M, m**2), dtype=np.int64) row = 0 for j in range(1, m): col = (j - 1)*m + j s = m - j K[row:(row+s), col:(col+s)] = np.eye(s) row += s return K def _AtildeTerm(N, h, m, k, dW, Km0, Pm0): """kth term in the sum for Atilde (Wiktorsson2001 p481, 1st eqn)""" M = m*(m-1)//2 Xk = np.random.normal(0.0, 1.0, (N, m, 1)) Yk = np.random.normal(0.0, 1.0, (N, m, 1)) factor1 = np.dot(Km0, Pm0 - np.eye(m**2)) factor1 = broadcast_to(factor1, (N, M, m**2)) factor2 = _kp(Yk + np.sqrt(2.0/h)*dW, Xk) return _dot(factor1, factor2)/k def _sigmainf(N, h, m, dW, Km0, Pm0): r"""Asymptotic covariance matrix \Sigma_\infty Wiktorsson2001 eqn (4.5)""" M = m*(m-1)//2 Im = broadcast_to(np.eye(m), (N, m, m)) IM = broadcast_to(np.eye(M), (N, M, M)) Ims0 = np.eye(m**2) factor1 = broadcast_to((2.0/h)*np.dot(Km0, Ims0 - Pm0), (N, M, m**2)) factor2 = _kp2(Im, _dot(dW, _t(dW))) factor3 = broadcast_to(np.dot(Ims0 - Pm0, Km0.T), (N, m**2, M)) return 2*IM + _dot(_dot(factor1, factor2), factor3) def _a(n): r""" \sum_{n+1}^\infty 1/k^2 """ return np.pi**2/6.0 - sum(1.0/k**2 for k in range(1, n+1)) def Iwik(dW, h, n=5): """matrix I approximating repeated Ito integrals for each of N time intervals, using the method of Wiktorsson (2001). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using sdeint.deltaW()) h (float): the time step size n (int, optional): how many terms to take in the series expansion Returns: (Atilde, I) where Atilde: array of shape (N,m(m-1)//2,1) giving the area integrals used. I: array of shape (N, m, m) giving an m x m matrix of repeated Ito integral values for each of the N time intervals. """ N = dW.shape[0] m = dW.shape[1] if dW.ndim < 3: dW = dW.reshape((N, -1, 1)) # change to array of shape (N, m, 1) if dW.shape[2] != 1 or dW.ndim > 3: raise(ValueError) if m == 1: return (np.zeros((N, 1, 1)), (dW*dW - h)/2.0) Pm0 = _P(m) Km0 = _K(m) M = m*(m-1)//2 Atilde_n = _AtildeTerm(N, h, m, 1, dW, Km0, Pm0) for k in range(2, n+1): Atilde_n += _AtildeTerm(N, h, m, k, dW, Km0, Pm0) Atilde_n = (h/(2.0*np.pi))*Atilde_n # approximation after n terms S = _sigmainf(N, h, m, dW, Km0, Pm0) normdW2 = np.sum(np.abs(dW)**2, axis=1) radical = np.sqrt(1.0 + normdW2/h).reshape((N, 1, 1)) IM = broadcast_to(np.eye(M), (N, M, M)) Im = broadcast_to(np.eye(m), (N, m, m)) Ims0 = np.eye(m**2) sqrtS = (S + 2.0*radical*IM)/(np.sqrt(2.0)*(1.0 + radical)) G = np.random.normal(0.0, 1.0, (N, M, 1)) tailsum = h/(2.0*np.pi)*_a(n)**0.5*_dot(sqrtS, G) Atilde = Atilde_n + tailsum # our final approximation of the areas factor3 = broadcast_to(np.dot(Ims0 - Pm0, Km0.T), (N, m**2, M)) vecI = 0.5*(_kp(dW, dW) - _vec(h*Im)) + _dot(factor3, Atilde) I = _unvec(vecI) dW = dW.reshape((N, -1)) # change back to shape (N, m) return (Atilde, I) def Jwik(dW, h, n=5): """matrix J approximating repeated Stratonovich integrals for each of N time intervals, using the method of Wiktorsson (2001). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using sdeint.deltaW()) h (float): the time step size n (int, optional): how many terms to take in the series expansion Returns: (Atilde, J) where Atilde: array of shape (N,m(m-1)//2,1) giving the area integrals used. J: array of shape (N, m, m) giving an m x m matrix of repeated Stratonovich integral values for each of the N time intervals. """ m = dW.shape[1] Atilde, I = Iwik(dW, h, n) J = I + 0.5*h*np.eye(m).reshape((1, m, m)) return (Atilde, J)<|fim▁end|>
"""transpose the last two axes of a three axis array""" return a.transpose((0, 2, 1))
<|file_name|>stage01_rnasequencing_analysis_postgresql_models.py<|end_file_name|><|fim▁begin|>from SBaaS_base.postgresql_orm_base import * class data_stage01_rnasequencing_analysis(Base): __tablename__ = 'data_stage01_rnasequencing_analysis' id = Column(Integer, Sequence('data_stage01_rnasequencing_analysis_id_seq'), primary_key=True) analysis_id = Column(String(500)) experiment_id = Column(String(50)) sample_name_abbreviation = Column(String(500)) # equivalent to sample_name_abbreviation sample_name = Column(String(500)) # equivalent to sample_name_abbreviation time_point = Column(String(10)) # converted to intermediate in lineage analysis analysis_type = Column(String(100)); # time-course (i.e., multiple time points), paired (i.e., control compared to multiple replicates), group (i.e., single grouping of samples). used_ = Column(Boolean); comment_ = Column(Text); __table_args__ = ( UniqueConstraint('experiment_id','sample_name_abbreviation','sample_name','time_point','analysis_type','analysis_id'), ) def __init__(self, row_dict_I, ):<|fim▁hole|> self.sample_name=row_dict_I['sample_name']; self.time_point=row_dict_I['time_point']; self.analysis_type=row_dict_I['analysis_type']; self.used_=row_dict_I['used_']; self.comment_=row_dict_I['comment_']; def __set__row__(self,analysis_id_I, experiment_id_I, sample_name_abbreviation_I, sample_name_I, time_point_I, analysis_type_I, used__I, comment__I): self.analysis_id=analysis_id_I self.experiment_id=experiment_id_I self.sample_name_abbreviation=sample_name_abbreviation_I self.sample_name=sample_name_I self.time_point=time_point_I self.analysis_type=analysis_type_I self.used_=used__I self.comment_=comment__I def __repr__dict__(self): return {'id':self.id, 'analysis_id':self.analysis_id, 'experiment_id':self.experiment_id, 'sample_name_abbreviation':self.sample_name_abbreviation, 'sample_name':self.sample_name, 'time_point':self.time_point, 'analysis_type':self.analysis_type, 'used_':self.used_, 'comment_':self.comment_} def __repr__json__(self): return json.dumps(self.__repr__dict__())<|fim▁end|>
self.analysis_id=row_dict_I['analysis_id']; self.experiment_id=row_dict_I['experiment_id']; self.sample_name_abbreviation=row_dict_I['sample_name_abbreviation'];
<|file_name|>scale_strict.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 ### rev: 5.0 ### author: <zhq> ### features: ### errors included ### up to 63 bases (2 to 64) ### caps recognition and same output format (deprecated) ### for the function parameters, `cur` represents the current (input) base, `res` represents the result (output) base, and `num` represents the current (input) number. def scale(cur, res, num): # int, int, str -> str # Default Settings num = str(num) iscaps = False positive = True # Input if cur == res: return num if num == "0": return "0" assert cur in range(2, 65) and res in range(2, 65), "Base not defined." if num[0] == "-": positive = False num = num[1:] result = 0 unit = 1 if cur != 10: for i in num[::-1]: value = ord(i) if value in range(48, 58): value -= 48 elif value in range(65, 92): value -= 55 elif value in range(97, 123): value -= 61 elif value == 64: value = 62 elif value == 95: value = 63 assert value <= cur, "Digit larger than original base. v:%d(%s) b:%d\nCall: scale(%d, %d, %s)" % (value, i, cur, cur, res, num) result += value * unit unit *= cur result = str(result) # Output if res != 10: num = int(result or num) result = "" while num > 0: num, value = divmod(num, res) if value < 10: digit = value + 48 elif value < 36: digit = value + 55 elif value < 62: digit = value + 61 elif value == 62: digit = 64 elif value == 63: digit = 95<|fim▁hole|><|fim▁end|>
result = chr(digit) + result if not positive: result = "-" + result return result
<|file_name|>status_effect.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """Status effect data.""" from components.status_effect import StatusEffect from status_effect_functions import damage_of_time # todo: generate new object not copy STATUS_EFFECT_CATALOG = { 'POISONED': { 'name': 'poisoned', 'tile_path': 'status_effect/poisoned.png', 'color': 'green', 'tick_function': damage_of_time,<|fim▁hole|> 'OFF_BALANCED': { 'name': 'off-balanced', 'tile_path': 'status_effect/off_balanced.png', 'color': 'gray', 'duration': 4, 'stats': {'phys_pow': -1, 'defense': -2} }, 'VIGILANT': { 'name': 'vigilant', 'tile_path': 'status_effect/vigilant.png', 'color': 'blue', 'duration': 6, 'stats': {'defense': 5} }, } def generate_status_effect(statfx_id): """Return a status effect generated from catalog.""" statfx_data = STATUS_EFFECT_CATALOG.get(statfx_id) # char and color are set as placeholder, ASCII graphics features will be removed in future. return StatusEffect(statfx_data.get('name'), statfx_data.get('tile_path'), statfx_data.get('color'), function_kwargs=statfx_data.get('function_kwargs'), tick_function=statfx_data.get('tick_function'), duration=statfx_data.get('duration'), stats=statfx_data.get('stats'))<|fim▁end|>
'duration': 6, 'function_kwargs': {'init_dmg': 2} # specify as dictionary },
<|file_name|>LessonHeader.js<|end_file_name|><|fim▁begin|>'use strict'; import Flickity from 'flickity-imagesloaded' export default function LessonHeader() { console.log("-- LessonHeader initialized") let photosSelector = '.LessonHeader__photos' let $photos = $(photosSelector) if ($photos.length > 0) { let photoSelector = '.LessonHeader__photo' let $status = $('.LessonHeader__photos__status') let $current = $status.find('.current') let $total = $status.find('.total') // Init flickity for all carousels let flkty = new Flickity(photosSelector, { cellAlign: 'left', cellSelector: photoSelector, contain: true, pageDots: false, prevNextButtons: false, wrapAround: true, imagesLoaded: true, percentPosition: false, }) document.addEventListener("turbolinks:request-start", function() { flkty.destroy() }) $total.html($(photoSelector).length) flkty.on( 'select', function() { $current.html(flkty.selectedIndex + 1) }) return flkty }<|fim▁hole|><|fim▁end|>
}
<|file_name|>iqiyi.py<|end_file_name|><|fim▁begin|># coding: utf-8 from __future__ import unicode_literals import hashlib import math import random import time import uuid from .common import InfoExtractor from ..compat import compat_urllib_parse from ..utils import ExtractorError class IqiyiIE(InfoExtractor): IE_NAME = 'iqiyi' IE_DESC = '爱奇艺' _VALID_URL = r'http://(?:[^.]+\.)?iqiyi\.com/.+\.html' _TESTS = [{ 'url': 'http://www.iqiyi.com/v_19rrojlavg.html', 'md5': '2cb594dc2781e6c941a110d8f358118b', 'info_dict': { 'id': '9c1fb1b99d192b21c559e5a1a2cb3c73', 'title': '美国德州空中惊现奇异云团 酷似UFO', 'ext': 'f4v', } }, { 'url': 'http://www.iqiyi.com/v_19rrhnnclk.html', 'info_dict': { 'id': 'e3f585b550a280af23c98b6cb2be19fb', 'title': '名侦探柯南第752集', }, 'playlist': [{ 'info_dict': { 'id': 'e3f585b550a280af23c98b6cb2be19fb_part1', 'ext': 'f4v', 'title': '名侦探柯南第752集', }, }, { 'info_dict': { 'id': 'e3f585b550a280af23c98b6cb2be19fb_part2', 'ext': 'f4v', 'title': '名侦探柯南第752集', }, }, { 'info_dict': { 'id': 'e3f585b550a280af23c98b6cb2be19fb_part3', 'ext': 'f4v', 'title': '名侦探柯南第752集', }, }, { 'info_dict': { 'id': 'e3f585b550a280af23c98b6cb2be19fb_part4', 'ext': 'f4v', 'title': '名侦探柯南第752集', }, }, { 'info_dict': { 'id': 'e3f585b550a280af23c98b6cb2be19fb_part5', 'ext': 'f4v', 'title': '名侦探柯南第752集', }, }, { 'info_dict': { 'id': 'e3f585b550a280af23c98b6cb2be19fb_part6', 'ext': 'f4v', 'title': '名侦探柯南第752集', }, }, { 'info_dict': { 'id': 'e3f585b550a280af23c98b6cb2be19fb_part7', 'ext': 'f4v', 'title': '名侦探柯南第752集', }, }, { 'info_dict': { 'id': 'e3f585b550a280af23c98b6cb2be19fb_part8', 'ext': 'f4v', 'title': '名侦探柯南第752集', }, }], 'params': { 'skip_download': True, }, }, { 'url': 'http://www.iqiyi.com/w_19rt6o8t9p.html', 'only_matching': True, }, { 'url': 'http://www.iqiyi.com/a_19rrhbc6kt.html', 'only_matching': True, }, { 'url': 'http://yule.iqiyi.com/pcb.html', 'only_matching': True, }] _FORMATS_MAP = [ ('1', 'h6'), ('2', 'h5'), ('3', 'h4'), ('4', 'h3'), ('5', 'h2'), ('10', 'h1'), ] @staticmethod def md5_text(text): return hashlib.md5(text.encode('utf-8')).hexdigest() def construct_video_urls(self, data, video_id, _uuid): def do_xor(x, y): a = y % 3 if a == 1: return x ^ 121 if a == 2: return x ^ 72 return x ^ 103 def get_encode_code(l): a = 0 b = l.split('-') c = len(b) s = '' for i in range(c - 1, -1, -1): a = do_xor(int(b[c - i - 1], 16), i) s += chr(a) return s[::-1] def get_path_key(x, format_id, segment_index): mg = ')(*&^flash@#$%a' tm = self._download_json( 'http://data.video.qiyi.com/t?tn=' + str(random.random()), video_id, note='Download path key of segment %d for format %s' % (segment_index + 1, format_id) )['t'] t = str(int(math.floor(int(tm) / (600.0)))) return self.md5_text(t + mg + x)<|fim▁hole|> format_id = self.get_format(format_item['bid']) else: continue video_urls = [] video_urls_info = format_item['fs'] if not format_item['fs'][0]['l'].startswith('/'): t = get_encode_code(format_item['fs'][0]['l']) if t.endswith('mp4'): video_urls_info = format_item['flvs'] for segment_index, segment in enumerate(video_urls_info): vl = segment['l'] if not vl.startswith('/'): vl = get_encode_code(vl) key = get_path_key( vl.split('/')[-1].split('.')[0], format_id, segment_index) filesize = segment['b'] base_url = data['vp']['du'].split('/') base_url.insert(-1, key) base_url = '/'.join(base_url) param = { 'su': _uuid, 'qyid': uuid.uuid4().hex, 'client': '', 'z': '', 'bt': '', 'ct': '', 'tn': str(int(time.time())) } api_video_url = base_url + vl + '?' + \ compat_urllib_parse.urlencode(param) js = self._download_json( api_video_url, video_id, note='Download video info of segment %d for format %s' % (segment_index + 1, format_id)) video_url = js['l'] video_urls.append( (video_url, filesize)) video_urls_dict[format_id] = video_urls return video_urls_dict def get_format(self, bid): matched_format_ids = [_format_id for _bid, _format_id in self._FORMATS_MAP if _bid == str(bid)] return matched_format_ids[0] if len(matched_format_ids) else None def get_bid(self, format_id): matched_bids = [_bid for _bid, _format_id in self._FORMATS_MAP if _format_id == format_id] return matched_bids[0] if len(matched_bids) else None def get_raw_data(self, tvid, video_id, enc_key, _uuid): tm = str(int(time.time())) tail = tm + tvid param = { 'key': 'fvip', 'src': self.md5_text('youtube-dl'), 'tvId': tvid, 'vid': video_id, 'vinfo': 1, 'tm': tm, 'enc': self.md5_text(enc_key + tail), 'qyid': _uuid, 'tn': random.random(), 'um': 0, 'authkey': self.md5_text(self.md5_text('') + tail), } api_url = 'http://cache.video.qiyi.com/vms' + '?' + \ compat_urllib_parse.urlencode(param) raw_data = self._download_json(api_url, video_id) return raw_data def get_enc_key(self, swf_url, video_id): # TODO: automatic key extraction # last update at 2015-12-18 for Zombie::bite enc_key = '8b6b683780897eb8d9a48a02ccc4817d'[::-1] return enc_key def _real_extract(self, url): webpage = self._download_webpage( url, 'temp_id', note='download video page') tvid = self._search_regex( r'data-player-tvid\s*=\s*[\'"](\d+)', webpage, 'tvid') video_id = self._search_regex( r'data-player-videoid\s*=\s*[\'"]([a-f\d]+)', webpage, 'video_id') swf_url = self._search_regex( r'(http://[^\'"]+MainPlayer[^.]+\.swf)', webpage, 'swf player URL') _uuid = uuid.uuid4().hex enc_key = self.get_enc_key(swf_url, video_id) raw_data = self.get_raw_data(tvid, video_id, enc_key, _uuid) if raw_data['code'] != 'A000000': raise ExtractorError('Unable to load data. Error code: ' + raw_data['code']) if not raw_data['data']['vp']['tkl']: raise ExtractorError('No support iQiqy VIP video') data = raw_data['data'] title = data['vi']['vn'] # generate video_urls_dict video_urls_dict = self.construct_video_urls( data, video_id, _uuid) # construct info entries = [] for format_id in video_urls_dict: video_urls = video_urls_dict[format_id] for i, video_url_info in enumerate(video_urls): if len(entries) < i + 1: entries.append({'formats': []}) entries[i]['formats'].append( { 'url': video_url_info[0], 'filesize': video_url_info[-1], 'format_id': format_id, 'preference': int(self.get_bid(format_id)) } ) for i in range(len(entries)): self._sort_formats(entries[i]['formats']) entries[i].update( { 'id': '%s_part%d' % (video_id, i + 1), 'title': title, } ) if len(entries) > 1: info = { '_type': 'multi_video', 'id': video_id, 'title': title, 'entries': entries, } else: info = entries[0] info['id'] = video_id info['title'] = title return info<|fim▁end|>
video_urls_dict = {} for format_item in data['vp']['tkl'][0]['vs']: if 0 < int(format_item['bid']) <= 10:
<|file_name|>ios-star-outline.d.ts<|end_file_name|><|fim▁begin|>import * as React from 'react'; import { IconBaseProps } from 'react-icon-base';<|fim▁hole|><|fim▁end|>
export default class IoIosStarOutline extends React.Component<IconBaseProps> { }
<|file_name|>pySpan.cpp<|end_file_name|><|fim▁begin|>/* This file is part of HSPlasma. * * HSPlasma is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HSPlasma is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HSPlasma. If not, see <http://www.gnu.org/licenses/>. */ #include <PyPlasma.h> #include <PRP/Geometry/plSpan.h> #include "pySpan.h" #include "PRP/KeyedObject/pyKey.h" #include "PRP/Region/pyBounds.h" #include "Stream/pyStream.h" #include "Math/pyMatrix.h" extern "C" { static void pySpan_dealloc(pySpan* self) { if (self->fPyOwned) delete self->fThis; Py_TYPE(self)->tp_free((PyObject*)self); } static int pySpan___init__(pySpan* self, PyObject* args, PyObject* kwds) { if (!PyArg_ParseTuple(args, "")) return -1; return 0; } static PyObject* pySpan_new(PyTypeObject* type, PyObject* args, PyObject* kwds) { pySpan* self = (pySpan*)type->tp_alloc(type, 0); if (self != NULL) { self->fThis = new plSpan(); self->fPyOwned = true; } return (PyObject*)self; } static PyObject* pySpan_ClassName(pySpan* self) { return PyString_FromString(self->fThis->ClassName()); } static PyObject* pySpan_read(pySpan* self, PyObject* args) { pyStream* stream; if (!PyArg_ParseTuple(args, "O", &stream)) { PyErr_SetString(PyExc_TypeError, "read expects an hsStream"); return NULL; } if (!pyStream_Check((PyObject*)stream)) { PyErr_SetString(PyExc_TypeError, "read expects an hsStream"); return NULL; } self->fThis->read(stream->fThis); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_write(pySpan* self, PyObject* args) { pyStream* stream; if (!PyArg_ParseTuple(args, "O", &stream)) { PyErr_SetString(PyExc_TypeError, "write expects an hsStream"); return NULL; } if (!pyStream_Check((PyObject*)stream)) { PyErr_SetString(PyExc_TypeError, "write expects an hsStream"); return NULL; } self->fThis->write(stream->fThis); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_clearPermaLights(pySpan* self, PyObject* args) { self->fThis->clearPermaLights(); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_clearPermaProjs(pySpan* self, PyObject* args) { self->fThis->clearPermaProjs(); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_addPermaLight(pySpan* self, PyObject* args) { pyKey* key; if (!PyArg_ParseTuple(args, "O", &key)) { PyErr_SetString(PyExc_TypeError, "addPermaLight expects a plKey"); return NULL; } if (!pyKey_Check((PyObject*)key)) { PyErr_SetString(PyExc_TypeError, "addPermaLight expects a plKey"); return NULL; } self->fThis->addPermaLight(*key->fThis); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_addPermaProj(pySpan* self, PyObject* args) { pyKey* key; if (!PyArg_ParseTuple(args, "O", &key)) { PyErr_SetString(PyExc_TypeError, "addPermaProj expects a plKey"); return NULL; } if (!pyKey_Check((PyObject*)key)) { PyErr_SetString(PyExc_TypeError, "addPermaProj expects a plKey"); return NULL; } self->fThis->addPermaProj(*key->fThis); Py_INCREF(Py_None); return Py_None; } static PyObject* pySpan_getFog(pySpan* self, void*) { return pyKey_FromKey(self->fThis->getFogEnvironment()); } static PyObject* pySpan_getLights(pySpan* self, void*) { PyObject* list = PyList_New(self->fThis->getPermaLights().size()); for (size_t i=0; i<self->fThis->getPermaLights().size(); i++) PyList_SET_ITEM(list, i, pyKey_FromKey(self->fThis->getPermaLights()[i])); return list; } static PyObject* pySpan_getProjs(pySpan* self, void*) { PyObject* list = PyList_New(self->fThis->getPermaProjs().size()); for (size_t i=0; i<self->fThis->getPermaProjs().size(); i++) PyList_SET_ITEM(list, i, pyKey_FromKey(self->fThis->getPermaProjs()[i])); return list; } static PyObject* pySpan_getL2W(pySpan* self, void*) { return pyMatrix44_FromMatrix44(self->fThis->getLocalToWorld()); } static PyObject* pySpan_getW2L(pySpan* self, void*) { return pyMatrix44_FromMatrix44(self->fThis->getWorldToLocal()); } static PyObject* pySpan_getSubType(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getSubType()); } static PyObject* pySpan_getMaterial(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getMaterialIdx()); } static PyObject* pySpan_getNumMatrices(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getNumMatrices()); } static PyObject* pySpan_getProps(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getProps()); } static PyObject* pySpan_getBaseMatrix(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getBaseMatrix()); } static PyObject* pySpan_getMaxBoneIdx(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getMaxBoneIdx()); } static PyObject* pySpan_getPenBoneIdx(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getPenBoneIdx()); } static PyObject* pySpan_getLocalUVWChans(pySpan* self, void*) { return PyInt_FromLong(self->fThis->getLocalUVWChans()); } static PyObject* pySpan_getMinDist(pySpan* self, void*) { return PyFloat_FromDouble(self->fThis->getMinDist()); } static PyObject* pySpan_getMaxDist(pySpan* self, void*) { return PyFloat_FromDouble(self->fThis->getMaxDist()); } static PyObject* pySpan_getWaterHeight(pySpan* self, void*) { return PyFloat_FromDouble(self->fThis->getWaterHeight()); } static PyObject* pySpan_getLocalBounds(pySpan* self, void*) { return pyBounds3Ext_FromBounds3Ext(self->fThis->getLocalBounds()); } static PyObject* pySpan_getWorldBounds(pySpan* self, void*) { return pyBounds3Ext_FromBounds3Ext(self->fThis->getWorldBounds()); } static int pySpan_setFog(pySpan* self, PyObject* value, void*) { if (value == NULL || !pyKey_Check(value)) { PyErr_SetString(PyExc_TypeError, "fog should be a plKey"); return -1; } self->fThis->setFogEnvironment(*((pyKey*)value)->fThis); return 0; } static int pySpan_setLights(pySpan* self, PyObject* value, void*) { PyErr_SetString(PyExc_RuntimeError, "To add Lights, use addPermaLight and addPermaProj"); return -1; } static int pySpan_setL2W(pySpan* self, PyObject* value, void*) { if (value == NULL || !pyMatrix44_Check(value)) { PyErr_SetString(PyExc_TypeError, "localToWorld should be an hsMatrix44"); return -1; } self->fThis->setLocalToWorld(*((pyMatrix44*)value)->fThis); return 0; } static int pySpan_setW2L(pySpan* self, PyObject* value, void*) { if (value == NULL || !pyMatrix44_Check(value)) { PyErr_SetString(PyExc_TypeError, "worldToLocal should be an hsMatrix44"); return -1; } self->fThis->setWorldToLocal(*((pyMatrix44*)value)->fThis); return 0; } static int pySpan_setSubType(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "subType should be an int"); return -1; } self->fThis->setSubType(PyInt_AsLong(value)); return 0; } static int pySpan_setMaterial(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "materialIdx should be an int"); return -1; } self->fThis->setMaterialIdx(PyInt_AsLong(value)); return 0; } static int pySpan_setNumMatrices(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "numMatrices should be an int"); return -1; } self->fThis->setNumMatrices(PyInt_AsLong(value)); return 0; } static int pySpan_setProps(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "props should be an int"); return -1; } self->fThis->setProps(PyInt_AsLong(value)); return 0; } static int pySpan_setBaseMatrix(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "baseMatrix should be an int"); return -1; }<|fim▁hole|> static int pySpan_setMaxBoneIdx(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "maxBoneIdx should be an int"); return -1; } self->fThis->setMaxBoneIdx(PyInt_AsLong(value)); return 0; } static int pySpan_setPenBoneIdx(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "penBoneIdx should be an int"); return -1; } self->fThis->setPenBoneIdx(PyInt_AsLong(value)); return 0; } static int pySpan_setLocalUVWChans(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyInt_Check(value)) { PyErr_SetString(PyExc_TypeError, "localUVWChans should be an int"); return -1; } self->fThis->setLocalUVWChans(PyInt_AsLong(value)); return 0; } static int pySpan_setMinDist(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "minDist should be an int"); return -1; } self->fThis->setMinDist(PyFloat_AsDouble(value)); return 0; } static int pySpan_setMaxDist(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "maxDist should be an int"); return -1; } self->fThis->setMaxDist(PyFloat_AsDouble(value)); return 0; } static int pySpan_setWaterHeight(pySpan* self, PyObject* value, void*) { if (value == NULL || !PyFloat_Check(value)) { PyErr_SetString(PyExc_TypeError, "waterHeight should be an int"); return -1; } self->fThis->setWaterHeight(PyFloat_AsDouble(value)); return 0; } static int pySpan_setLocalBounds(pySpan* self, PyObject* value, void*) { if (value == NULL || !pyBounds3Ext_Check(value)) { PyErr_SetString(PyExc_TypeError, "localBounds should be an hsBounds3Ext"); return -1; } self->fThis->setLocalBounds(*((pyBounds3Ext*)value)->fThis); return 0; } static int pySpan_setWorldBounds(pySpan* self, PyObject* value, void*) { if (value == NULL || !pyBounds3Ext_Check(value)) { PyErr_SetString(PyExc_TypeError, "worldBounds should be an hsBounds3Ext"); return -1; } self->fThis->setWorldBounds(*((pyBounds3Ext*)value)->fThis); return 0; } static PyMethodDef pySpan_Methods[] = { { "ClassName", (PyCFunction)pySpan_ClassName, METH_NOARGS, "Returns the RTTI Class name of this Span object" }, { "read", (PyCFunction)pySpan_read, METH_VARARGS, "Params: stream\n" "Read this Span object from the stream" }, { "write", (PyCFunction)pySpan_write, METH_VARARGS, "Params: stream\n" "Write this Span object to the stream" }, { "clearPermaLights", (PyCFunction)pySpan_clearPermaLights, METH_NOARGS, "Remove all Perma Lights from this Span" }, { "clearPermaProjs", (PyCFunction)pySpan_clearPermaProjs, METH_NOARGS, "Remove all Perma Projs from this Span" }, { "addPermaLight", (PyCFunction)pySpan_addPermaLight, METH_VARARGS, "Params: key\n" "Add a Perma Light to the span" }, { "addPermaProj", (PyCFunction)pySpan_addPermaProj, METH_VARARGS, "Params: key\n" "Add a Perma Proj to the span" }, { NULL, NULL, 0, NULL } }; static PyGetSetDef pySpan_GetSet[] = { { _pycs("fog"), (getter)pySpan_getFog, (setter)pySpan_setFog, _pycs("Fog Environment key"), NULL }, { _pycs("permaLights"), (getter)pySpan_getLights, (setter)pySpan_setLights, NULL, NULL }, { _pycs("permaProjs"), (getter)pySpan_getProjs, (setter)pySpan_setLights, NULL, NULL }, { _pycs("localToWorld"), (getter)pySpan_getL2W, (setter)pySpan_setL2W, NULL, NULL }, { _pycs("worldToLocal"), (getter)pySpan_getW2L, (setter)pySpan_setW2L, NULL, NULL }, { _pycs("subType"), (getter)pySpan_getSubType, (setter)pySpan_setSubType, NULL, NULL }, { _pycs("materialIdx"), (getter)pySpan_getMaterial, (setter)pySpan_setMaterial, _pycs("Index of the material from the DrawableSpans to use"), NULL }, { _pycs("numMatrices"), (getter)pySpan_getNumMatrices, (setter)pySpan_setNumMatrices, NULL, NULL }, { _pycs("props"), (getter)pySpan_getProps, (setter)pySpan_setProps, NULL, NULL }, { _pycs("baseMatrix"), (getter)pySpan_getBaseMatrix, (setter)pySpan_setBaseMatrix, NULL, NULL }, { _pycs("maxBoneIdx"), (getter)pySpan_getMaxBoneIdx, (setter)pySpan_setMaxBoneIdx, NULL, NULL }, { _pycs("penBoneIdx"), (getter)pySpan_getPenBoneIdx, (setter)pySpan_setPenBoneIdx, NULL, NULL }, { _pycs("localUVWChans"), (getter)pySpan_getLocalUVWChans, (setter)pySpan_setLocalUVWChans, NULL, NULL }, { _pycs("minDist"), (getter)pySpan_getMinDist, (setter)pySpan_setMinDist, NULL, NULL }, { _pycs("maxDist"), (getter)pySpan_getMaxDist, (setter)pySpan_setMaxDist, NULL, NULL }, { _pycs("waterHeight"), (getter)pySpan_getWaterHeight, (setter)pySpan_setWaterHeight, NULL, NULL }, { _pycs("localBounds"), (getter)pySpan_getLocalBounds, (setter)pySpan_setLocalBounds, NULL, NULL }, { _pycs("worldBounds"), (getter)pySpan_getWorldBounds, (setter)pySpan_setWorldBounds, NULL, NULL }, { NULL, NULL, NULL, NULL, NULL } }; PyTypeObject pySpan_Type = { PyVarObject_HEAD_INIT(NULL, 0) "PyHSPlasma.plSpan", /* tp_name */ sizeof(pySpan), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)pySpan_dealloc, /* tp_dealloc */ NULL, /* tp_print */ NULL, /* tp_getattr */ NULL, /* tp_setattr */ NULL, /* tp_compare */ NULL, /* tp_repr */ NULL, /* tp_as_number */ NULL, /* tp_as_sequence */ NULL, /* tp_as_mapping */ NULL, /* tp_hash */ NULL, /* tp_call */ NULL, /* tp_str */ NULL, /* tp_getattro */ NULL, /* tp_setattro */ NULL, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "plSpan wrapper", /* tp_doc */ NULL, /* tp_traverse */ NULL, /* tp_clear */ NULL, /* tp_richcompare */ 0, /* tp_weaklistoffset */ NULL, /* tp_iter */ NULL, /* tp_iternext */ pySpan_Methods, /* tp_methods */ NULL, /* tp_members */ pySpan_GetSet, /* tp_getset */ NULL, /* tp_base */ NULL, /* tp_dict */ NULL, /* tp_descr_get */ NULL, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)pySpan___init__, /* tp_init */ NULL, /* tp_alloc */ pySpan_new, /* tp_new */ NULL, /* tp_free */ NULL, /* tp_is_gc */ NULL, /* tp_bases */ NULL, /* tp_mro */ NULL, /* tp_cache */ NULL, /* tp_subclasses */ NULL, /* tp_weaklist */ NULL, /* tp_del */ TP_VERSION_TAG_INIT /* tp_version_tag */ TP_FINALIZE_INIT /* tp_finalize */ }; PyObject* Init_pySpan_Type() { if (PyType_Ready(&pySpan_Type) < 0) return NULL; PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteMaterial", PyInt_FromLong(plSpan::kLiteMaterial)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropNoDraw", PyInt_FromLong(plSpan::kPropNoDraw)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropNoShadowCast", PyInt_FromLong(plSpan::kPropNoShadowCast)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropFacesSortable", PyInt_FromLong(plSpan::kPropFacesSortable)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropVolatile", PyInt_FromLong(plSpan::kPropVolatile)); PyDict_SetItemString(pySpan_Type.tp_dict, "kWaterHeight", PyInt_FromLong(plSpan::kWaterHeight)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropRunTimeLight", PyInt_FromLong(plSpan::kPropRunTimeLight)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropReverseSort", PyInt_FromLong(plSpan::kPropReverseSort)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropHasPermaLights", PyInt_FromLong(plSpan::kPropHasPermaLights)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropHasPermaProjs", PyInt_FromLong(plSpan::kPropHasPermaProjs)); PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteVtxPreshaded", PyInt_FromLong(plSpan::kLiteVtxPreshaded)); PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteVtxNonPreshaded", PyInt_FromLong(plSpan::kLiteVtxNonPreshaded)); PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteProjection", PyInt_FromLong(plSpan::kLiteProjection)); PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteShadowErase", PyInt_FromLong(plSpan::kLiteShadowErase)); PyDict_SetItemString(pySpan_Type.tp_dict, "kLiteShadow", PyInt_FromLong(plSpan::kLiteShadow)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropMatHasSpecular", PyInt_FromLong(plSpan::kPropMatHasSpecular)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropProjAsVtx", PyInt_FromLong(plSpan::kPropProjAsVtx)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropSkipProjection", PyInt_FromLong(plSpan::kPropSkipProjection)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropNoShadow", PyInt_FromLong(plSpan::kPropNoShadow)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropForceShadow", PyInt_FromLong(plSpan::kPropForceShadow)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropDisableNormal", PyInt_FromLong(plSpan::kPropDisableNormal)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPropCharacter", PyInt_FromLong(plSpan::kPropCharacter)); PyDict_SetItemString(pySpan_Type.tp_dict, "kPartialSort", PyInt_FromLong(plSpan::kPartialSort)); PyDict_SetItemString(pySpan_Type.tp_dict, "kVisLOS", PyInt_FromLong(plSpan::kVisLOS)); // plSpanType PyDict_SetItemString(pySpan_Type.tp_dict, "kSpan", PyInt_FromLong(plSpan::kSpan)); PyDict_SetItemString(pySpan_Type.tp_dict, "kVertexSpan", PyInt_FromLong(plSpan::kVertexSpan)); PyDict_SetItemString(pySpan_Type.tp_dict, "kIcicleSpan", PyInt_FromLong(plSpan::kIcicleSpan)); PyDict_SetItemString(pySpan_Type.tp_dict, "kNullSpan", PyInt_FromLong(plSpan::kNullSpan)); PyDict_SetItemString(pySpan_Type.tp_dict, "kParticleSpan", PyInt_FromLong(plSpan::kParticleSpan)); PyDict_SetItemString(pySpan_Type.tp_dict, "kParticleSet", PyInt_FromLong(plSpan::kParticleSet)); Py_INCREF(&pySpan_Type); return (PyObject*)&pySpan_Type; } int pySpan_Check(PyObject* obj) { if (obj->ob_type == &pySpan_Type || PyType_IsSubtype(obj->ob_type, &pySpan_Type)) return 1; return 0; } PyObject* pySpan_FromSpan(plSpan* span) { if (span == NULL) { Py_INCREF(Py_None); return Py_None; } pySpan* obj = PyObject_New(pySpan, &pySpan_Type); obj->fThis = span; obj->fPyOwned = false; return (PyObject*)obj; } }<|fim▁end|>
self->fThis->setBaseMatrix(PyInt_AsLong(value)); return 0; }
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from setuptools import setup, find_packages __doc__ = """ Falsify data """ version = '0.0.1' setup(name='perjury', version=version, description=__doc__, author='Aaron Merriam', author_email='[email protected]', keywords='content',<|fim▁hole|> license='BSD', test_suite='tests', classifiers=[ 'Development Status :: 3 - Alpha', 'Natural Language :: English', ], )<|fim▁end|>
long_description=__doc__, url='https://github.com/aaronmerriam/foundry', packages=find_packages(), platforms="any",
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>//! Variable header in MQTT use std::io; use std::string::FromUtf8Error; use crate::topic_name::{TopicNameDecodeError, TopicNameError}; pub use self::connect_ack_flags::ConnackFlags; pub use self::connect_flags::ConnectFlags; pub use self::connect_ret_code::ConnectReturnCode; pub use self::keep_alive::KeepAlive; pub use self::packet_identifier::PacketIdentifier; pub use self::protocol_level::ProtocolLevel; pub use self::protocol_name::ProtocolName; pub use self::topic_name::TopicNameHeader; mod connect_ack_flags; mod connect_flags; mod connect_ret_code; mod keep_alive; mod packet_identifier; pub mod protocol_level; mod protocol_name; mod topic_name; /// Errors while decoding variable header #[derive(Debug, thiserror::Error)] pub enum VariableHeaderError { #[error(transparent)] IoError(#[from] io::Error), #[error("invalid reserved flags")] InvalidReservedFlag, #[error(transparent)] FromUtf8Error(#[from] FromUtf8Error), #[error(transparent)] TopicNameError(#[from] TopicNameError), #[error("invalid protocol version")] InvalidProtocolVersion, }<|fim▁hole|> TopicNameDecodeError::IoError(e) => Self::IoError(e), TopicNameDecodeError::InvalidTopicName(e) => Self::TopicNameError(e), } } }<|fim▁end|>
impl From<TopicNameDecodeError> for VariableHeaderError { fn from(err: TopicNameDecodeError) -> VariableHeaderError { match err {
<|file_name|>mutating_webhook_manager.go<|end_file_name|><|fim▁begin|>/* Copyright 2017 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package configuration import ( "fmt"<|fim▁hole|> "k8s.io/api/admissionregistration/v1beta1" "k8s.io/apimachinery/pkg/labels" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apiserver/pkg/admission/plugin/webhook" "k8s.io/apiserver/pkg/admission/plugin/webhook/generic" "k8s.io/client-go/informers" admissionregistrationlisters "k8s.io/client-go/listers/admissionregistration/v1beta1" "k8s.io/client-go/tools/cache" ) // mutatingWebhookConfigurationManager collects the mutating webhook objects so that they can be called. type mutatingWebhookConfigurationManager struct { configuration *atomic.Value lister admissionregistrationlisters.MutatingWebhookConfigurationLister hasSynced func() bool } var _ generic.Source = &mutatingWebhookConfigurationManager{} func NewMutatingWebhookConfigurationManager(f informers.SharedInformerFactory) generic.Source { informer := f.Admissionregistration().V1beta1().MutatingWebhookConfigurations() manager := &mutatingWebhookConfigurationManager{ configuration: &atomic.Value{}, lister: informer.Lister(), hasSynced: informer.Informer().HasSynced, } // Start with an empty list manager.configuration.Store([]webhook.WebhookAccessor{}) // On any change, rebuild the config informer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(_ interface{}) { manager.updateConfiguration() }, UpdateFunc: func(_, _ interface{}) { manager.updateConfiguration() }, DeleteFunc: func(_ interface{}) { manager.updateConfiguration() }, }) return manager } // Webhooks returns the merged MutatingWebhookConfiguration. func (m *mutatingWebhookConfigurationManager) Webhooks() []webhook.WebhookAccessor { return m.configuration.Load().([]webhook.WebhookAccessor) } func (m *mutatingWebhookConfigurationManager) HasSynced() bool { return m.hasSynced() } func (m *mutatingWebhookConfigurationManager) updateConfiguration() { configurations, err := m.lister.List(labels.Everything()) if err != nil { utilruntime.HandleError(fmt.Errorf("error updating configuration: %v", err)) return } m.configuration.Store(mergeMutatingWebhookConfigurations(configurations)) } func mergeMutatingWebhookConfigurations(configurations []*v1beta1.MutatingWebhookConfiguration) []webhook.WebhookAccessor { // The internal order of webhooks for each configuration is provided by the user // but configurations themselves can be in any order. As we are going to run these // webhooks in serial, they are sorted here to have a deterministic order. sort.SliceStable(configurations, MutatingWebhookConfigurationSorter(configurations).ByName) accessors := []webhook.WebhookAccessor{} for _, c := range configurations { // webhook names are not validated for uniqueness, so we check for duplicates and // add a int suffix to distinguish between them names := map[string]int{} for i := range c.Webhooks { n := c.Webhooks[i].Name uid := fmt.Sprintf("%s/%s/%d", c.Name, n, names[n]) names[n]++ accessors = append(accessors, webhook.NewMutatingWebhookAccessor(uid, c.Name, &c.Webhooks[i])) } } return accessors } type MutatingWebhookConfigurationSorter []*v1beta1.MutatingWebhookConfiguration func (a MutatingWebhookConfigurationSorter) ByName(i, j int) bool { return a[i].Name < a[j].Name }<|fim▁end|>
"sort" "sync/atomic"
<|file_name|>NamespaceTestCase.js<|end_file_name|><|fim▁begin|>/* * Copyright 2012 Amadeus s.a.s. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Aria.classDefinition({ $classpath : "test.aria.storage.localStorage.NamespaceTestCase",<|fim▁hole|> $dependencies : ["aria.storage.LocalStorage"], $extends : "test.aria.storage.base.GeneralNamespaceBase", $constructor : function () { this.storageLocation = "localStorage"; this.$GeneralNamespaceBase.constructor.call(this); }, $prototype : { /** * Check what happens when you use namespaces, one namespaced shouldn't affect the others */ testNamespaceAPI : function () { if (this.canRunHTML5Tests(false) || this.canRunUserDataTests()) { this.$GeneralNamespaceBase.testNamespaceAPI.call(this); } }, /** * Verify if the events are raised correctly */ testNamespaceEvents : function () { if (this.canRunHTML5Tests(false) || this.canRunUserDataTests()) { this.$GeneralNamespaceBase.testNamespaceEvents.call(this); } } } });<|fim▁end|>
<|file_name|>upload.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python import argparse import errno import hashlib import os import shutil import subprocess import sys import tempfile from io import StringIO from lib.config import PLATFORM, get_target_arch, get_env_var, s3_config, \ get_zip_name from lib.util import electron_gyp, execute, get_electron_version, \ parse_version, scoped_cwd, s3put from lib.github import GitHub ELECTRON_REPO = 'electron/electron' ELECTRON_VERSION = get_electron_version() PROJECT_NAME = electron_gyp()['project_name%'] PRODUCT_NAME = electron_gyp()['product_name%'] SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) OUT_DIR = os.path.join(SOURCE_ROOT, 'out', 'R') DIST_DIR = os.path.join(SOURCE_ROOT, 'dist') DIST_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION) SYMBOLS_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'symbols') DSYM_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'dsym') PDB_NAME = get_zip_name(PROJECT_NAME, ELECTRON_VERSION, 'pdb') def main(): args = parse_args() if not args.publish_release: if not dist_newer_than_head(): run_python_script('create-dist.py') build_version = get_electron_build_version() if not ELECTRON_VERSION.startswith(build_version): error = 'Tag name ({0}) should match build version ({1})\n'.format( ELECTRON_VERSION, build_version) sys.stderr.write(error) sys.stderr.flush() return 1 github = GitHub(auth_token()) releases = github.repos(ELECTRON_REPO).releases.get() tag_exists = False for release in releases: if not release['draft'] and release['tag_name'] == args.version: tag_exists = True break release = create_or_get_release_draft(github, releases, args.version, tag_exists) if args.publish_release: # Upload the Node SHASUMS*.txt. run_python_script('upload-node-checksums.py', '-v', ELECTRON_VERSION) # Upload the index.json. run_python_script('upload-index-json.py') # Create and upload the Electron SHASUMS*.txt release_electron_checksums(github, release) # Press the publish button. publish_release(github, release['id']) # Do not upload other files when passed "-p". return # Upload Electron with GitHub Releases API. upload_electron(github, release, os.path.join(DIST_DIR, DIST_NAME)) upload_electron(github, release, os.path.join(DIST_DIR, SYMBOLS_NAME)) if PLATFORM == 'darwin': upload_electron(github, release, os.path.join(DIST_DIR, 'electron-api.json')) upload_electron(github, release, os.path.join(DIST_DIR, 'electron.d.ts')) upload_electron(github, release, os.path.join(DIST_DIR, DSYM_NAME)) elif PLATFORM == 'win32': upload_electron(github, release, os.path.join(DIST_DIR, PDB_NAME)) # Upload free version of ffmpeg. ffmpeg = get_zip_name('ffmpeg', ELECTRON_VERSION) upload_electron(github, release, os.path.join(DIST_DIR, ffmpeg)) # Upload chromedriver and mksnapshot for minor version update. if parse_version(args.version)[2] == '0': chromedriver = get_zip_name('chromedriver', ELECTRON_VERSION) upload_electron(github, release, os.path.join(DIST_DIR, chromedriver)) mksnapshot = get_zip_name('mksnapshot', ELECTRON_VERSION) upload_electron(github, release, os.path.join(DIST_DIR, mksnapshot)) if PLATFORM == 'win32' and not tag_exists: # Upload PDBs to Windows symbol server. run_python_script('upload-windows-pdb.py') # Upload node headers. run_python_script('create-node-headers.py', '-v', args.version) run_python_script('upload-node-headers.py', '-v', args.version) def parse_args(): parser = argparse.ArgumentParser(description='upload distribution file') parser.add_argument('-v', '--version', help='Specify the version', default=ELECTRON_VERSION) parser.add_argument('-p', '--publish-release', help='Publish the release', action='store_true') return parser.parse_args() def run_python_script(script, *args): script_path = os.path.join(SOURCE_ROOT, 'script', script) return execute([sys.executable, script_path] + list(args)) def get_electron_build_version(): if get_target_arch() == 'arm' or os.environ.has_key('CI'): # In CI we just build as told. return ELECTRON_VERSION if PLATFORM == 'darwin': electron = os.path.join(SOURCE_ROOT, 'out', 'R', '{0}.app'.format(PRODUCT_NAME), 'Contents', 'MacOS', PRODUCT_NAME) elif PLATFORM == 'win32': electron = os.path.join(SOURCE_ROOT, 'out', 'R', '{0}.exe'.format(PROJECT_NAME)) else: electron = os.path.join(SOURCE_ROOT, 'out', 'R', PROJECT_NAME) return subprocess.check_output([electron, '--version']).strip() def dist_newer_than_head(): with scoped_cwd(SOURCE_ROOT): try: head_time = subprocess.check_output(['git', 'log', '--pretty=format:%at', '-n', '1']).strip() dist_time = os.path.getmtime(os.path.join(DIST_DIR, DIST_NAME)) except OSError as e: if e.errno != errno.ENOENT: raise return False return dist_time > int(head_time) def get_text_with_editor(name): editor = os.environ.get('EDITOR', 'nano') initial_message = '\n# Please enter the body of your release note for %s.' \ % name t = tempfile.NamedTemporaryFile(suffix='.tmp', delete=False) t.write(initial_message) t.close() subprocess.call([editor, t.name]) text = '' for line in open(t.name, 'r'): if len(line) == 0 or line[0] != '#': text += line os.unlink(t.name) return text def create_or_get_release_draft(github, releases, tag, tag_exists): # Search for existing draft. for release in releases: if release['draft']: return release if tag_exists: tag = 'do-not-publish-me' return create_release_draft(github, tag) def create_release_draft(github, tag): name = '{0} {1}'.format(PROJECT_NAME, tag) if os.environ.has_key('CI'): body = '(placeholder)' else: body = get_text_with_editor(name) if body == '': sys.stderr.write('Quit due to empty release note.\n') sys.exit(0) data = dict(tag_name=tag, name=name, body=body, draft=True) r = github.repos(ELECTRON_REPO).releases.post(data=data) return r def release_electron_checksums(github, release): checksums = run_python_script('merge-electron-checksums.py', '-v', ELECTRON_VERSION) upload_io_to_github(github, release, 'SHASUMS256.txt', StringIO(checksums.decode('utf-8')), 'text/plain') def upload_electron(github, release, file_path): # Delete the original file before uploading in CI. filename = os.path.basename(file_path) if os.environ.has_key('CI'): try: for asset in release['assets']: if asset['name'] == filename: github.repos(ELECTRON_REPO).releases.assets(asset['id']).delete() except Exception: pass # Upload the file. with open(file_path, 'rb') as f: upload_io_to_github(github, release, filename, f, 'application/zip') # Upload the checksum file. upload_sha256_checksum(release['tag_name'], file_path) # Upload ARM assets without the v7l suffix for backwards compatibility # TODO Remove for 2.0 if 'armv7l' in filename: arm_filename = filename.replace('armv7l', 'arm') arm_file_path = os.path.join(os.path.dirname(file_path), arm_filename) shutil.copy2(file_path, arm_file_path) upload_electron(github, release, arm_file_path) def upload_io_to_github(github, release, name, io, content_type): params = {'name': name} headers = {'Content-Type': content_type} github.repos(ELECTRON_REPO).releases(release['id']).assets.post( params=params, headers=headers, data=io, verify=False) def upload_sha256_checksum(version, file_path): bucket, access_key, secret_key = s3_config() checksum_path = '{}.sha256sum'.format(file_path) sha256 = hashlib.sha256() with open(file_path, 'rb') as f: sha256.update(f.read()) filename = os.path.basename(file_path) with open(checksum_path, 'w') as checksum: checksum.write('{} *{}'.format(sha256.hexdigest(), filename)) s3put(bucket, access_key, secret_key, os.path.dirname(checksum_path), 'atom-shell/tmp/{0}'.format(version), [checksum_path]) def publish_release(github, release_id): data = dict(draft=False) github.repos(ELECTRON_REPO).releases(release_id).patch(data=data) def auth_token(): token = get_env_var('GITHUB_TOKEN')<|fim▁hole|> assert token, message return token if __name__ == '__main__': import sys sys.exit(main())<|fim▁end|>
message = ('Error: Please set the $ELECTRON_GITHUB_TOKEN ' 'environment variable, which is your personal token')
<|file_name|>ScheduleEventAddOptionsNextRequestHandler.java<|end_file_name|><|fim▁begin|>/** * Copyright (C) 2000 - 2013 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.scheduleevent.servlets.handlers; import javax.servlet.http.HttpServletRequest; import com.silverpeas.scheduleevent.control.ScheduleEventSessionController; public class ScheduleEventAddOptionsNextRequestHandler implements ScheduleEventRequestHandler { @Override public String getDestination(String function, ScheduleEventSessionController scheduleeventSC, HttpServletRequest request) throws Exception { // keep session object identical -> nothing to do request.setAttribute(CURRENT_SCHEDULE_EVENT, scheduleeventSC.getCurrentScheduleEvent()); return "form/optionshour.jsp"; } <|fim▁hole|><|fim▁end|>
}
<|file_name|>tankipas.js<|end_file_name|><|fim▁begin|>/* * grunt-tankipas * https://github.com/Leny/grunt-tankipas * * Copyright (c) 2014 Leny * Licensed under the MIT license. */ "use strict"; var chalk, error, spinner, tankipas; tankipas = require("tankipas"); chalk = require("chalk"); error = chalk.bold.red; (spinner = require("simple-spinner")).change_sequence(["◓", "◑", "◒", "◐"]); module.exports = function(grunt) { var tankipasTask; tankipasTask = function() { var fNext, oOptions; fNext = this.async(); oOptions = this.options({ system: null, gap: 120, user: null, branch: null, commit: null, raw: false }); spinner.start(50); return tankipas(process.cwd(), oOptions, function(oError, iTotal) { var iHours, iMinutes, sUserString; spinner.stop(); if (oError) {<|fim▁hole|> grunt.log.error(oError); fNext(false); } if (oOptions.raw) { grunt.log.writeln(iTotal); } else { iTotal /= 1000; iMinutes = (iMinutes = Math.floor(iTotal / 60)) > 60 ? iMinutes % 60 : iMinutes; iHours = Math.floor(iTotal / 3600); sUserString = oOptions.user ? " (for " + (chalk.cyan(oOptions.user)) + ")" : ""; grunt.log.writeln("Time spent on project" + sUserString + ": ±" + (chalk.yellow(iHours)) + " hours & " + (chalk.yellow(iMinutes)) + " minutes."); } return fNext(); }); }; if (grunt.config.data.tankipas) { return grunt.registerMultiTask("tankipas", "Compute approximate development time spent on a project, using logs from version control system.", tankipasTask); } else { return grunt.registerTask("tankipas", "Compute approximate development time spent on a project, using logs from version control system.", tankipasTask); } };<|fim▁end|>
<|file_name|>3.28.cpp<|end_file_name|><|fim▁begin|>#include <string> using std::string;<|fim▁hole|> string sa[10]; // ten elements of empty string int ia[10]; // ten elements of 0 int main() { string sa2[10]; // ten elements of empty string int ia2[10]; // ten elements of undefined value }<|fim▁end|>
<|file_name|>products.ts<|end_file_name|><|fim▁begin|>const product = [ { name: 'Bananas', description: 'Yummy yellow fruit', id: 'sku_GBJ2Ep8246qeeT', price: 400, image: 'https://images.unsplash.com/photo-1574226516831-e1dff420e562?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=225&q=80', attribution: 'Photo by Priscilla Du Preez on Unsplash', currency: 'USD', }, { name: 'Tangerines', id: 'sku_GBJ2WWfMaGNC2Z',<|fim▁hole|> attribution: 'Photo by Jonathan Pielmayer on Unsplash', currency: 'USD', }, ] export default product<|fim▁end|>
price: 100, image: 'https://images.unsplash.com/photo-1482012792084-a0c3725f289f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=225&q=80',
<|file_name|>anim-debug.js<|end_file_name|><|fim▁begin|>YUI.add('anim-base', function(Y) { /** * The Animation Utility provides an API for creating advanced transitions. * @module anim */ /** * Provides the base Anim class, for animating numeric properties. * * @module anim * @submodule anim-base */ /** * A class for constructing animation instances. * @class Anim * @for Anim * @constructor * @extends Base */ var RUNNING = 'running', START_TIME = 'startTime', ELAPSED_TIME = 'elapsedTime', /** * @for Anim * @event start * @description fires when an animation begins. * @param {Event} ev The start event. * @type Event.Custom */ START = 'start', /** * @event tween * @description fires every frame of the animation. * @param {Event} ev The tween event. * @type Event.Custom */ TWEEN = 'tween', /** * @event end * @description fires after the animation completes. * @param {Event} ev The end event. * @type Event.Custom */ END = 'end', NODE = 'node', PAUSED = 'paused', REVERSE = 'reverse', // TODO: cleanup ITERATION_COUNT = 'iterationCount', NUM = Number; var _running = {}, _instances = {}, _timer; Y.Anim = function() { Y.Anim.superclass.constructor.apply(this, arguments); _instances[Y.stamp(this)] = this; }; Y.Anim.NAME = 'anim'; /** * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ Y.Anim.RE_DEFAULT_UNIT = /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i; /** * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ Y.Anim.DEFAULT_UNIT = 'px'; Y.Anim.DEFAULT_EASING = function (t, b, c, d) { return c * t / d + b; // linear easing }; /** * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ Y.Anim._intervalTime = 20; /** * Bucket for custom getters and setters * * @property behaviors * @static */ Y.Anim.behaviors = { left: { get: function(anim, attr) { return anim._getOffset(attr); } } }; Y.Anim.behaviors.top = Y.Anim.behaviors.left; /** * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ Y.Anim.DEFAULT_SETTER = function(anim, att, from, to, elapsed, duration, fn, unit) { unit = unit || ''; anim._node.setStyle(att, fn(elapsed, NUM(from), NUM(to) - NUM(from), duration) + unit); }; /** * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ Y.Anim.DEFAULT_GETTER = function(anim, prop) { return anim._node.getComputedStyle(prop); }; Y.Anim.ATTRS = { /** * The object to be animated. * @attribute node * @type Node */ node: { setter: function(node) { node = Y.one(node); this._node = node; if (!node) { Y.log(node + ' is not a valid node', 'warn', 'Anim'); } return node; } }, /** * The length of the animation. Defaults to "1" (second). * @attribute duration * @type NUM */ duration: { value: 1 }, /** * The method that will provide values to the attribute(s) during the animation. * Defaults to "Easing.easeNone". * @attribute easing * @type Function */ easing: { value: Y.Anim.DEFAULT_EASING, setter: function(val) { if (typeof val === 'string' && Y.Easing) { return Y.Easing[val]; } } }, /** * The starting values for the animated properties. * Fields may be strings, numbers, or functions. * If a function is used, the return value becomes the from value. * If no from value is specified, the DEFAULT_GETTER will be used. * @attribute from * @type Object */ from: {}, /** * The ending values for the animated properties. * Fields may be strings, numbers, or functions. * @attribute to * @type Object */ to: {}, /** * Date stamp for the first frame of the animation. * @attribute startTime * @type Int * @default 0 * @readOnly */ startTime: { value: 0, readOnly: true }, /** * Current time the animation has been running. * @attribute elapsedTime * @type Int * @default 0 * @readOnly */ elapsedTime: { value: 0, readOnly: true }, /** * Whether or not the animation is currently running. * @attribute running * @type Boolean * @default false * @readOnly */ running: { getter: function() { return !!_running[Y.stamp(this)]; }, value: false, readOnly: true }, /** * The number of times the animation should run * @attribute iterations * @type Int * @default 1 */ iterations: { value: 1 }, /** * The number of iterations that have occurred. * Resets when an animation ends (reaches iteration count or stop() called). * @attribute iterationCount * @type Int * @default 0 * @readOnly */ iterationCount: { value: 0, readOnly: true }, /** * How iterations of the animation should behave. * Possible values are "normal" and "alternate". * Normal will repeat the animation, alternate will reverse on every other pass. * * @attribute direction * @type String * @default "normal" */ direction: { value: 'normal' // | alternate (fwd on odd, rev on even per spec) }, /** * Whether or not the animation is currently paused. * @attribute paused * @type Boolean * @default false * @readOnly */ paused: { readOnly: true, value: false }, /** * If true, animation begins from last frame * @attribute reverse * @type Boolean * @default false */ reverse: { value: false } }; /** * Runs all animation instances. * @method run * @static */ Y.Anim.run = function() { for (var i in _instances) { if (_instances[i].run) { _instances[i].run(); } } }; /** * Pauses all animation instances. * @method pause * @static */ Y.Anim.pause = function() { for (var i in _running) { // stop timer if nothing running if (_running[i].pause) { _running[i].pause(); } } Y.Anim._stopTimer(); }; /** * Stops all animation instances. * @method stop * @static */ Y.Anim.stop = function() { for (var i in _running) { // stop timer if nothing running if (_running[i].stop) { _running[i].stop(); } } Y.Anim._stopTimer(); }; Y.Anim._startTimer = function() { if (!_timer) { _timer = setInterval(Y.Anim._runFrame, Y.Anim._intervalTime); } }; Y.Anim._stopTimer = function() { clearInterval(_timer); _timer = 0; }; /** * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ Y.Anim._runFrame = function() { var done = true; for (var anim in _running) { if (_running[anim]._runFrame) { done = false; _running[anim]._runFrame(); } } if (done) { Y.Anim._stopTimer(); } }; Y.Anim.RE_UNITS = /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/; var proto = { /** * Starts or resumes an animation. * @method run * @chainable */ run: function() { if (this.get(PAUSED)) { this._resume(); } else if (!this.get(RUNNING)) { this._start(); } return this; }, /** * Pauses the animation and * freezes it in its current state and time. * Calling run() will continue where it left off. * @method pause * @chainable */ pause: function() { if (this.get(RUNNING)) { this._pause(); } return this; }, /** * Stops the animation and resets its time. * @method stop * @chainable */ stop: function(finish) { if (this.get(RUNNING) || this.get(PAUSED)) { this._end(finish); } return this; }, _added: false, _start: function() { this._set(START_TIME, new Date() - this.get(ELAPSED_TIME)); this._actualFrames = 0; if (!this.get(PAUSED)) { this._initAnimAttr(); } _running[Y.stamp(this)] = this; Y.Anim._startTimer(); this.fire(START); }, _pause: function() { this._set(START_TIME, null); this._set(PAUSED, true); delete _running[Y.stamp(this)]; /** * @event pause * @description fires when an animation is paused. * @param {Event} ev The pause event. * @type Event.Custom */ this.fire('pause'); }, _resume: function() { this._set(PAUSED, false); _running[Y.stamp(this)] = this; /** * @event resume * @description fires when an animation is resumed (run from pause). * @param {Event} ev The pause event. * @type Event.Custom */ this.fire('resume'); }, _end: function(finish) { var duration = this.get('duration') * 1000; if (finish) { // jump to last frame this._runAttrs(duration, duration, this.get(REVERSE)); } this._set(START_TIME, null); this._set(ELAPSED_TIME, 0); this._set(PAUSED, false); delete _running[Y.stamp(this)]; this.fire(END, {elapsed: this.get(ELAPSED_TIME)}); }, _runFrame: function() { var d = this._runtimeAttr.duration, t = new Date() - this.get(START_TIME), reverse = this.get(REVERSE), done = (t >= d), attribute, setter; this._runAttrs(t, d, reverse); this._actualFrames += 1; this._set(ELAPSED_TIME, t); this.fire(TWEEN); if (done) { this._lastFrame(); } }, _runAttrs: function(t, d, reverse) { var attr = this._runtimeAttr, customAttr = Y.Anim.behaviors, easing = attr.easing, lastFrame = d, attribute, setter, i; if (reverse) { t = d - t; lastFrame = 0; } for (i in attr) { if (attr[i].to) { attribute = attr[i]; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Y.Anim.DEFAULT_SETTER; if (t < d) { setter(this, i, attribute.from, attribute.to, t, d, easing, attribute.unit); } else { setter(this, i, attribute.from, attribute.to, lastFrame, d, easing, attribute.unit); } } } }, _lastFrame: function() { var iter = this.get('iterations'), iterCount = this.get(ITERATION_COUNT); iterCount += 1; if (iter === 'infinite' || iterCount < iter) { if (this.get('direction') === 'alternate') { this.set(REVERSE, !this.get(REVERSE)); // flip it } /** * @event iteration * @description fires when an animation begins an iteration. * @param {Event} ev The iteration event. * @type Event.Custom */ this.fire('iteration'); } else { iterCount = 0; this._end(); } this._set(START_TIME, new Date()); this._set(ITERATION_COUNT, iterCount); }, _initAnimAttr: function() { var from = this.get('from') || {}, to = this.get('to') || {}, attr = { duration: this.get('duration') * 1000, easing: this.get('easing') }, customAttr = Y.Anim.behaviors, node = this.get(NODE), // implicit attr init unit, begin, end; Y.each(to, function(val, name) { if (typeof val === 'function') { val = val.call(this, node); } begin = from[name]; if (begin === undefined) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(this, name) : Y.Anim.DEFAULT_GETTER(this, name); } else if (typeof begin === 'function') { begin = begin.call(this, node); } var mFrom = Y.Anim.RE_UNITS.exec(begin); var mTo = Y.Anim.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Y.Anim.RE_DEFAULT_UNIT.test(name)) { unit = Y.Anim.DEFAULT_UNIT; } if (!begin || !end) { Y.error('invalid "from" or "to" for "' + name + '"', 'Anim'); return; } attr[name] = { from: begin, to: end, unit: unit }; }, this); this._runtimeAttr = attr; }, // TODO: move to computedStyle? (browsers dont agree on default computed offsets) _getOffset: function(attr) { var node = this._node, val = node.getComputedStyle(attr), get = (attr === 'left') ? 'getX': 'getY', set = (attr === 'left') ? 'setX': 'setY'; if (val === 'auto') { var position = node.getStyle('position'); if (position === 'absolute' || position === 'fixed') { val = node[get](); node[set](val); } else { val = 0; } } return val; } }; Y.extend(Y.Anim, Y.Base, proto); }, '@VERSION@' ,{requires:['base-base', 'node-style']}); YUI.add('anim-color', function(Y) { /** * Adds support for color properties in <code>to</code> * and <code>from</code> attributes. * @module anim * @submodule anim-color<|fim▁hole|> Y.Anim.behaviors.color = { set: function(anim, att, from, to, elapsed, duration, fn) { from = Y.Color.re_RGB.exec(Y.Color.toRGB(from)); to = Y.Color.re_RGB.exec(Y.Color.toRGB(to)); if (!from || from.length < 3 || !to || to.length < 3) { Y.error('invalid from or to passed to color behavior'); } anim._node.setStyle(att, 'rgb(' + [ Math.floor(fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration)), Math.floor(fn(elapsed, NUM(from[2]), NUM(to[2]) - NUM(from[2]), duration)), Math.floor(fn(elapsed, NUM(from[3]), NUM(to[3]) - NUM(from[3]), duration)) ].join(', ') + ')'); }, // TODO: default bgcolor const get: function(anim, att) { var val = anim._node.getComputedStyle(att); val = (val === 'transparent') ? 'rgb(255, 255, 255)' : val; return val; } }; Y.each(['backgroundColor', 'borderColor', 'borderTopColor', 'borderRightColor', 'borderBottomColor', 'borderLeftColor'], function(v, i) { Y.Anim.behaviors[v] = Y.Anim.behaviors.color; } ); }, '@VERSION@' ,{requires:['anim-base']}); YUI.add('anim-curve', function(Y) { /** * Adds support for the <code>curve</code> property for the <code>to</code> * attribute. A curve is zero or more control points and an end point. * @module anim * @submodule anim-curve */ Y.Anim.behaviors.curve = { set: function(anim, att, from, to, elapsed, duration, fn) { from = from.slice.call(from); to = to.slice.call(to); var t = fn(elapsed, 0, 100, duration) / 100; to.unshift(from); anim._node.setXY(Y.Anim.getBezier(to, t)); }, get: function(anim, att) { return anim._node.getXY(); } }; /** * Get the current position of the animated element based on t. * Each point is an array of "x" and "y" values (0 = x, 1 = y) * At least 2 points are required (start and end). * First point is start. Last point is end. * Additional control points are optional. * @for Anim * @method getBezier * @static * @param {Array} points An array containing Bezier points * @param {Number} t A number between 0 and 1 which is the basis for determining current position * @return {Array} An array containing int x and y member data */ Y.Anim.getBezier = function(points, t) { var n = points.length; var tmp = []; for (var i = 0; i < n; ++i){ tmp[i] = [points[i][0], points[i][1]]; // save input } for (var j = 1; j < n; ++j) { for (i = 0; i < n - j; ++i) { tmp[i][0] = (1 - t) * tmp[i][0] + t * tmp[parseInt(i + 1, 10)][0]; tmp[i][1] = (1 - t) * tmp[i][1] + t * tmp[parseInt(i + 1, 10)][1]; } } return [ tmp[0][0], tmp[0][1] ]; }; }, '@VERSION@' ,{requires:['anim-xy']}); YUI.add('anim-easing', function(Y) { /* TERMS OF USE - EASING EQUATIONS Open source under the BSD License. Copyright 2001 Robert Penner All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * The easing module provides methods for customizing * how an animation behaves during each run. * @class Easing * @module anim * @submodule anim-easing */ Y.Easing = { /** * Uniform speed between points. * @for Easing * @method easeNone * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeNone: function (t, b, c, d) { return c*t/d + b; }, /** * Begins slowly and accelerates towards end. (quadratic) * @method easeIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeIn: function (t, b, c, d) { return c*(t/=d)*t + b; }, /** * Begins quickly and decelerates towards end. (quadratic) * @method easeOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeOut: function (t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, /** * Begins slowly and decelerates towards end. (quadratic) * @method easeBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeBoth: function (t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t + b; } return -c/2 * ((--t)*(t-2) - 1) + b; }, /** * Begins slowly and accelerates towards end. (quartic) * @method easeInStrong * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeInStrong: function (t, b, c, d) { return c*(t/=d)*t*t*t + b; }, /** * Begins quickly and decelerates towards end. (quartic) * @method easeOutStrong * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeOutStrong: function (t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, /** * Begins slowly and decelerates towards end. (quartic) * @method easeBothStrong * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ easeBothStrong: function (t, b, c, d) { if ((t/=d/2) < 1) { return c/2*t*t*t*t + b; } return -c/2 * ((t-=2)*t*t*t - 2) + b; }, /** * Snap in elastic effect. * @method elasticIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} a Amplitude (optional) * @param {Number} p Period (optional) * @return {Number} The computed value for the current animation frame */ elasticIn: function (t, b, c, d, a, p) { var s; if (t === 0) { return b; } if ( (t /= d) === 1 ) { return b+c; } if (!p) { p = d* 0.3; } if (!a || a < Math.abs(c)) { a = c; s = p/4; } else { s = p/(2*Math.PI) * Math.asin (c/a); } return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, /** * Snap out elastic effect. * @method elasticOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} a Amplitude (optional) * @param {Number} p Period (optional) * @return {Number} The computed value for the current animation frame */ elasticOut: function (t, b, c, d, a, p) { var s; if (t === 0) { return b; } if ( (t /= d) === 1 ) { return b+c; } if (!p) { p=d * 0.3; } if (!a || a < Math.abs(c)) { a = c; s = p / 4; } else { s = p/(2*Math.PI) * Math.asin (c/a); } return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, /** * Snap both elastic effect. * @method elasticBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} a Amplitude (optional) * @param {Number} p Period (optional) * @return {Number} The computed value for the current animation frame */ elasticBoth: function (t, b, c, d, a, p) { var s; if (t === 0) { return b; } if ( (t /= d/2) === 2 ) { return b+c; } if (!p) { p = d*(0.3*1.5); } if ( !a || a < Math.abs(c) ) { a = c; s = p/4; } else { s = p/(2*Math.PI) * Math.asin (c/a); } if (t < 1) { return -0.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; } return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b; }, /** * Backtracks slightly, then reverses direction and moves to end. * @method backIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} s Overshoot (optional) * @return {Number} The computed value for the current animation frame */ backIn: function (t, b, c, d, s) { if (s === undefined) { s = 1.70158; } if (t === d) { t -= 0.001; } return c*(t/=d)*t*((s+1)*t - s) + b; }, /** * Overshoots end, then reverses and comes back to end. * @method backOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} s Overshoot (optional) * @return {Number} The computed value for the current animation frame */ backOut: function (t, b, c, d, s) { if (typeof s === 'undefined') { s = 1.70158; } return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, /** * Backtracks slightly, then reverses direction, overshoots end, * then reverses and comes back to end. * @method backBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @param {Number} s Overshoot (optional) * @return {Number} The computed value for the current animation frame */ backBoth: function (t, b, c, d, s) { if (typeof s === 'undefined') { s = 1.70158; } if ((t /= d/2 ) < 1) { return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; } return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, /** * Bounce off of start. * @method bounceIn * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ bounceIn: function (t, b, c, d) { return c - Y.Easing.bounceOut(d-t, 0, c, d) + b; }, /** * Bounces off end. * @method bounceOut * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ bounceOut: function (t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b; } return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b; }, /** * Bounces off start and end. * @method bounceBoth * @param {Number} t Time value used to compute current value * @param {Number} b Starting value * @param {Number} c Delta between start and end values * @param {Number} d Total length of animation * @return {Number} The computed value for the current animation frame */ bounceBoth: function (t, b, c, d) { if (t < d/2) { return Y.Easing.bounceIn(t * 2, 0, c, d) * 0.5 + b; } return Y.Easing.bounceOut(t * 2 - d, 0, c, d) * 0.5 + c * 0.5 + b; } }; }, '@VERSION@' ,{requires:['anim-base']}); YUI.add('anim-node-plugin', function(Y) { /** * Binds an Anim instance to a Node instance * @module anim * @class Plugin.NodeFX * @extends Base * @submodule anim-node-plugin */ var NodeFX = function(config) { config = (config) ? Y.merge(config) : {}; config.node = config.host; NodeFX.superclass.constructor.apply(this, arguments); }; NodeFX.NAME = "nodefx"; NodeFX.NS = "fx"; Y.extend(NodeFX, Y.Anim); Y.namespace('Plugin'); Y.Plugin.NodeFX = NodeFX; }, '@VERSION@' ,{requires:['node-pluginhost', 'anim-base']}); YUI.add('anim-scroll', function(Y) { /** * Adds support for the <code>scroll</code> property in <code>to</code> * and <code>from</code> attributes. * @module anim * @submodule anim-scroll */ var NUM = Number; //TODO: deprecate for scrollTop/Left properties? Y.Anim.behaviors.scroll = { set: function(anim, att, from, to, elapsed, duration, fn) { var node = anim._node, val = ([ fn(elapsed, NUM(from[0]), NUM(to[0]) - NUM(from[0]), duration), fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration) ]); if (val[0]) { node.set('scrollLeft', val[0]); } if (val[1]) { node.set('scrollTop', val[1]); } }, get: function(anim) { var node = anim._node; return [node.get('scrollLeft'), node.get('scrollTop')]; } }; }, '@VERSION@' ,{requires:['anim-base']}); YUI.add('anim-xy', function(Y) { /** * Adds support for the <code>xy</code> property in <code>from</code> and * <code>to</code> attributes. * @module anim * @submodule anim-xy */ var NUM = Number; Y.Anim.behaviors.xy = { set: function(anim, att, from, to, elapsed, duration, fn) { anim._node.setXY([ fn(elapsed, NUM(from[0]), NUM(to[0]) - NUM(from[0]), duration), fn(elapsed, NUM(from[1]), NUM(to[1]) - NUM(from[1]), duration) ]); }, get: function(anim) { return anim._node.getXY(); } }; }, '@VERSION@' ,{requires:['anim-base', 'node-screen']}); YUI.add('anim', function(Y){}, '@VERSION@' ,{use:['anim-base', 'anim-color', 'anim-curve', 'anim-easing', 'anim-node-plugin', 'anim-scroll', 'anim-xy'], skinnable:false});<|fim▁end|>
*/ var NUM = Number;
<|file_name|>issue-44730.rs<|end_file_name|><|fim▁begin|>// check-pass //! dox #![deny(missing_docs)] macro_rules! doc { ($e:expr) => ( #[doc = $e] pub struct Foo; ) } doc!("a"); <|fim▁hole|>fn main() {}<|fim▁end|>
<|file_name|>decompose.rs<|end_file_name|><|fim▁begin|>// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::fmt::{self, Write}; #[derive(Clone)] enum DecompositionType { Canonical, Compatible } /// External iterator for a string decomposition's characters. #[derive(Clone)] pub struct Decompositions<I> { kind: DecompositionType, iter: I, done: bool, // This buffer stores pairs of (canonical combining class, character), // pushed onto the end in text order. // // It's split into two contiguous regions by the `ready` offset. The first // `ready` pairs are sorted and ready to emit on demand. The "pending" // suffix afterwards still needs more characters for us to be able to sort // in canonical order and is not safe to emit. buffer: Vec<(u8, char)>, ready: usize, } #[inline] pub fn new_canonical<I: Iterator<Item=char>>(iter: I) -> Decompositions<I> { Decompositions { kind: self::DecompositionType::Canonical, iter: iter, done: false, buffer: Vec::new(), ready: 0, } } #[inline] pub fn new_compatible<I: Iterator<Item=char>>(iter: I) -> Decompositions<I> { Decompositions { kind: self::DecompositionType::Compatible, iter: iter, done: false, buffer: Vec::new(), ready: 0, } } impl<I> Decompositions<I> { #[inline] fn push_back(&mut self, ch: char) { let class = super::char::canonical_combining_class(ch); if class == 0 {<|fim▁hole|> self.sort_pending(); } self.buffer.push((class, ch)); } #[inline] fn sort_pending(&mut self) { if self.ready == 0 && self.buffer.is_empty() { return; } // NB: `sort_by_key` is stable, so it will preserve the original text's // order within a combining class. self.buffer[self.ready..].sort_by_key(|k| k.0); self.ready = self.buffer.len(); } #[inline] fn pop_front(&mut self) -> Option<char> { if self.ready == 0 { None } else { self.ready -= 1; Some(self.buffer.remove(0).1) } } } impl<I: Iterator<Item=char>> Iterator for Decompositions<I> { type Item = char; #[inline] fn next(&mut self) -> Option<char> { while self.ready == 0 && !self.done { match (self.iter.next(), &self.kind) { (Some(ch), &DecompositionType::Canonical) => { super::char::decompose_canonical(ch, |d| self.push_back(d)); }, (Some(ch), &DecompositionType::Compatible) => { super::char::decompose_compatible(ch, |d| self.push_back(d)); }, (None, _) => { self.sort_pending(); self.done = true; }, } } self.pop_front() } fn size_hint(&self) -> (usize, Option<usize>) { let (lower, _) = self.iter.size_hint(); (lower, None) } } impl<I: Iterator<Item=char> + Clone> fmt::Display for Decompositions<I> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { for c in self.clone() { f.write_char(c)?; } Ok(()) } }<|fim▁end|>
<|file_name|>session_plus.go<|end_file_name|><|fim▁begin|>// Copyright 2015 The Xorm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package xorm import ( "database/sql" "encoding/json" "fmt" "os" "reflect" "regexp" "strings" "github.com/Chronokeeper/anyxml" "github.com/xormplus/xorm/core" "github.com/xormplus/xorm/dialects" "github.com/xormplus/xorm/internal/utils" "github.com/xormplus/xorm/schemas" ) type Record map[string]Value type Result []Record type ResultValue struct { Result Result Error error } func (resultValue *ResultValue) List() (Result, error) { return resultValue.Result, resultValue.Error } func (resultValue *ResultValue) Count() (int, error) { if resultValue.Error != nil { return 0, resultValue.Error } if resultValue.Result == nil { return 0, nil } return len(resultValue.Result), nil } func (resultValue *ResultValue) ListPage(firstResult int, maxResults int) (Result, error) { if resultValue.Error != nil { return nil, resultValue.Error } if resultValue.Result == nil { return nil, nil } if firstResult > maxResults { return nil, ErrParamsFormat } if firstResult < 0 { return nil, ErrParamsFormat } if maxResults < 0 { return nil, ErrParamsFormat } if maxResults > len(resultValue.Result) { return nil, ErrParamsFormat } return resultValue.Result[(firstResult - 1):maxResults], resultValue.Error } type ResultBean struct { Has bool Result interface{} Error error } func (resultBean *ResultBean) Json() (bool, string, error) { if resultBean.Error != nil { return resultBean.Has, "", resultBean.Error } if !resultBean.Has { return resultBean.Has, "", nil } result, err := JSONString(resultBean.Result, true) return resultBean.Has, result, err } func (resultBean *ResultBean) GetResult() (bool, interface{}, error) { return resultBean.Has, resultBean.Result, resultBean.Error } func (session *Session) GetFirst(bean interface{}) *ResultBean { has, err := session.Get(bean) r := &ResultBean{Has: has, Result: bean, Error: err} return r } func (resultBean *ResultBean) Xml() (bool, string, error) { if resultBean.Error != nil { return false, "", resultBean.Error } if !resultBean.Has { return resultBean.Has, "", nil } has, result, err := resultBean.Json() if err != nil { return false, "", err } if !has { return has, "", nil } var anydata = []byte(result) var i interface{} err = json.Unmarshal(anydata, &i) if err != nil { return false, "", err } resultByte, err := anyxml.Xml(i) if err != nil { return false, "", err } return resultBean.Has, string(resultByte), err } func (resultBean *ResultBean) XmlIndent(prefix string, indent string, recordTag string) (bool, string, error) { if resultBean.Error != nil { return false, "", resultBean.Error } if !resultBean.Has { return resultBean.Has, "", nil } has, result, err := resultBean.Json() if err != nil { return false, "", err } if !has { return has, "", nil } var anydata = []byte(result) var i interface{} err = json.Unmarshal(anydata, &i) if err != nil { return false, "", err } resultByte, err := anyxml.XmlIndent(i, prefix, indent, recordTag) if err != nil { return false, "", err } return resultBean.Has, string(resultByte), err } type ResultMap struct { Result []map[string]interface{} Error error } func (resultMap *ResultMap) List() ([]map[string]interface{}, error) { return resultMap.Result, resultMap.Error } func (resultMap *ResultMap) Count() (int, error) { if resultMap.Error != nil { return 0, resultMap.Error } if resultMap.Result == nil { return 0, nil } return len(resultMap.Result), nil } func (resultMap *ResultMap) ListPage(firstResult int, maxResults int) ([]map[string]interface{}, error) { if resultMap.Error != nil { return nil, resultMap.Error } if resultMap.Result == nil { return nil, nil } if firstResult > maxResults { return nil, ErrParamsFormat } if firstResult < 0 { return nil, ErrParamsFormat } if maxResults < 0 { return nil, ErrParamsFormat } if maxResults > len(resultMap.Result) { return nil, ErrParamsFormat } return resultMap.Result[(firstResult - 1):maxResults], resultMap.Error } func (resultMap *ResultMap) Json() (string, error) { if resultMap.Error != nil { return "", resultMap.Error } return JSONString(resultMap.Result, true) } func (resultMap *ResultMap) Xml() (string, error) { if resultMap.Error != nil { return "", resultMap.Error } results, err := anyxml.Xml(resultMap.Result) if err != nil { return "", err } return string(results), nil } func (resultMap *ResultMap) XmlIndent(prefix string, indent string, recordTag string) (string, error) { if resultMap.Error != nil { return "", resultMap.Error } results, err := anyxml.XmlIndent(resultMap.Result, prefix, indent, recordTag) if err != nil { return "", err } return string(results), nil } func (resultMap *ResultMap) SaveAsCSV(filename string, headers []string, perm os.FileMode) error { if resultMap.Error != nil { return resultMap.Error } dataset, err := NewDatasetWithData(headers, resultMap.Result, true) if err != nil { return err } csv, err := dataset.CSV() if err != nil { return err } return csv.WriteFile(filename, perm) } func (resultMap *ResultMap) SaveAsTSV(filename string, headers []string, perm os.FileMode) error { if resultMap.Error != nil { return resultMap.Error } dataset, err := NewDatasetWithData(headers, resultMap.Result, true) if err != nil { return err } tsv, err := dataset.TSV() if err != nil { return err } return tsv.WriteFile(filename, perm) } func (resultMap *ResultMap) SaveAsHTML(filename string, headers []string, perm os.FileMode) error { if resultMap.Error != nil { return resultMap.Error } dataset, err := NewDatasetWithData(headers, resultMap.Result, true) if err != nil { return err } html := dataset.HTML() return html.WriteFile(filename, perm) } func (resultMap *ResultMap) SaveAsXML(filename string, headers []string, perm os.FileMode) error { if resultMap.Error != nil { return resultMap.Error } dataset, err := NewDatasetWithData(headers, resultMap.Result, false) if err != nil { return err } xml, err := dataset.XML() if err != nil { return err } return xml.WriteFile(filename, perm) } func (resultMap *ResultMap) SaveAsXMLWithTagNamePrefixIndent(tagName string, prifix string, indent string, filename string, headers []string, perm os.FileMode) error { if resultMap.Error != nil { return resultMap.Error } dataset, err := NewDatasetWithData(headers, resultMap.Result, false) if err != nil { return err } xml, err := dataset.XMLWithTagNamePrefixIndent(tagName, prifix, indent) if err != nil { return err } return xml.WriteFile(filename, perm) } func (resultMap *ResultMap) SaveAsYAML(filename string, headers []string, perm os.FileMode) error { if resultMap.Error != nil { return resultMap.Error } dataset, err := NewDatasetWithData(headers, resultMap.Result, false) if err != nil { return err } yaml, err := dataset.YAML() if err != nil { return err } return yaml.WriteFile(filename, perm) } func (resultMap *ResultMap) SaveAsJSON(filename string, headers []string, perm os.FileMode) error { if resultMap.Error != nil { return resultMap.Error } dataset, err := NewDatasetWithData(headers, resultMap.Result, false) if err != nil { return err } json, err := dataset.JSON() if err != nil { return err } return json.WriteFile(filename, perm) } func (resultMap *ResultMap) SaveAsXLSX(filename string, headers []string, perm os.FileMode) error { if resultMap.Error != nil { return resultMap.Error } dataset, err := NewDatasetWithData(headers, resultMap.Result, true) if err != nil { return err } xlsx, err := dataset.XLSX() if err != nil { return err } return xlsx.WriteFile(filename, perm) } type ResultStructs struct { Result interface{} Error error } func (resultStructs *ResultStructs) Json() (string, error) { if resultStructs.Error != nil { return "", resultStructs.Error } return JSONString(resultStructs.Result, true) } func (resultStructs *ResultStructs) Xml() (string, error) { if resultStructs.Error != nil { return "", resultStructs.Error } result, err := resultStructs.Json() if err != nil { return "", err } var anydata = []byte(result) var i interface{} err = json.Unmarshal(anydata, &i) if err != nil { return "", err } resultByte, err := anyxml.Xml(i) if err != nil { return "", err } return string(resultByte), nil } func (resultStructs *ResultStructs) XmlIndent(prefix string, indent string, recordTag string) (string, error) { if resultStructs.Error != nil { return "", resultStructs.Error } result, err := resultStructs.Json() if err != nil { return "", err } var anydata = []byte(result) var i interface{} err = json.Unmarshal(anydata, &i) if err != nil { return "", err } resultByte, err := anyxml.XmlIndent(i, prefix, indent, recordTag) if err != nil { return "", err } return string(resultByte), nil } func (session *Session) SqlMapClient(sqlTagName string, args ...interface{}) *Session { return session.SQL(session.engine.SqlMap.Sql[sqlTagName], args...) } func (session *Session) SqlTemplateClient(sqlTagName string, args ...interface{}) *Session { session.isSqlFunc = true sql, err := session.engine.SqlTemplate.Execute(sqlTagName, args...) if err != nil { session.engine.logger.Errorf("%v", err) } if len(args) == 0 { return session.SQL(sql) } else { map1 := args[0].(*map[string]interface{}) return session.SQL(sql, map1) } } func (session *Session) Search(rowsSlicePtr interface{}, condiBean ...interface{}) *ResultStructs { err := session.Find(rowsSlicePtr, condiBean...) r := &ResultStructs{Result: rowsSlicePtr, Error: err} return r } func (session *Session) genSelectSql(dialect dialects.Dialect, rownumber string) string { var sql = session.statement.RawSQL var orderBys = session.statement.OrderStr pLimitN := session.statement.LimitN if dialect.URI().DBType != schemas.MSSQL && dialect.URI().DBType != schemas.ORACLE { if session.statement.Start > 0 { if pLimitN != nil { sql = fmt.Sprintf("%v LIMIT %v OFFSET %v", sql, *pLimitN, session.statement.Start) } else { sql = fmt.Sprintf("%v LIMIT 0 OFFSET %v", sql, *pLimitN) } } else if pLimitN != nil { sql = fmt.Sprintf("%v LIMIT %v", sql, *pLimitN) } } else if dialect.URI().DBType == schemas.ORACLE { if session.statement.Start != 0 || pLimitN != nil { sql = fmt.Sprintf("SELECT aat.* FROM (SELECT at.*,ROWNUM %v FROM (%v) at WHERE ROWNUM <= %d) aat WHERE %v > %d", rownumber, sql, session.statement.Start+*pLimitN, rownumber, session.statement.Start) } } else { keepSelect := false var fullQuery string if session.statement.Start > 0 { fullQuery = fmt.Sprintf("SELECT sq.* FROM (SELECT ROW_NUMBER() OVER (ORDER BY %v) AS %v,", orderBys, rownumber) } else if pLimitN != nil { fullQuery = fmt.Sprintf("SELECT TOP %d", *pLimitN) } else { keepSelect = true } if !keepSelect { expr := `^\s*SELECT\s*` reg, err := regexp.Compile(expr) if err != nil { fmt.Println(err) } sql = strings.ToUpper(sql) if reg.MatchString(sql) { str := reg.FindAllString(sql, -1) fullQuery = fmt.Sprintf("%v %v", fullQuery, sql[len(str[0]):]) } } if session.statement.Start > 0 { // T-SQL offset starts with 1, not like MySQL with 0; if pLimitN != nil { fullQuery = fmt.Sprintf("%v) AS sq WHERE %v BETWEEN %d AND %d", fullQuery, rownumber, session.statement.Start+1, session.statement.Start+*pLimitN) } else { fullQuery = fmt.Sprintf("%v) AS sq WHERE %v >= %d", fullQuery, rownumber, session.statement.Start+1) } } else { fullQuery = fmt.Sprintf("%v ORDER BY %v", fullQuery, orderBys) } if keepSelect { if len(orderBys) > 0 { sql = fmt.Sprintf("%v ORDER BY %v", sql, orderBys) } } else { sql = fullQuery } }<|fim▁hole|> // Exec a raw sql and return records as ResultMap func (session *Session) Query() *ResultMap { defer session.resetStatement() if session.isAutoClose { defer session.Close() } var dialect = session.engine.Dialect() rownumber := "xorm" + utils.NewShortUUID().String() sql := session.genSelectSql(dialect, rownumber) params := session.statement.RawParams i := len(params) var result []map[string]interface{} var err error if i == 1 { vv := reflect.ValueOf(params[0]) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map { result, err = session.queryAll(sql, params...) } else { result, err = session.queryAllByMap(sql, params[0]) } } else { result, err = session.queryAll(sql, params...) } pLimitN := session.statement.LimitN if dialect.URI().DBType == schemas.MSSQL { if session.statement.Start > 0 { for i, _ := range result { delete(result[i], rownumber) } } } else if dialect.URI().DBType == schemas.ORACLE { if session.statement.Start != 0 || pLimitN != nil { for i, _ := range result { delete(result[i], rownumber) } } } r := &ResultMap{Result: result, Error: err} return r } // Exec a raw sql and return records as ResultMap func (session *Session) QueryWithDateFormat(dateFormat string) *ResultMap { defer session.resetStatement() if session.isAutoClose { defer session.Close() } var dialect = session.engine.Dialect() rownumber := "xorm" + utils.NewShortUUID().String() sql := session.genSelectSql(dialect, rownumber) params := session.statement.RawParams i := len(params) var result []map[string]interface{} var err error if i == 1 { vv := reflect.ValueOf(params[0]) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map { result, err = session.queryAllWithDateFormat(dateFormat, sql, params...) } else { result, err = session.queryAllByMapWithDateFormat(dateFormat, sql, params[0]) } } else { result, err = session.queryAllWithDateFormat(dateFormat, sql, params...) } pLimitN := session.statement.LimitN if dialect.URI().DBType == schemas.MSSQL { if session.statement.Start > 0 { for i, _ := range result { delete(result[i], rownumber) } } } else if dialect.URI().DBType == schemas.ORACLE { if session.statement.Start != 0 || pLimitN != nil { for i, _ := range result { delete(result[i], rownumber) } } } r := &ResultMap{Result: result, Error: err} return r } // Execute raw sql func (session *Session) Execute() (sql.Result, error) { defer session.resetStatement() if session.isAutoClose { defer session.Close() } sqlStr := session.statement.RawSQL params := session.statement.RawParams i := len(params) if i == 1 { vv := reflect.ValueOf(params[0]) if vv.Kind() != reflect.Ptr || vv.Elem().Kind() != reflect.Map { return session.exec(sqlStr, params...) } else { sqlStr1, args, _ := core.MapToSlice(sqlStr, params[0]) return session.exec(sqlStr1, args...) } } else { return session.exec(sqlStr, params...) } } // ============================= // for Object // ============================= func (session *Session) queryAll(sqlStr string, paramStr ...interface{}) (resultsSlice []map[string]interface{}, err error) { session.queryPreprocess(&sqlStr, paramStr...) if session.showSQL { if len(paramStr) > 0 { session.engine.logger.Infof("[SQL][%p] %v %#v", session, sqlStr, paramStr) } else { session.engine.logger.Infof("[SQL][%p] %v", session, sqlStr) } } if session.isAutoCommit { return query3(session.DB(), sqlStr, paramStr...) } return txQuery3(session.tx, sqlStr, paramStr...) } func (session *Session) queryAllByMap(sqlStr string, paramMap interface{}) (resultsSlice []map[string]interface{}, err error) { sqlStr1, param, _ := core.MapToSlice(sqlStr, paramMap) session.queryPreprocess(&sqlStr1, param...) if session.showSQL { if len(param) > 0 { session.engine.logger.Infof("[SQL][%p] %v %#v", session, sqlStr1, param) } else { session.engine.logger.Infof("[SQL][%p] %v", session, sqlStr1) } } if session.isAutoCommit { return query3(session.DB(), sqlStr1, param...) } return txQuery3(session.tx, sqlStr1, param...) } func (session *Session) queryAllByMapWithDateFormat(dateFormat string, sqlStr string, paramMap interface{}) (resultsSlice []map[string]interface{}, err error) { sqlStr1, param, _ := core.MapToSlice(sqlStr, paramMap) session.queryPreprocess(&sqlStr1, param...) if session.showSQL { if len(param) > 0 { session.engine.logger.Infof("[SQL][%p] %v %#v", session, sqlStr1, param) } else { session.engine.logger.Infof("[SQL][%p] %v", session, sqlStr1) } } if session.isAutoCommit { return query3WithDateFormat(session.DB(), dateFormat, sqlStr1, param...) } return txQuery3WithDateFormat(session.tx, dateFormat, sqlStr1, param...) } func (session *Session) queryAllWithDateFormat(dateFormat string, sqlStr string, paramStr ...interface{}) (resultsSlice []map[string]interface{}, err error) { session.queryPreprocess(&sqlStr, paramStr...) if session.showSQL { if len(paramStr) > 0 { session.engine.logger.Infof("[SQL][%p] %v %#v", session, sqlStr, paramStr) } else { session.engine.logger.Infof("[SQL][%p] %v", session, sqlStr) } } if session.isAutoCommit { return query3WithDateFormat(session.DB(), dateFormat, sqlStr, paramStr...) } return txQuery3WithDateFormat(session.tx, dateFormat, sqlStr, paramStr...) } func (session *Session) queryAllToJsonString(sql string, paramStr ...interface{}) (string, error) { results, err := session.queryAll(sql, paramStr...) if err != nil { return "", err } return JSONString(results, true) } func (session *Session) queryAllToXmlString(sql string, paramStr ...interface{}) (string, error) { resultMap, err := session.queryAll(sql, paramStr...) if err != nil { return "", err } results, err := anyxml.Xml(resultMap) if err != nil { return "", err } return string(results), nil } func (session *Session) queryAllToXmlIndentString(sql string, prefix string, indent string, paramStr ...interface{}) (string, error) { resultSlice, err := session.queryAll(sql, paramStr...) if err != nil { return "", err } results, err := anyxml.XmlIndent(resultSlice, prefix, indent, "result") if err != nil { return "", err } return string(results), nil } func (session *Session) queryAllToXmlStringWithDateFormat(dateFormat string, sql string, paramStr ...interface{}) (string, error) { resultSlice, err := session.queryAll(sql, paramStr...) if err != nil { return "", err } results, err := anyxml.XmlWithDateFormat(dateFormat, resultSlice) if err != nil { return "", err } return string(results), nil } func (session *Session) queryAllToXmlIndentStringWithDateFormat(dateFormat string, sql string, prefix string, indent string, paramStr ...interface{}) (string, error) { resultSlice, err := session.queryAll(sql, paramStr...) if err != nil { return "", err } results, err := anyxml.XmlIndentWithDateFormat(dateFormat, resultSlice, prefix, indent, "results") if err != nil { return "", err } return string(results), nil } func (session *Session) queryAllByMapToJsonString(sql string, paramMap interface{}) (string, error) { results, err := session.queryAllByMap(sql, paramMap) if err != nil { return "", err } return JSONString(results, true) } func (session *Session) queryAllByMapToJsonStringWithDateFormat(dateFormat string, sql string, paramMap interface{}) (string, error) { results, err := session.queryAllByMapWithDateFormat(dateFormat, sql, paramMap) if err != nil { return "", err } return JSONString(results, true) } func (session *Session) queryAllToJsonStringWithDateFormat(dateFormat string, sql string, paramStr ...interface{}) (string, error) { results, err := session.queryAllWithDateFormat(dateFormat, sql, paramStr...) if err != nil { return "", err } return JSONString(results, true) } func (session *Session) queryPreprocessByMap(sqlStr *string, paramMap interface{}) { re := regexp.MustCompile(`[?](\w+)`) query := *sqlStr names := make(map[string]int) var i int query = re.ReplaceAllStringFunc(query, func(src string) string { names[src[1:]] = i i += 1 return "?" }) for _, filter := range session.engine.dialect.Filters() { query = filter.Do(query) } *sqlStr = query // session.engine.logSQL(session, *sqlStr, paramMap) session.logSQL(*sqlStr, paramMap) } func (session *Session) Sqls(sqls interface{}, parmas ...interface{}) *SqlsExecutor { sqlsExecutor := new(SqlsExecutor) switch sqls.(type) { case string: sqlsExecutor.sqls = sqls.(string) case []string: sqlsExecutor.sqls = sqls.([]string) case map[string]string: sqlsExecutor.sqls = sqls.(map[string]string) default: sqlsExecutor.sqls = nil sqlsExecutor.err = ErrParamsType } if len(parmas) == 0 { sqlsExecutor.parmas = nil } if len(parmas) > 1 { sqlsExecutor.parmas = nil sqlsExecutor.err = ErrParamsType } if len(parmas) == 1 { switch parmas[0].(type) { case map[string]interface{}: sqlsExecutor.parmas = parmas[0].(map[string]interface{}) case []map[string]interface{}: sqlsExecutor.parmas = parmas[0].([]map[string]interface{}) case map[string]map[string]interface{}: sqlsExecutor.parmas = parmas[0].(map[string]map[string]interface{}) default: sqlsExecutor.parmas = nil sqlsExecutor.err = ErrParamsType } } sqlsExecutor.session = session return sqlsExecutor } func (session *Session) SqlMapsClient(sqlkeys interface{}, parmas ...interface{}) *SqlMapsExecutor { sqlMapsExecutor := new(SqlMapsExecutor) switch sqlkeys.(type) { case string: sqlMapsExecutor.sqlkeys = sqlkeys.(string) case []string: sqlMapsExecutor.sqlkeys = sqlkeys.([]string) case map[string]string: sqlMapsExecutor.sqlkeys = sqlkeys.(map[string]string) default: sqlMapsExecutor.sqlkeys = nil sqlMapsExecutor.err = ErrParamsType } if len(parmas) == 0 { sqlMapsExecutor.parmas = nil } if len(parmas) > 1 { sqlMapsExecutor.parmas = nil sqlMapsExecutor.err = ErrParamsType } if len(parmas) == 1 { switch parmas[0].(type) { case map[string]interface{}: sqlMapsExecutor.parmas = parmas[0].(map[string]interface{}) case []map[string]interface{}: sqlMapsExecutor.parmas = parmas[0].([]map[string]interface{}) case map[string]map[string]interface{}: sqlMapsExecutor.parmas = parmas[0].(map[string]map[string]interface{}) default: sqlMapsExecutor.parmas = nil sqlMapsExecutor.err = ErrParamsType } } sqlMapsExecutor.session = session return sqlMapsExecutor } func (session *Session) SqlTemplatesClient(sqlkeys interface{}, parmas ...interface{}) *SqlTemplatesExecutor { sqlTemplatesExecutor := new(SqlTemplatesExecutor) switch sqlkeys.(type) { case string: sqlTemplatesExecutor.sqlkeys = sqlkeys.(string) case []string: sqlTemplatesExecutor.sqlkeys = sqlkeys.([]string) case map[string]string: sqlTemplatesExecutor.sqlkeys = sqlkeys.(map[string]string) default: sqlTemplatesExecutor.sqlkeys = nil sqlTemplatesExecutor.err = ErrParamsType } if len(parmas) == 0 { sqlTemplatesExecutor.parmas = nil } if len(parmas) > 1 { sqlTemplatesExecutor.parmas = nil sqlTemplatesExecutor.err = ErrParamsType } if len(parmas) == 1 { switch parmas[0].(type) { case map[string]interface{}: sqlTemplatesExecutor.parmas = parmas[0].(map[string]interface{}) case []map[string]interface{}: sqlTemplatesExecutor.parmas = parmas[0].([]map[string]interface{}) case map[string]map[string]interface{}: sqlTemplatesExecutor.parmas = parmas[0].(map[string]map[string]interface{}) default: sqlTemplatesExecutor.parmas = nil sqlTemplatesExecutor.err = ErrParamsType } } sqlTemplatesExecutor.session = session return sqlTemplatesExecutor }<|fim▁end|>
return sql }
<|file_name|>package.py<|end_file_name|><|fim▁begin|># Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. #<|fim▁hole|>from spack import * class DhpmmF(MakefilePackage): """DHPMM_P:High-precision Matrix Multiplication with Faithful Rounding""" homepage = "http://www.math.twcu.ac.jp/ogita/post-k/" url = "http://www.math.twcu.ac.jp/ogita/post-k/software/DHPMM_F/DHPMM_F_alpha.tar.gz" version('alpha', sha256='35321ecbc749f2682775ffcd27833afc8c8eb4fa7753ce769727c9d1fe097848') depends_on('blas', type='link') depends_on('lapack', type='link') def patch(self): math_libs = self.spec['lapack'].libs + self.spec['blas'].libs makefile = FileFilter('Makefile') if self.spec.satisfies('%gcc'): makefile.filter(r'^MKL\s+=\s1', 'MKL=0') makefile.filter(r'^CC\s+=\sgcc', 'CC={0}'.format(spack_cc)) makefile.filter(r'^CXX\s+=\sg\+\+', 'CXX={0}'.format(spack_cxx)) makefile.filter(r'^BLASLIBS\s+=\s-llapack\s-lblas', 'BLASLIBS={0}'.format(math_libs.ld_flags)) elif self.spec.satisfies('%fj'): makefile.filter(r'^#ENV\s+=\sFX100', 'ENV=FX100') makefile.filter(r'^ENV\s+=\sGCC', '#ENV=GCC') makefile.filter(r'^MKL\s+=\s1', 'MKL=0') makefile.filter(r'^CC\s+=\sfccpx', 'CC={0}'.format(spack_cc)) makefile.filter(r'^CXX\s+=\sFCCpx', 'CXX={0}'.format(spack_cxx)) makefile.filter(r'^BLASLIBS\s+=\s-llapack\s-lblas', 'BLASLIBS={0}'.format(math_libs.ld_flags)) elif self.spec.satisfies('%intel'): makefile.filter(r'^ENV\s+=\sGCC', '#ENV=GCC') makefile.filter(r'^ENV\s+=\sICC', 'ENV=ICC') makefile.filter(r'^CC\s+=\sicc', 'CC={0}'.format(spack_cc)) makefile.filter(r'^CXX\s+=\sicc', 'CXX={0}'.format(spack_cxx)) def install(self, spec, prefix): mkdirp(prefix.bin) install('test/source4_SpMV', prefix.bin)<|fim▁end|>
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>use crate::rendering::*; use crate::geometry::*; /// IMPORTANT: Must form a star domain at its center #[derive(Clone, Debug)] pub struct Polygon { pub corners: Vec<Point>, /// defined anti-clockwise pub center: Point, pub rot: Rotation, /// anti-clockwise angle w.r.t. positive z-axis pub pos: Point3, pub color: Color, pub fixed: bool } impl Polygon { pub fn new_regular( corners: Vec<Point>, center: Point, pos: Point3, color: Color, fixed: bool ) -> Polygon { Polygon { corners, center, rot: Rotation::new(0.0), pos, color, fixed, } } pub fn get_vertices(self) -> Vec<PolygonVertex> { let mut output: Vec<PolygonVertex> = vec![]; let corners_it_shift = self.corners.clone().into_iter().cycle().skip(1); for (corner1, corner2) in self.corners.into_iter().zip(corners_it_shift) { output.push(PolygonVertex { corner1: corner1.into(), corner2: corner2.into(), center: self.center.into(), rot: self.rot.get_matrix_f32(), pos: self.pos.into(), color: self.color.get_array_f32(), fixed_pos: self.fixed as u32 }); } output } } impl GliumStandardPrimitive for Polygon { type Vertex = PolygonVertex; fn get_shaders() -> Shaders { Shaders::VertexGeometryFragment( include_str!("polygon.vs"), include_str!("polygon.ges"), include_str!("polygon.fs") ) } fn get_vertex(self) -> Vec<Self::Vertex> { self.get_vertices() } } #[derive(Copy, Clone, Debug)] pub struct PolygonVertex { pub corner1: [f32; 2], pub corner2: [f32; 2], pub center: [f32; 2], pub rot: [[f32; 2]; 2], pub pos: [f32; 3], pub color: [f32; 4], pub fixed_pos: u32 }<|fim▁hole|><|fim▁end|>
implement_vertex!(PolygonVertex, corner1, corner2, center, rot, pos, color, fixed_pos);
<|file_name|>low_high33_backtest.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*- import tradeStrategy as tds import sendEmail as se import tradeTime as tt import tushare as ts import pdSql_common as pds from pdSql import StockSQL import numpy as np import sys,datetime from pydoc import describe from multiprocessing import Pool import os, time import file_config as fc from position_history_update import combine_file,CHINESE_DICT from position_history_update import get_latest_yh_k_stocks_from_csv def get_stop_trade_symbol(): today_df = ts.get_today_all() today_df = today_df[today_df.amount>0] today_df_high_open = today_df[today_df.open>today_df.settlement*1.005] all_trade_code = today_df['code'].values.tolist() all_a_code = pds.get_all_code(hist_dir="C:/中国银河证券海王星/T0002/export/") #all_a_code = pds.get_all_code(hist_dir="C:/hist/day/data/") all_stop_codes = list(set(all_a_code).difference(set(all_trade_code))) return all_stop_codes def get_stopped_stocks(given_stocks=[],except_stocks=[],hist_dir='C:/hist/day/data/'): import easyquotation quotation =easyquotation.use('qq') stop_stocks = [] if given_stocks: this_quotation = quotation.stocks(given_stocks) else: this_quotation = quotation.all all_stocks = list(this_quotation.keys()) #print('all_stocks=',('150251' in all_stocks)) #print('hist_dir=',hist_dir) exist_codes = pds.get_all_code(hist_dir) #print('exist_codes=',('150251' in exist_codes)) #print('all_stocks=',all_stocks) all_codes = list(set(all_stocks) & (set(exist_codes))) #print('all_codes=',all_codes) for stock_code in all_codes: if this_quotation[stock_code]: #print(this_quotation[stock_code]) if this_quotation[stock_code]['ask1']==0 and this_quotation[stock_code]['volume']==0: stop_stocks.append(stock_code) else: pass if except_stocks: all_codes = list(set(all_codes).difference(set(except_stocks))) #print('all_codes=',('150251' in all_codes)) #print('stop_stocks=', stop_stocks) #print(len(stop_stocks)) #print('all_stocks=',all_stocks) #print(len(all_stocks)) return stop_stocks,all_codes def get_exit_data(symbols,last_date_str): refer_index = ['sh','cyb'] symbols = symbols +refer_index temp_datas = {} for symbol in symbols: dest_df=pds.pd.read_csv('C:/hist/day/data/%s.csv' % symbol) print(dest_df) #dest_df = get_raw_hist_df(code_str=symbol) if dest_df.empty: pass else: dest_df_last_date = dest_df.tail(1).iloc[0]['date'] if dest_df_last_date==last_date_str: exit_price = dest_df.tail(3) return #get_exit_data(symbols=['000029'],last_date_str='2016/08/23') #get_stopped_stocks() def back_test_dapan(test_codes,k_num=0,source='yh',rate_to_confirm = 0.01,processor_id=0): i=0 for stock_symbol in test_codes: if stock_symbol=='000029' and source=='easyhistory': continue print(i,stock_symbol) s_stock=tds.Stockhistory(stock_symbol,'D',test_num=k_num,source=source,rate_to_confirm=rate_to_confirm) if s_stock.h_df.empty: print('New stock %s and no history data' % stock_symbol) continue if True: if dapan_stocks and (stock_symbol in dapan_stocks): dapan_criteria = ((s_stock.temp_hist_df['o_change']> 0.30) & (s_stock.temp_hist_df['pos20'].shift(1)<=1.0)) dapan_regress_column_type = 'open' dapan_high_o_df,dapan_high_open_columns = s_stock.regress_common(dapan_criteria,post_days=[0,-1,-2,-3,-4,-5,-10,-20,-60],regress_column = dapan_regress_column_type, base_column='open',fix_columns=['date','close','p_change','o_change','position','pos20','oo_chg','oh_chg','ol_chg','oc_chg']) dapan_high_o_df['code'] = stock_symbol dapan_high_o_df['ho_index'] = np.where(dapan_high_o_df['pos20']<=0,0,(dapan_high_o_df['o_change']/dapan_high_o_df['pos20']).round(2)) dapan_ho_df= dapan_ho_df.append(dapan_high_o_df) else: pass def back_test_stocks(test_codes,k_num=0,source='yh',rate_to_confirm = 0.01,processor_id=0,save_type='', all_result_columns=[],trend_columns=[],all_temp_columns=[],deep_star_columns=[]): i=0 ma_num = 20 regress_column_type = 'close' all_result_df = tds.pd.DataFrame({}, columns=all_result_columns) all_trend_result_df = tds.pd.DataFrame({}, columns=trend_columns) all_temp_hist_df = tds.pd.DataFrame({}, columns=all_temp_columns) #deep_star_columns = ['date','close','p_change','o_change','position','low_high_open','high_o_day0','high_o_day1','high_o_day3', # 'high_o_day5','high_o_day10','high_o_day20','high_o_day50'] #deep_star_columns = [] deep_star_df = tds.pd.DataFrame({}, columns=deep_star_columns) print('processor_id=%s : %s'% (processor_id, test_codes)) for stock_symbol in test_codes: if stock_symbol=='000029' and source=='easyhistory': continue print('processor_id=%s :%s,%s' %(processor_id,i,stock_symbol)) s_stock=tds.Stockhistory(stock_symbol,'D',test_num=k_num,source=source,rate_to_confirm=rate_to_confirm) if s_stock.h_df.empty: print('New stock %s and no history data' % stock_symbol) continue if True: #try: result_df = s_stock.form_temp_df(stock_symbol) test_result = s_stock.regression_test(rate_to_confirm) recent_trend = s_stock.get_recent_trend(num=ma_num,column='close') s_stock.diff_ma(ma=[10,30],target_column='close',win_num=5) temp_hist_df = s_stock.temp_hist_df.set_index('date') #temp_hist_df.to_csv('C:/hist/day/temp/%s.csv' % stock_symbol) temp_hist_df_tail = temp_hist_df.tail(1) temp_hist_df_tail['code'] = stock_symbol all_temp_hist_df= all_temp_hist_df.append(temp_hist_df_tail) #columns = ['close','p_change','o_change','position','low_high_open','high_o_day0','high_o_day1','high_o_day3','high_o_day5','high_o_day10','high_o_day20'] #high_o_df,high_open_columns = s_stock.regress_high_open(regress_column = regress_column_type,base_column='open') #criteria = s_stock.temp_hist_df['low_high_open']!= 0 criteria = ((s_stock.temp_hist_df['star_l']> 0.50) & (s_stock.temp_hist_df['l_change']<-3.0) & (s_stock.temp_hist_df['pos20'].shift(1)<0.2)) high_o_df,high_open_columns = s_stock.regress_common(criteria,post_days=[0,-1,-2,-3,-4,-5,-10,-20,-60],regress_column = regress_column_type, base_column='close',fix_columns=['date','close','p_change','o_change','position','pos20','MAX20high','star_l']) high_o_df['code'] = stock_symbol high_o_df['star_index'] = np.where(high_o_df['pos20']<=0,0,(high_o_df['star_l']/high_o_df['pos20']*((high_o_df['MAX20high']-high_o_df['close'])/high_o_df['MAX20high'])).round(2)) deep_star_df= deep_star_df.append(high_o_df) i = i+1 if test_result.empty: pass else: test_result_df = tds.pd.DataFrame(test_result.to_dict(), columns=all_result_columns, index=[stock_symbol]) all_result_df = all_result_df.append(test_result_df,ignore_index=False) if recent_trend.empty: pass else: trend_result_df = tds.pd.DataFrame(recent_trend.to_dict(), columns=trend_columns, index=[stock_symbol]) all_trend_result_df = all_trend_result_df.append(trend_result_df,ignore_index=False) #except: # print('Regression test exception for stock: %s' % stock_symbol) if save_type=='csv': #write to csv all_temp_hist_df_file_name = 'C:/work/temp1/all_temp_hist_%s' %processor_id +'.csv' all_result_df_file_name = 'C:/work/temp1/all_result_%s' %processor_id +'.csv' deep_star_df_file_name = 'C:/work/temp1/deep_star_%s' %processor_id +'.csv' all_trend_result_df_file_name = 'C:/work/temp1/all_trend_result_%s' %processor_id +'.csv' all_temp_hist_df.to_csv(all_temp_hist_df_file_name) all_result_df.to_csv(all_result_df_file_name) deep_star_df.to_csv(deep_star_df_file_name) all_trend_result_df.to_csv(all_trend_result_df_file_name) return all_temp_hist_df,all_result_df,deep_star_df,all_trend_result_df def back_test_one_stock(stock_symbol,rate_to_confirm=0.0001,temp_dir=fc.ALL_TEMP_DIR,bs_temp_dir=fc.ALL_BACKTEST_DIR): if stock_symbol=='000029' and source=='easyhistory': return s_stock=tds.Stockhistory(stock_symbol,'D',test_num=0,source='yh',rate_to_confirm=0.01) if s_stock.h_df.empty: print('New stock %s and no history data' % stock_symbol) return result_df = s_stock.form_temp_df(stock_symbol) s_stock.form_regression_result(save_dir=bs_temp_dir,rate_to_confirm = 0.0001) #recent_trend = s_stock.get_recent_trend(num=20,column='close') s_stock.diff_ma_score(ma=[10,30,60,120,250],target_column='close',win_num=5) temp_hist_df = s_stock.temp_hist_df.set_index('date') try: temp_hist_df.to_csv(temp_dir + '%s.csv' % stock_symbol) except: pass """ temp_hist_df_tail = temp_hist_df.tail(1) temp_hist_df_tail['code'] = stock_symbol """ return def multiprocess_back_test(allcodes,pool_num=10): #(code_list_dict,k_num=0,source='yh',rate_to_confirm = 0.01,processor_id=0,save_type='', #all_result_columns=[],trend_columns=[],all_temp_columns=[],deep_star_columns=[]): #code_list_dict = seprate_list(all_codes,4) #print('code_list_dict=',code_list_dict) print('Parent process %s.' % os.getpid()) print('num_stocks=',len(allcodes)) start = time.time() """ processor_num=len(code_list_dict) #update_yh_hist_data(codes_list=[],process_id=0) p = Pool() for i in range(processor_num): p.apply_async(back_test_stocks, args=(code_list_dict[i],k_num,source,rate_to_confirm,i,'csv', all_result_columns,trend_columns,all_temp_columns,deep_star_columns,)) """ """ Map multiprocess """ p = Pool(pool_num) p.map(back_test_one_stock,allcodes) print('Waiting for all subprocesses done...') p.close() p.join() print('All subprocesses done.') end = time.time() time_cost = end - start print('Task multiprocess_back_test runs %0.2f seconds.' % time_cost) return time_cost def combine_multi_process_result(processor_num=4,all_result_columns=[],all_temp_columns=[],trend_columns=[],deep_star_columns=[]): #all_result_columns,all_temp_columns,trend_columns,deep_star_columns=[],[],[],[] all_result_df = tds.pd.DataFrame({}, columns=[])#all_result_columns) all_trend_result_df = tds.pd.DataFrame({}, columns=[])#trend_columns) all_temp_hist_df = tds.pd.DataFrame({}, columns=[])#all_temp_columns) deep_star_df = tds.pd.DataFrame({}, columns=[])#deep_star_columns) df0 = None for processor_id in range(4): all_temp_hist_df_file_name = 'C:/work/temp1/all_temp_hist_%s' %processor_id +'.csv' all_result_df_file_name = 'C:/work/temp1/all_result_%s' %processor_id +'.csv' deep_star_df_file_name = 'C:/work/temp1/deep_star_%s' %processor_id +'.csv' all_trend_result_df_file_name = 'C:/work/temp1/all_trend_result_%s' %processor_id +'.csv' all_temp_hist_df = all_temp_hist_df.append(tds.pd.read_csv(all_temp_hist_df_file_name, header=0,encoding='gb2312'),ignore_index=True) #names=all_temp_columns all_result_df = all_result_df.append(tds.pd.read_csv(all_result_df_file_name, header=0,encoding='gb2312'),ignore_index=True) #names=all_result_columns, deep_star_df = deep_star_df.append(tds.pd.read_csv(deep_star_df_file_name, header=0,encoding='gb2312'),ignore_index=True)#names=deep_star_columns, all_trend_result_df = all_trend_result_df.append(tds.pd.read_csv(all_trend_result_df_file_name, header=0,encoding='gb2312'),ignore_index=True) #names=trend_columns, return all_temp_hist_df,all_result_df,deep_star_df,all_trend_result_df def seprate_list(all_codes,seprate_num=4): #all_codes = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] c = len(all_codes) sub_c = int(c/seprate_num) code_list_dict = {} for j in range(seprate_num-1): code_list_dict[j] = all_codes[j*sub_c:(j+1)*sub_c] code_list_dict[j+1] = all_codes[(j+1)*sub_c:] return code_list_dict def get_latest_backtest_datas(write_file_name=fc.ALL_BACKTEST_FILE,data_dir=fc.ALL_BACKTEST_DIR): """ 获取所有回测最后一个K线的数据:特定目录下 """ #columns = ['date', 'close', 'id', 'trade', 'p_change', 'position', 'operation', 's_price', 'b_price', 'profit', 'cum_prf', 'fuli_prf', 'hold_count'] #df = combine_file(tail_num=1,dest_dir=data_dir,keyword='bs_',prefile_slip_num=3,columns=columns) columns = pds.get_data_columns(dest_dir=data_dir) df = combine_file(tail_num=1,dest_dir=data_dir,keyword='',prefile_slip_num=0,columns=columns) if df.empty: return df df['counts']=df.index df = df[columns+['counts','code']] df['code'] = df['code'].apply(lambda x: pds.format_code(x)) df['name'] = df['code'].apply(lambda x: pds.format_name_by_code(x,CHINESE_DICT)) df = df.set_index('code') if write_file_name: df.to_csv(write_file_name,encoding='utf-8') return df def get_latest_backtest_datas_from_csv(file_name=fc.ALL_BACKTEST_FILE): """ 获取所有回测最后一个K线的数据 """ #file_name = 'D:/work/backtest/all_bs_stocks.csv' columns = ['date', 'close', 'id', 'trade', 'p_change', 'position', 'operation', 's_price', 'b_price', 'profit', 'cum_prf', 'fuli_prf', 'hold_count'] columns = pds.get_data_columns(dest_dir=fc.ALL_BACKTEST_DIR) + ['counts','code','name'] try: df = pd.read_csv(file_name,usecols=columns) df['code'] = df['code'].apply(lambda x: pds.format_code(x)) df = df.set_index('code') return df except: return get_latest_backtest_datas(write_file_name=file_name) def get_latest_temp_datas(write_file_name=fc.ALL_TEMP_FILE,data_dir=fc.ALL_TEMP_DIR,files=[]): """ 获取所有回测最后一个K线的数据:特定目录下 """ #columns = ['date', 'close', 'id', 'trade', 'p_change', 'position', 'operation', 's_price', 'b_price', 'profit', 'cum_prf', 'fuli_prf', 'hold_count'] columns = pds.get_data_columns(dest_dir=data_dir) #df = combine_file(tail_num=1,dest_dir=data_dir,keyword='bs_',prefile_slip_num=3,columns=columns) df = combine_file(tail_num=1,dest_dir=data_dir,keyword='',prefile_slip_num=0,columns=columns,file_list=files) if df.empty: return df df['counts']=df.index df = df[columns+['counts','code']] df['code'] = df['code'].apply(lambda x: pds.format_code(x)) df['name'] = df['code'].apply(lambda x: pds.format_name_by_code(x,CHINESE_DICT)) df = df.set_index('code') if write_file_name: df.to_csv(write_file_name,encoding='utf-8') return df def get_latest_temp_datas_from_csv(file_name=fc.ALL_TEMP_FILE): """ 获取所有回测最后一个K线的数据 """ #file_name = 'D:/work/backtest/all_bs_stocks.csv' #columns = ['date', 'close', 'id', 'trade', 'p_change', 'position', 'operation', 's_price', 'b_price', 'profit', 'cum_prf', 'fuli_prf', 'hold_count'] columns = pds.get_data_columns(dest_dir=fc.ALL_TEMP_DIR) + ['counts','code','name'] try: df = pd.read_csv(file_name,usecols=columns) df['code'] = df['code'].apply(lambda x: pds.format_code(x)) df = df.set_index('code') return df except: return get_latest_backtest_datas(write_file_name=file_name) def get_all_regress_summary(given_stocks=[],confirm=0.01,dest_file=fc.ALL_SUMMARY_FILE): all_result_df = tds.pd.DataFrame({}) """ latest_temp_df = tds.pd.read_csv( fc.ALL_TEMP_FILE) latest_temp_df['code'] = latest_temp_df['code'].apply(lambda x: pds.format_code(x)) stock_codes = latest_temp_df['code'].values.tolist() latest_temp_df = latest_temp_df.set_index('code') #print(latest_temp_df.ix['000014'].date) """ #given_stocks = ['000001','000002'] for stock_symbol in given_stocks: s_stock = tds.Stockhistory(stock_symbol,'D',test_num=0,source='yh',rate_to_confirm=confirm) result_series = s_stock.get_regression_result(rate_to_confirm=confirm,refresh_regression=False, from_csv=True,bs_csv_dir=fc.ALL_BACKTEST_DIR,temp_csv_dir=fc.ALL_TEMP_DIR) if not result_series.empty: test_result_df = tds.pd.DataFrame({stock_symbol:result_series}).T all_result_df = all_result_df.append(test_result_df,ignore_index=False) if dest_file: try: all_result_df['code'] = all_result_df.index all_result_df['name'] = all_result_df['code'].apply(lambda x: pds.format_name_by_code(x,CHINESE_DICT)) del all_result_df['code'] #dest_file = 'D:/work/result/all_summary1.csv' all_result_df.to_csv(dest_file,encoding='utf-8') except: pass return all_result_df def back_test_yh_only(given_codes=[],except_stocks=[],mark_insql=True): """ 高于三天收盘最大值时买入,低于三天最低价的最小值时卖出: 33策略 """ """ :param k_num: string type or int type: mean counts of history if int type; mean start date of history if date str :param given_codes: str type, :param except_stocks: list type, :param type: str type, force update K data from YH :return: source: history data from web if 'easyhistory', history data from YH if 'YH' """ #addition_name = '' #if type == 'index': last_date_str = pds.tt.get_last_trade_date(date_format='%Y/%m/%d') print('last_date_str=',last_date_str) all_stock_df = get_latest_yh_k_stocks_from_csv() print('all_stock_df:',all_stock_df) all_stocks = all_stock_df.index.values.tolist() if given_codes: all_stocks = list(set(all_stocks).intersection(set(given_codes))) print('所有股票数量: ',len(all_stocks)) stop_df = all_stock_df[all_stock_df.date<last_date_str] all_stop_codes = stop_df.index.values.tolist() print('停牌股票数量',len(all_stop_codes)) all_trade_codes = list(set(all_stocks).difference(set(all_stop_codes))) final_codes = list(set(all_trade_codes).difference(set(except_stocks))) print('最后回测股票数量',len(final_codes)) #stock_sql = StockSQL() #pre_is_tdx_uptodate,pre_is_pos_uptodate,pre_is_backtest_uptodate,systime_dict = stock_sql.is_histdata_uptodate() #print(pre_is_tdx_uptodate,pre_is_pos_uptodate,pre_is_backtest_uptodate,systime_dict) pre_is_backtest_uptodate = False #print('final_codes=',final_codes) #stock_sql.close() if not pre_is_backtest_uptodate: time_cost = multiprocess_back_test(final_codes,pool_num=10) #20分钟左右 """ if time_cost>300:#防止超时 stock_sql = StockSQL() if mark_insql: #标识已经更新回测数据至数据库 stock_sql.update_system_time(update_field='backtest_time') print('完成回测') is_tdx_uptodate,is_pos_uptodate,is_backtest_uptodate,systime_dict = stock_sql.is_histdata_uptodate() """ is_backtest_uptodate = True if is_backtest_uptodate: print('触发手动回测数据持久化,', datetime.datetime.now()) """汇总回测数据,并写入CSV文件,方便交易调用,2分钟左右""" df = get_latest_backtest_datas(write_file_name=fc.ALL_BACKTEST_FILE,data_dir=fc.ALL_BACKTEST_DIR) print('完成回测数据汇总,',datetime.datetime.now()) df = get_latest_backtest_datas_from_csv() #从CSV文件读取所有回测数据 """汇总temp数据,并写入CSV文件,方便交易调用,8分钟""" #temp_df = get_latest_temp_datas(write_file_name=fc.ALL_TEMP_FILE,data_dir=fc.ALL_TEMP_DIR) print('完成temp数据汇总,',datetime.datetime.now()) temp_df = get_latest_temp_datas_from_csv() summary_df = get_all_regress_summary(given_stocks=final_codes,dest_file=fc.ALL_SUMMARY_FILE) print('完成回测数据分析汇总,约20分钟,',datetime.datetime.now()) print('完成回测数据持久化') else: print('数据未标识至数据库:显示数据未更新') def back_test_yh(given_codes=[],except_stocks=[],mark_insql=True): """ 高于三天收盘最大值时买入,低于三天最低价的最小值时卖出: 33策略 """ """ :param k_num: string type or int type: mean counts of history if int type; mean start date of history if date str :param given_codes: str type, :param except_stocks: list type, :param type: str type, force update K data from YH :return: source: history data from web if 'easyhistory', history data from YH if 'YH' """ #addition_name = '' #if type == 'index': last_date_str = pds.tt.get_last_trade_date(date_format='%Y/%m/%d') print('last_date_str=',last_date_str) all_stock_df = get_latest_yh_k_stocks_from_csv() #print('all_stock_df:',all_stock_df) all_stocks = all_stock_df.index.values.tolist() if given_codes: all_stocks = list(set(all_stocks).intersection(set(given_codes))) print('所有股票数量: ',len(all_stocks)) stop_df = all_stock_df[all_stock_df.date<last_date_str] all_stop_codes = stop_df.index.values.tolist() print('停牌股票数量',len(all_stop_codes)) all_trade_codes = list(set(all_stocks).difference(set(all_stop_codes))) final_codes = list(set(all_trade_codes).difference(set(except_stocks))) print('最后回测股票数量',len(final_codes)) stock_sql = StockSQL() pre_is_tdx_uptodate,pre_is_pos_uptodate,pre_is_backtest_uptodate,systime_dict = stock_sql.is_histdata_uptodate() #print(pre_is_tdx_uptodate,pre_is_pos_uptodate,pre_is_backtest_uptodate,systime_dict) pre_is_backtest_uptodate = False #print('final_codes=',final_codes) #stock_sql.close() if not pre_is_backtest_uptodate: time_cost = multiprocess_back_test(final_codes,pool_num=10) if time_cost>300:#防止超时 stock_sql = StockSQL() if mark_insql: """标识已经更新回测数据至数据库""" stock_sql.update_system_time(update_field='backtest_time') print('完成回测') is_tdx_uptodate,is_pos_uptodate,is_backtest_uptodate,systime_dict = stock_sql.is_histdata_uptodate() #is_backtest_uptodate = True if is_backtest_uptodate: print('触发手动回测数据持久化,', datetime.datetime.now()) """汇总回测数据,并写入CSV文件,方便交易调用""" df = get_latest_backtest_datas(write_file_name=fc.ALL_BACKTEST_FILE,data_dir=fc.ALL_BACKTEST_DIR) print('完成回测数据汇总,',datetime.datetime.now()) #df = get_latest_backtest_datas_from_csv() #从CSV文件读取所有回测数据 """汇总temp数据,并写入CSV文件,方便交易调用""" temp_df = get_latest_temp_datas(write_file_name=fc.ALL_TEMP_FILE,data_dir=fc.ALL_TEMP_DIR) print('完成temp数据汇总,',datetime.datetime.now()) #temp_df = get_latest_temp_datas_from_csv() summary_df = get_all_regress_summary(given_stocks=final_codes,dest_file=fc.ALL_SUMMARY_FILE) print('完成回测数据分析汇总,',datetime.datetime.now()) print('完成回测数据持久化') else: print('数据未标识至数据库:显示数据未更新') #stock_sql.close() else: print('已经完成回测,无需回测;上一次回测时间:%s' % systime_dict['backtest_time']) munual_update_csv_data = True if munual_update_csv_data: print('触发手动回测数据持久化,', datetime.datetime.now()) """汇总回测数据,并写入CSV文件,方便交易调用""" df = get_latest_backtest_datas(write_file_name=fc.ALL_BACKTEST_FILE,data_dir=fc.ALL_BACKTEST_DIR) print('完成回测数据汇总,',datetime.datetime.now()) #df = get_latest_backtest_datas_from_csv() #从CSV文件读取所有回测数据 """汇总temp数据,并写入CSV文件,方便交易调用""" temp_df = get_latest_temp_datas(write_file_name=fc.ALL_TEMP_FILE,data_dir=fc.ALL_TEMP_DIR) print('完成temp数据汇总,',datetime.datetime.now()) #temp_df = get_latest_temp_datas_from_csv() summary_df = get_all_regress_summary(given_stocks=final_codes,dest_file=fc.ALL_SUMMARY_FILE) print('完成回测数据分析汇总,',datetime.datetime.now()) print('完成回测数据持久化') else: print('数据未标识至数据库:显示数据未更新') return True def back_test0(k_num=0,given_codes=[],except_stocks=['000029'], type='stock', source='easyhistory',rate_to_confirm = 0.01,dapan_stocks=['000001','000002']): """ 高于三天收盘最大值时买入,低于三天最低价的最小值时卖出: 33策略 """ """ :param k_num: string type or int type: mean counts of history if int type; mean start date of history if date str :param given_codes: str type, :param except_stocks: list type, :param type: str type, force update K data from YH :return: source: history data from web if 'easyhistory', history data from YH if 'YH' """ #addition_name = '' #if type == 'index': start = time.time() addition_name = type all_codes = [] all_stop_codes = [] all_stocks = [] all_trade_codes = [] #print('source=',source) if source =='yh' or source=='YH': hist_dir='C:/中国银河证券海王星/T0002/export/' #print(given_codes,except_stocks) all_stop_codes,all_stocks1 = get_stopped_stocks(given_codes,except_stocks,hist_dir) #print('all_stocks1=',('150251' in all_stocks1)) all_trade_codes = list(set(all_stocks1).difference(set(all_stop_codes))) else: hist_dir='C:/hist/day/data/' all_stop_codes,all_stocks = get_stopped_stocks(given_codes,except_stocks,hist_dir) #print('all_stocks2=',('150251' in all_stocks)) all_trade_codes = list(set(all_stocks).difference(set(all_stop_codes))) #print('all_trade_codes=',('150251' in all_trade_codes)) #all_codes = ['300128', '002288', '002156', '300126','300162','002717','002799','300515','300516','600519', # '000418','002673','600060','600887','000810','600115','600567','600199','000596','000538','002274','600036','600030','601398'] column_list = ['count', 'mean', 'std', 'max', 'min', '25%','50%','75%','cum_prf', 'fuli_prf','yearly_prf','last_trade_date','last_trade_price','min_hold_count', 'max_hold_count','avrg_hold_count','this_hold_count','exit','enter', 'position','max_amount_rate','max_amount_distance','break_in', 'break_in_count','break_in_date', 'break_in_distance','success_rate','days'] all_result_df = tds.pd.DataFrame({}, columns=column_list) i=0 trend_column_list = ['count', 'mean','chg_fuli', 'std', 'min', '25%', '50%', '75%', 'max', 'c_state', 'c_mean', 'pos_mean', 'ft_rate', 'presure', 'holding', 'close','cont_num','amount_rate','ma_amount_rate'] all_trend_result_df = tds.pd.DataFrame({}, columns=trend_column_list) all_temp_hist_df = tds.pd.DataFrame({}, columns=[]) ma_num = 20 stock_basic_df=ts.get_stock_basics() basic_code = stock_basic_df['code'].to_dict() basic_code_keys = basic_code.keys() #print('all_trade_codes=',all_trade_codes) deep_columns = ['date','close','p_change','o_change','position','low_high_open','high_o_day0','high_o_day1','high_o_day3', 'high_o_day5','high_o_day10','high_o_day20','high_o_day50'] high_open_columns = [] deep_star_df = tds.pd.DataFrame({}, columns=high_open_columns) dapan_ho_df = tds.pd.DataFrame({}, columns=high_open_columns) regress_column_type = 'close' #s_stock=tds.Stockhistory('300689','D',test_num=0,source='yh',rate_to_confirm=0.01) #print(s_stock.h_df) temp_columns = ['open', 'high', 'low', 'last_close', 'close', 'p_change', 'volume', 'amount', 'ROC1', 'MAX20', 'MAX20high', 'MIN20', 'MIN20low', 'h_change', 'l_change', 'o_change', 'MAX3', 'MIN3low', 'MA5', 'v_rate', 'amount_rate', 'ma_amount_rate', 'MA10', 'LINEARREG_ANGLE6MA10', 'LINEARREG_ANGLE10MA10', 'diff_ma10', 'MA6diff_ma10', 'MA20', 'MA30', 'LINEARREG_ANGLE14MA30', 'LINEARREG_ANGLE30MA30', 'diff_ma30', 'MA14diff_ma30', 'LINEARREG_ANGLE14diff_ma30', 'MA60', 'MA120', 'MA250', 'CCI', 'macd', 'macdsignal', 'macdhist', 'u_band', 'm_band', 'l_band', 'fastK', 'slowD', 'fastJ', 'MFI', 'ATR', 'NATR', 'MOM', 'CDLMORNINGDOJISTAR', 'CDLABANDONEDBABY', 'CDLBELTHOLD', 'CDLBREAKAWAY', 'CDL3WHITESOLDIERS', 'CDLPIERCING', 'SAR', 'RSI', 'LINEARREG14', 'LINEARREG30', 'LINEARREG_ANGLE14', 'LINEARREG_ANGLE8', 'LINEARREG_INTERCEPT14', 'LINEARREG_SLOPE14', 'LINEARREG_SLOPE30', 'LINEARREG_ANGLE8ROC1', 'LINEARREG_ANGLE5MA5', 'LINEARREG_ANGLE8MA20', 'LINEARREG_ANGLE14MA60', 'LINEARREG_ANGLE14MA120', 'LINEARREG_ANGLE14MA250', 'LINEARREG_ANGLE8CCI', 'LINEARREG_ANGLE14SAR', 'LINEARREG_ANGLE14RSI', 'LINEARREG_ANGLE8macdhist', 'LINEARREG_ANGLE8MOM', 'LINEARREG_ANGLE14MOM', 'MTM', 'ma5', 'ma10', 'ma20', 'ma30', 'ma60', 'ma120', 'ma250', 'v_ma5', 'v_ma10', 'amount_ma5', 'amount_ma10', 'atr', 'atr_ma5', 'atr_ma10', 'atr_5_rate', 'atr_5_max_r', 'atr_10_rate', 'atr_10_max_r', 'c_max10', 'c_min10', 'h_max10', 'l_min10', 'h_max20', 'l_min20', 'c_max20', 'c_min20', 'c_max60', 'c_min60', 'l_max3', 'h_max3', 'c_max3', 'l_min3', 'c_min2', 'chg_mean2', 'chg_min2', 'chg_min3', 'chg_min4', 'chg_min5', 'chg_max2', 'chg_max3', 'amount_rate_min2', 'rate_1.8', 'atr_in', 'star', 'star_h', 'star_l', 'star_chg', 'k_chg', 'k_rate', 'reverse', 'p_rate', 'oo_chg', 'oh_chg', 'ol_chg', 'oc_chg', 'gap', 'island', 'cross1', 'cross2', 'cross3', 'cross4', 'std', 'pos20', 'pos60', 'cOma5', 'cOma10', 'ma5_k', 'ma5_k2', 'ma5_turn', 'ma10_k', 'ma10_k2', 'ma10_turn', 'ma20_k', 'ma20_k2', 'ma20_turn', 'trend_chg', 'ma5Cma20', 'ma5Cma30', 'ma10Cma20', 'ma10Cma30', 'tangle_p', 'tangle_p1', 'star_in', 'low_high_open', 'break_in', 'break_in_p', 'ma_score0', 'ma30_c_ma60', 'ma10_c_ma30', 'ma5_c_ma10', 'ma_trend_score', 'ma_score', 'gt_open', 'gt_close', 'great_v_rate', 'gt2_amount', 'gt3_amount', 'gt_cont_close', 'k_trend', 'k_score0', 'k_score_m', 'k_score', 'position', 'operation', 'exit_3p', 's_price0', 's_price1', 's_price', 'b_price0', 'b_price1', 'b_price', 'trade', 'trade_na', 'diff_v_MA10', 'diff_MA10', 'diff_std_MA10', 'diff_v_MA30', 'diff_MA30', 'diff_std_MA30','code'] #multiprocess_back_test() code_list_dict = seprate_list(all_trade_codes,seprate_num=4) multiprocess_back_test(code_list_dict,k_num=0,source='yh',rate_to_confirm = 0.01,processor_id=0,save_type='', all_result_columns=column_list,trend_columns=trend_column_list,all_temp_columns=[],deep_star_columns=[]) all_temp_hist_df,all_result_df,deep_star_df,all_trend_result_df =combine_multi_process_result(processor_num=4,all_result_columns=column_list, all_temp_columns=temp_columns,trend_columns=trend_column_list,deep_star_columns=deep_columns) #print(result_df.tail(20)) #all_result_df = all_result_df.sort_index(axis=0, by='sum', ascending=False) print('all_result_df=',all_result_df) all_result_df = all_result_df.sort_values(axis=0, by='cum_prf', ascending=False) all_trend_result_df = all_trend_result_df.sort_values(axis=0, by='chg_fuli', ascending=False) result_summary = all_result_df.describe() result_codes = all_result_df.index.values.tolist() result_codes_dict = {} on_trade_dict = {} valid_dict = {} for code in result_codes: if code in basic_code_keys: result_codes_dict[code] = basic_code[code] else: result_codes_dict[code] = 'NA' if code in all_stop_codes: on_trade_dict[code] = 1 else: on_trade_dict[code] = 0 if code in except_stocks: valid_dict[code] = 1 else: valid_dict[code] = 0 """ all_temp_dict = {} all_temp_codes = all_temp_hist_df.index.values.tolist() for code in result_codes: if code in all_temp_codes: all_temp_dict[code]= basic_code[code] else: result_codes_dict[code] = 'NA' all_temp_hist_df['code'] = tds.Series(result_codes_dict,index=all_result_df.index) """ #print(result_codes_dict) #print(tds.pd.DataFrame(result_codes_dict, columns=['code'], index=list(result_codes_dict.keys()))) #all_result_df['code'] = result_codes_dict all_result_df['code'] = tds.Series(result_codes_dict,index=all_result_df.index) deep_star_df['code'] = tds.Series(result_codes_dict,index=deep_star_df.index) print('deep_star_df=',deep_star_df) deep_star_df = deep_star_df[['code','code','star_index']+high_open_columns] dapan_codes_dict = {} all_trend_result_df['code'] = tds.Series(result_codes_dict,index=all_trend_result_df.index) all_result_df['stopped'] = tds.Series(on_trade_dict,index=all_result_df.index) all_trend_result_df['stopped'] = tds.Series(on_trade_dict,index=all_trend_result_df.index) all_result_df['invalid'] = tds.Series(valid_dict, index=all_result_df.index) all_trend_result_df['invalid'] = tds.Series(valid_dict, index=all_trend_result_df.index) all_result_df['max_r'] = all_result_df['max']/all_result_df['cum_prf'] ma_c_name = '%s日趋势数' % ma_num trend_column_chiness = {'count':ma_c_name, 'mean': '平均涨幅','chg_fuli': '复利涨幅', 'std': '标准差', 'min': '最小涨幅', '25%': '25%', '50%': '50%', '75%': '75%', 'max': '最大涨幅', 'c_state': '收盘价状态', 'c_mean': '平均收盘价', 'pos_mean': '平均仓位', 'ft_rate': '低点反弹率', 'presure': '压力', 'holding': '支撑', 'close': '收盘价','cont_num': '连涨天数', 'code': '名字', 'stopped': '停牌','invalid': '除外', 'amount_rate':'量比','ma_amount_rate':'短长量比'} print(all_trend_result_df) all_trend_result_df_chinese = all_trend_result_df.rename(index=str, columns=trend_column_chiness) print(all_result_df) print(all_result_df.describe()) if isinstance(k_num, str): k_num = k_num.replace('/','').replace('-','') latest_date_str = pds.tt.get_latest_trade_date(date_format='%Y/%m/%d') latest_date_str = latest_date_str.replace('/','').replace('-','') rate_to_confirm_str = '%s' % rate_to_confirm rate_to_confirm_str = 'rate' + rate_to_confirm_str.replace('.', '_') #print('latest_date_str=',latest_date_str) tail_name = '%s_from_%s_%s.csv' % (latest_date_str,k_num,rate_to_confirm_str) #all_result_df['yearly_prf'] = all_result_df['fuli_prf']**(1.0/(all_result_df['days']/365.0)) result_column_list = ['count','code', 'mean', 'std', 'max', 'min', 'cum_prf', 'fuli_prf','yearly_prf','success_rate','last_trade_date','last_trade_price','min_hold_count', 'max_hold_count','avrg_hold_count','this_hold_count','exit','enter', 'position','max_amount_rate','max_amount_distance','break_in', 'break_in_count','break_in_date', 'break_in_distance', 'stopped','invalid','max_r','25%','50%','75%',] all_result_df = all_result_df[result_column_list] all_result_df.to_csv('C:/work/temp/regression_test_' + addition_name +tail_name) deep_star_df.to_csv('C:/work/temp/pos20_star_%s'% regress_column_type + addition_name +tail_name) if all_result_df.empty: pass else: consider_df = all_result_df[(all_result_df['max_amount_rate']>2.0) & (all_result_df['position']>0.35) & (all_result_df['stopped']==0) & (all_result_df['invalid']==0)]# & (all_result_df['last_trade_price'] ==0)] consider_df.to_csv('C:/work/temp/consider_' + addition_name +tail_name) active_df = all_result_df[(all_result_df['max_r']<0.4) & (all_result_df['code']!='NA') & # (all_result_df['min']>-0.08) & (all_result_df['position']>0.35) & (all_result_df['max']>(3.9 *all_result_df['min'].abs())) & (all_result_df['invalid']==0) &(all_result_df['stopped']==0)] active_df['active_score'] = active_df['fuli_prf']/active_df['max_r']/active_df['std']*active_df['fuli_prf']/active_df['cum_prf'] active_df = active_df.sort_values(axis=0, by='active_score', ascending=False) active_df.to_csv('C:/work/temp/active_' + addition_name +tail_name) tupo_df = all_result_df[(all_result_df['break_in_distance']!=0) &(all_result_df['break_in_distance']<=20) & (all_result_df['position']>0.35) & (all_result_df['stopped']==0) & (all_result_df['invalid']==0) & (all_result_df['code']!='NA') & (all_result_df['last_trade_price']!=0)]# & (all_result_df['last_trade_price'] ==0)] tupo_df.to_csv('C:/work/temp/tupo_' + addition_name +tail_name) result_summary.to_csv('C:/work/temp/result_summary_' + addition_name +tail_name) all_trend_result_df_chinese.to_csv('C:/work/temp/trend_result_%s' % ma_num + addition_name +'%s_to_%s_%s.csv' % (k_num,latest_date_str,rate_to_confirm_str)) if not all_temp_hist_df.empty: #all_temp_hist_df = all_temp_hist_df[column_list] all_temp_hist_df = all_temp_hist_df.set_index('code') all_temp_hist_df.to_csv('C:/work/temp/all_temp_' + addition_name +tail_name) reverse_df = all_temp_hist_df[(all_temp_hist_df['reverse']>0) & (all_temp_hist_df['LINEARREG_ANGLE8']<-2.0) & (all_temp_hist_df['position']>0.35)]# #reverse_df['r_sort'] = reverse_df['star_chg']/reverse_df['pos20'] reverse_df.to_csv('C:/work/temp/reverse_df_' + addition_name +tail_name) long_turn_min_angle = -0.5 short_turn_min_angle = 0.2 ma30_df = all_temp_hist_df[(all_temp_hist_df['LINEARREG_ANGLE14MA120']>long_turn_min_angle) & <|fim▁hole|> (all_temp_hist_df['LINEARREG_ANGLE5MA5']>short_turn_min_angle) & (all_temp_hist_df['LINEARREG_ANGLE6MA10']>short_turn_min_angle) & (all_temp_hist_df['LINEARREG_ANGLE5MA5']>=all_temp_hist_df['LINEARREG_ANGLE6MA10']) & (all_temp_hist_df['LINEARREG_ANGLE8ROC1']>0.0) & (all_temp_hist_df['close']>all_temp_hist_df['ma30']) & (all_temp_hist_df['position']>0.35)]# ma30_df.to_csv('C:/work/temp/ma30_df_' + addition_name +tail_name) """ if dapan_ho_df.empty: pass else: for code in dapan_stocks: if code in basic_code_keys: dapan_codes_dict[code] = basic_code[code] else: dapan_codes_dict[code] = 'NA' dapan_ho_df['code'] = tds.Series(dapan_codes_dict,index=dapan_ho_df.index) dapan_ho_df = dapan_ho_df[['code','code','ho_index']+dapan_high_open_columns] dapan_ho_df.to_csv('C:/work/temp/dapan_high_open_%s'% regress_column_type + addition_name +tail_name) """ end = time.time() print('Task Mybacktest runs %0.2f seconds.' % (end - start)) return all_result_df #back_test(k_num='2015/08/30',given_codes=['000004','000005'],except_stocks=['000029'], type='stock', source='YH')<|fim▁end|>
(all_temp_hist_df['LINEARREG_ANGLE14MA250']>long_turn_min_angle) & (all_temp_hist_df['LINEARREG_ANGLE14MA60']>long_turn_min_angle) & (all_temp_hist_df['LINEARREG_ANGLE14MA30']<1.0) &
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import render, HttpResponseRedirect, redirect from django.contrib.auth.decorators import login_required from django.views.generic.edit import CreateView from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django.forms.models import inlineformset_factory from django.core.exceptions import PermissionDenied from django.core.urlresolvers import reverse_lazy from .models import Profile from .forms import ProfileForm class RegistrationView(CreateView): model = User form_class = UserCreationForm template_name = 'profiles/user_create.html' success_url = reverse_lazy('profiles:redirect') @login_required def account_redirect(request): return redirect('profiles:edit', pk=request.user.pk) @login_required def edit_user(request, pk): user = User.objects.get(pk=pk) user_form = ProfileForm(instance=user) # In the line below list the names of your Profile model fields. These are the ones I used. ProfileInlineFormset = inlineformset_factory(User, Profile, fields=('preferred_name', 'birthdate', 'interests', 'state')) formset = ProfileInlineFormset(instance=user) if request.user.is_authenticated() and request.user.id == user.id: if request.method == "POST": user_form = ProfileForm(request.POST, request.FILES, instance=user) formset = ProfileInlineFormset(request.POST, request.FILES, instance=user) if user_form.is_valid(): created_user = user_form.save(commit=False) formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user) if formset.is_valid(): created_user.save() formset.save() return HttpResponseRedirect('/documentaries/') return render(request, "profiles/profile_update.html", { "noodle": pk, "noodle_form": user_form,<|fim▁hole|><|fim▁end|>
"formset": formset, }) else: raise PermissionDenied
<|file_name|>imageQueryParser.py<|end_file_name|><|fim▁begin|>import random class ImageQueryParser: def __init__(self): pass def parse(self, query_string): tab = query_string.split(" ") last = tab[-1].lower() is_random = False index = 0 if last.startswith("-"): if last == "-r": is_random = True tab.pop() else: try: index = int(last[1:]) tab.pop() except ValueError: pass query_string = " ".join(tab) return ImageQuery(query_string, is_random, index) class ImageQuery: def __init__(self, query, is_random, index): self.__query = query self.__is_random = is_random self.__index = index def query(self): return self.__query def is_random(self): return self.__is_random def next_index(self):<|fim▁hole|> self.__index += 1 return i<|fim▁end|>
if self.is_random(): return random.randrange(0, 100) else: i = self.__index
<|file_name|>sneaky_bastard_sword.js<|end_file_name|><|fim▁begin|>/** * Created by ionagamed on 8/19/16. */ import { Card } from '../../../Card'; import { Item } from '../helpers/Item'; const id = 'sneaky_bastard_sword'; class _ extends Item { constructor() { super();<|fim▁hole|> this.hands = 1; this.wieldable = true; this.price = 400; } getAttackFor(player) { return 2; } } Card.cards[id] = new _();<|fim▁end|>
this.id = id; this.pack = 'pack1'; this.kind = 'treasure'; this.type = '1-handed';
<|file_name|>sum_of_two_integers_371.py<|end_file_name|><|fim▁begin|>""" Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Example: Given a = 1 and b = 2, return 3. """ class Solution(object): def getSum(self, a, b): """ :type a: int :type b: int :rtype: int """ while a != 0 and b != 0:<|fim▁hole|> if a > 1<<31 or b > 1<<31: a %= 1<<31 b %= 1<<31 return a or b if __name__ == "__main__": a = Solution() print a.getSum(-14, 16)<|fim▁end|>
a, b = a^b, (a&b)<<1
<|file_name|>ex41.py<|end_file_name|><|fim▁begin|>""" ******************************************************************************** Learn Python the Hard Way Third Edition, by Zed A. Shaw ISBN: 978-0321884916 ******************************************************************************** """ import random from urllib import urlopen import sys #debug = "DEBUG: " WORD_URL = "http://learncodethehardway.org/words.txt" WORDS = [] PHRASES = { "class %%%(%%%):": "Make a class named %%% that is-a %%%.", "class %%%(object):\n\tdef __init__(self, ***)": "class %%% has-a __init__ that takes self and *** parameters.", "class %%%(object):\n\tdef ***(self,@@@)": "class %%% has-a function named *** that takes self and @@@ parameters.", "*** = %%%()": "Set *** to an instance of class %%%.", "***.***(@@@)": "From *** get the *** function, and call it with parameters self, @@@.", "***.*** = '***'": "From *** get the *** attribute and set it to '***'." } # do they want to drill phrases first PHRASE_FIRST = False if len(sys.argv) == 2 and sys.argv[1] == "english": PHRASE_FIRST = True #print debug + "0" # load up the words from the website #for word in urlopen(WORD_URL).readlines(): # once downloaded just open the file locally): for word in open('words.txt').readlines(): WORDS.append(word.strip()) #print debug + word def convert(snippet, phrase): class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))] other_names = random.sample(WORDS, snippet.count("***")) results = [] param_names = [] <|fim▁hole|> for sentence in snippet, phrase: result = sentence[:] #fake class names for word in class_names: result = result.replace("%%%", word, 1) #fake other names for word in other_names: result = result.replace("***", word, 1) #fake parameter lists for word in param_names: result = result.replace("@@@", word, 1) results.append(result) return results # keep going until EOF try: while True: snippets = PHRASES.keys() #print debug + "3" random.shuffle(snippets) for snippet in snippets: #print debug + "4" phrase = PHRASES[snippet] question, answer = convert(snippet, phrase) if PHRASE_FIRST: question, answer = answer, question print question raw_input("> ") print "ANSWER: %s\n\n" % answer except EOFError: print "\nBye"<|fim▁end|>
for i in range(0, snippet.count("@@@")): param_count = random.randint(1,3) param_names.append(', '.join(random.sample(WORDS, param_count)))
<|file_name|>nvme_common.cc<|end_file_name|><|fim▁begin|>/* eXokernel Development Kit (XDK) Based on code by Samsung Research America Copyright (C) 2013 The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. As a special exception, if you link the code in this file with files compiled with a GNU compiler to produce an executable, that does not cause the resulting executable to be covered by the GNU Lesser General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU Lesser General Public License. This exception applies to code released by its copyright holders in files containing the exception. */ #include <stdio.h> #include <stdarg.h> #include <common/logging.h> #include "nvme_common.h" #ifdef NVME_VERBOSE void NVME_INFO(const char *fmt, ...) { printf(NORMAL_MAGENTA); va_list list; va_start(list, fmt); printf("[NVME]:"); vprintf(fmt, list); va_end(list);<|fim▁hole|>#endif<|fim▁end|>
printf(RESET); }
<|file_name|>th_dlg.js<|end_file_name|><|fim▁begin|>tinyMCE.addI18n('th.advimage_dlg',{ tab_general:"\u0E17\u0E31\u0E48\u0E27\u0E44\u0E1B", tab_appearance:"\u0E25\u0E31\u0E01\u0E29\u0E13\u0E30", tab_advanced:"\u0E02\u0E31\u0E49\u0E19\u0E2A\u0E39\u0E07", general:"\u0E17\u0E31\u0E48\u0E27\u0E44\u0E1B", title:"\u0E0A\u0E37\u0E48\u0E2D", preview:"\u0E14\u0E39\u0E15\u0E31\u0E27\u0E2D\u0E22\u0E48\u0E32\u0E07", constrain_proportions:"\u0E04\u0E07\u0E2A\u0E31\u0E14\u0E2A\u0E48\u0E27\u0E19", langdir:"\u0E17\u0E34\u0E28\u0E17\u0E32\u0E07\u0E01\u0E32\u0E23\u0E2D\u0E48\u0E32\u0E19", langcode:"\u0E42\u0E04\u0E49\u0E14\u0E20\u0E32\u0E29\u0E32", long_desc:"\u0E23\u0E32\u0E22\u0E25\u0E30\u0E40\u0E2D\u0E35\u0E22\u0E14\u0E25\u0E34\u0E49\u0E07\u0E04\u0E4C", style:"\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A", classes:"\u0E04\u0E25\u0E32\u0E2A", ltr:"\u0E0B\u0E49\u0E32\u0E22\u0E44\u0E1B\u0E02\u0E27\u0E32", rtl:"\u0E02\u0E27\u0E32\u0E44\u0E1B\u0E0B\u0E49\u0E32\u0E22", id:"Id", map:"Image map", swap_image:"Swap image", alt_image:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E23\u0E39\u0E1B", mouseover:"\u0E40\u0E21\u0E37\u0E48\u0E2D\u0E40\u0E2D\u0E32\u0E40\u0E21\u0E49\u0E32\u0E2A\u0E4C\u0E0A\u0E35\u0E49", mouseout:"\u0E40\u0E21\u0E37\u0E48\u0E2D\u0E40\u0E2D\u0E32\u0E40\u0E21\u0E49\u0E32\u0E2A\u0E4C\u0E2D\u0E2D\u0E01", <|fim▁hole|>example_img:"\u0E14\u0E39\u0E15\u0E31\u0E27\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E25\u0E31\u0E01\u0E29\u0E13\u0E30\u0E02\u0E2D\u0E07\u0E23\u0E39\u0E1B", missing_alt:"\u0E04\u0E38\u0E13\u0E41\u0E19\u0E48\u0E43\u0E08\u0E2B\u0E23\u0E37\u0E2D\u0E44\u0E21\u0E48\u0E27\u0E48\u0E32\u0E15\u0E49\u0E2D\u0E07\u0E01\u0E32\u0E23\u0E14\u0E33\u0E40\u0E19\u0E34\u0E19\u0E01\u0E32\u0E23\u0E15\u0E48\u0E2D\u0E42\u0E14\u0E22\u0E44\u0E21\u0E48\u0E43\u0E2A\u0E48\u0E04\u0E33\u0E2D\u0E18\u0E34\u0E1A\u0E32\u0E22\u0E23\u0E39\u0E1B\u0E20\u0E32\u0E1E ? \u0E01\u0E32\u0E23\u0E43\u0E2A\u0E48\u0E04\u0E33\u0E2D\u0E18\u0E34\u0E1A\u0E32\u0E22\u0E23\u0E39\u0E1B\u0E17\u0E33\u0E43\u0E2B\u0E49\u0E1C\u0E39\u0E49\u0E1E\u0E34\u0E01\u0E32\u0E23\u0E17\u0E32\u0E07\u0E2A\u0E32\u0E22\u0E15\u0E32\u0E2A\u0E32\u0E21\u0E32\u0E23\u0E16\u0E23\u0E39\u0E49\u0E44\u0E14\u0E49\u0E27\u0E48\u0E32\u0E23\u0E39\u0E1B\u0E04\u0E38\u0E13\u0E04\u0E37\u0E2D\u0E23\u0E39\u0E1B\u0E2D\u0E30\u0E44\u0E23", dialog_title:"\u0E40\u0E1E\u0E34\u0E48\u0E21/\u0E41\u0E01\u0E49\u0E44\u0E02 image", src:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E23\u0E39\u0E1B", alt:"\u0E23\u0E32\u0E22\u0E25\u0E30\u0E40\u0E2D\u0E35\u0E22\u0E14\u0E23\u0E39\u0E1B", list:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\u0E23\u0E39\u0E1B", border:"\u0E01\u0E23\u0E2D\u0E1A", dimensions:"\u0E15\u0E33\u0E41\u0E2B\u0E19\u0E48\u0E07", vspace:"\u0E23\u0E30\u0E22\u0E30\u0E2B\u0E48\u0E32\u0E07\u0E41\u0E19\u0E27\u0E15\u0E31\u0E49\u0E07", hspace:"\u0E23\u0E30\u0E22\u0E30\u0E2B\u0E48\u0E32\u0E07\u0E41\u0E19\u0E27\u0E19\u0E2D\u0E19", align:"\u0E15\u0E33\u0E41\u0E2B\u0E19\u0E48\u0E07\u0E08\u0E31\u0E14\u0E27\u0E32\u0E07", align_baseline:"\u0E40\u0E2A\u0E49\u0E19\u0E1E\u0E37\u0E49\u0E19", align_top:"\u0E1A\u0E19", align_middle:"\u0E01\u0E25\u0E32\u0E07", align_bottom:"\u0E25\u0E48\u0E32\u0E07", align_texttop:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23\u0E2D\u0E22\u0E39\u0E48\u0E1A\u0E19", align_textbottom:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23\u0E2D\u0E22\u0E39\u0E48\u0E25\u0E48\u0E32\u0E07", align_left:"\u0E0B\u0E49\u0E32\u0E22", align_right:"\u0E02\u0E27\u0E32", image_list:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23\u0E23\u0E39\u0E1B" });<|fim▁end|>
misc:"\u0E40\u0E1A\u0E47\u0E14\u0E40\u0E15\u0E25\u0E47\u0E14",
<|file_name|>test_polygon.cpp<|end_file_name|><|fim▁begin|>#include <catch2/catch.hpp> #include "libslic3r/Point.hpp" #include "libslic3r/Polygon.hpp" using namespace Slic3r; SCENARIO("Converted Perl tests", "[Polygon]") { GIVEN("ccw_square") { Polygon ccw_square{ { 100, 100 }, { 200, 100 }, { 200, 200 }, { 100, 200 } }; Polygon cw_square(ccw_square); cw_square.reverse(); THEN("ccw_square is valid") { REQUIRE(ccw_square.is_valid()); } THEN("cw_square is valid") { REQUIRE(cw_square.is_valid()); } THEN("ccw_square.area") { REQUIRE(ccw_square.area() == 100 * 100); } THEN("cw_square.area") { REQUIRE(cw_square.area() == - 100 * 100); } THEN("ccw_square.centroid") { REQUIRE(ccw_square.centroid() == Point { 150, 150 }); } THEN("cw_square.centroid") { REQUIRE(cw_square.centroid() == Point { 150, 150 }); } THEN("ccw_square.contains_point(150, 150)") { REQUIRE(ccw_square.contains({ 150, 150 })); } THEN("cw_square.contains_point(150, 150)") { REQUIRE(cw_square.contains({ 150, 150 })); } THEN("conversion to lines") { REQUIRE(ccw_square.lines() == Lines{ { { 100, 100 }, { 200, 100 } }, { { 200, 100 }, { 200, 200 } }, { { 200, 200 }, { 100, 200 } }, { { 100, 200 }, { 100, 100 } } }); } THEN("split_at_first_point") { REQUIRE(ccw_square.split_at_first_point() == Polyline { ccw_square[0], ccw_square[1], ccw_square[2], ccw_square[3], ccw_square[0] }); } THEN("split_at_index(2)") { REQUIRE(ccw_square.split_at_index(2) == Polyline { ccw_square[2], ccw_square[3], ccw_square[0], ccw_square[1], ccw_square[2] }); } THEN("split_at_vertex(ccw_square[2])") { REQUIRE(ccw_square.split_at_vertex(ccw_square[2]) == Polyline { ccw_square[2], ccw_square[3], ccw_square[0], ccw_square[1], ccw_square[2] }); } THEN("is_counter_clockwise") { REQUIRE(ccw_square.is_counter_clockwise()); }<|fim▁hole|> } THEN("make_counter_clockwise") { cw_square.make_counter_clockwise(); REQUIRE(cw_square.is_counter_clockwise()); } THEN("make_counter_clockwise^2") { cw_square.make_counter_clockwise(); cw_square.make_counter_clockwise(); REQUIRE(cw_square.is_counter_clockwise()); } THEN("first_point") { REQUIRE(&ccw_square.first_point() == &ccw_square.points.front()); } } GIVEN("Triangulating hexagon") { Polygon hexagon{ { 100, 0 } }; for (size_t i = 1; i < 6; ++ i) { Point p = hexagon.points.front(); p.rotate(PI / 3 * i); hexagon.points.emplace_back(p); } Polygons triangles; hexagon.triangulate_convex(&triangles); THEN("right number of triangles") { REQUIRE(triangles.size() == 4); } THEN("all triangles are ccw") { auto it = std::find_if(triangles.begin(), triangles.end(), [](const Polygon &tri) { return tri.is_clockwise(); }); REQUIRE(it == triangles.end()); } } GIVEN("General triangle") { Polygon polygon { { 50000000, 100000000 }, { 300000000, 102000000 }, { 50000000, 104000000 } }; Line line { { 175992032, 102000000 }, { 47983964, 102000000 } }; Point intersection; bool has_intersection = polygon.intersection(line, &intersection); THEN("Intersection with line") { REQUIRE(has_intersection); REQUIRE(intersection == Point { 50000000, 102000000 }); } } } TEST_CASE("Centroid of Trapezoid must be inside", "[Polygon][Utils]") { Slic3r::Polygon trapezoid { { 4702134, 1124765853 }, { -4702134, 1124765853 }, { -9404268, 1049531706 }, { 9404268, 1049531706 }, }; Point centroid = trapezoid.centroid(); CHECK(trapezoid.contains(centroid)); } // This test currently only covers remove_collinear_points. // All remaining tests are to be ported from xs/t/06_polygon.t Slic3r::Points collinear_circle({ Slic3r::Point::new_scale(0, 0), // 3 collinear points at beginning Slic3r::Point::new_scale(10, 0), Slic3r::Point::new_scale(20, 0), Slic3r::Point::new_scale(30, 10), Slic3r::Point::new_scale(40, 20), // 2 collinear points Slic3r::Point::new_scale(40, 30), Slic3r::Point::new_scale(30, 40), // 3 collinear points Slic3r::Point::new_scale(20, 40), Slic3r::Point::new_scale(10, 40), Slic3r::Point::new_scale(-10, 20), Slic3r::Point::new_scale(-20, 10), Slic3r::Point::new_scale(-20, 0), // 3 collinear points at end Slic3r::Point::new_scale(-10, 0), Slic3r::Point::new_scale(-5, 0) }); SCENARIO("Remove collinear points from Polygon", "[Polygon]") { GIVEN("Polygon with collinear points"){ Slic3r::Polygon p(collinear_circle); WHEN("collinear points are removed") { remove_collinear(p); THEN("Leading collinear points are removed") { REQUIRE(p.points.front() == Slic3r::Point::new_scale(20, 0)); } THEN("Trailing collinear points are removed") { REQUIRE(p.points.back() == Slic3r::Point::new_scale(-20, 0)); } THEN("Number of remaining points is correct") { REQUIRE(p.points.size() == 7); } } } }<|fim▁end|>
THEN("! is_counter_clockwise") { REQUIRE(! cw_square.is_counter_clockwise());
<|file_name|>package.py<|end_file_name|><|fim▁begin|>############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, [email protected], All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public<|fim▁hole|>from spack import * class RAffyio(RPackage): """Routines for parsing Affymetrix data files based upon file format information. Primary focus is on accessing the CEL and CDF file formats.""" homepage = "https://bioconductor.org/packages/affyio/" url = "https://bioconductor.org/packages/3.5/bioc/src/contrib/affyio_1.46.0.tar.gz" version('1.46.0', 'e1f7a89ae16940aa29b998a4dbdc0ef9') depends_on('r-zlibbioc', type=('build', 'run')) depends_on('[email protected]:3.4.9', when='@1.46.0')<|fim▁end|>
# License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ##############################################################################
<|file_name|>copy_qt_frameworks_mac.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright 2010-2015, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Copy Qt frameworks to the target application's frameworks directory. Typical usage: % python copy_qt_frameworks.py --qtdir=/path/to/qtdir/ \ --target=/path/to/target.app/Contents/Frameworks/ """ __author__ = "horo" import optparse import os from copy_file import CopyFiles from util import PrintErrorAndExit from util import RunOrDie def ParseOption(): """Parse command line options.""" parser = optparse.OptionParser() parser.add_option('--qtdir', dest='qtdir') parser.add_option('--target', dest='target') (opts, _) = parser.parse_args() return opts<|fim▁hole|>def main(): opt = ParseOption() if not opt.qtdir: PrintErrorAndExit('--qtdir option is mandatory.') if not opt.target: PrintErrorAndExit('--target option is mandatory.') qtdir = os.path.abspath(opt.qtdir) target = os.path.abspath(opt.target) # Copies QtCore. For codesign, Info.plist should be copied to Resources/. CopyFiles(['%s/lib/QtCore.framework/Versions/4/QtCore' % qtdir], '%s/QtCore.framework/Versions/4/QtCore' % target) CopyFiles(['%s/lib/QtCore.framework/Contents/Info.plist' % qtdir], '%s/QtCore.framework/Resources/' % target) # Copies QtGui. For codesign, Info.plist should be copied to Resources/. CopyFiles(['%s/lib/QtGui.framework/Versions/4/QtGui' % qtdir], '%s/QtGui.framework/Versions/4/QtGui' % target) CopyFiles(['%s/lib/QtGui.framework/Contents/Info.plist' % qtdir], '%s/QtGui.framework/Resources/' % target) # Copies Resources of QtGui CopyFiles(['%s/lib/QtGui.framework/Versions/4/Resources' % qtdir], '%s/QtGui.framework/Resources' % target, recursive=True) # Changes QtGui id cmd = ["install_name_tool", "-id", "@executable_path/../Frameworks/QtGui.framework/Versions/4/QtGui", "%s/QtGui.framework/Versions/4/QtGui" % target] RunOrDie(cmd) # Changes QtCore id cmd = ["install_name_tool", "-id", "@executable_path/../Frameworks/QtCore.framework/Versions/4/QtCore", '%s/QtCore.framework/Versions/4/QtCore' % target] RunOrDie(cmd) # Changes the reference to QtCore framework from QtGui cmd = ["install_name_tool", "-change", "%s/lib/QtCore.framework/Versions/4/QtCore" % qtdir, "@executable_path/../Frameworks/QtCore.framework/Versions/4/QtCore", "%s/QtGui.framework/Versions/4/QtGui" % target] RunOrDie(cmd) if __name__ == '__main__': main()<|fim▁end|>
<|file_name|>node_item.py<|end_file_name|><|fim▁begin|>__author__ = 'djw' class FieldNodeItem(object): """ An item built on a player's field board, held within a node/cell on that board """ def __init__(self): self.cattle = 0 self.boars = 0 self.sheep = 0 self.grain = 0 self.vegetables = 0 def update_animals(self, animal, count): if animal == 'sheep': self.sheep += count if animal == 'boar': self.boars += count if animal == 'cattle': self.cattle += count def update_crop(self, crop): if crop == 'grain': self.grain += 3 if crop == 'vegetables': self.vegetables += 2 @property def has_resources(self): num_resources = self.cattle + self.boars + self.sheep + self.grain + self.vegetables return num_resources > 0 def update(self): """ Called every turn """ raise NotImplementedError() def harvest(self, player): """ Initiates and controls the harvest process for this item """ return def score(self): """ Calculates and returns the current score of this item. """ raise NotImplementedError() def describe(self): """ Return the current state of this item as a string that will be drawn """ raise NotImplementedError() class RoomItem(FieldNodeItem): """ A single room on a player's field board """ MATERIAL_CHOICES = frozenset(['wood', 'stone', 'clay']) def __init__(self, material='wood'): super(RoomItem, self).__init__() if material not in self.MATERIAL_CHOICES: raise ValueError('Invalid material %s not in %s' % (material, self.MATERIAL_CHOICES)) self.material = material def set_material(self, material): if material not in self.MATERIAL_CHOICES: raise ValueError('Invalid material %s not in %s' % (material, self.MATERIAL_CHOICES)) self.material = material def update(self): pass # rooms do not update from turn to turn def score(self): if self.material == 'wood': return 0 elif self.material == 'clay': return 1 elif self.material == 'stone': return 2 def describe(self): return u"\u25A1" # white square (unicode) class StableItem(FieldNodeItem): """ A stable on the player's field board """ def update(self):<|fim▁hole|> return 1 def describe(self): return u"\u039E" # Greek letter Xi (unicode) class PlowedFieldItem(FieldNodeItem): """ A space on the player's field board that has been plowed and can be sowed upon """ def update(self): pass def score(self): return 1 def harvest(self, player): # harvest crops if self.grain > 0: self.grain -= 1 player.grain += 1 elif self.vegetables > 0: self.vegetables -= 1 player.vegetable += 1 def describe(self): return u"\u25A7" # Square with upper left to lower right fill<|fim▁end|>
pass def score(self):
<|file_name|>TwitchSource.py<|end_file_name|><|fim▁begin|>"""News source to send a notification whenever a twitch streamer goes live.""" import datetime import logging import discord from dateutil import parser from .AbstractSources import DataBasedSource DOZER_LOGGER = logging.getLogger('dozer') class TwitchSource(DataBasedSource): """News source to send a notification whenever a twitch streamer goes live.""" full_name = "Twitch" short_name = "twitch" base_url = "https://twitch.tv" description = "Makes a post whenever a specified user goes live on Twitch" token_url = "https://id.twitch.tv/oauth2/token" api_url = "https://api.twitch.tv/helix" color = discord.Color.from_rgb(145, 70, 255) class TwitchUser(DataBasedSource.DataPoint): """A helper class to represent a single Twitch streamer""" def __init__(self, user_id, display_name, profile_image_url, login): super().__init__(login, display_name) self.user_id = user_id self.display_name = display_name self.profile_image_url = profile_image_url self.login = login def __init__(self, aiohttp_session, bot): super().__init__(aiohttp_session, bot) self.access_token = None self.client_id = None self.expiry_time = None self.users = {} self.seen_streams = set() async def get_token(self): """Use OAuth2 to request a new token. If token fails, disable the source.""" client_id = self.bot.config['news']['twitch']['client_id'] self.client_id = client_id client_secret = self.bot.config['news']['twitch']['client_secret'] params = { 'client_id': client_id, 'client_secret': client_secret, 'grant_type': 'client_credentials' } response = await self.http_session.post(self.token_url, params=params) response = await response.json() try: self.access_token = response['access_token'] except KeyError: DOZER_LOGGER.critical(f"Error in {self.full_name} Token Get: {response['message']}") self.disabled = True return expiry_seconds = response['expires_in'] time_delta = datetime.timedelta(seconds=expiry_seconds) self.expiry_time = datetime.datetime.now() + time_delta async def request(self, url, *args, headers=None, **kwargs): """Make a OAuth2 verified request to a API Endpoint""" if headers is None:<|fim▁hole|> url = f"{self.api_url}/{url}" response = await self.http_session.get(url, headers=headers, *args, **kwargs) if response.status == 401: if 'WWW-Authenticate' in response.headers: DOZER_LOGGER.info("Twitch token expired when request made, request new token and retrying.") await self.get_token() return await self.request(url, headers=headers, *args, **kwargs) json = await response.json() return json async def first_run(self, data=None): """Make sure we have a token, then verify and add all the current users in the DB""" await self.get_token() if not data: return params = [] for login in data: params.append(('login', login)) json = await self.request("users", params=params) for user in json['data']: user_obj = TwitchSource.TwitchUser(user['id'], user['display_name'], user['profile_image_url'], user['login']) self.users[user['id']] = user_obj async def clean_data(self, text): """Request user data from Twitch to verify the username exists and clean the data""" try: user_obj = self.users[text] except KeyError: json = await self.request('users', params={'login': text}) if len(json['data']) == 0: raise DataBasedSource.InvalidDataException("No user with that login name found") elif len(json['data']) > 1: raise DataBasedSource.InvalidDataException("More than one user with that login name found") user_obj = TwitchSource.TwitchUser(json['data'][0]['id'], json['data'][0]['display_name'], json['data'][0]['profile_image_url'], json['data'][0]['login']) return user_obj async def add_data(self, obj): """Add the user object to the store""" self.users[obj.user_id] = obj return True async def remove_data(self, obj): """Remove the user object from the store""" try: del self.users[obj.user_id] return True except KeyError: return False async def get_new_posts(self): """Assemble all the current user IDs, get any game names and return the embeds and strings""" if datetime.datetime.now() > self.expiry_time: DOZER_LOGGER.info("Refreshing Twitch token due to expiry time") await self.get_token() params = [] for user in self.users.values(): params.append(('user_id', user.user_id)) params.append(('first', len(self.users))) json = await self.request("streams", params=params) if len(json['data']) == 0: return {} # streams endpoint only returns game ID, do a second request to get game names game_ids = [] for stream in json['data']: game_ids.append(stream['game_id']) params = [] for game in game_ids: params.append(('id', game)) games_json = await self.request("games", params=params) games = {} for game in games_json['data']: games[game['id']] = game['name'] posts = {} for stream in json['data']: if stream['id'] not in self.seen_streams: embed = self.generate_embed(stream, games) plain = self.generate_plain_text(stream, games) posts[stream['user_name']] = { 'embed': [embed], 'plain': [plain] } self.seen_streams.add(stream['id']) return posts def generate_embed(self, data, games): """Given data on a stream and a dict of games, assemble an embed""" try: display_name = data['display_name'] except KeyError: display_name = data['user_name'] embed = discord.Embed() embed.title = f"{display_name} is now live on Twitch!" embed.colour = self.color embed.description = data['title'] embed.url = f"https://www.twitch.tv/{data['user_name']}" embed.add_field(name="Playing", value=games[data['game_id']], inline=True) embed.add_field(name="Watching", value=data['viewer_count'], inline=True) embed.set_author(name=display_name, url=embed.url, icon_url=self.users[data['user_id']].profile_image_url) embed.set_image(url=data['thumbnail_url'].format(width=1920, height=1080)) start_time = parser.isoparse(data['started_at']) embed.timestamp = start_time return embed def generate_plain_text(self, data, games): """Given data on a stream and a dict of games, assemble a string""" try: display_name = data['display_name'] except KeyError: display_name = data['user_name'] return f"{display_name} is now live on Twitch!\n" \ f"Playing {games[data['game_id']]} with {data['viewer_count']} currently watching\n" \ f"Watch at https://www.twitch.tv/{data['user_name']}"<|fim▁end|>
headers = {'Authorization': f"Bearer {self.access_token}", "Client-ID": self.client_id} else: headers['Authorization'] = f"Bearer {self.access_token}"
<|file_name|>bitcoin_hi_IN.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="hi_IN" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About HazeCoin</source> <translation>बिटकोइन के संबंध में</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;HazeCoin&lt;/b&gt; version</source> <translation>बिटकोइन वर्सन</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>कापीराइट</translation> </message> <message> <location line="+0"/> <source>The HazeCoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>पता पुस्तक</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>दो बार क्लिक करे पता या लेबल संपादन करने के लिए !</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>नया पता लिखिए !</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>चुनिन्दा पते को सिस्टम क्लिपबोर्ड पर कापी करे !</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;नया पता</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your HazeCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;पता कॉपी करे</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a HazeCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified HazeCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;मिटाए !!</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your HazeCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>&amp;लेबल कॉपी करे </translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;एडिट</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>पता पुस्तक का डेटा एक्सपोर्ट (निर्यात) करे !</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>ग़लतियाँ एक्सपोर्ट (निर्यात) करे!</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>फाइल में लिख नही सके %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>लेबल</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(कोई लेबल नही !)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>दोबारा नया पहचान शब्द/अक्षर डालिए !</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>नया पहचान शब्द/अक्षर वॉलेट मे डालिए ! &lt;br/&gt; कृपा करके पहचान शब्द में &lt;br&gt; 10 से ज़्यादा अक्षॉरों का इस्तेमाल करे &lt;/b&gt;,या &lt;b&gt;आठ या उससे से ज़्यादा शब्दो का इस्तेमाल करे&lt;/b&gt; !</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>एनक्रिप्ट वॉलेट !</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>वॉलेट खोलने के आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>वॉलेट खोलिए</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>वॉलेट डीक्रिप्ट( विकोड) करने के लिए आपका वॉलेट पहचान शब्द्‌/अक्षर चाईए !</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation> डीक्रिप्ट वॉलेट</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>पहचान शब्द/अक्षर बदलिये !</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>कृपा करके पुराना एवं नया पहचान शब्द/अक्षर वॉलेट में डालिए !</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>वॉलेट एनक्रिपशन को प्रमाणित कीजिए !</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR HAZECOINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>वॉलेट एनक्रिप्ट हो गया !</translation> </message> <message> <location line="-56"/> <source>HazeCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your hazecoins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>वॉलेट एनक्रिप्ट नही हुआ!</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>वॉलेट एनक्रिपशन नाकाम हो गया इंटर्नल एरर की वजह से! आपका वॉलेट एनक्रीपत नही हुआ है!</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>आपके द्वारा डाले गये पहचान शब्द/अक्षर मिलते नही है !</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>वॉलेट का लॉक नही खुला !</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>वॉलेट डीक्रिप्ट करने के लिए जो पहचान शब्द/अक्षर डाले गये है वो सही नही है!</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>वॉलेट का डीक्रिप्ट-ष्ण असफल !</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>नेटवर्क से समकालिक (मिल) रहा है ...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;विवरण</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>वॉलेट का सामानया विवरण दिखाए !</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp; लेन-देन </translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>देखिए पुराने लेन-देन के विवरण !</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>स्टोर किए हुए पते और लेबलओ को बदलिए !</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>पते की सूची दिखाए जिन्हे भुगतान करना है !</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>बाहर जायें</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>अप्लिकेशन से बाहर निकलना !</translation> </message> <message> <location line="+4"/> <source>Show information about HazeCoin</source> <translation>बीटकोइन के बारे में जानकारी !</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;विकल्प</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;बैकप वॉलेट</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a HazeCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Modify configuration options for HazeCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>पहचान शब्द/अक्षर जो वॉलेट एनक्रिपशन के लिए इस्तेमाल किया है उसे बदलिए!</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-165"/> <location line="+530"/> <source>HazeCoin</source> <translation>बीटकोइन</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About HazeCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your HazeCoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified HazeCoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;फाइल</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;सेट्टिंग्स</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;मदद</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>टैबस टूलबार</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[टेस्टनेट]</translation> </message> <message> <location line="+47"/> <source>HazeCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to HazeCoin network</source> <translation><numerusform>%n सक्रिया संपर्क बीटकोइन नेटवर्क से</numerusform><numerusform>%n सक्रिया संपर्क बीटकोइन नेटवर्क से</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n घंटा</numerusform><numerusform>%n घंटे</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n दिन</numerusform><numerusform>%n दिनो</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n हफ़्ता</numerusform><numerusform>%n हफ्ते</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 पीछे</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation>भूल</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>जानकारी</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>नवीनतम</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>भेजी ट्रांजक्शन</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>प्राप्त हुई ट्रांजक्शन</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>तारीख: %1\n राशि: %2\n टाइप: %3\n पता:%4\n</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid HazeCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड नहीं है</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>वॉलेट एन्क्रिप्टेड है तथा अभी लॉक्ड है</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. HazeCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>पता एडिट करना</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;लेबल</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>इस एड्रेस बुक से जुड़ा एड्रेस</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;पता</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>इस एड्रेस बुक से जुड़ी प्रविष्टि केवल भेजने वाले addresses के लिए बदली जा सकती है|</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>नया स्वीकार्य पता</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>नया भेजने वाला पता</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>एडिट स्वीकार्य पता </translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>एडिट भेजने वाला पता</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>डाला गया पता &quot;%1&quot; एड्रेस बुक में पहले से ही मोजूद है|</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid HazeCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>वॉलेट को unlock नहीं किया जा सकता|</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>नयी कुंजी का निर्माण असफल रहा|</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>HazeCoin-Qt</source> <translation>बीटकोइन-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>संस्करण</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>खपत :</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source><|fim▁hole|> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>विकल्प</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start HazeCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start HazeCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the HazeCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the HazeCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting HazeCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show HazeCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;ओके</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;कैन्सल</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting HazeCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>फार्म</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the HazeCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>बाकी रकम :</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>अपुष्ट :</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>वॉलेट</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;हाल का लेन-देन&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>आपका चालू बॅलेन्स</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>लेन देन की पुष्टि अभी नहीं हुई है, इसलिए इन्हें अभी मोजुदा बैलेंस में गिना नहीं गया है|</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start hazecoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>भुगतान का अनुरोध</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>राशि :</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>लेबल :</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>लागू नही </translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the HazeCoin-Qt help message to get a list with possible HazeCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>HazeCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>HazeCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the HazeCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the HazeCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>सिक्के भेजें|</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>एक साथ कई प्राप्तकर्ताओं को भेजें</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>बाकी रकम :</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>भेजने की पुष्टि करें</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; से %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>सिक्के भेजने की पुष्टि करें</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>क्या आप %1 भेजना चाहते हैं?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation>और</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>भेजा गया अमाउंट शुन्य से अधिक होना चाहिए|</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>फार्म</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>अमाउंट:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>प्राप्तकर्ता:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>आपकी एड्रेस बुक में इस एड्रेस के लिए एक लेबल लिखें</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>लेबल:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>प्राप्तकर्ता हटायें</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a HazeCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>HazeCoin एड्रेस लिखें (उदाहरण: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt-A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Clipboard से एड्रेस paste करें</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt-P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Signature</source> <translation>हस्ताक्षर</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this HazeCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified HazeCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a HazeCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>HazeCoin एड्रेस लिखें (उदाहरण: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter HazeCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The HazeCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/अपुष्ट</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 पुष्टियाँ</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 20 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>राशि</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>सही</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>ग़लत</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, अभी तक सफलतापूर्वक प्रसारित नहीं किया गया है</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>अज्ञात</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>लेन-देन का विवरण</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation> ये खिड़की आपको लेन-देन का विस्तृत विवरण देगी !</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>टाइप</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>राशि</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>खुला है जबतक %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>ऑफलाइन ( %1 पक्का करना)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>अपुष्ट ( %1 मे %2 पक्के )</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>पक्के ( %1 पक्का करना)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>यह ब्लॉक किसी भी और नोड को मिला नही है ! शायद यह ब्लॉक कोई भी नोड स्वीकारे गा नही !</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>जेनरेट किया गया किंतु स्वीकारा नही गया !</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>स्वीकारा गया</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>स्वीकार्य ओर से</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>भेजा खुद को भुगतान</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>माइंड</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(लागू नहीं)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>ट्रांसेक्शन स्तिथि| पुष्टियों की संख्या जानने के लिए इस जगह पर माउस लायें|</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>तारीख तथा समय जब ये ट्रांसेक्शन प्राप्त हुई थी|</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>ट्रांसेक्शन का प्रकार|</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>ट्रांसेक्शन की मंजिल का पता|</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>अमाउंट बैलेंस से निकला या जमा किया गया |</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>सभी</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>आज</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>इस हफ्ते</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>इस महीने</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>पिछले महीने</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>इस साल</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>विस्तार...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>स्वीकार करना</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>भेजा गया</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>अपनेआप को</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>माइंड</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>अन्य</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>ढूँदने के लिए कृपा करके पता या लेबल टाइप करे !</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>लघुत्तम राशि</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>पता कॉपी करे</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>लेबल कॉपी करे </translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>कॉपी राशि</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>एडिट लेबल</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>लेन-देन का डेटा निर्यात करे !</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Comma separated file (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>पक्का</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>taareek</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>टाइप</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>लेबल</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>पता</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>राशि</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>ग़लतियाँ एक्सपोर्ट (निर्यात) करे!</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>फाइल में लिख नही सके %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>विस्तार:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>तक</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>बैकप वॉलेट</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>वॉलेट डेटा (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>बैकप असफल</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>बैकप सफल</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>HazeCoin version</source> <translation>बीटकोइन संस्करण</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>खपत :</translation> </message> <message> <location line="-29"/> <source>Send command to -server or hazecoind</source> <translation>-server या hazecoind को कमांड भेजें</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>commands की लिस्ट बनाएं</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>किसी command के लिए मदद लें</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>विकल्प:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: hazecoin.conf)</source> <translation>configuraion की फाइल का विवरण दें (default: hazecoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: hazecoind.pid)</source> <translation>pid फाइल का विवरण दें (default: hazecoin.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 4369 or testnet: 14369)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 4370 or testnet: 14370)</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=hazecoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;HazeCoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. HazeCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong HazeCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>ब्लॉक्स जाँचे जा रहा है...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>वॉलेट जाँचा जा रहा है...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation>जानकारी</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>SSL options: (see the HazeCoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Warning</source> <translation>चेतावनी</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+165"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>पता पुस्तक आ रही है...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of HazeCoin</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart HazeCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>राशि ग़लत है</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>ब्लॉक इंडेक्स आ रहा है...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. HazeCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>वॉलेट आ रहा है...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>रि-स्केनी-इंग...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>लोड हो गया|</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>भूल</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<|file_name|>react-tap-event-plugin-tests.ts<|end_file_name|><|fim▁begin|>/// <reference path="react-tap-event-plugin.d.ts"/> import * as injectTapEventPluginAll from 'react-tap-event-plugin'; // since the export is a function, this is the only actual correct way: import injectTapEventPluginRequire = require("react-tap-event-plugin"); injectTapEventPluginAll(); injectTapEventPluginAll({<|fim▁hole|> return true; } }); injectTapEventPluginRequire(); injectTapEventPluginRequire({});<|fim▁end|>
shouldRejectClick: function (lastTouchEventTimestamp, clickEventTimestamp) {
<|file_name|>export.js<|end_file_name|><|fim▁begin|>const getExport = require('../services/get-export') const getSubNav = require('../services/get-sub-nav') const organisationUnit = require('../constants/organisation-unit') const authorisation = require('../authorisation') const workloadTypes = require('../constants/workload-type') const getLastUpdated = require('../services/data/get-last-updated') const dateFormatter = require('../services/date-formatter') const getArmsExport = require('../services/data/get-arms-export') const getCMSExport = require('../services/data/get-cms-export') const getCaseDetailsExport = require('../services/data/get-case-details-export') const getSuspendedLifersExport = require('../services/data/get-suspended-lifers-export') const getGroupSupervisionExport = require('../services/data/get-group-supervision-export') const getT2aDetailExport = require('../services/data/get-t2a-detail-export') const getScenarioExport = require('../services/get-scenario') const getWorkloadPercentageBreakdown = require('../services/data/get-workload-percentage-breakdown') const getExportCsv = require('../services/get-export-csv') const tabs = require('../constants/wmt-tabs') const getExpiringReductions = require('../services/data/get-expiring-reductions-for-export') const Forbidden = require('../services/errors/authentication-error').Forbidden const { SUPER_USER, APPLICATION_SUPPORT, MANAGER } = require('../constants/user-roles') const messages = require('../constants/messages') const canExportRoles = [SUPER_USER, MANAGER] let lastUpdated module.exports = function (router) { router.get('/' + workloadTypes.PROBATION + '/:organisationLevel/:id/export', function (req, res, next) {<|fim▁hole|> if (error instanceof Forbidden) { return res.status(error.statusCode).render(error.redirect, { heading: messages.ACCESS_DENIED }) } } const organisationLevel = req.params.organisationLevel let id if (organisationLevel !== organisationUnit.NATIONAL.name) { id = req.params.id } const authorisedUserRole = authorisation.getAuthorisedUserRole(req) return getLastUpdated().then(function (lastUpdatedDate) { lastUpdated = dateFormatter.formatDate(lastUpdatedDate.date_processed, 'DD-MM-YYYY HH:mm') return getExport(id, organisationLevel).then(function (result) { result.date = lastUpdated return res.render('export', { organisationLevel: organisationLevel, linkId: req.params.id, title: result.title, subTitle: result.subTitle, breadcrumbs: result.breadcrumbs, subNav: getSubNav(id, organisationLevel, req.path, workloadTypes.PROBATION, authorisedUserRole.authorisation, authorisedUserRole.userRole), date: result.date, canExport: canExportRoles.includes(authorisedUserRole.userRole) }) }) }).catch(function (error) { next(error) }) }) router.post('/' + workloadTypes.PROBATION + '/:organisationLevel/:id/export', function (req, res, next) { try { authorisation.hasRole(req, canExportRoles) } catch (error) { if (error instanceof Forbidden) { return res.status(error.statusCode).render(error.redirect, { heading: messages.ACCESS_DENIED }) } } const organisationLevel = req.params.organisationLevel let id if (organisationLevel !== organisationUnit.NATIONAL.name) { id = req.params.id } const radioButton = req.body.radioInlineGroup return getLastUpdated().then(function (result) { lastUpdated = dateFormatter.formatDate(result.date_processed, 'DD-MM-YYYY HH:mm') let tabType let exportPromise switch (radioButton) { case '1': exportPromise = getArmsExport(id, organisationLevel) tabType = tabs.EXPORT.ARMS_EXPORT break case '2': exportPromise = getCaseDetailsExport(id, organisationLevel) tabType = tabs.EXPORT.CASE_DETAILS_EXPORT break case '3': exportPromise = getCMSExport(id, organisationLevel) tabType = tabs.EXPORT.CMS_EXPORT break case '4': exportPromise = getGroupSupervisionExport(id, organisationLevel) tabType = tabs.EXPORT.GROUP_SUPERVISION_EXPORT break case '5': exportPromise = getScenarioExport(id, organisationLevel) break case '6': exportPromise = getSuspendedLifersExport(id, organisationLevel) tabType = tabs.EXPORT.SUSPENDED_LIFERS_EXPORT break case '7': exportPromise = getWorkloadPercentageBreakdown(id, organisationLevel) tabType = tabs.EXPORT.WORKLOAD_PERCENTAGE_EXPORT break case '8': exportPromise = getT2aDetailExport(id, organisationLevel) tabType = tabs.EXPORT.T2A_EXPORT break case '9': exportPromise = getExpiringReductions(id, organisationLevel) tabType = tabs.EXPORT.EXPIRING_REDUCTIONS break default: exportPromise = Promise.resolve() } return exportPromise.then(function (results) { if (radioButton === '5') { const scenarioFileName = `${organisationLevel}_Scenario_${dateFormatter.formatDate(result.date_processed, 'DD-MM-YYYY')}.xlsx` results.write(scenarioFileName, res) } else { formatResults(results, tabType) result.date = lastUpdated results.title = dateFormatter.formatDate(result.date_processed, 'DD-MM-YYYY') let dateFileName = null dateFileName = result.title const exportCsv = getExportCsv(dateFileName, results, tabType) res.attachment(exportCsv.filename) res.send(exportCsv.csv) } }) }).catch(function (error) { next(error) }) }) } const formatResults = function (results, tabType) { let newDate, year, month, dt results.forEach(function (result) { if ((tabType === tabs.EXPORT.GROUP_SUPERVISION_EXPORT) || (tabType === tabs.EXPORT.CMS_EXPORT)) { newDate = new Date(result.contactDate) year = newDate.getFullYear() month = newDate.getMonth() + 1 dt = newDate.getDate() result.contactDate = dt + '-' + month + '-' + year } }) return results }<|fim▁end|>
try { authorisation.hasRole(req, [SUPER_USER, APPLICATION_SUPPORT, MANAGER]) } catch (error) {
<|file_name|>switch.py<|end_file_name|><|fim▁begin|>"""Integration with the Rachio Iro sprinkler system controller.""" from abc import abstractmethod from contextlib import suppress from datetime import timedelta import logging import voluptuous as vol from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_ENTITY_ID, ATTR_ID from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_validation as cv, entity_platform from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util.dt import as_timestamp, now, parse_datetime, utc_from_timestamp from .const import ( CONF_MANUAL_RUN_MINS, DEFAULT_MANUAL_RUN_MINS, DOMAIN as DOMAIN_RACHIO, KEY_CUSTOM_CROP, KEY_CUSTOM_SHADE, KEY_CUSTOM_SLOPE, KEY_DEVICE_ID, KEY_DURATION, KEY_ENABLED, KEY_ID, KEY_IMAGE_URL, KEY_NAME, KEY_ON, KEY_RAIN_DELAY, KEY_RAIN_DELAY_END, KEY_SCHEDULE_ID, KEY_SUBTYPE, KEY_SUMMARY, KEY_TYPE, KEY_ZONE_ID, KEY_ZONE_NUMBER, SCHEDULE_TYPE_FIXED, SCHEDULE_TYPE_FLEX, SERVICE_SET_ZONE_MOISTURE, SERVICE_START_MULTIPLE_ZONES, SIGNAL_RACHIO_CONTROLLER_UPDATE, SIGNAL_RACHIO_RAIN_DELAY_UPDATE, SIGNAL_RACHIO_SCHEDULE_UPDATE, SIGNAL_RACHIO_ZONE_UPDATE, SLOPE_FLAT, SLOPE_MODERATE, SLOPE_SLIGHT, SLOPE_STEEP, ) from .entity import RachioDevice from .webhooks import ( SUBTYPE_RAIN_DELAY_OFF, SUBTYPE_RAIN_DELAY_ON, SUBTYPE_SCHEDULE_COMPLETED, SUBTYPE_SCHEDULE_STARTED, SUBTYPE_SCHEDULE_STOPPED, SUBTYPE_SLEEP_MODE_OFF, SUBTYPE_SLEEP_MODE_ON, SUBTYPE_ZONE_COMPLETED, SUBTYPE_ZONE_PAUSED, SUBTYPE_ZONE_STARTED, SUBTYPE_ZONE_STOPPED, ) _LOGGER = logging.getLogger(__name__) ATTR_DURATION = "duration" ATTR_PERCENT = "percent" ATTR_SCHEDULE_SUMMARY = "Summary" ATTR_SCHEDULE_ENABLED = "Enabled" ATTR_SCHEDULE_DURATION = "Duration" ATTR_SCHEDULE_TYPE = "Type" ATTR_SORT_ORDER = "sortOrder" ATTR_ZONE_NUMBER = "Zone number" ATTR_ZONE_SHADE = "Shade" ATTR_ZONE_SLOPE = "Slope" ATTR_ZONE_SUMMARY = "Summary" ATTR_ZONE_TYPE = "Type" START_MULTIPLE_ZONES_SCHEMA = vol.Schema( { vol.Required(ATTR_ENTITY_ID): cv.entity_ids, vol.Required(ATTR_DURATION): cv.ensure_list_csv, } ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the Rachio switches.""" zone_entities = [] has_flex_sched = False entities = await hass.async_add_executor_job(_create_entities, hass, config_entry) for entity in entities: if isinstance(entity, RachioZone): zone_entities.append(entity) if isinstance(entity, RachioSchedule) and entity.type == SCHEDULE_TYPE_FLEX: has_flex_sched = True async_add_entities(entities) _LOGGER.info("%d Rachio switch(es) added", len(entities)) def start_multiple(service: ServiceCall) -> None: """Service to start multiple zones in sequence.""" zones_list = [] person = hass.data[DOMAIN_RACHIO][config_entry.entry_id] entity_id = service.data[ATTR_ENTITY_ID] duration = iter(service.data[ATTR_DURATION]) default_time = service.data[ATTR_DURATION][0] entity_to_zone_id = { entity.entity_id: entity.zone_id for entity in zone_entities } for (count, data) in enumerate(entity_id): if data in entity_to_zone_id: # Time can be passed as a list per zone, # or one time for all zones time = int(next(duration, default_time)) * 60 zones_list.append( { ATTR_ID: entity_to_zone_id.get(data), ATTR_DURATION: time, ATTR_SORT_ORDER: count, } ) if len(zones_list) != 0: person.start_multiple_zones(zones_list) _LOGGER.debug("Starting zone(s) %s", entity_id) else: raise HomeAssistantError("No matching zones found in given entity_ids") hass.services.async_register( DOMAIN_RACHIO, SERVICE_START_MULTIPLE_ZONES, start_multiple, schema=START_MULTIPLE_ZONES_SCHEMA, ) if has_flex_sched: platform = entity_platform.async_get_current_platform() platform.async_register_entity_service( SERVICE_SET_ZONE_MOISTURE, {vol.Required(ATTR_PERCENT): cv.positive_int}, "set_moisture_percent", ) def _create_entities(hass, config_entry): entities = [] person = hass.data[DOMAIN_RACHIO][config_entry.entry_id] # Fetch the schedule once at startup # in order to avoid every zone doing it for controller in person.controllers: entities.append(RachioStandbySwitch(controller)) entities.append(RachioRainDelay(controller)) zones = controller.list_zones() schedules = controller.list_schedules() flex_schedules = controller.list_flex_schedules() current_schedule = controller.current_schedule for zone in zones: entities.append(RachioZone(person, controller, zone, current_schedule)) for sched in schedules + flex_schedules: entities.append(RachioSchedule(person, controller, sched, current_schedule)) _LOGGER.debug("Added %s", entities) return entities class RachioSwitch(RachioDevice, SwitchEntity): """Represent a Rachio state that can be toggled.""" def __init__(self, controller): """Initialize a new Rachio switch.""" super().__init__(controller) self._state = None<|fim▁hole|> @property def name(self) -> str: """Get a name for this switch.""" return f"Switch on {self._controller.name}" @property def is_on(self) -> bool: """Return whether the switch is currently on.""" return self._state @callback def _async_handle_any_update(self, *args, **kwargs) -> None: """Determine whether an update event applies to this device.""" if args[0][KEY_DEVICE_ID] != self._controller.controller_id: # For another device return # For this device self._async_handle_update(args, kwargs) @abstractmethod def _async_handle_update(self, *args, **kwargs) -> None: """Handle incoming webhook data.""" class RachioStandbySwitch(RachioSwitch): """Representation of a standby status/button.""" @property def name(self) -> str: """Return the name of the standby switch.""" return f"{self._controller.name} in standby mode" @property def unique_id(self) -> str: """Return a unique id by combining controller id and purpose.""" return f"{self._controller.controller_id}-standby" @property def icon(self) -> str: """Return an icon for the standby switch.""" return "mdi:power" @callback def _async_handle_update(self, *args, **kwargs) -> None: """Update the state using webhook data.""" if args[0][0][KEY_SUBTYPE] == SUBTYPE_SLEEP_MODE_ON: self._state = True elif args[0][0][KEY_SUBTYPE] == SUBTYPE_SLEEP_MODE_OFF: self._state = False self.async_write_ha_state() def turn_on(self, **kwargs) -> None: """Put the controller in standby mode.""" self._controller.rachio.device.turn_off(self._controller.controller_id) def turn_off(self, **kwargs) -> None: """Resume controller functionality.""" self._controller.rachio.device.turn_on(self._controller.controller_id) async def async_added_to_hass(self): """Subscribe to updates.""" if KEY_ON in self._controller.init_data: self._state = not self._controller.init_data[KEY_ON] self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_RACHIO_CONTROLLER_UPDATE, self._async_handle_any_update, ) ) class RachioRainDelay(RachioSwitch): """Representation of a rain delay status/switch.""" def __init__(self, controller): """Set up a Rachio rain delay switch.""" self._cancel_update = None super().__init__(controller) @property def name(self) -> str: """Return the name of the switch.""" return f"{self._controller.name} rain delay" @property def unique_id(self) -> str: """Return a unique id by combining controller id and purpose.""" return f"{self._controller.controller_id}-delay" @property def icon(self) -> str: """Return an icon for rain delay.""" return "mdi:camera-timer" @callback def _async_handle_update(self, *args, **kwargs) -> None: """Update the state using webhook data.""" if self._cancel_update: self._cancel_update() self._cancel_update = None if args[0][0][KEY_SUBTYPE] == SUBTYPE_RAIN_DELAY_ON: endtime = parse_datetime(args[0][0][KEY_RAIN_DELAY_END]) _LOGGER.debug("Rain delay expires at %s", endtime) self._state = True assert endtime is not None self._cancel_update = async_track_point_in_utc_time( self.hass, self._delay_expiration, endtime ) elif args[0][0][KEY_SUBTYPE] == SUBTYPE_RAIN_DELAY_OFF: self._state = False self.async_write_ha_state() @callback def _delay_expiration(self, *args) -> None: """Trigger when a rain delay expires.""" self._state = False self._cancel_update = None self.async_write_ha_state() def turn_on(self, **kwargs) -> None: """Activate a 24 hour rain delay on the controller.""" self._controller.rachio.device.rain_delay(self._controller.controller_id, 86400) _LOGGER.debug("Starting rain delay for 24 hours") def turn_off(self, **kwargs) -> None: """Resume controller functionality.""" self._controller.rachio.device.rain_delay(self._controller.controller_id, 0) _LOGGER.debug("Canceling rain delay") async def async_added_to_hass(self): """Subscribe to updates.""" if KEY_RAIN_DELAY in self._controller.init_data: self._state = self._controller.init_data[ KEY_RAIN_DELAY ] / 1000 > as_timestamp(now()) # If the controller was in a rain delay state during a reboot, this re-sets the timer if self._state is True: delay_end = utc_from_timestamp( self._controller.init_data[KEY_RAIN_DELAY] / 1000 ) _LOGGER.debug("Re-setting rain delay timer for %s", delay_end) self._cancel_update = async_track_point_in_utc_time( self.hass, self._delay_expiration, delay_end ) self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_RACHIO_RAIN_DELAY_UPDATE, self._async_handle_any_update, ) ) class RachioZone(RachioSwitch): """Representation of one zone of sprinklers connected to the Rachio Iro.""" def __init__(self, person, controller, data, current_schedule): """Initialize a new Rachio Zone.""" self.id = data[KEY_ID] self._zone_name = data[KEY_NAME] self._zone_number = data[KEY_ZONE_NUMBER] self._zone_enabled = data[KEY_ENABLED] self._entity_picture = data.get(KEY_IMAGE_URL) self._person = person self._shade_type = data.get(KEY_CUSTOM_SHADE, {}).get(KEY_NAME) self._zone_type = data.get(KEY_CUSTOM_CROP, {}).get(KEY_NAME) self._slope_type = data.get(KEY_CUSTOM_SLOPE, {}).get(KEY_NAME) self._summary = "" self._current_schedule = current_schedule super().__init__(controller) def __str__(self): """Display the zone as a string.""" return f'Rachio Zone "{self.name}" on {str(self._controller)}' @property def zone_id(self) -> str: """How the Rachio API refers to the zone.""" return self.id @property def name(self) -> str: """Return the friendly name of the zone.""" return self._zone_name @property def unique_id(self) -> str: """Return a unique id by combining controller id and zone number.""" return f"{self._controller.controller_id}-zone-{self.zone_id}" @property def icon(self) -> str: """Return the icon to display.""" return "mdi:water" @property def zone_is_enabled(self) -> bool: """Return whether the zone is allowed to run.""" return self._zone_enabled @property def entity_picture(self): """Return the entity picture to use in the frontend, if any.""" return self._entity_picture @property def extra_state_attributes(self) -> dict: """Return the optional state attributes.""" props = {ATTR_ZONE_NUMBER: self._zone_number, ATTR_ZONE_SUMMARY: self._summary} if self._shade_type: props[ATTR_ZONE_SHADE] = self._shade_type if self._zone_type: props[ATTR_ZONE_TYPE] = self._zone_type if self._slope_type: if self._slope_type == SLOPE_FLAT: props[ATTR_ZONE_SLOPE] = "Flat" elif self._slope_type == SLOPE_SLIGHT: props[ATTR_ZONE_SLOPE] = "Slight" elif self._slope_type == SLOPE_MODERATE: props[ATTR_ZONE_SLOPE] = "Moderate" elif self._slope_type == SLOPE_STEEP: props[ATTR_ZONE_SLOPE] = "Steep" return props def turn_on(self, **kwargs) -> None: """Start watering this zone.""" # Stop other zones first self.turn_off() # Start this zone manual_run_time = timedelta( minutes=self._person.config_entry.options.get( CONF_MANUAL_RUN_MINS, DEFAULT_MANUAL_RUN_MINS ) ) # The API limit is 3 hours, and requires an int be passed self._controller.rachio.zone.start(self.zone_id, manual_run_time.seconds) _LOGGER.debug( "Watering %s on %s for %s", self.name, self._controller.name, str(manual_run_time), ) def turn_off(self, **kwargs) -> None: """Stop watering all zones.""" self._controller.stop_watering() def set_moisture_percent(self, percent) -> None: """Set the zone moisture percent.""" _LOGGER.debug("Setting %s moisture to %s percent", self._zone_name, percent) self._controller.rachio.zone.set_moisture_percent(self.id, percent / 100) @callback def _async_handle_update(self, *args, **kwargs) -> None: """Handle incoming webhook zone data.""" if args[0][KEY_ZONE_ID] != self.zone_id: return self._summary = args[0][KEY_SUMMARY] if args[0][KEY_SUBTYPE] == SUBTYPE_ZONE_STARTED: self._state = True elif args[0][KEY_SUBTYPE] in [ SUBTYPE_ZONE_STOPPED, SUBTYPE_ZONE_COMPLETED, SUBTYPE_ZONE_PAUSED, ]: self._state = False self.async_write_ha_state() async def async_added_to_hass(self): """Subscribe to updates.""" self._state = self.zone_id == self._current_schedule.get(KEY_ZONE_ID) self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_RACHIO_ZONE_UPDATE, self._async_handle_update ) ) class RachioSchedule(RachioSwitch): """Representation of one fixed schedule on the Rachio Iro.""" def __init__(self, person, controller, data, current_schedule): """Initialize a new Rachio Schedule.""" self._schedule_id = data[KEY_ID] self._schedule_name = data[KEY_NAME] self._duration = data[KEY_DURATION] self._schedule_enabled = data[KEY_ENABLED] self._summary = data[KEY_SUMMARY] self.type = data.get(KEY_TYPE, SCHEDULE_TYPE_FIXED) self._current_schedule = current_schedule super().__init__(controller) @property def name(self) -> str: """Return the friendly name of the schedule.""" return f"{self._schedule_name} Schedule" @property def unique_id(self) -> str: """Return a unique id by combining controller id and schedule.""" return f"{self._controller.controller_id}-schedule-{self._schedule_id}" @property def icon(self) -> str: """Return the icon to display.""" return "mdi:water" if self.schedule_is_enabled else "mdi:water-off" @property def extra_state_attributes(self) -> dict: """Return the optional state attributes.""" return { ATTR_SCHEDULE_SUMMARY: self._summary, ATTR_SCHEDULE_ENABLED: self.schedule_is_enabled, ATTR_SCHEDULE_DURATION: f"{round(self._duration / 60)} minutes", ATTR_SCHEDULE_TYPE: self.type, } @property def schedule_is_enabled(self) -> bool: """Return whether the schedule is allowed to run.""" return self._schedule_enabled def turn_on(self, **kwargs) -> None: """Start this schedule.""" self._controller.rachio.schedulerule.start(self._schedule_id) _LOGGER.debug( "Schedule %s started on %s", self.name, self._controller.name, ) def turn_off(self, **kwargs) -> None: """Stop watering all zones.""" self._controller.stop_watering() @callback def _async_handle_update(self, *args, **kwargs) -> None: """Handle incoming webhook schedule data.""" # Schedule ID not passed when running individual zones, so we catch that error with suppress(KeyError): if args[0][KEY_SCHEDULE_ID] == self._schedule_id: if args[0][KEY_SUBTYPE] in [SUBTYPE_SCHEDULE_STARTED]: self._state = True elif args[0][KEY_SUBTYPE] in [ SUBTYPE_SCHEDULE_STOPPED, SUBTYPE_SCHEDULE_COMPLETED, ]: self._state = False self.async_write_ha_state() async def async_added_to_hass(self): """Subscribe to updates.""" self._state = self._schedule_id == self._current_schedule.get(KEY_SCHEDULE_ID) self.async_on_remove( async_dispatcher_connect( self.hass, SIGNAL_RACHIO_SCHEDULE_UPDATE, self._async_handle_update ) )<|fim▁end|>
<|file_name|>YeastType.java<|end_file_name|><|fim▁begin|>/* * Copyright 2006, 2007 Alessandro Chiari. * * This file is part of BrewPlus. * * BrewPlus is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * BrewPlus is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with BrewPlus; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package jmash; import jmash.interfaces.XmlAble; import org.apache.log4j.Logger; import org.jdom.Element; /** * * @author Alessandro */ public class YeastType implements XmlAble { private static Logger LOGGER = Logger.getLogger(YeastType.class); /** Creates a new instance of YeastType */ public YeastType() { } private String nome; private String codice; private String produttore; private String forma; private String categoria; private String descrizione; private String attenuazioneMed; private String attenuazioneMin; private String attenuazioneMax; private String temperaturaMin; private String temperaturaMax; private String temperaturaMaxFerm; private static String campiXml[] = { "nome", "codice", "produttore", "forma", "categoria", "attenuazioneMed", "attenuazioneMin", "attenuazioneMax", "temperaturaMin", "temperaturaMax", "descrizione"}; public String getNome() { return this.nome; } public void setNome(String nome) {<|fim▁hole|> this.nome = nome; } public String getCodice() { return this.codice; } public void setCodice(String codice) { this.codice = codice; } public String getProduttore() { return this.produttore; } public void setProduttore(String produttore) { this.produttore = produttore; } public String getForma() { return this.forma; } public void setForma(String forma) { this.forma = forma; } public String getCategoria() { return this.categoria; } public void setCategoria(String categoria) { this.categoria = categoria; } public String getDescrizione() { return this.descrizione; } public void setDescrizione(String descrizione) { this.descrizione = descrizione; } public String getAttenuazioneMin() { return this.attenuazioneMin; } public void setAttenuazioneMin(String attenuazioneMin) { this.attenuazioneMin = attenuazioneMin; } public String getAttenuazioneMax() { return this.attenuazioneMax; } public void setAttenuazioneMax(String attenuazioneMax) { this.attenuazioneMax = attenuazioneMax; } public String getTemperaturaMin() { return this.temperaturaMin; } public void setTemperaturaMin(String temperaturaMin) { this.temperaturaMin = temperaturaMin; } public String getTemperaturaMax() { return this.temperaturaMax; } public void setTemperaturaMax(String temperaturaMax) { this.temperaturaMax = temperaturaMax; } public String getAttenuazioneMed() { if (attenuazioneMed != null && !"".equals(attenuazioneMed)) { return this.attenuazioneMed; } else if (getAttenuazioneMin() != null && !"".equals(getAttenuazioneMin()) && getAttenuazioneMax() != null && !"".equals(getAttenuazioneMax())) { return (String.valueOf((Integer.valueOf(getAttenuazioneMin())+Integer.valueOf(getAttenuazioneMax()))/2)); } return this.attenuazioneMed; } public void setAttenuazioneMed(String attenuazioneMed) { this.attenuazioneMed = attenuazioneMed; } public String getTemperaturaMaxFerm() { return temperaturaMaxFerm; } public void setTemperaturaMaxFerm(String temperaturaMaxFerm) { this.temperaturaMaxFerm = temperaturaMaxFerm; } public static String[] getCampiXml() { return campiXml; } public static void setCampiXml(String[] aCampiXml) { campiXml = aCampiXml; } @Override public Element toXml() { try { return Utils.toXml(this, campiXml); } catch (Exception ex) { LOGGER.error(ex.getMessage(), ex); } return null; } @Override public String getTag() { return "yeasts"; } @Override public String[] getXmlFields() { return campiXml; } }<|fim▁end|>
<|file_name|>filter.js<|end_file_name|><|fim▁begin|>/*! * Jade - nodes - Filter * Copyright(c) 2010 TJ Holowaychuk <[email protected]> * MIT Licensed */ /** * Module dependencies. */ var Node = require('./node'); /** * Initialize a `Filter` node with the given * filter `name` and `block`. * * @param {String} name * @param {Block|Node} block * @api public */ var Filter = module.exports = function Filter(name, block, attrs) { this.name = name; this.block = block; this.attrs = attrs; }; <|fim▁hole|> * Inherit from `Node`. */ Filter.prototype.__proto__ = Node.prototype;<|fim▁end|>
/**
<|file_name|>create_fakes.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """Fake data generator. To use: 1. Install fake-factory. pip install fake-factory 2. Create your OSF user account 3. Run the script, passing in your username (email). :: python3 -m scripts.create_fakes --user [email protected] This will create 3 fake public projects, each with 3 fake contributors (with you as the creator). To create a project with a complex component structure, pass in a list representing the depth you would like each component to contain. Examples: python3 -m scripts.create_fakes -u fred@cos --components '[1, 1, 1, 1]' --nprojects 1 ...will create a project with 4 components. python3 -m scripts.create_fakes -u fred@cos --components '4' --nprojects 1 ...will create a project with a series of components, 4 levels deep. python3 -m scripts.create_fakes -u fred@cos --components '[1, [1, 1]]' --nprojects 1 ...will create a project with two top level components, and one with a depth of 2 components. python3 -m scripts.create_fakes -u fred@cos --nprojects 3 --preprint True ...will create 3 preprints with the default provider osf python3 -m scripts.create_fakes -u fred@cos --nprojects 3 --preprint True --preprintprovider osf,test_provider ...will create 3 preprints with the providers osf and test_provider """ from __future__ import print_function, absolute_import import ast import sys import mock import argparse import logging import django<|fim▁hole|>from faker.providers import BaseProvider django.setup() from framework.auth import Auth from osf_tests.factories import UserFactory, ProjectFactory, NodeFactory, RegistrationFactory, PreprintFactory, PreprintProviderFactory, fake_email from osf import models from website.app import init_app class Sciencer(BaseProvider): # Science term Faker Provider created by @csheldonhess # https://github.com/csheldonhess/FakeConsumer/blob/master/faker/providers/science.py word_list = ('abiosis', 'abrade', 'absorption', 'acceleration', 'accumulation', 'acid', 'acidic', 'activist', 'adaptation', 'agonistic', 'agrarian', 'airborne', 'alchemist', 'alignment', 'allele', 'alluvial', 'alveoli', 'ambiparous', 'amphibian', 'amplitude', 'analysis', 'ancestor', 'anodize', 'anomaly', 'anther', 'antigen', 'apiary', 'apparatus', 'application', 'approximation', 'aquatic', 'aquifer', 'arboreal', 'archaeology', 'artery', 'assessment', 'asteroid', 'atmosphere', 'atomic', 'atrophy', 'attenuate', 'aven', 'aviary', 'axis', 'bacteria', 'balance', 'bases', 'biome', 'biosphere', 'black hole', 'blight', 'buoyancy', 'calcium', 'canopy', 'capacity', 'capillary', 'carapace', 'carcinogen', 'catalyst', 'cauldron', 'celestial', 'cells', 'centigrade', 'centimeter', 'centrifugal', 'chemical reaction', 'chemicals', 'chemistry', 'chlorophyll', 'choked', 'chromosome', 'chronic', 'churn', 'classification', 'climate', 'cloud', 'comet', 'composition', 'compound', 'compression', 'condensation', 'conditions', 'conduction', 'conductivity', 'conservation', 'constant', 'constellation', 'continental', 'convection', 'convention', 'cool', 'core', 'cosmic', 'crater', 'creature', 'crepuscular', 'crystals', 'cycle', 'cytoplasm', 'dampness', 'data', 'decay', 'decibel', 'deciduous', 'defoliate', 'density', 'denude', 'dependency', 'deposits', 'depth', 'desiccant', 'detritus', 'development', 'digestible', 'diluted', 'direction', 'disappearance', 'discovery', 'dislodge', 'displace', 'dissection', 'dissolution', 'dissolve', 'distance', 'diurnal', 'diverse', 'doldrums', 'dynamics', 'earthquake', 'eclipse', 'ecology', 'ecosystem', 'electricity', 'elements', 'elevation', 'embryo', 'endangered', 'endocrine', 'energy', 'entropy', 'environment', 'enzyme', 'epidermis', 'epoch', 'equilibrium', 'equine', 'erosion', 'essential', 'estuary', 'ethical', 'evaporation', 'event', 'evidence', 'evolution', 'examination', 'existence', 'expansion', 'experiment', 'exploration ', 'extinction', 'extreme', 'facet', 'fault', 'fauna', 'feldspar', 'fermenting', 'fission', 'fissure', 'flora', 'flourish', 'flowstone', 'foliage', 'food chain', 'forage', 'force', 'forecast', 'forensics', 'formations', 'fossil fuel', 'frequency', 'friction', 'fungi', 'fusion', 'galaxy', 'gastric', 'geo-science', 'geothermal', 'germination', 'gestation', 'global', 'gravitation', 'green', 'greenhouse effect', 'grotto', 'groundwater', 'habitat', 'heat', 'heavens', 'hemisphere', 'hemoglobin', 'herpetologist', 'hormones', 'host', 'humidity', 'hyaline', 'hydrogen', 'hydrology', 'hypothesis', 'ichthyology', 'illumination', 'imagination', 'impact of', 'impulse', 'incandescent', 'indigenous', 'inertia', 'inevitable', 'inherit', 'inquiry', 'insoluble', 'instinct', 'instruments', 'integrity', 'intelligence', 'interacts with', 'interdependence', 'interplanetary', 'invertebrate', 'investigation', 'invisible', 'ions', 'irradiate', 'isobar', 'isotope', 'joule', 'jungle', 'jurassic', 'jutting', 'kilometer', 'kinetics', 'kingdom', 'knot', 'laser', 'latitude', 'lava', 'lethal', 'life', 'lift', 'light', 'limestone', 'lipid', 'lithosphere', 'load', 'lodestone', 'luminous', 'luster', 'magma', 'magnet', 'magnetism', 'mangrove', 'mantle', 'marine', 'marsh', 'mass', 'matter', 'measurements', 'mechanical', 'meiosis', 'meridian', 'metamorphosis', 'meteor', 'microbes', 'microcosm', 'migration', 'millennia', 'minerals', 'modulate', 'moisture', 'molecule', 'molten', 'monograph', 'monolith', 'motion', 'movement', 'mutant', 'mutation', 'mysterious', 'natural', 'navigable', 'navigation', 'negligence', 'nervous system', 'nesting', 'neutrons', 'niche', 'nocturnal', 'nuclear energy', 'numerous', 'nurture', 'obsidian', 'ocean', 'oceanography', 'omnivorous', 'oolites (cave pearls)', 'opaque', 'orbit', 'organ', 'organism', 'ornithology', 'osmosis', 'oxygen', 'paleontology', 'parallax', 'particle', 'penumbra', 'percolate', 'permafrost', 'permutation', 'petrify', 'petrograph', 'phenomena', 'physical property', 'planetary', 'plasma', 'polar', 'pole', 'pollination', 'polymer', 'population', 'precipitation', 'predator', 'prehensile', 'preservation', 'preserve', 'pressure', 'primate', 'pristine', 'probe', 'process', 'propagation', 'properties', 'protected', 'proton', 'pulley', 'qualitative data', 'quantum', 'quark', 'quarry', 'radiation', 'radioactivity', 'rain forest', 'ratio', 'reaction', 'reagent', 'realm', 'redwoods', 'reeds', 'reflection', 'refraction', 'relationships between', 'reptile', 'research', 'resistance', 'resonate', 'rookery', 'rubble', 'runoff', 'salinity', 'sandbar', 'satellite', 'saturation', 'scientific investigation', 'scientist\'s', 'sea floor', 'season', 'sedentary', 'sediment', 'sedimentary', 'seepage', 'seismic', 'sensors', 'shard', 'similarity', 'solar', 'soluble', 'solvent', 'sonic', 'sound', 'source', 'species', 'spectacular', 'spectrum', 'speed', 'sphere', 'spring', 'stage', 'stalactite', 'stalagmites', 'stimulus', 'substance', 'subterranean', 'sulfuric acid', 'surface', 'survival', 'swamp', 'sylvan', 'symbiosis', 'symbol', 'synergy', 'synthesis', 'taiga', 'taxidermy', 'technology', 'tectonics', 'temperate', 'temperature', 'terrestrial', 'thermals', 'thermometer', 'thrust', 'torque', 'toxin', 'trade winds', 'pterodactyl', 'transformation tremors', 'tropical', 'umbra', 'unbelievable', 'underwater', 'unearth', 'unique', 'unite', 'unity', 'universal', 'unpredictable', 'unusual', 'ursine', 'vacuole', 'valuable', 'vapor', 'variable', 'variety', 'vast', 'velocity', 'ventifact', 'verdant', 'vespiary', 'viable', 'vibration', 'virus', 'viscosity', 'visible', 'vista', 'vital', 'vitreous', 'volt', 'volume', 'vulpine', 'wave', 'wax', 'weather', 'westerlies', 'wetlands', 'whitewater', 'xeriscape', 'xylem', 'yield', 'zero-impact', 'zone', 'zygote', 'achieving', 'acquisition of', 'an alternative', 'analysis of', 'approach toward', 'area', 'aspects of', 'assessment of', 'assuming', 'authority', 'available', 'benefit of', 'circumstantial', 'commentary', 'components', 'concept of', 'consistent', 'corresponding', 'criteria', 'data', 'deduction', 'demonstrating', 'derived', 'distribution', 'dominant', 'elements', 'equation', 'estimate', 'evaluation', 'factors', 'features', 'final', 'function', 'initial', 'instance ', 'interpretation of', 'maintaining ', 'method', 'perceived', 'percent', 'period', 'positive', 'potential', 'previous', 'primary', 'principle', 'procedure', 'process', 'range', 'region', 'relevant', 'required', 'research', 'resources', 'response', 'role', 'section', 'select', 'significant ', 'similar', 'source', 'specific', 'strategies', 'structure', 'theory', 'transfer', 'variables', 'corvidae', 'passerine', 'Pica pica', 'Chinchilla lanigera', 'Nymphicus hollandicus', 'Melopsittacus undulatus', ) def science_word(cls): """ :example 'Lorem' """ return cls.random_element(cls.word_list) def science_words(cls, nb=3): """ Generate an array of random words :example array('Lorem', 'ipsum', 'dolor') :param nb how many words to return """ return [cls.science_word() for _ in range(0, nb)] def science_sentence(cls, nb_words=6, variable_nb_words=True): """ Generate a random sentence :example 'Lorem ipsum dolor sit amet.' :param nb_words around how many words the sentence should contain :param variable_nb_words set to false if you want exactly $nbWords returned, otherwise $nbWords may vary by +/-40% with a minimum of 1 """ if nb_words <= 0: return '' if variable_nb_words: nb_words = cls.randomize_nb_elements(nb_words) words = cls.science_words(nb_words) words[0] = words[0].title() return ' '.join(words) + '.' def science_sentences(cls, nb=3): """ Generate an array of sentences :example array('Lorem ipsum dolor sit amet.', 'Consectetur adipisicing eli.') :param nb how many sentences to return :return list """ return [cls.science_sentence() for _ in range(0, nb)] def science_paragraph(cls, nb_sentences=3, variable_nb_sentences=True): """ Generate a single paragraph :example 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.' :param nb_sentences around how many sentences the paragraph should contain :param variable_nb_sentences set to false if you want exactly $nbSentences returned, otherwise $nbSentences may vary by +/-40% with a minimum of 1 :return string """ if nb_sentences <= 0: return '' if variable_nb_sentences: nb_sentences = cls.randomize_nb_elements(nb_sentences) return ' '.join(cls.science_sentences(nb_sentences)) def science_paragraphs(cls, nb=3): """ Generate an array of paragraphs :example array($paragraph1, $paragraph2, $paragraph3) :param nb how many paragraphs to return :return array """ return [cls.science_paragraph() for _ in range(0, nb)] def science_text(cls, max_nb_chars=200): """ Generate a text string. Depending on the $maxNbChars, returns a string made of words, sentences, or paragraphs. :example 'Sapiente sunt omnis. Ut pariatur ad autem ducimus et. Voluptas rem voluptas sint modi dolorem amet.' :param max_nb_chars Maximum number of characters the text should contain (minimum 5) :return string """ text = [] if max_nb_chars < 5: raise ValueError('text() can only generate text of at least 5 characters') if max_nb_chars < 25: # join words while not text: size = 0 # determine how many words are needed to reach the $max_nb_chars once; while size < max_nb_chars: word = (' ' if size else '') + cls.science_word() text.append(word) size += len(word) text.pop() text[0] = text[0][0].upper() + text[0][1:] last_index = len(text) - 1 text[last_index] += '.' elif max_nb_chars < 100: # join sentences while not text: size = 0 # determine how many sentences are needed to reach the $max_nb_chars once while size < max_nb_chars: sentence = (' ' if size else '') + cls.science_sentence() text.append(sentence) size += len(sentence) text.pop() else: # join paragraphs while not text: size = 0 # determine how many paragraphs are needed to reach the $max_nb_chars once while size < max_nb_chars: paragraph = ('\n' if size else '') + cls.science_paragraph() text.append(paragraph) size += len(paragraph) text.pop() return ''.join(text) logger = logging.getLogger('create_fakes') SILENT_LOGGERS = [ 'factory', 'website.mails', ] for logger_name in SILENT_LOGGERS: logging.getLogger(logger_name).setLevel(logging.CRITICAL) fake = Factory.create() fake.add_provider(Sciencer) def create_fake_user(): email = fake_email() name = fake.name() user = UserFactory(username=email, fullname=name, is_registered=True, emails=[email], date_registered=fake.date_time(tzinfo=pytz.UTC), ) user.set_password('faker123') user.save() logger.info('Created user: {0} <{1}>'.format(user.fullname, user.username)) return user def parse_args(): parser = argparse.ArgumentParser(description='Create fake data.') parser.add_argument('-u', '--user', dest='user', required=True) parser.add_argument('--nusers', dest='n_users', type=int, default=3) parser.add_argument('--nprojects', dest='n_projects', type=int, default=3) parser.add_argument('-c', '--components', dest='n_components', type=evaluate_argument, default='0') parser.add_argument('-p', '--privacy', dest='privacy', type=str, default='private', choices=['public', 'private']) parser.add_argument('-n', '--name', dest='name', type=str, default=None) parser.add_argument('-t', '--tags', dest='n_tags', type=int, default=5) parser.add_argument('--presentation', dest='presentation_name', type=str, default=None) parser.add_argument('-r', '--registration', dest='is_registration', type=bool, default=False) parser.add_argument('-pre', '--preprint', dest='is_preprint', type=bool, default=False) parser.add_argument('-preprovider', '--preprintprovider', dest='preprint_provider', type=str, default=None) return parser.parse_args() def evaluate_argument(string): return ast.literal_eval(string) def create_fake_project(creator, n_users, privacy, n_components, name, n_tags, presentation_name, is_registration, is_preprint, preprint_provider): auth = Auth(user=creator) project_title = name if name else fake.science_sentence() if is_preprint: provider = None if preprint_provider: try: provider = models.PreprintProvider.objects.get(_id=provider) except models.PreprintProvider.DoesNotExist: pass if not provider: provider = PreprintProviderFactory(name=fake.science_word()) privacy = 'public' mock_change_identifier_preprints = mock.patch('website.identifiers.client.CrossRefClient.update_identifier') mock_change_identifier_preprints.start() project = PreprintFactory(title=project_title, description=fake.science_paragraph(), creator=creator, provider=provider) node = project.node elif is_registration: project = RegistrationFactory(title=project_title, description=fake.science_paragraph(), creator=creator) node = project else: project = ProjectFactory(title=project_title, description=fake.science_paragraph(), creator=creator) node = project node.set_privacy(privacy) for _ in range(n_users): contrib = create_fake_user() node.add_contributor(contrib, auth=auth) if isinstance(n_components, int): for _ in range(n_components): NodeFactory(parent=node, title=fake.science_sentence(), description=fake.science_paragraph(), creator=creator) elif isinstance(n_components, list): render_generations_from_node_structure_list(node, creator, n_components) for _ in range(n_tags): node.add_tag(fake.science_word(), auth=auth) if presentation_name is not None: node.add_tag(presentation_name, auth=auth) node.add_tag('poster', auth=auth) node.save() project.save() logger.info('Created project: {0}'.format(node.title)) return project def render_generations_from_parent(parent, creator, num_generations): current_gen = parent for generation in range(0, num_generations): next_gen = NodeFactory( parent=current_gen, creator=creator, title=fake.science_sentence(), description=fake.science_paragraph() ) current_gen = next_gen return current_gen def render_generations_from_node_structure_list(parent, creator, node_structure_list): new_parent = None for node_number in node_structure_list: if isinstance(node_number, list): render_generations_from_node_structure_list(new_parent or parent, creator, node_number) else: new_parent = render_generations_from_parent(parent, creator, node_number) return new_parent def main(): args = parse_args() creator = models.OSFUser.objects.get(username=args.user) for i in range(args.n_projects): name = args.name + str(i) if args.name else '' create_fake_project(creator, args.n_users, args.privacy, args.n_components, name, args.n_tags, args.presentation_name, args.is_registration, args.is_preprint, args.preprint_provider) print('Created {n} fake projects.'.format(n=args.n_projects)) sys.exit(0) if __name__ == '__main__': init_app(set_backends=True, routes=False) main()<|fim▁end|>
import pytz from faker import Factory
<|file_name|>niconico.js<|end_file_name|><|fim▁begin|>#!/usr/bin/env node /*jshint -W100*/ 'use strict'; /** * ニコニコ動画ログインサンプル *<|fim▁hole|> * 以下のusernameとpasswordを書き換えてから実行してください */ var username = 'hogehoge'; var password = 'fugafuga'; var client = require('../index'); console.info('ニコニコTOPページにアクセスします'); client.fetch('http://nicovideo.jp/') .then(function (result) { console.info('ログインリンクをクリックします'); return result.$('#sideNav .loginBtn').click(); }) .then(function (result) { console.info('ログインフォームを送信します'); return result.$('#login_form').submit({ mail_tel: username, password: password }); }) .then(function (result) { console.info('ログイン可否をチェックします'); if (! result.response.headers['x-niconico-id']) { throw new Error('login failed'); } console.info('クッキー', result.response.cookies); console.info('マイページに移動します'); return client.fetch('http://www.nicovideo.jp/my/top'); }) .then(function (result) { console.info('マイページに表示されるアカウント名を取得します'); console.info(result.$('#siteHeaderUserNickNameContainer').text()); }) .catch(function (err) { console.error('エラーが発生しました', err.message); }) .finally(function () { console.info('終了します'); });<|fim▁end|>
<|file_name|>check_mrz_ocr.py<|end_file_name|><|fim▁begin|>import logging def same_ocr_mrz(mrz_data, zones): last_name_is_valid = mrz_data["last_name"][:25] == zones["last_name"]["value"][:25] logging.debug( "MRZ last name: {}; OCR last name: {}; matching {}".format( mrz_data["last_name"], zones["last_name"]["value"], last_name_is_valid ) ) first_names_ocr = zones["first_name"]["value"].split() first_names_ocr_joined = "".join(first_names_ocr)<|fim▁hole|> length_checked = min([ len(first_names_mrz_joined), 12 ]) first_name_is_valid = first_names_mrz_joined[:length_checked] == first_names_ocr_joined[:length_checked] logging.debug( "MRZ first names: {}; OCR first names: {}; matching {}".format( first_names_mrz, first_names_ocr, first_name_is_valid ) ) return last_name_is_valid and first_name_is_valid<|fim▁end|>
first_names_mrz = mrz_data["first_name"].split() first_names_mrz_joined = "".join(first_names_mrz)
<|file_name|>cmdline_test.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from __future__ import print_function try: import ConfigParser except ImportError: import configparser as ConfigParser import logging import mock import os import subprocess from helpers import unittest import warnings from luigi import six import luigi from luigi.mock import MockTarget class SomeTask(luigi.Task): n = luigi.IntParameter() def output(self): return MockTarget('/tmp/test_%d' % self.n) def run(self): f = self.output().open('w') f.write('done') f.close() class AmbiguousClass(luigi.Task): pass class AmbiguousClass(luigi.Task): pass class TaskWithSameName(luigi.Task): def run(self): self.x = 42 class TaskWithSameName(luigi.Task): # there should be no ambiguity def run(self): self.x = 43 class WriteToFile(luigi.Task): filename = luigi.Parameter() def output(self): return luigi.LocalTarget(self.filename) def run(self): f = self.output().open('w') print('foo', file=f) f.close() class FooBaseClass(luigi.Task): x = luigi.Parameter(default='foo_base_default') class FooSubClass(FooBaseClass): pass class CmdlineTest(unittest.TestCase): def setUp(self): MockTarget.fs.clear() @mock.patch("logging.getLogger") def test_cmdline_main_task_cls(self, logger): luigi.run(['--local-scheduler', '--no-lock', '--n', '100'], main_task_cls=SomeTask) self.assertEqual(dict(MockTarget.fs.get_all_data()), {'/tmp/test_100': b'done'}) @mock.patch("logging.getLogger") def test_cmdline_local_scheduler(self, logger): luigi.run(['SomeTask', '--no-lock', '--n', '101'], local_scheduler=True) self.assertEqual(dict(MockTarget.fs.get_all_data()), {'/tmp/test_101': b'done'}) @mock.patch("logging.getLogger") def test_cmdline_other_task(self, logger): luigi.run(['--local-scheduler', '--no-lock', 'SomeTask', '--n', '1000']) self.assertEqual(dict(MockTarget.fs.get_all_data()), {'/tmp/test_1000': b'done'}) @mock.patch("logging.getLogger") def test_cmdline_ambiguous_class(self, logger): self.assertRaises(Exception, luigi.run, ['--local-scheduler', '--no-lock', 'AmbiguousClass']) @mock.patch("logging.getLogger") @mock.patch("logging.StreamHandler") def test_setup_interface_logging(self, handler, logger): handler.return_value = mock.Mock(name="stream_handler") with mock.patch("luigi.interface.setup_interface_logging.has_run", new=False): luigi.interface.setup_interface_logging() self.assertEqual([mock.call(handler.return_value)], logger.return_value.addHandler.call_args_list) with mock.patch("luigi.interface.setup_interface_logging.has_run", new=False): if six.PY2: error = ConfigParser.NoSectionError else: error = KeyError self.assertRaises(error, luigi.interface.setup_interface_logging, '/blah') @mock.patch("warnings.warn") @mock.patch("luigi.interface.setup_interface_logging") def test_cmdline_logger(self, setup_mock, warn): with mock.patch("luigi.interface.core") as env_params: env_params.return_value.logging_conf_file = None luigi.run(['SomeTask', '--n', '7', '--local-scheduler', '--no-lock']) self.assertEqual([mock.call(None)], setup_mock.call_args_list) with mock.patch("luigi.configuration.get_config") as getconf: getconf.return_value.get.side_effect = ConfigParser.NoOptionError(section='foo', option='bar') getconf.return_value.getint.return_value = 0 luigi.interface.setup_interface_logging.call_args_list = [] luigi.run(['SomeTask', '--n', '42', '--local-scheduler', '--no-lock']) self.assertEqual([], setup_mock.call_args_list) @mock.patch('argparse.ArgumentParser.print_usage') def test_non_existent_class(self, print_usage): self.assertRaises(luigi.task_register.TaskClassNotFoundException, luigi.run, ['--local-scheduler', '--no-lock', 'XYZ']) @mock.patch('argparse.ArgumentParser.print_usage') def test_no_task(self, print_usage): self.assertRaises(SystemExit, luigi.run, ['--local-scheduler', '--no-lock']) class InvokeOverCmdlineTest(unittest.TestCase): def _run_cmdline(self, args): env = os.environ.copy() env['PYTHONPATH'] = env.get('PYTHONPATH', '') + ':.:test' p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) stdout, stderr = p.communicate() # Unfortunately subprocess.check_output is 2.7+ return p.returncode, stdout, stderr def test_bin_luigi(self): t = luigi.LocalTarget(is_tmp=True) args = ['./bin/luigi', '--module', 'cmdline_test', 'WriteToFile', '--filename', t.path, '--local-scheduler', '--no-lock'] self._run_cmdline(args) self.assertTrue(t.exists()) def test_direct_python(self): t = luigi.LocalTarget(is_tmp=True) args = ['python', 'test/cmdline_test.py', 'WriteToFile', '--filename', t.path, '--local-scheduler', '--no-lock'] self._run_cmdline(args) self.assertTrue(t.exists()) def test_direct_python_help(self): returncode, stdout, stderr = self._run_cmdline(['python', 'test/cmdline_test.py', '--help']) self.assertTrue(stdout.find(b'--FooBaseClass-x') != -1) self.assertFalse(stdout.find(b'--x') != -1) def test_direct_python_help_class(self): returncode, stdout, stderr = self._run_cmdline(['python', 'test/cmdline_test.py', 'FooBaseClass', '--help']) self.assertTrue(stdout.find(b'--FooBaseClass-x') != -1) self.assertTrue(stdout.find(b'--x') != -1) def test_bin_luigi_help(self): returncode, stdout, stderr = self._run_cmdline(['./bin/luigi', '--module', 'cmdline_test', '--help']) self.assertTrue(stdout.find(b'--FooBaseClass-x') != -1) self.assertFalse(stdout.find(b'--x') != -1) def test_bin_luigi_help_no_module(self): returncode, stdout, stderr = self._run_cmdline(['./bin/luigi', '--help']) self.assertTrue(stdout.find(b'usage:') != -1) def test_bin_luigi_no_parameters(self): returncode, stdout, stderr = self._run_cmdline(['./bin/luigi']) self.assertTrue(stderr.find(b'No task specified') != -1) def test_bin_luigi_help_class(self): returncode, stdout, stderr = self._run_cmdline(['./bin/luigi', '--module', 'cmdline_test', 'FooBaseClass', '--help']) self.assertTrue(stdout.find(b'--FooBaseClass-x') != -1) self.assertTrue(stdout.find(b'--x') != -1) class NewStyleParameters822Test(unittest.TestCase): # See https://github.com/spotify/luigi/issues/822 def test_subclasses(self): ap = luigi.interface.ArgParseInterface() task, = ap.parse(['--local-scheduler', '--no-lock', 'FooSubClass', '--x', 'xyz', '--FooBaseClass-x', 'xyz']) self.assertEquals(task.x, 'xyz') # This won't work because --FooSubClass-x doesn't exist self.assertRaises(BaseException, ap.parse, (['--local-scheduler', '--no-lock', 'FooBaseClass', '--x', 'xyz', '--FooSubClass-x', 'xyz'])) def test_subclasses_2(self): ap = luigi.interface.ArgParseInterface() # https://github.com/spotify/luigi/issues/822#issuecomment-77782714<|fim▁hole|> self.assertEquals(task.x, 'xyz') if __name__ == '__main__': # Needed for one of the tests luigi.run()<|fim▁end|>
task, = ap.parse(['--local-scheduler', '--no-lock', 'FooBaseClass', '--FooBaseClass-x', 'xyz'])
<|file_name|>generated_content.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! The generated content assignment phase. //! //! This phase handles CSS counters, quotes, and ordered lists per CSS § 12.3-12.5. It cannot be //! done in parallel and is therefore a sequential pass that runs on as little of the flow tree //! as possible. use context::{LayoutContext, with_thread_local_font_context}; use flow::{Flow, FlowFlags, GetBaseFlow, ImmutableFlowUtils}; use fragment::{Fragment, GeneratedContentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo}; use gfx::display_list::OpaqueNode; use script_layout_interface::wrapper_traits::PseudoElementType; use smallvec::SmallVec; use std::collections::{HashMap, LinkedList}; use style::computed_values::display::T as Display; use style::computed_values::list_style_type::T as ListStyleType; use style::properties::ComputedValues; use style::selector_parser::RestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage; use style::values::computed::counters::ContentItem; use text::TextRunScanner; use traversal::InorderFlowTraversal; // Decimal styles per CSS-COUNTER-STYLES § 6.1: static DECIMAL: [char; 10] = [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' ]; // TODO(pcwalton): `decimal-leading-zero` static ARABIC_INDIC: [char; 10] = [ '٠', '١', '٢', '٣', '٤', '٥', '٦', '٧', '٨', '٩' ]; // TODO(pcwalton): `armenian`, `upper-armenian`, `lower-armenian` static BENGALI: [char; 10] = [ '০', '১', '২', '৩', '৪', '৫', '৬', '৭', '৮', '৯' ]; static CAMBODIAN: [char; 10] = [ '០', '១', '២', '៣', '៤', '៥', '៦', '៧', '៨', '៩' ]; // TODO(pcwalton): Suffix for CJK decimal. static CJK_DECIMAL: [char; 10] = [ '〇', '一', '二', '三', '四', '五', '六', '七', '八', '九' ]; static DEVANAGARI: [char; 10] = [ '०', '१', '२', '३', '४', '५', '६', '७', '८', '९' ]; // TODO(pcwalton): `georgian` static GUJARATI: [char; 10] = ['૦', '૧', '૨', '૩', '૪', '૫', '૬', '૭', '૮', '૯']; static GURMUKHI: [char; 10] = ['੦', '੧', '੨', '੩', '੪', '੫', '੬', '੭', '੮', '੯']; // TODO(pcwalton): `hebrew` static KANNADA: [char; 10] = ['೦', '೧', '೨', '೩', '೪', '೫', '೬', '೭', '೮', '೯']; static LAO: [char; 10] = ['໐', '໑', '໒', '໓', '໔', '໕', '໖', '໗', '໘', '໙']; static MALAYALAM: [char; 10] = ['൦', '൧', '൨', '൩', '൪', '൫', '൬', '൭', '൮', '൯']; static MONGOLIAN: [char; 10] = ['᠐', '᠑', '᠒', '᠓', '᠔', '᠕', '᠖', '᠗', '᠘', '᠙']; static MYANMAR: [char; 10] = ['၀', '၁', '၂', '၃', '၄', '၅', '၆', '၇', '၈', '၉']; static ORIYA: [char; 10] = ['୦', '୧', '୨', '୩', '୪', '୫', '୬', '୭', '୮', '୯']; static PERSIAN: [char; 10] = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹']; // TODO(pcwalton): `lower-roman`, `upper-roman` static TELUGU: [char; 10] = ['౦', '౧', '౨', '౩', '౪', '౫', '౬', '౭', '౮', '౯']; static THAI: [char; 10] = ['๐', '๑', '๒', '๓', '๔', '๕', '๖', '๗', '๘', '๙']; static TIBETAN: [char; 10] = ['༠', '༡', '༢', '༣', '༤', '༥', '༦', '༧', '༨', '༩']; // Alphabetic styles per CSS-COUNTER-STYLES § 6.2: static LOWER_ALPHA: [char; 26] = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' ]; static UPPER_ALPHA: [char; 26] = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]; static CJK_EARTHLY_BRANCH: [char; 12] = [ '子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥' ]; static CJK_HEAVENLY_STEM: [char; 10] = [ '甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸' ]; static LOWER_GREEK: [char; 24] = [ 'α', 'β', 'γ', 'δ', 'ε', 'ζ', 'η', 'θ', 'ι', 'κ', 'λ', 'μ', 'ν', 'ξ', 'ο', 'π', 'ρ', 'σ', 'τ', 'υ', 'φ', 'χ', 'ψ', 'ω' ]; static HIRAGANA: [char; 48] = [ 'あ', 'い', 'う', 'え', 'お', 'か', 'き', 'く', 'け', 'こ', 'さ', 'し', 'す', 'せ', 'そ', 'た', 'ち', 'つ', 'て', 'と', 'な', 'に', 'ぬ', 'ね', 'の', 'は', 'ひ', 'ふ', 'へ', 'ほ', 'ま', 'み', 'む', 'め', 'も', 'や', 'ゆ', 'よ', 'ら', 'り', 'る', 'れ', 'ろ', 'わ', 'ゐ', 'ゑ', 'を', 'ん' ]; static HIRAGANA_IROHA: [char; 47] = [ 'い', 'ろ', 'は', 'に', 'ほ', 'へ', 'と', 'ち', 'り', 'ぬ', 'る', 'を', 'わ', 'か', 'よ', 'た', 'れ', 'そ', 'つ', 'ね', 'な', 'ら', 'む', 'う', 'ゐ', 'の', 'お', 'く', 'や', 'ま', 'け', 'ふ', 'こ', 'え', 'て', 'あ', 'さ', 'き', 'ゆ', 'め', 'み', 'し', 'ゑ', 'ひ', 'も', 'せ', 'す' ]; static KATAKANA: [char; 48] = [ 'ア', 'イ', 'ウ', 'エ', 'オ', 'カ', 'キ', 'ク', 'ケ', 'コ', 'サ', 'シ', 'ス', 'セ', 'ソ', 'タ', 'チ', 'ツ', 'テ', 'ト', 'ナ', 'ニ', 'ヌ', 'ネ', 'ノ', 'ハ', 'ヒ', 'フ', 'ヘ', 'ホ', 'マ', 'ミ', 'ム', 'メ', 'モ', 'ヤ', 'ユ', 'ヨ', 'ラ', 'リ', 'ル', 'レ', 'ロ', 'ワ', 'ヰ', 'ヱ', 'ヲ', 'ン' ]; static KATAKANA_IROHA: [char; 47] = [ 'イ', 'ロ', 'ハ', 'ニ', 'ホ', 'ヘ', 'ト', 'チ', 'リ', 'ヌ', 'ル', 'ヲ', 'ワ', 'カ', 'ヨ', 'タ', 'レ', 'ソ', 'ツ', 'ネ', 'ナ', 'ラ', 'ム', 'ウ', 'ヰ', 'ノ', 'オ', 'ク', 'ヤ', 'マ', 'ケ', 'フ', 'コ', 'エ', 'テ', 'ア', 'サ', 'キ', 'ユ', 'メ', 'ミ', 'シ', 'ヱ', 'ヒ', 'モ', 'セ', 'ス' ]; /// The generated content resolution traversal. pub struct ResolveGeneratedContent<'a> { /// The layout context. layout_context: &'a LayoutContext<'a>, /// The counter representing an ordered list item. list_item: Counter, /// Named CSS counters. counters: HashMap<String, Counter>, /// The level of quote nesting. quote: u32, } impl<'a> ResolveGeneratedContent<'a> { /// Creates a new generated content resolution traversal. pub fn new(layout_context: &'a LayoutContext) -> ResolveGeneratedContent<'a> { ResolveGeneratedContent { layout_context: layout_context, list_item: Counter::new(), counters: HashMap::new(), quote: 0, } } } impl<'a> InorderFlowTraversal for ResolveGeneratedContent<'a> { #[inline] fn process(&mut self, flow: &mut Flow, level: u32) { let mut mutator = ResolveGeneratedContentFragmentMutator { traversal: self, level: level, is_block: flow.is_block_like(), incremented: false, }; flow.mutate_fragments(&mut |fragment| mutator.mutate_fragment(fragment)) } #[inline] fn should_process_subtree(&mut self, flow: &mut Flow) -> bool { flow.base().restyle_damage.intersects(ServoRestyleDamage::RESOLVE_GENERATED_CONTENT) || flow.base().flags.intersects(FlowFlags::AFFECTS_COUNTERS | FlowFlags::HAS_COUNTER_AFFECTING_CHILDREN) } } /// The object that mutates the generated content fragments. struct ResolveGeneratedContentFragmentMutator<'a, 'b: 'a> { /// The traversal. traversal: &'a mut ResolveGeneratedContent<'b>, /// The level we're at in the flow tree. level: u32, /// Whether this flow is a block flow. is_block: bool, /// Whether we've incremented the counter yet. incremented: bool, } impl<'a, 'b> ResolveGeneratedContentFragmentMutator<'a, 'b> { fn mutate_fragment(&mut self, fragment: &mut Fragment) { // We only reset and/or increment counters once per flow. This avoids double-incrementing // counters on list items (once for the main fragment and once for the marker). if !self.incremented { self.reset_and_increment_counters_as_necessary(fragment);<|fim▁hole|> let mut list_style_type = fragment.style().get_list().list_style_type; if fragment.style().get_box().display != Display::ListItem { list_style_type = ListStyleType::None } let mut new_info = None; { let info = if let SpecificFragmentInfo::GeneratedContent(ref mut info) = fragment.specific { info } else { return }; match **info { GeneratedContentInfo::ListItem => { new_info = self.traversal.list_item.render(self.traversal.layout_context, fragment.node, fragment.pseudo.clone(), fragment.style.clone(), list_style_type, RenderingMode::Suffix(".\u{00a0}")) } GeneratedContentInfo::Empty | GeneratedContentInfo::ContentItem(ContentItem::String(_)) => { // Nothing to do here. } GeneratedContentInfo::ContentItem(ContentItem::Counter(ref counter_name, counter_style)) => { let temporary_counter = Counter::new(); let counter = self.traversal .counters .get(&**counter_name) .unwrap_or(&temporary_counter); new_info = counter.render(self.traversal.layout_context, fragment.node, fragment.pseudo.clone(), fragment.style.clone(), counter_style, RenderingMode::Plain) } GeneratedContentInfo::ContentItem(ContentItem::Counters(ref counter_name, ref separator, counter_style)) => { let temporary_counter = Counter::new(); let counter = self.traversal .counters .get(&**counter_name) .unwrap_or(&temporary_counter); new_info = counter.render(self.traversal.layout_context, fragment.node, fragment.pseudo, fragment.style.clone(), counter_style, RenderingMode::All(&separator)); } GeneratedContentInfo::ContentItem(ContentItem::OpenQuote) => { new_info = render_text(self.traversal.layout_context, fragment.node, fragment.pseudo, fragment.style.clone(), self.quote(&*fragment.style, false)); self.traversal.quote += 1 } GeneratedContentInfo::ContentItem(ContentItem::CloseQuote) => { if self.traversal.quote >= 1 { self.traversal.quote -= 1 } new_info = render_text(self.traversal.layout_context, fragment.node, fragment.pseudo, fragment.style.clone(), self.quote(&*fragment.style, true)); } GeneratedContentInfo::ContentItem(ContentItem::NoOpenQuote) => { self.traversal.quote += 1 } GeneratedContentInfo::ContentItem(ContentItem::NoCloseQuote) => { if self.traversal.quote >= 1 { self.traversal.quote -= 1 } } } }; fragment.specific = match new_info { Some(new_info) => new_info, // If the fragment did not generate any content, replace it with a no-op placeholder // so that it isn't processed again on the next layout. FIXME (mbrubeck): When // processing an inline flow, this traversal should be allowed to insert or remove // fragments. Then we can just remove these fragments rather than adding placeholders. None => SpecificFragmentInfo::GeneratedContent(Box::new(GeneratedContentInfo::Empty)) }; } fn reset_and_increment_counters_as_necessary(&mut self, fragment: &mut Fragment) { let mut list_style_type = fragment.style().get_list().list_style_type; if !self.is_block || fragment.style().get_box().display != Display::ListItem { list_style_type = ListStyleType::None } match list_style_type { ListStyleType::Disc | ListStyleType::None | ListStyleType::Circle | ListStyleType::Square | ListStyleType::DisclosureOpen | ListStyleType::DisclosureClosed => {} _ => self.traversal.list_item.increment(self.level, 1), } // Truncate down counters. for (_, counter) in &mut self.traversal.counters { counter.truncate_to_level(self.level); } self.traversal.list_item.truncate_to_level(self.level); for &(ref counter_name, value) in &*fragment.style().get_counters().counter_reset { let counter_name = &*counter_name.0; if let Some(ref mut counter) = self.traversal.counters.get_mut(counter_name) { counter.reset(self.level, value); continue } let mut counter = Counter::new(); counter.reset(self.level, value); self.traversal.counters.insert(counter_name.to_owned(), counter); } for &(ref counter_name, value) in &*fragment.style().get_counters().counter_increment { let counter_name = &*counter_name.0; if let Some(ref mut counter) = self.traversal.counters.get_mut(counter_name) { counter.increment(self.level, value); continue } let mut counter = Counter::new(); counter.increment(self.level, value); self.traversal.counters.insert(counter_name.to_owned(), counter); } self.incremented = true } fn quote(&self, style: &ComputedValues, close: bool) -> String { let quotes = &style.get_list().quotes; if quotes.0.is_empty() { return String::new() } let &(ref open_quote, ref close_quote) = if self.traversal.quote as usize >= quotes.0.len() { quotes.0.last().unwrap() } else { &quotes.0[self.traversal.quote as usize] }; if close { close_quote.to_string() } else { open_quote.to_string() } } } /// A counter per CSS 2.1 § 12.4. struct Counter { /// The values at each level. values: Vec<CounterValue>, } impl Counter { fn new() -> Counter { Counter { values: Vec::new(), } } fn reset(&mut self, level: u32, value: i32) { // Do we have an instance of the counter at this level? If so, just mutate it. if let Some(ref mut existing_value) = self.values.last_mut() { if level == existing_value.level { existing_value.value = value; return } } // Otherwise, push a new instance of the counter. self.values.push(CounterValue { level: level, value: value, }) } fn truncate_to_level(&mut self, level: u32) { if let Some(position) = self.values.iter().position(|value| value.level > level) { self.values.truncate(position) } } fn increment(&mut self, level: u32, amount: i32) { if let Some(ref mut value) = self.values.last_mut() { value.value += amount; return } self.values.push(CounterValue { level: level, value: amount, }) } fn render(&self, layout_context: &LayoutContext, node: OpaqueNode, pseudo: PseudoElementType, style: ::ServoArc<ComputedValues>, list_style_type: ListStyleType, mode: RenderingMode) -> Option<SpecificFragmentInfo> { let mut string = String::new(); match mode { RenderingMode::Plain => { let value = match self.values.last() { Some(ref value) => value.value, None => 0, }; push_representation(value, list_style_type, &mut string) } RenderingMode::Suffix(suffix) => { let value = match self.values.last() { Some(ref value) => value.value, None => 0, }; push_representation(value, list_style_type, &mut string); string.push_str(suffix) } RenderingMode::All(separator) => { let mut first = true; for value in &self.values { if !first { string.push_str(separator) } first = false; push_representation(value.value, list_style_type, &mut string) } } } if string.is_empty() { None } else { render_text(layout_context, node, pseudo, style, string) } } } /// How a counter value is to be rendered. enum RenderingMode<'a> { /// The innermost counter value is rendered with no extra decoration. Plain, /// The innermost counter value is rendered with the given string suffix. Suffix(&'a str), /// All values of the counter are rendered with the given separator string between them. All(&'a str), } /// The value of a counter at a given level. struct CounterValue { /// The level of the flow tree that this corresponds to. level: u32, /// The value of the counter at this level. value: i32, } /// Creates fragment info for a literal string. fn render_text(layout_context: &LayoutContext, node: OpaqueNode, pseudo: PseudoElementType, style: ::ServoArc<ComputedValues>, string: String) -> Option<SpecificFragmentInfo> { let mut fragments = LinkedList::new(); let info = SpecificFragmentInfo::UnscannedText( Box::new(UnscannedTextFragmentInfo::new(string.into_boxed_str(), None)) ); fragments.push_back(Fragment::from_opaque_node_and_style(node, pseudo, style.clone(), style, RestyleDamage::rebuild_and_reflow(), info)); // FIXME(pcwalton): This should properly handle multiple marker fragments. This could happen // due to text run splitting. let fragments = with_thread_local_font_context(layout_context, |font_context| { TextRunScanner::new().scan_for_runs(font_context, fragments) }); if fragments.is_empty() { None } else { Some(fragments.fragments.into_iter().next().unwrap().specific) } } /// Appends string that represents the value rendered using the system appropriate for the given /// `list-style-type` onto the given string. fn push_representation(value: i32, list_style_type: ListStyleType, accumulator: &mut String) { match list_style_type { ListStyleType::None => {} ListStyleType::Disc | ListStyleType::Circle | ListStyleType::Square | ListStyleType::DisclosureOpen | ListStyleType::DisclosureClosed => { accumulator.push(static_representation(list_style_type)) } ListStyleType::Decimal => push_numeric_representation(value, &DECIMAL, accumulator), ListStyleType::ArabicIndic => { push_numeric_representation(value, &ARABIC_INDIC, accumulator) } ListStyleType::Bengali => push_numeric_representation(value, &BENGALI, accumulator), ListStyleType::Cambodian | ListStyleType::Khmer => { push_numeric_representation(value, &CAMBODIAN, accumulator) } ListStyleType::CjkDecimal => { push_numeric_representation(value, &CJK_DECIMAL, accumulator) } ListStyleType::Devanagari => { push_numeric_representation(value, &DEVANAGARI, accumulator) } ListStyleType::Gujarati => push_numeric_representation(value, &GUJARATI, accumulator), ListStyleType::Gurmukhi => push_numeric_representation(value, &GURMUKHI, accumulator), ListStyleType::Kannada => push_numeric_representation(value, &KANNADA, accumulator), ListStyleType::Lao => push_numeric_representation(value, &LAO, accumulator), ListStyleType::Malayalam => { push_numeric_representation(value, &MALAYALAM, accumulator) } ListStyleType::Mongolian => { push_numeric_representation(value, &MONGOLIAN, accumulator) } ListStyleType::Myanmar => push_numeric_representation(value, &MYANMAR, accumulator), ListStyleType::Oriya => push_numeric_representation(value, &ORIYA, accumulator), ListStyleType::Persian => push_numeric_representation(value, &PERSIAN, accumulator), ListStyleType::Telugu => push_numeric_representation(value, &TELUGU, accumulator), ListStyleType::Thai => push_numeric_representation(value, &THAI, accumulator), ListStyleType::Tibetan => push_numeric_representation(value, &TIBETAN, accumulator), ListStyleType::LowerAlpha => { push_alphabetic_representation(value, &LOWER_ALPHA, accumulator) } ListStyleType::UpperAlpha => { push_alphabetic_representation(value, &UPPER_ALPHA, accumulator) } ListStyleType::CjkEarthlyBranch => { push_alphabetic_representation(value, &CJK_EARTHLY_BRANCH, accumulator) } ListStyleType::CjkHeavenlyStem => { push_alphabetic_representation(value, &CJK_HEAVENLY_STEM, accumulator) } ListStyleType::LowerGreek => { push_alphabetic_representation(value, &LOWER_GREEK, accumulator) } ListStyleType::Hiragana => { push_alphabetic_representation(value, &HIRAGANA, accumulator) } ListStyleType::HiraganaIroha => { push_alphabetic_representation(value, &HIRAGANA_IROHA, accumulator) } ListStyleType::Katakana => { push_alphabetic_representation(value, &KATAKANA, accumulator) } ListStyleType::KatakanaIroha => { push_alphabetic_representation(value, &KATAKANA_IROHA, accumulator) } } } /// Returns the static character that represents the value rendered using the given list-style, if /// possible. pub fn static_representation(list_style_type: ListStyleType) -> char { match list_style_type { ListStyleType::Disc => '•', ListStyleType::Circle => '◦', ListStyleType::Square => '▪', ListStyleType::DisclosureOpen => '▾', ListStyleType::DisclosureClosed => '‣', _ => panic!("No static representation for this list-style-type!"), } } /// Pushes the string that represents the value rendered using the given *alphabetic system* onto /// the accumulator per CSS-COUNTER-STYLES § 3.1.4. fn push_alphabetic_representation(value: i32, system: &[char], accumulator: &mut String) { let mut abs_value = handle_negative_value(value, accumulator); let mut string: SmallVec<[char; 8]> = SmallVec::new(); while abs_value != 0 { // Step 1. abs_value = abs_value - 1; // Step 2. string.push(system[abs_value % system.len()]); // Step 3. abs_value = abs_value / system.len(); } accumulator.extend(string.iter().cloned().rev()) } /// Pushes the string that represents the value rendered using the given *numeric system* onto the /// accumulator per CSS-COUNTER-STYLES § 3.1.5. fn push_numeric_representation(value: i32, system: &[char], accumulator: &mut String) { let mut abs_value = handle_negative_value(value, accumulator); // Step 1. if abs_value == 0 { accumulator.push(system[0]); return } // Step 2. let mut string: SmallVec<[char; 8]> = SmallVec::new(); while abs_value != 0 { // Step 2.1. string.push(system[abs_value % system.len()]); // Step 2.2. abs_value = abs_value / system.len(); } // Step 3. accumulator.extend(string.iter().cloned().rev()) } /// If the system uses a negative sign, handle negative values per CSS-COUNTER-STYLES § 2. /// /// Returns the absolute value of the counter. fn handle_negative_value(value: i32, accumulator: &mut String) -> usize { // 3. If the counter value is negative and the counter style uses a negative sign, instead // generate an initial representation using the absolute value of the counter value. if value < 0 { // TODO: Support different negative signs using the 'negative' descriptor. // https://drafts.csswg.org/date/2015-07-16/css-counter-styles/#counter-style-negative accumulator.push('-'); value.abs() as usize } else { value as usize } }<|fim▁end|>
}
<|file_name|>install.py<|end_file_name|><|fim▁begin|># -*- coding=utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals<|fim▁hole|>from ._base import BaseCommand from .options import dev, no_check, no_clean class Command(BaseCommand): name = "install" description = "Generate Pipfile.lock to synchronize the environment." arguments = [no_check, dev, no_clean] def run(self, options): return install(project=options.project, check=options.check, dev=options.dev, clean=options.clean) if __name__ == "__main__": Command.run_parser()<|fim▁end|>
from ..actions.install import install
<|file_name|>node_group.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # This demonstrates a node group configurations. # # Node groups can be defined with the syntax "-g N@IP0,IP1-IP2,IP3". # This says to create a group of N nodes with IPs IP0, IP1, ..., IP2, # IP3. Run it with deterministic IPs causes lots of gratuitous IP # reassignments. Running with --nd fixes this. import ctdb_takeover import sys<|fim▁hole|> ctdb_takeover.process_args([ make_option("-g", "--group", action="append", type="string", dest="groups", help="define a node group using N@IPs syntax"), ]) def expand_range(r): sr = r.split("-", 1) if len(sr) == 2: all = string.ascii_uppercase + string.ascii_lowercase sr = list(all[all.index(sr[0]):all.index(sr[1])+1]) return sr def add_node_group(s): (count, ips_str) = s.split("@", 1) ips = [i for r in ips_str.split(",") \ for i in expand_range(r) if r != ""] for i in range(int(count)): c.add_node(ctdb_takeover.Node(ips)) c = ctdb_takeover.Cluster() if ctdb_takeover.options.groups is None: print "Error: no node groups defined." sys.exit(1) for g in ctdb_takeover.options.groups: add_node_group(g) c.recover() c.random_iterations()<|fim▁end|>
from optparse import make_option import string
<|file_name|>jade.rs<|end_file_name|><|fim▁begin|>use std::collections::HashMap; use parser::Parser; struct Jade { input_path: String } struct ParsedJade { template: HashMap<String, String> } impl Jade { fn new(input_path: String) -> Jade { Jade {input_path: input_path} } <|fim▁hole|> } }<|fim▁end|>
fn parse() { let parser = Parser::new();
<|file_name|>gitsetup.py<|end_file_name|><|fim▁begin|>from configparser import RawConfigParser import os import re from subprocess import call, check_call, Popen, PIPE, STDOUT import sys from errors import Errors from general import ( exists_and_is_directory, shellquote, print_stderr ) from githelpers import has_objects_and_refs class OptionFrom: '''enum-like values to indicate the source of different options, used in directory_to_backup_from, git_directory_from and branch_from''' COMMAND_LINE = 1 CONFIGURATION_FILE = 2 DEFAULT_VALUE = 3 string_versions = { COMMAND_LINE : "command line", CONFIGURATION_FILE : "configuration file", DEFAULT_VALUE : "default value" } class GibSetup: def __init__(self, command_line_options): self.configuration_file = '.gib.conf' self.directory_to_backup = None self.directory_to_backup_from = None self.git_directory = None self.git_directory_from = None self.branch = None self.branch_from = None if command_line_options.directory: self.directory_to_backup = command_line_options.directory self.directory_to_backup_from = OptionFrom.COMMAND_LINE else: if 'HOME' not in os.environ: # Then we can't use HOME as default directory: print_stderr("The HOME environment variable was not set") sys.exit(Errors.STRANGE_ENVIRONMENT) self.directory_to_backup = os.environ['HOME'] self.directory_to_backup_from = OptionFrom.DEFAULT_VALUE # We need to make sure that this is an absolute path before # changing directory: self.directory_to_backup = os.path.abspath(self.directory_to_backup) if not exists_and_is_directory(self.directory_to_backup): sys.exit(Errors.DIRECTORY_TO_BACKUP_MISSING) # Now we know the directory that we're backing up, try to load the # config file: configuration = RawConfigParser() configuration.read(os.path.join(self.directory_to_backup, self.configuration_file)) # Now set the git directory: if command_line_options.git_directory: self.git_directory = command_line_options.git_directory self.git_directory_from = OptionFrom.COMMAND_LINE elif configuration.has_option('repository','git_directory'): self.git_directory = configuration.get( 'repository','git_directory' ) self.git_directory_from = OptionFrom.CONFIGURATION_FILE else: self.git_directory = os.path.join(self.directory_to_backup,'.git') self.git_directory_from = OptionFrom.DEFAULT_VALUE if not os.path.isabs(self.git_directory): print_stderr("The git directory must be an absolute path.") sys.exit(Errors.GIT_DIRECTORY_RELATIVE) # And finally the branch: if command_line_options.branch: self.branch = command_line_options.branch self.branch_from = OptionFrom.COMMAND_LINE elif configuration.has_option('repository','branch'): self.branch = configuration.get('repository','branch') self.branch_from = OptionFrom.CONFIGURATION_FILE else: self.branch = 'master' self.branch_from = OptionFrom.DEFAULT_VALUE # Check that the git_directory ends in '.git': if not re.search('\.git/*$',self.git_directory): message = "The git directory ({}) did not end in '.git'" print_stderr(message.format(self.git_directory)) sys.exit(Errors.BAD_GIT_DIRECTORY) # Also check that it actually exists: if not os.path.exists(self.git_directory): message = "The git directory '{}' does not exist." print_stderr(message.format(self.git_directory)) sys.exit(Errors.GIT_DIRECTORY_MISSING) def get_directory_to_backup(self): return self.directory_to_backup def get_git_directory(self): return self.git_directory def get_file_list_directory(self): return os.path.join( self.get_git_directory(), 'file-lists' ) def get_branch(self): return self.branch def print_settings(self): print_stderr('''Settings for backup: backing up the directory {} (set from the {}) ... to the branch "{}" (set from the {}) ... in the git repository {} (set from the {})'''.format( self.directory_to_backup, OptionFrom.string_versions[self.directory_to_backup_from], self.branch, OptionFrom.string_versions[self.branch_from], self.git_directory, OptionFrom.string_versions[self.git_directory_from]), ) def get_invocation(self): '''Return an invocation that would run the script with options that will set directory_to_backup, git_directory and branch as on this invocation. After init has been called, we can just specify the directory to backup, since the configuration file .gib.conf in that directory will store the git_directory and the branch. If the directory to backup is just the current user's home directory, then that doesn't need to be specified either.''' invocation = sys.argv[0] if self.directory_to_backup != os.environ['HOME']: invocation += " " + "--directory=" invocation += shellquote(self.directory_to_backup) return invocation def git(self,rest_of_command): '''Create an list (suitable for passing to subprocess.call or subprocess.check_call) which runs a git command with the correct git directory and work tree''' return [ "git", "--git-dir="+self.git_directory, "--work-tree="+self.directory_to_backup ] + rest_of_command def git_for_shell(self): '''Returns a string with shell-safe invocation of git which can be used in calls that are subject to shell interpretation.''' command = "git --git-dir="+shellquote(self.git_directory) command += " --work-tree="+shellquote(self.directory_to_backup) return command def git_initialized(self): '''Returns True if it seems as if the git directory has already been intialized, and returns False otherwise''' return has_objects_and_refs(self.git_directory) def abort_if_not_initialized(self): '''Check that the git repository exists and exit otherwise''' if not self.git_initialized(): message = "You don't seem to have initialized {} for backup." print_stderr(message.format(self.directory_to_backup)) message = "Please use '{} init' to initialize it" print_stderr(message.format(self.get_invocation()))<|fim▁hole|> '''Returns True if a ref can be resolved to a commit and False otherwise.''' return 0 == call( self.git(["rev-parse","--verify",ref]), stdout=open('/dev/null','w'), stderr=STDOUT ) def check_tree(self,tree): '''Returns True if 'tree' can be understood as a tree, e.g. with "git ls-tree" or false otherwise''' with open('/dev/null','w') as null: return 0 == call( self.git(["ls-tree",tree]), stdout=null, stderr=STDOUT ) def set_HEAD_to(self,ref): '''Update head to point to a particular branch, without touching the index or the working tree''' check_call( self.git(["symbolic-ref","HEAD","refs/heads/{}".format(ref)]) ) def currently_on_correct_branch(self): '''Return True if HEAD currently points to 'self.branch', and return False otherwise.''' p = Popen(self.git(["symbolic-ref","HEAD"]),stdout=PIPE) c = p.communicate() if 0 != p.returncode: print_stderr("Finding what HEAD points to failed") sys.exit(Errors.FINDING_HEAD) result = c[0].decode().strip() if self.branch == result: return True elif ("refs/heads/"+self.branch) == result: return True else: return False def switch_to_correct_branch(self): self.set_HEAD_to(self.branch) self.abort_unless_HEAD_exists() # Also reset the index to match HEAD. Otherwise things go # horribly wrong when switching from backing up one computer to # another, since the index is still that from the first one. msg = "Now working on a new branch, so resetting the index to match..." print_stderr(msg) check_call(self.git(["read-tree","HEAD"])) def config_value(self,key): '''Retrieve the git config value for "key", or return None if it is not defined''' p = Popen(self.git(["config",key]),stdout=PIPE) c = p.communicate() if 0 == p.returncode: # Then check that the option is right: return c[0].decode().strip() else: return None def set_config_value(self,key,value): check_call(self.git(["config",key,value])) def unset_config_value(self,key): call(self.git(["config","--unset",key])) def abort_unless_particular_config(self,key,required_value): '''Unless the git config has "required_value" set for "key", exit.''' current_value = self.config_value(key) if current_value: if current_value != required_value: message = "The current value for {} is {}, should be: {}" print_stderr(message.format( key, current_value, required_value )) sys.exit(Errors.GIT_CONFIG_ERROR) else: message = "The {} config option was not set, setting to {}" print_stderr(message.format(key,required_value)) self.set_config_value(key,required_value) def abort_unless_no_auto_gc(self): '''Exit unless git config has gc.auto set to "0"''' self.abort_unless_particular_config("gc.auto","0") def abort_unless_HEAD_exists(self): if not self.check_ref("HEAD"): message = '''The branch you are trying to back up to does not exist. (Perhaps you haven't run "{} init")''' print_stderr(message.format(self.get_invocation())) sys.exit(Errors.NO_SUCH_BRANCH)<|fim▁end|>
sys.exit(Errors.REPOSITORY_NOT_INITIALIZED) def check_ref(self,ref):
<|file_name|>get.js<|end_file_name|><|fim▁begin|>/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /** * Returns the y-scale function. * * @private * @returns {Function} scale function */ function get() { /* eslint-disable no-invalid-this */ return this._yScale; }<|fim▁hole|> // EXPORTS // module.exports = get;<|fim▁end|>
<|file_name|>ai.rs<|end_file_name|><|fim▁begin|>use level::*; pub fn ai_step(level : &mut Level, player_pos: (i32,i32)) { let mut x = 0; let mut y = 0; let mut enemies = Vec::with_capacity(16); for line in &level.tiles { for tile in line { match tile.entity { Some(Entity::Dragon{..}) => { enemies.push((x,y)); }, _ => {}<|fim▁hole|> x=0; } let (px, py) = player_pos; for e in enemies { let (x,y) = e; let dx = (px-x) as f32; let dy = (py-y) as f32; let distance = (dx*dx + dy*dy).sqrt(); if distance<6f32 { let dir = if dx<0f32 { Direction::Left } else if dx>0f32 { Direction::Right } else if dy<0f32 { Direction::Up } else { Direction::Down }; level.interact((x,y), dir); } } }<|fim▁end|>
} x+=1; } y+=1;
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> extern crate build;<|fim▁hole|><|fim▁end|>
fn main() { build::link("mincore_downlevel", true) }
<|file_name|>job_runner.py<|end_file_name|><|fim▁begin|>import sys from drone.actions.emr_launcher import launch_emr_task from drone.actions.ssh_launcher import launch_ssh_task from drone.job_runner.dependency_manager import dependencies_are_met from drone.job_runner.job_progress_checker import check_running_job_progress from drone.metadata.metadata import get_job_info, job_status, set_ready, set_running, set_failed task_launcher = {'ssh': launch_ssh_task, 'emr': launch_emr_task} def process(job_config, settings): for job_id, schedule_time, execution_time, status, runs, uid in get_job_info(job_config.get('id'), db_name=settings.metadata): if status == job_status.get('failed'): if (int(job_config.get('retry')) if job_config.get('retry') else 0) > int(runs): settings.logger.debug( '%s runs %s. set retries %s.' % (job_config.get('id'), runs, job_config.get('retry'))) if dependencies_are_met(job_config, schedule_time, settings): set_ready(job_config.get('id'), schedule_time, db_name=settings.metadata) settings.logger.info('Job "%s" "%s" set as ready' % (job_config.get('id'), schedule_time)) run(job_config, schedule_time, settings) continue else: continue else: continue elif status == job_status.get('running'): check_running_job_progress(job_config, schedule_time, uid, settings) continue elif status == job_status.get('ready'): run(job_config, schedule_time, settings) elif status == job_status.get('succeeded'): continue elif status == job_status.get('not_ready'): if dependencies_are_met(job_config, schedule_time, settings): set_ready(job_config.get('id'), schedule_time, db_name=settings.metadata) settings.logger.info('Job "%s" "%s" set as ready' % (job_config.get('id'), schedule_time)) run(job_config, schedule_time, settings) else: continue else: settings.logger.error('Unknown job status "%s"' % status) sys.exit(1) <|fim▁hole|> job_type = job_config.get('type') try: assert job_type in settings.supported_job_types except: settings.logger.warning( 'Unsupported job type %s. Valid types are %s' % (job_type, str(settings.supported_job_types))) task_lauched_successfully, uid = task_launcher.get(job_type)(job_config, schedule_time, settings) if task_lauched_successfully: set_running(job_config.get('id'), schedule_time, uid, db_name=settings.metadata) settings.logger.info('Started job "%s" "%s"' % (job_config.get('id'), schedule_time)) else: set_failed(job_config.get('id'), schedule_time, db_name=settings.metadata) settings.logger.warning('Failed to start job "%s" "%s"' % (job_config.get('id'), schedule_time))<|fim▁end|>
def run(job_config, schedule_time, settings): settings.logger.info('Starting job "%s" "%s"' % (job_config.get('id'), schedule_time))
<|file_name|>path_to_enlightenment.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python # -*- coding: utf-8 -*- # The path to enlightenment starts with the following: import unittest from koans.about_asserts import AboutAsserts from koans.about_strings import AboutStrings from koans.about_none import AboutNone from koans.about_lists import AboutLists from koans.about_list_assignments import AboutListAssignments from koans.about_dictionaries import AboutDictionaries from koans.about_string_manipulation import AboutStringManipulation from koans.about_tuples import AboutTuples from koans.about_methods import AboutMethods from koans.about_control_statements import AboutControlStatements from koans.about_true_and_false import AboutTrueAndFalse from koans.about_sets import AboutSets from koans.about_triangle_project import AboutTriangleProject from koans.about_exceptions import AboutExceptions from koans.about_triangle_project2 import AboutTriangleProject2 from koans.about_iteration import AboutIteration from koans.about_comprehension import AboutComprehension from koans.about_generators import AboutGenerators from koans.about_lambdas import AboutLambdas from koans.about_scoring_project import AboutScoringProject from koans.about_classes import AboutClasses from koans.about_with_statements import AboutWithStatements from koans.about_monkey_patching import AboutMonkeyPatching from koans.about_dice_project import AboutDiceProject from koans.about_method_bindings import AboutMethodBindings from koans.about_decorating_with_functions import AboutDecoratingWithFunctions from koans.about_decorating_with_classes import AboutDecoratingWithClasses from koans.about_inheritance import AboutInheritance from koans.about_multiple_inheritance import AboutMultipleInheritance from koans.about_regex import AboutRegex from koans.about_scope import AboutScope from koans.about_modules import AboutModules from koans.about_packages import AboutPackages from koans.about_class_attributes import AboutClassAttributes from koans.about_attribute_access import AboutAttributeAccess from koans.about_deleting_objects import AboutDeletingObjects from koans.about_proxy_object_project import * from koans.about_extra_credit import AboutExtraCredit def koans(): loader = unittest.TestLoader() suite = unittest.TestSuite() loader.sortTestMethodsUsing = None suite.addTests(loader.loadTestsFromTestCase(AboutAsserts)) suite.addTests(loader.loadTestsFromTestCase(AboutStrings)) suite.addTests(loader.loadTestsFromTestCase(AboutNone)) suite.addTests(loader.loadTestsFromTestCase(AboutLists)) suite.addTests(loader.loadTestsFromTestCase(AboutListAssignments)) suite.addTests(loader.loadTestsFromTestCase(AboutDictionaries)) suite.addTests(loader.loadTestsFromTestCase(AboutStringManipulation)) suite.addTests(loader.loadTestsFromTestCase(AboutTuples)) suite.addTests(loader.loadTestsFromTestCase(AboutMethods)) suite.addTests(loader.loadTestsFromTestCase(AboutControlStatements)) suite.addTests(loader.loadTestsFromTestCase(AboutTrueAndFalse)) suite.addTests(loader.loadTestsFromTestCase(AboutSets)) suite.addTests(loader.loadTestsFromTestCase(AboutTriangleProject)) suite.addTests(loader.loadTestsFromTestCase(AboutExceptions)) suite.addTests(loader.loadTestsFromTestCase(AboutTriangleProject2)) suite.addTests(loader.loadTestsFromTestCase(AboutIteration)) suite.addTests(loader.loadTestsFromTestCase(AboutComprehension)) suite.addTests(loader.loadTestsFromTestCase(AboutGenerators)) suite.addTests(loader.loadTestsFromTestCase(AboutLambdas)) suite.addTests(loader.loadTestsFromTestCase(AboutScoringProject)) suite.addTests(loader.loadTestsFromTestCase(AboutClasses)) suite.addTests(loader.loadTestsFromTestCase(AboutWithStatements)) suite.addTests(loader.loadTestsFromTestCase(AboutMonkeyPatching)) suite.addTests(loader.loadTestsFromTestCase(AboutDiceProject))<|fim▁hole|> suite.addTests(loader.loadTestsFromTestCase(AboutMultipleInheritance)) suite.addTests(loader.loadTestsFromTestCase(AboutScope)) suite.addTests(loader.loadTestsFromTestCase(AboutModules)) suite.addTests(loader.loadTestsFromTestCase(AboutPackages)) suite.addTests(loader.loadTestsFromTestCase(AboutClassAttributes)) suite.addTests(loader.loadTestsFromTestCase(AboutAttributeAccess)) suite.addTests(loader.loadTestsFromTestCase(AboutDeletingObjects)) suite.addTests(loader.loadTestsFromTestCase(AboutProxyObjectProject)) suite.addTests(loader.loadTestsFromTestCase(TelevisionTest)) suite.addTests(loader.loadTestsFromTestCase(AboutExtraCredit)) return suite<|fim▁end|>
suite.addTests(loader.loadTestsFromTestCase(AboutMethodBindings)) suite.addTests(loader.loadTestsFromTestCase(AboutDecoratingWithFunctions)) suite.addTests(loader.loadTestsFromTestCase(AboutDecoratingWithClasses)) suite.addTests(loader.loadTestsFromTestCase(AboutInheritance))
<|file_name|>model_link_token_create_request_update.go<|end_file_name|><|fim▁begin|>/* * The Plaid API * * The Plaid REST API. Please see https://plaid.com/docs/api for more details. * * API version: 2020-09-14_1.78.0 */ // Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package plaid import ( "encoding/json" ) // LinkTokenCreateRequestUpdate Specifies options for initializing Link for [update mode](https://plaid.com/docs/link/update-mode). type LinkTokenCreateRequestUpdate struct { // If `true`, enables [update mode with Account Select](https://plaid.com/docs/link/update-mode/#using-update-mode-to-request-new-accounts). AccountSelectionEnabled *bool `json:"account_selection_enabled,omitempty"` } // NewLinkTokenCreateRequestUpdate instantiates a new LinkTokenCreateRequestUpdate object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments // will change when the set of required properties is changed func NewLinkTokenCreateRequestUpdate() *LinkTokenCreateRequestUpdate { this := LinkTokenCreateRequestUpdate{} var accountSelectionEnabled bool = false this.AccountSelectionEnabled = &accountSelectionEnabled return &this } // NewLinkTokenCreateRequestUpdateWithDefaults instantiates a new LinkTokenCreateRequestUpdate object // This constructor will only assign default values to properties that have it defined, // but it doesn't guarantee that properties required by API are set func NewLinkTokenCreateRequestUpdateWithDefaults() *LinkTokenCreateRequestUpdate { this := LinkTokenCreateRequestUpdate{} var accountSelectionEnabled bool = false this.AccountSelectionEnabled = &accountSelectionEnabled return &this } // GetAccountSelectionEnabled returns the AccountSelectionEnabled field value if set, zero value otherwise. func (o *LinkTokenCreateRequestUpdate) GetAccountSelectionEnabled() bool { if o == nil || o.AccountSelectionEnabled == nil { var ret bool return ret } return *o.AccountSelectionEnabled } // GetAccountSelectionEnabledOk returns a tuple with the AccountSelectionEnabled field value if set, nil otherwise // and a boolean to check if the value has been set. func (o *LinkTokenCreateRequestUpdate) GetAccountSelectionEnabledOk() (*bool, bool) { if o == nil || o.AccountSelectionEnabled == nil { return nil, false } return o.AccountSelectionEnabled, true } // HasAccountSelectionEnabled returns a boolean if a field has been set. func (o *LinkTokenCreateRequestUpdate) HasAccountSelectionEnabled() bool { if o != nil && o.AccountSelectionEnabled != nil { return true } return false } // SetAccountSelectionEnabled gets a reference to the given bool and assigns it to the AccountSelectionEnabled field. func (o *LinkTokenCreateRequestUpdate) SetAccountSelectionEnabled(v bool) { o.AccountSelectionEnabled = &v } func (o LinkTokenCreateRequestUpdate) MarshalJSON() ([]byte, error) { toSerialize := map[string]interface{}{} if o.AccountSelectionEnabled != nil {<|fim▁hole|> return json.Marshal(toSerialize) } type NullableLinkTokenCreateRequestUpdate struct { value *LinkTokenCreateRequestUpdate isSet bool } func (v NullableLinkTokenCreateRequestUpdate) Get() *LinkTokenCreateRequestUpdate { return v.value } func (v *NullableLinkTokenCreateRequestUpdate) Set(val *LinkTokenCreateRequestUpdate) { v.value = val v.isSet = true } func (v NullableLinkTokenCreateRequestUpdate) IsSet() bool { return v.isSet } func (v *NullableLinkTokenCreateRequestUpdate) Unset() { v.value = nil v.isSet = false } func NewNullableLinkTokenCreateRequestUpdate(val *LinkTokenCreateRequestUpdate) *NullableLinkTokenCreateRequestUpdate { return &NullableLinkTokenCreateRequestUpdate{value: val, isSet: true} } func (v NullableLinkTokenCreateRequestUpdate) MarshalJSON() ([]byte, error) { return json.Marshal(v.value) } func (v *NullableLinkTokenCreateRequestUpdate) UnmarshalJSON(src []byte) error { v.isSet = true return json.Unmarshal(src, &v.value) }<|fim▁end|>
toSerialize["account_selection_enabled"] = o.AccountSelectionEnabled }
<|file_name|>CmsComparatorType.java<|end_file_name|><|fim▁begin|>/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */<|fim▁hole|>import java.util.Comparator; /** * Comparator for objects with a type property.<p> * * @see I_CmsHasType * * @since 8.0.0 */ public class CmsComparatorType implements Comparator<I_CmsHasType> { /** Sort order flag. */ private boolean m_ascending; /** * Constructor.<p> * * @param ascending if <code>true</code> order is ascending */ public CmsComparatorType(boolean ascending) { m_ascending = ascending; } /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(I_CmsHasType o1, I_CmsHasType o2) { int result = o1.getType().compareTo(o2.getType()); return m_ascending ? result : -result; } }<|fim▁end|>
package org.opencms.gwt.shared.sort;
<|file_name|>format-money.js<|end_file_name|><|fim▁begin|>export default Ember.Handlebars.makeBoundHelper(function(price) { var number = parseFloat(price/100).toFixed(2), dollar = number.split('.')[0], cents = number.split('.')[1],<|fim▁hole|> .split('').reverse().join(''); return '$' + dollars + '.' + cents; });<|fim▁end|>
dollars = dollar.split('').reverse().join('') .replace(/(\d{3}(?!$))/g, '$1,')
<|file_name|>next_power_of_2.rs<|end_file_name|><|fim▁begin|>use malachite_base::num::basic::floats::PrimitiveFloat; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base::num::float::NiceFloat; use malachite_base_test_util::bench::bucketers::{primitive_float_bucketer, unsigned_bit_bucketer}; use malachite_base_test_util::bench::{run_benchmark, BenchmarkType}; use malachite_base_test_util::generators::common::{GenConfig, GenMode}; use malachite_base_test_util::generators::{primitive_float_gen_var_19, unsigned_gen_var_14}; use malachite_base_test_util::runner::Runner; pub(crate) fn register(runner: &mut Runner) { register_primitive_float_demos!(runner, demo_next_power_of_2_primitive_float); register_unsigned_demos!(runner, demo_next_power_of_2_assign_unsigned); register_primitive_float_demos!(runner, demo_next_power_of_2_assign_primitive_float); register_primitive_float_benches!(runner, benchmark_next_power_of_2_primitive_float); register_unsigned_benches!(runner, benchmark_next_power_of_2_assign_unsigned); register_primitive_float_benches!(runner, benchmark_next_power_of_2_assign_primitive_float); } fn demo_next_power_of_2_primitive_float<T: PrimitiveFloat>( gm: GenMode, config: GenConfig, limit: usize, ) { for n in primitive_float_gen_var_19::<T>() .get(gm, &config) .take(limit) { println!( "{}.next_power_of_2() = {}", NiceFloat(n), NiceFloat(n.next_power_of_2()) ); } } fn demo_next_power_of_2_assign_unsigned<T: PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, ) { for mut n in unsigned_gen_var_14::<T>().get(gm, &config).take(limit) { let old_n = n; n.next_power_of_2_assign(); println!("n := {}; n.next_power_of_2_assign(); n = {}", old_n, n); } } fn demo_next_power_of_2_assign_primitive_float<T: PrimitiveFloat>( gm: GenMode, config: GenConfig, limit: usize, ) { for mut n in primitive_float_gen_var_19::<T>() .get(gm, &config) .take(limit) { let old_n = n; n.next_power_of_2_assign(); println!( "n := {}; n.next_power_of_2_assign(); n = {}", NiceFloat(old_n), NiceFloat(n) ); } } fn benchmark_next_power_of_2_primitive_float<T: PrimitiveFloat>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) { run_benchmark( &format!("{}.next_power_of_2()", T::NAME), BenchmarkType::Single, primitive_float_gen_var_19::<T>().get(gm, &config), gm.name(), limit, file_name, &primitive_float_bucketer("x"), &mut [("Malachite", &mut |n| no_out!(n.next_power_of_2()))], ); } fn benchmark_next_power_of_2_assign_unsigned<T: PrimitiveUnsigned>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) { run_benchmark( &format!("{}.next_power_of_2_assign()", T::NAME), BenchmarkType::Single, unsigned_gen_var_14::<T>().get(gm, &config), gm.name(), limit, file_name, &unsigned_bit_bucketer(), &mut [("Malachite", &mut |mut n| n.next_power_of_2_assign())], ); } fn benchmark_next_power_of_2_assign_primitive_float<T: PrimitiveFloat>( gm: GenMode, config: GenConfig, limit: usize, file_name: &str, ) { run_benchmark( &format!("{}.next_power_of_2_assign()", T::NAME), BenchmarkType::Single, primitive_float_gen_var_19::<T>().get(gm, &config), gm.name(), limit, file_name, &primitive_float_bucketer("x"), &mut [("Malachite", &mut |mut n| n.next_power_of_2_assign())], );<|fim▁hole|><|fim▁end|>
}
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>extern crate regex; use regex::Regex; const MIN_BOUND: u32 = 0; const MAX_BOUND: u32 = 10;//((1u64 << 32) - 1) as u32; #[derive(Debug)] struct Range { lo: u32, hi: u32, } impl Range { fn default() -> Range { Range { lo: MIN_BOUND, hi: MAX_BOUND, } } fn new(lo: u32, hi: u32) -> Range { assert!(lo <= hi); Range { lo: lo, hi: hi } } fn parse(s: &str) -> Range { let re: Regex = Regex::new(r"^(\d+)-(\d+)$").unwrap(); match re.captures(s) { None => Range::default(), Some(caps) => { match (caps.at(1), caps.at(2)) { (Some(a), Some(b)) => { Range::new(a.parse().unwrap_or(MIN_BOUND), b.parse().unwrap_or(MAX_BOUND)) } _ => Range::default(), } } } } } impl Iterator for Range { type Item = u32;<|fim▁hole|> let lo = self.lo; let hi = self.hi; self.lo += 1; if lo > hi { None } else { Some(lo) } } } fn mark_off(a: &mut[bool; MAX_BOUND as usize], r: Range) { for i in r { a[i as usize] = false; } } fn main() { let test_input = "5-8\n0-2\n4-7"; let ranges = test_input.lines().map(Range::parse); let mut a = [true; MAX_BOUND as usize]; for r in ranges { println!("{:?}", r); mark_off(&mut a, r); } for i in MIN_BOUND .. MAX_BOUND { if a[i as usize] { println!("{}", i); break; } } }<|fim▁end|>
fn next(&mut self) -> Option<u32> {
<|file_name|>test_log_abort.py<|end_file_name|><|fim▁begin|>import logging from unittest.mock import MagicMock, call from ert_logging._log_util_abort import _log_util_abort <|fim▁hole|> shutdown_mock = MagicMock() monkeypatch.setattr(logging, "shutdown", shutdown_mock) with caplog.at_level(logging.ERROR): _log_util_abort("fname", 1, "some_func", "err_message", "my_backtrace") assert ( "C trace:\nmy_backtrace \nwith message: err_message \nfrom file: " "fname in some_func at line: 1\n\nPython backtrace:" ) in caplog.text shutdown_mock.assert_called_once_with() # must shutdown to propagate message<|fim▁end|>
def test_log_util_abort(caplog, monkeypatch):
<|file_name|>advancedFilter.js<|end_file_name|><|fim▁begin|>isc.VStack.create({ membersMargin: 30, members: [ isc.VStack.create({ membersMargin: 30, members: [ isc.DynamicForm.create({ ID: "filterForm", width: 300, operator: "and", saveOnEnter: true, dataSource: worldDS, submit: function () { filterGrid.filterData(filterForm.getValuesAsCriteria()); }, fields: [ {name: "countryName", title: "Country Name contains", wrapTitle: false, type: "text" }, {type: "blurb", defaultValue: "<b>AND</b>" }, {name: "population", title: "Population smaller than", wrapTitle: false, type: "number", operator: "lessThan" }, {type: "blurb", defaultValue: "<b>AND</b>" }, {name: "independence", title: "Nationhood later than", wrapTitle: false, type: "date", useTextField: true, operator: "greaterThan" } ] }), isc.IButton.create({ title: "Filter", click: function () { filterForm.submit();<|fim▁hole|> ] }), isc.ListGrid.create({ ID: "filterGrid", width:850, height:300, alternateRecordStyles:true, dataSource: worldDS, autoFetchData: true, useAllDataSourceFields: true, fields: [ {name:"countryCode", width: 50}, {name:"government", title:"Government", width: 95}, {name:"independence", title:"Nationhood", width: 100}, {name:"population", title:"Population", width: 100}, {name:"gdp", title:"GDP ($M)", width: 85} ] }) ] });<|fim▁end|>
} })
<|file_name|>test_gamma.py<|end_file_name|><|fim▁begin|>from pytest import approx, raises from fastats.maths.gamma import gammaln def test_gamma_ints(): assert gammaln(10) == approx(12.801827480081469, rel=1e-6) assert gammaln(5) == approx(3.1780538303479458, rel=1e-6)<|fim▁hole|>def test_gamma_floats(): assert gammaln(3.141) == approx(0.8271155090776673, rel=1e-6) assert gammaln(8.8129) == approx(10.206160943471318, rel=1e-6) assert gammaln(12.001) == approx(17.50475055100354, rel=1e-6) assert gammaln(0.007812) == approx(4.847635060148693, rel=1e-6) assert gammaln(86.13) == approx(296.3450079998172, rel=1e-6) def test_gamma_negative(): raises(AssertionError, gammaln, -1) raises(AssertionError, gammaln, -0.023) raises(AssertionError, gammaln, -10.9) if __name__ == '__main__': import pytest pytest.main([__file__])<|fim▁end|>
assert gammaln(19) == approx(36.39544520803305, rel=1e-6)
<|file_name|>build.py<|end_file_name|><|fim▁begin|>import os from torch.utils.ffi import create_extension sources = ["src/lib_cffi.cpp"] headers = ["src/lib_cffi.h"] extra_objects = ["src/bn.o"] with_cuda = True this_file = os.path.dirname(os.path.realpath(__file__)) extra_objects = [os.path.join(this_file, fname) for fname in extra_objects] ffi = create_extension( "_ext",<|fim▁hole|> extra_objects=extra_objects, extra_compile_args=["-std=c++11"], ) if __name__ == "__main__": ffi.build()<|fim▁end|>
headers=headers, sources=sources, relative_to=__file__, with_cuda=with_cuda,
<|file_name|>test_dogma_extra.py<|end_file_name|><|fim▁begin|>from unittest import TestCase import dogma from test_dogma_values import * class TestDogmaExtra(TestCase): def test(self): ctx = dogma.Context() slot = ctx.add_module(TYPE_125mmGatlingAutoCannonII) loc = dogma.Location.module(slot) affectors = ctx.get_affectors(loc) ctx.set_ship(TYPE_Rifter) affectors_with_ship = ctx.get_affectors(loc) self.assertTrue(dogma.type_has_effect(TYPE_125mmGatlingAutoCannonII, dogma.State.ONLINE, EFFECT_HiPower)) self.assertTrue(dogma.type_has_active_effects(TYPE_125mmGatlingAutoCannonII)) self.assertTrue(dogma.type_has_overload_effects(TYPE_125mmGatlingAutoCannonII)) self.assertTrue(dogma.type_has_projectable_effects(TYPE_StasisWebifierI)) self.assertEqual(dogma.type_base_attribute(TYPE_Rifter, ATT_LauncherSlotsLeft), 2) ctx.add_charge(slot, TYPE_BarrageS) self.assertEqual(ctx.get_number_of_module_cycles_before_reload(slot), 200) effect = dogma.get_nth_type_effect_with_attributes(TYPE_125mmGatlingAutoCannonII, 0) (duration, tracking, discharge, att_range, falloff, usagechance, ) = ctx.get_location_effect_attributes(loc, effect) self.assertEqual(falloff, 7500) self.assertEqual(att_range, 1200) self.assertEqual(discharge, 0) capacitors = ctx.get_capacitor_all(False)<|fim▁hole|><|fim▁end|>
self.assertEqual(len(capacitors), 1) self.assertIn(ctx, capacitors)
<|file_name|>vue-store.js<|end_file_name|><|fim▁begin|>import Vuex from 'vuex' import store from './file-store' export default new Vuex.Store({ state: { characters: [] },<|fim▁hole|> characters: state => { return state.characters; }, fileNames: state => { return store.getLists(); } }, mutations: { loadFile(state, fileName) { state.characters = JSON.parse(store.loadFile(fileName)); } }, actions: { loadFile(context, fileName) { context.commit('loadFile', fileName); } } })<|fim▁end|>
getters: {
<|file_name|>LinkPortalPlugin.java<|end_file_name|><|fim▁begin|>package com.winthier.linkportal; import java.util.HashSet; import java.util.Set; import java.util.UUID; import lombok.Getter; import org.bukkit.plugin.java.JavaPlugin; @Getter public final class LinkPortalPlugin extends JavaPlugin { private final LinkPortalListener listener = new LinkPortalListener(this); private final LinkPortals portals = new LinkPortals(this); private boolean debugMode; Set<UUID> serverPortal = new HashSet<>(); @Override public void onEnable() { saveDefaultConfig(); loadConf(); getServer().getPluginManager().registerEvents(listener, this); getCommand("linkportal").setExecutor(new LinkPortalCommand(this)); getServer().getScheduler().runTaskTimer(this, listener::tick, 1L, 1L); } void loadConf() {<|fim▁hole|> this.debugMode = getConfig().getBoolean("debug"); if (this.debugMode) { getLogger().info("Debug mode enabled in config.yml!"); } } }<|fim▁end|>
reloadConfig();
<|file_name|>delta.rs<|end_file_name|><|fim▁begin|>//! Add a delta to a weave file. use regex::Regex; use std::{ collections::BTreeMap, fs::{remove_file, rename}, io::{self, BufRead, BufReader, BufWriter, Write}, mem::replace, path::PathBuf, process::{Command, Stdio}, }; use crate::{header::Header, Entry, Error, NamingConvention, Parser, PullParser, Result, Sink, WriterInfo}; /// A DeltaWriter is used to write a new delta. Data should be written to the writer, and then the /// `close` method called to update the weave file with the new delta. pub struct DeltaWriter<'n> { naming: &'n dyn NamingConvention, // Where the temporary file will be written. temp: Option<WriterInfo>, // The base delta. base: usize, // The new delta. new_delta: usize, // The name of the file with the base written to it. base_name: PathBuf, // The regex for parsing diff output. diff_re: Regex, // The header to be written for the new delta. header: Header, } impl<'n> DeltaWriter<'n> { /// Construct a writer for a new delta. The naming convention and the tags set where the names /// will be written, and what tags will be associated with the convention. The `base` is the /// existing delta that the change should be based on. pub fn new<'a, 'b, I>(nc: &dyn NamingConvention, tags: I, base: usize) -> Result<DeltaWriter> where I: Iterator<Item = (&'a str, &'b str)>, { // Copy the tags, making sure there is a "name", which is used to index. // TODO: Ensure that "name" is unique among the existing deltas. let mut ntags = BTreeMap::new(); for (k, v) in tags { ntags.insert(k.to_owned(), v.to_owned()); } if !ntags.contains_key("name") { return Err(Error::NameMissing); } // Extract the base delta to a file. let (base_name, mut base_file) = nc.temp_file()?; let mut header = { let mut parser = PullParser::new(nc, base)?; for node in &mut parser { match node? { Entry::Plain { text, keep } => { if keep { writeln!(base_file, "{}", text)?; } } _ => (), } } parser.into_header() }; let new_delta = header.add(ntags)?; let (new_name, new_file) = nc.temp_file()?; let new_info = WriterInfo { name: new_name, writer: Box::new(BufWriter::new(new_file)), }; Ok(DeltaWriter { naming: nc, temp: Some(new_info), base, new_delta, base_name, diff_re: Regex::new(r"^(\d+)(,(\d+))?([acd]).*$").unwrap(), header, }) } pub fn close(mut self) -> Result<()> { // Close the temporary file, getting its name. let temp = replace(&mut self.temp, None); let temp_name = match temp { Some(mut wi) => { wi.writer.flush()?; drop(wi.writer); wi.name } None => return Err(Error::AlreadyClosed), }; let tweave_info = self.naming.new_temp()?; // Invoke diff on the files. let mut child = Command::new("diff") .arg(self.base_name.as_os_str()) .arg(temp_name.as_os_str()) .stdout(Stdio::piped()) .spawn()?; { let lines = BufReader::new(child.stdout.as_mut().unwrap()).lines(); let weave_write = WeaveWriter { dest: tweave_info.writer, }; let mut parser = Parser::new(self.naming, weave_write, self.base)?; let weave_write = parser.get_sink(); <|fim▁hole|> for line in lines { let line = line?; if let Some(cap) = self.diff_re.captures(&line) { // If adding, this completes the add. if is_adding { weave_write.borrow_mut().end(self.new_delta)?; is_adding = false; } let left = cap.get(1).unwrap().as_str().parse::<usize>().unwrap(); let right = match cap.get(3) { None => left, Some(r) => r.as_str().parse().unwrap(), }; let cmd = cap.get(4).unwrap().as_str().chars().next().unwrap(); if cmd == 'd' || cmd == 'c' { // These include deletions. match parser.parse_to(left)? { 0 => return Err(Error::UnexpectedEof), n if n == left => (), _ => panic!("Unexpected parse result"), } weave_write.borrow_mut().delete(self.new_delta)?; match parser.parse_to(right + 1) { Ok(0) => is_done = true, Ok(n) if n == right + 1 => (), Ok(_) => panic!("Unexpected parse result"), Err(e) => return Err(e), } weave_write.borrow_mut().end(self.new_delta)?; } else { match parser.parse_to(right + 1) { Ok(0) => is_done = true, Ok(n) if n == right + 1 => (), Ok(_) => panic!("Unexpected parse result"), Err(e) => return Err(e), } } if cmd == 'c' || cmd == 'a' { weave_write.borrow_mut().insert(self.new_delta)?; is_adding = true; } continue; } match line.chars().next() { None => panic!("Unexpected blank line in diff"), Some('<') => continue, Some('-') => continue, Some('>') => { // Add lines should just be written as-is. weave_write.borrow_mut().plain(&line[2..], true)?; } Some(_) => panic!("Unexpected diff line: {:?}", line), } } if is_adding { weave_write.borrow_mut().end(self.new_delta)?; } if !is_done { match parser.parse_to(0) { Ok(0) => (), Ok(_) => panic!("Unexpected non-eof"), Err(e) => return Err(e), } } } match child.wait()?.code() { None => return Err(Error::DiffKilled), Some(0) => (), // No diffs Some(1) => (), // Normal with diffs Some(n) => return Err(Error::DiffError(n)), } // Now that is all done, clean up the temp files, and cycle the backup. let _ = rename(self.naming.main_file(), self.naming.backup_file()); rename(tweave_info.name, self.naming.main_file())?; remove_file(&self.base_name)?; remove_file(&temp_name)?; Ok(()) } } impl<'n> Write for DeltaWriter<'n> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.temp .as_mut() .expect("Attempt to write to DeltaWriter that is closed") .writer .write(buf) } fn flush(&mut self) -> io::Result<()> { self.temp .as_mut() .expect("Attempt to flush DeltaWriter that is closed") .writer .flush() } } struct RevWriter<W: Write> { dest: BufWriter<W>, } impl<W: Write> Sink for RevWriter<W> { fn plain(&mut self, text: &str, keep: bool) -> Result<()> { if !keep { return Ok(()); } writeln!(&mut self.dest, "{}", text)?; Ok(()) } } /// The weave writer writes out the contents of a weave to a file. struct WeaveWriter<W: Write> { dest: W, } impl<W: Write> Sink for WeaveWriter<W> { fn insert(&mut self, delta: usize) -> Result<()> { writeln!(&mut self.dest, "\x01I {}", delta)?; Ok(()) } fn delete(&mut self, delta: usize) -> Result<()> { writeln!(&mut self.dest, "\x01D {}", delta)?; Ok(()) } fn end(&mut self, delta: usize) -> Result<()> { writeln!(&mut self.dest, "\x01E {}", delta)?; Ok(()) } fn plain(&mut self, text: &str, _keep: bool) -> Result<()> { writeln!(&mut self.dest, "{}", text)?; Ok(()) } }<|fim▁end|>
self.header.write(&mut weave_write.borrow_mut().dest)?; let mut is_done = false; let mut is_adding = false;
<|file_name|>test-particle.py<|end_file_name|><|fim▁begin|>import pyxb.binding.generate import pyxb.utils.domutils from xml.dom import Node import os.path schema_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../schemas/particle.xsd')) code = pyxb.binding.generate.GeneratePython(schema_location=schema_path) rv = compile(code, 'test', 'exec') eval(rv) from pyxb.exceptions_ import * import unittest from pyxb.utils import domutils def ToDOM (instance, tag=None): return instance.toDOM().documentElement class TestParticle (unittest.TestCase): def test_bad_creation (self): xml = '<h01 xmlns="URN:test"/>' dom = pyxb.utils.domutils.StringToDOM(xml) # Creating with wrong element self.assertRaises(pyxb.StructuralBadDocumentError, h01b.createFromDOM, dom.documentElement) def test_h01_empty (self): xml = '<ns1:h01 xmlns:ns1="URN:test"/>' dom = pyxb.utils.domutils.StringToDOM(xml) instance = h01.createFromDOM(dom.documentElement) self.assert_(instance.elt is None) self.assertEqual(ToDOM(instance).toxml("utf-8"), xml) def test_h01_elt (self): xml = '<ns1:h01 xmlns:ns1="URN:test"><elt/></ns1:h01>' dom = pyxb.utils.domutils.StringToDOM(xml) instance = h01.createFromDOM(dom.documentElement) self.assert_(instance.elt is not None) self.assertEqual(ToDOM(instance).toxml("utf-8"), xml) def test_h01_elt2 (self): xml = '<h01 xmlns="URN:test"><elt/><elt/></h01>' dom = pyxb.utils.domutils.StringToDOM(xml) self.assertRaises(ExtraContentError, h01.createFromDOM, dom.documentElement) def test_h01b_empty (self): xml = '<ns1:h01b xmlns:ns1="URN:test"/>' dom = pyxb.utils.domutils.StringToDOM(xml) instance = h01b.createFromDOM(dom.documentElement) self.assert_(instance.elt is None) self.assertEqual(ToDOM(instance).toxml("utf-8"), xml) def test_h01b_elt (self): xml = '<ns1:h01b xmlns:ns1="URN:test"><elt/></ns1:h01b>' dom = pyxb.utils.domutils.StringToDOM(xml) instance = h01b.createFromDOM(dom.documentElement) self.assert_(instance.elt is not None) self.assertEqual(ToDOM(instance).toxml("utf-8"), xml) def test_h01b_elt2 (self): xml = '<ns1:h01b xmlns:ns1="URN:test"><elt/><elt/></ns1:h01b>' dom = pyxb.utils.domutils.StringToDOM(xml)<|fim▁hole|> def test_h11_empty (self): xml = '<ns1:h11 xmlns:ns1="URN:test"/>' dom = pyxb.utils.domutils.StringToDOM(xml) self.assertRaises(MissingContentError, h11.createFromDOM, dom.documentElement) def test_h11_elt (self): xml = '<ns1:h11 xmlns:ns1="URN:test"><elt/></ns1:h11>' dom = pyxb.utils.domutils.StringToDOM(xml) instance = h11.createFromDOM(dom.documentElement) self.assert_(instance.elt is not None) self.assertEqual(ToDOM(instance).toxml("utf-8"), xml) def test_h24 (self): xml = '<h24 xmlns="URN:test"></h24>' dom = pyxb.utils.domutils.StringToDOM(xml) self.assertRaises(MissingContentError, h24.createFromDOM, dom.documentElement) for num_elt in range(0, 5): xml = '<ns1:h24 xmlns:ns1="URN:test">%s</ns1:h24>' % (''.join(num_elt * ['<elt/>']),) dom = pyxb.utils.domutils.StringToDOM(xml) if 2 > num_elt: self.assertRaises(MissingContentError, h24.createFromDOM, dom.documentElement) elif 4 >= num_elt: instance = h24.createFromDOM(dom.documentElement) self.assertEqual(num_elt, len(instance.elt)) self.assertEqual(ToDOM(instance).toxml("utf-8"), xml) else: self.assertRaises(ExtraContentError, h24.createFromDOM, dom.documentElement) def test_h24b (self): xml = '<ns1:h24b xmlns:ns1="URN:test"></ns1:h24b>' dom = pyxb.utils.domutils.StringToDOM(xml) self.assertRaises(MissingContentError, h24b.createFromDOM, dom.documentElement) for num_elt in range(0, 5): xml = '<ns1:h24b xmlns:ns1="URN:test">%s</ns1:h24b>' % (''.join(num_elt * ['<elt/>']),) dom = pyxb.utils.domutils.StringToDOM(xml) if 2 > num_elt: self.assertRaises(MissingContentError, h24b.createFromDOM, dom.documentElement) elif 4 >= num_elt: instance = h24b.createFromDOM(dom.documentElement) self.assertEqual(num_elt, len(instance.elt)) self.assertEqual(ToDOM(instance).toxml("utf-8"), xml) else: self.assertRaises(ExtraContentError, h24b.createFromDOM, dom.documentElement) if __name__ == '__main__': unittest.main()<|fim▁end|>
self.assertRaises(ExtraContentError, h01b.createFromDOM, dom.documentElement)
<|file_name|>bootloader.py<|end_file_name|><|fim▁begin|># # Chris Lumens <[email protected]> # # Copyright 2007 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, modify, # copy, or redistribute it subject to the terms and conditions of the GNU # General Public License v.2. This program is distributed in the hope that it # will be useful, but WITHOUT ANY WARRANTY expressed or implied, including the # implied warranties of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along with # this program; if not, write to the Free Software Foundation, Inc., 51 # Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Any Red Hat # trademarks that are incorporated in the source code or documentation are not # subject to the GNU General Public License and may only be used or replicated # with the express permission of Red Hat, Inc. # from pykickstart.base import * from pykickstart.options import * class FC3_Bootloader(KickstartCommand): removedKeywords = KickstartCommand.removedKeywords removedAttrs = KickstartCommand.removedAttrs def __init__(self, writePriority=10, *args, **kwargs): KickstartCommand.__init__(self, writePriority, *args, **kwargs) self.op = self._getParser() self.driveorder = kwargs.get("driveorder", []) self.appendLine = kwargs.get("appendLine", "") self.forceLBA = kwargs.get("forceLBA", False) self.linear = kwargs.get("linear", True) self.location = kwargs.get("location", "") self.md5pass = kwargs.get("md5pass", "") self.password = kwargs.get("password", "") self.upgrade = kwargs.get("upgrade", False) self.useLilo = kwargs.get("useLilo", False) self.deleteRemovedAttrs() def _getArgsAsStr(self): retval = "" if self.appendLine != "": retval += " --append=\"%s\"" % self.appendLine if self.linear: retval += " --linear" if self.location: retval += " --location=%s" % self.location if hasattr(self, "forceLBA") and self.forceLBA: retval += " --lba32" if self.password != "": retval += " --password=\"%s\"" % self.password if self.md5pass != "":<|fim▁hole|> if self.useLilo: retval += " --useLilo" if len(self.driveorder) > 0: retval += " --driveorder=\"%s\"" % ",".join(self.driveorder) return retval def __str__(self): retval = KickstartCommand.__str__(self) if self.location != "": retval += "# System bootloader configuration\nbootloader" retval += self._getArgsAsStr() + "\n" return retval def _getParser(self): def driveorder_cb (option, opt_str, value, parser): for d in value.split(','): parser.values.ensure_value(option.dest, []).append(d) op = KSOptionParser() op.add_option("--append", dest="appendLine") op.add_option("--linear", dest="linear", action="store_true", default=True) op.add_option("--nolinear", dest="linear", action="store_false") op.add_option("--location", dest="location", type="choice", default="mbr", choices=["mbr", "partition", "none", "boot"]) op.add_option("--lba32", dest="forceLBA", action="store_true", default=False) op.add_option("--password", dest="password", default="") op.add_option("--md5pass", dest="md5pass", default="") op.add_option("--upgrade", dest="upgrade", action="store_true", default=False) op.add_option("--useLilo", dest="useLilo", action="store_true", default=False) op.add_option("--driveorder", dest="driveorder", action="callback", callback=driveorder_cb, nargs=1, type="string") return op def parse(self, args): (opts, extra) = self.op.parse_args(args=args, lineno=self.lineno) self._setToSelf(self.op, opts) if self.currentCmd == "lilo": self.useLilo = True return self class FC4_Bootloader(FC3_Bootloader): removedKeywords = FC3_Bootloader.removedKeywords + ["linear", "useLilo"] removedAttrs = FC3_Bootloader.removedAttrs + ["linear", "useLilo"] def __init__(self, writePriority=10, *args, **kwargs): FC3_Bootloader.__init__(self, writePriority, *args, **kwargs) def _getArgsAsStr(self): retval = "" if self.appendLine != "": retval += " --append=\"%s\"" % self.appendLine if self.location: retval += " --location=%s" % self.location if hasattr(self, "forceLBA") and self.forceLBA: retval += " --lba32" if self.password != "": retval += " --password=\"%s\"" % self.password if self.md5pass != "": retval += " --md5pass=\"%s\"" % self.md5pass if self.upgrade: retval += " --upgrade" if len(self.driveorder) > 0: retval += " --driveorder=\"%s\"" % ",".join(self.driveorder) return retval def _getParser(self): op = FC3_Bootloader._getParser(self) op.remove_option("--linear") op.remove_option("--nolinear") op.remove_option("--useLilo") return op def parse(self, args): (opts, extra) = self.op.parse_args(args=args, lineno=self.lineno) self._setToSelf(self.op, opts) return self class F8_Bootloader(FC4_Bootloader): removedKeywords = FC4_Bootloader.removedKeywords removedAttrs = FC4_Bootloader.removedAttrs def __init__(self, writePriority=10, *args, **kwargs): FC4_Bootloader.__init__(self, writePriority, *args, **kwargs) self.timeout = kwargs.get("timeout", None) self.default = kwargs.get("default", "") def _getArgsAsStr(self): ret = FC4_Bootloader._getArgsAsStr(self) if self.timeout is not None: ret += " --timeout=%d" %(self.timeout,) if self.default: ret += " --default=%s" %(self.default,) return ret def _getParser(self): op = FC4_Bootloader._getParser(self) op.add_option("--timeout", dest="timeout", type="int") op.add_option("--default", dest="default") return op class F12_Bootloader(F8_Bootloader): removedKeywords = F8_Bootloader.removedKeywords removedAttrs = F8_Bootloader.removedAttrs def _getParser(self): op = F8_Bootloader._getParser(self) op.add_option("--lba32", dest="forceLBA", deprecated=1, action="store_true") return op class F14_Bootloader(F12_Bootloader): removedKeywords = F12_Bootloader.removedKeywords + ["forceLBA"] removedAttrs = F12_Bootloader.removedKeywords + ["forceLBA"] def _getParser(self): op = F12_Bootloader._getParser(self) op.remove_option("--lba32") return op class F15_Bootloader(F14_Bootloader): removedKeywords = F14_Bootloader.removedKeywords removedAttrs = F14_Bootloader.removedAttrs def __init__(self, writePriority=10, *args, **kwargs): F14_Bootloader.__init__(self, writePriority, *args, **kwargs) self.isCrypted = kwargs.get("isCrypted", False) def _getArgsAsStr(self): ret = F14_Bootloader._getArgsAsStr(self) if self.isCrypted: ret += " --iscrypted" return ret def _getParser(self): def password_cb(option, opt_str, value, parser): parser.values.isCrypted = True parser.values.password = value op = F14_Bootloader._getParser(self) op.add_option("--iscrypted", dest="isCrypted", action="store_true", default=False) op.add_option("--md5pass", action="callback", callback=password_cb, nargs=1, type="string") return op class RHEL5_Bootloader(FC4_Bootloader): removedKeywords = FC4_Bootloader.removedKeywords removedAttrs = FC4_Bootloader.removedAttrs def __init__(self, writePriority=10, *args, **kwargs): FC4_Bootloader.__init__(self, writePriority, *args, **kwargs) self.hvArgs = kwargs.get("hvArgs", "") def _getArgsAsStr(self): ret = FC4_Bootloader._getArgsAsStr(self) if self.hvArgs: ret += " --hvargs=\"%s\"" %(self.hvArgs,) return ret def _getParser(self): op = FC4_Bootloader._getParser(self) op.add_option("--hvargs", dest="hvArgs", type="string") return op class RHEL6_Bootloader(F12_Bootloader): removedKeywords = F12_Bootloader.removedKeywords removedAttrs = F12_Bootloader.removedAttrs def __init__(self, writePriority=10, *args, **kwargs): F12_Bootloader.__init__(self, writePriority, *args, **kwargs) self.isCrypted = kwargs.get("isCrypted", False) def _getArgsAsStr(self): ret = F12_Bootloader._getArgsAsStr(self) if self.isCrypted: ret += " --iscrypted" return ret def _getParser(self): def password_cb(option, opt_str, value, parser): parser.values.isCrypted = True parser.values.password = value op = F12_Bootloader._getParser(self) op.add_option("--iscrypted", dest="isCrypted", action="store_true", default=False) op.add_option("--md5pass", action="callback", callback=password_cb, nargs=1, type="string") return op<|fim▁end|>
retval += " --md5pass=\"%s\"" % self.md5pass if self.upgrade: retval += " --upgrade"
<|file_name|>setting.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- import sae.const DEBUG = False SITE_TITLE = u"博客标题" SITE_SUB_TITLE = u"博客副标题" SITE_KEYWORDS = u"博客关键字" SITE_DECRIPTION = u"博客描述" AUTHOR_NAME = u"博客作者" #显示在RSS订阅里面 #CONACT_MAIL = "[email protected]" #暂未用到 THEMES = ['octopress','admin'] LINK_BROLL = [<|fim▁hole|> MAJOR_DOMAIN = 'www.yourdomain.com' #主域名 ##Mysql 数据库信息 MYSQL_DB = sae.const.MYSQL_DB MYSQL_USER = sae.const.MYSQL_USER MYSQL_PASS = sae.const.MYSQL_PASS MYSQL_HOST = "%s:%s" % (sae.const.MYSQL_HOST_S, sae.const.MYSQL_PORT) MYSQL_HOST_M = "%s:%s" % (sae.const.MYSQL_HOST, sae.const.MYSQL_PORT) JQUERY = "http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js" COOKIE_SECRET = "11orTzKXQAsaYdkL5gEtGeJJFuYh7EQnp2XdTP1o/Vo=" LANGUAGE = 'zh-CN' EACH_PAGE_POST_NUM = 10 #每页显示文章数 RECENT_POST_NUM = 10 #边栏显示最近文章数 RELATED_NUM = 10 #显示相关文章数 SIDER_TAG_NUM = 100 #边栏显示标签数 SIDER_CAT_NUM = 100 #边栏显示分类数 SHORTEN_CONTENT_WORDS = 150 #文章列表截取的字符数 DESCRIPTION_CUT_WORDS = 100 #meta description 显示的字符数 FEED_NUM = 10 #订阅输出文章数 #######下面是保存附件的空间,可选SAE Storage 和 七牛(有免费配额),只选一个 ## 1) 用SAE Storage 需要在SAE 控制面板开通 BUCKET = "" #Domain Name, 如 upload 。不用或用七牛请留空 ## 2) 七牛 注册可获永久10G空间和每月10G流量,注册地址 http://t.cn/z8h5lsg QN_AK = "" #七牛 ACCESS_KEY QN_SK = "" #七牛 SECRET_KEY QN_BUCKET = "" #空间名称 , 如 upload<|fim▁end|>
{'text': u"爱简单吧", 'url': "http://www.ijd8.com", 'title': u"ijd8官方博客"}, {'text': u"YouBBS", 'url': "http://youbbs.sinaapp.com", 'title': u"ijd8支持论坛"}, ]
<|file_name|>chinj01.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Jul 22 17:01:36 2019 @author: raf """ # IMPORT STUFF from pdb import set_trace as stop import copy import numpy as np from collections import OrderedDict import string as st import os import pandas as pd from vison.datamodel import cdp from vison.support import files from vison.fpa import fpa as fpamod from vison.metatests.metacal import MetaCal from vison.plot import plots_fpa as plfpa from vison.support import vcal, utils from vison.datamodel import core as vcore from vison.ogse import ogse from vison.inject import lib as ilib import matplotlib.cm as cm from matplotlib import pyplot as plt plt.switch_backend('TkAgg') from matplotlib.colors import Normalize # END IMPORT cols2keep = [ 'test', 'sn_ccd1', 'sn_ccd2', 'sn_ccd3', 'sn_roe', 'sn_rpsu', 'exptime', 'vstart', 'vend', 'rdmode', 'flushes', 'siflsh', 'siflsh_p', 'swellw', 'swelldly', 'inisweep', 'cdpu_clk', 'chinj', 'chinj_on', 'chinj_of', 'id_wid', 'id_dly', 'chin_dly', 'v_tpump', 's_tpump', 'v_tp_mod', 's_tp_mod', 'v_tp_cnt', 's_tp_cnt', 'dwell_v', 'dwell_s', 'toi_fl', 'toi_tp', 'toi_ro', 'toi_ch', 'motr', 'motr_cnt', 'motr_siz', 'source', 'wave', 'mirr_on', 'mirr_pos', 'R1C1_TT', 'R1C1_TB', 'R1C2_TT', 'R1C2_TB', 'R1C3_TT', 'R1C3_TB', 'IDL', 'IDH', 'IG1_1_T', 'IG1_2_T', 'IG1_3_T', 'IG1_1_B', 'IG1_2_B', 'IG1_3_B', 'IG2_T', 'IG2_B', 'OD_1_T', 'OD_2_T', 'OD_3_T', 'OD_1_B', 'OD_2_B', 'OD_3_B', 'RD_T', 'RD_B', 'time', 'HK_CCD1_TEMP_T', 'HK_CCD2_TEMP_T', 'HK_CCD3_TEMP_T', 'HK_CCD1_TEMP_B', 'HK_CCD2_TEMP_B', 'HK_CCD3_TEMP_B', 'HK_CCD1_OD_T', 'HK_CCD2_OD_T', 'HK_CCD3_OD_T', 'HK_CCD1_OD_B', 'HK_CCD2_OD_B', 'HK_CCD3_OD_B', 'HK_COMM_RD_T', 'HK_COMM_RD_B', 'HK_CCD1_IG1_T', 'HK_CCD2_IG1_T', 'HK_CCD3_IG1_T', 'HK_CCD1_IG1_B', 'HK_CCD2_IG1_B', 'HK_CCD3_IG1_B', 'HK_COMM_IG2_T', 'HK_COMM_IG2_B', 'HK_FPGA_BIAS_ID2', 'HK_VID_PCB_TEMP_T', 'HK_VID_PCB_TEMP_B', 'HK_RPSU_TEMP1', 'HK_FPGA_PCB_TEMP_T', 'HK_FPGA_PCB_TEMP_B', 'HK_RPSU_TEMP_2', 'HK_RPSU_28V_PRI_I', 'chk_NPIXOFF', 'chk_NPIXSAT', 'offset_pre', 'offset_ove', 'std_pre', 'std_ove'] class MetaChinj01(MetaCal): """ """ def __init__(self, **kwargs): """ """ super(MetaChinj01, self).__init__(**kwargs) self.testnames = ['CHINJ01'] self.incols = cols2keep self.ParsedTable = OrderedDict() allgains = files.cPickleRead(kwargs['cdps']['gain']) self.cdps['GAIN'] = OrderedDict() for block in self.blocks: self.cdps['GAIN'][block] = allgains[block]['PTC01'].copy() self.products['METAFIT'] = OrderedDict() self.products['VERPROFILES'] = OrderedDict() self.products['HORPROFILES'] = OrderedDict() self.init_fignames() self.init_outcdpnames() def parse_single_test(self, jrep, block, testname, inventoryitem): """ """ NCCDs = len(self.CCDs) NQuads = len(self.Quads) session = inventoryitem['session'] CCDkeys = ['CCD%i' % CCD for CCD in self.CCDs] IndexS = vcore.vMultiIndex([vcore.vIndex('ix', vals=[0])]) IndexCQ = vcore.vMultiIndex([vcore.vIndex('ix', vals=[0]), vcore.vIndex('CCD', vals=self.CCDs), vcore.vIndex('Quad', vals=self.Quads)]) #idd = copy.deepcopy(inventoryitem['dd']) sidd = self.parse_single_test_gen(jrep, block, testname, inventoryitem) # TEST SCPECIFIC # TO BE ADDED: # OFFSETS: pre, img, ove # RON: pre, img, ove # REFERENCES TO PROFILES CHAMBER = sidd.meta['inputs']['CHAMBER'] CHAMBER_key = CHAMBER[0] chamber_v = np.array([CHAMBER_key]) sidd.addColumn(chamber_v, 'CHAMBERKEY', IndexS, ix=0) block_v = np.array([block]) sidd.addColumn(block_v, 'BLOCK', IndexS, ix=0) test_v = np.array([jrep + 1]) sidd.addColumn(test_v, 'REP', IndexS, ix=0) test_v = np.array([session]) sidd.addColumn(test_v, 'SESSION', IndexS, ix=0) test_v = np.array([testname]) sidd.addColumn(test_v, 'TEST', IndexS, ix=0) productspath = os.path.join(inventoryitem['resroot'], 'products') metafitcdp_pick = os.path.join(productspath, os.path.split(sidd.products['METAFIT_CDP'])[-1]) metafitcdp = files.cPickleRead(metafitcdp_pick) metafit = copy.deepcopy(metafitcdp['data']['ANALYSIS']) metafitkey = '%s_%s_%s_%i' % (testname, block, session, jrep + 1) self.products['METAFIT'][metafitkey] = copy.deepcopy(metafit) metafitkey_v = np.array([metafitkey]) sidd.addColumn(metafitkey_v, 'METAFIT', IndexS, ix=0) metacdp_pick = os.path.join(productspath, os.path.split( sidd.products['META_CDP'])[-1]) # change to META_CDP metacdp = files.cPickleRead(metacdp_pick) meta = metacdp['data']['ANALYSIS'] # this is a pandas DataFrame tmp_v_CQ = np.zeros((1, NCCDs, NQuads)) bgd_adu_v = tmp_v_CQ.copy() ig1_thresh_v = tmp_v_CQ.copy() ig1_notch_v = tmp_v_CQ.copy() slope_v = tmp_v_CQ.copy() n_adu_v = tmp_v_CQ.copy() for iCCD, CCDk in enumerate(CCDkeys): for kQ, Q in enumerate(self.Quads): ixloc = np.where((meta['CCD'] == iCCD + 1) & (meta['Q'] == kQ + 1)) bgd_adu_v[0, iCCD, kQ] = meta['BGD_ADU'][ixloc[0][0]] ig1_thresh_v[0, iCCD, kQ] = meta['IG1_THRESH'][ixloc[0][0]] ig1_notch_v[0, iCCD, kQ] = meta['IG1_NOTCH'][ixloc[0][0]] slope_v[0, iCCD, kQ] = meta['S'][ixloc[0][0]] n_adu_v[0, iCCD, kQ] = meta['N_ADU'][ixloc[0][0]] sidd.addColumn(bgd_adu_v, 'FIT_BGD_ADU', IndexCQ) sidd.addColumn(ig1_thresh_v, 'FIT_IG1_THRESH', IndexCQ) sidd.addColumn(ig1_notch_v, 'FIT_IG1_NOTCH', IndexCQ) sidd.addColumn(slope_v, 'FIT_SLOPE', IndexCQ) sidd.addColumn(n_adu_v, 'FIT_N_ADU', IndexCQ) # charge injection profiles verprofspick = os.path.join(productspath, os.path.split(sidd.products['PROFS_ALCOL'])[-1]) verprofs = files.cPickleRead(verprofspick) vprofkey = '%s_%s_%s_%i' % (testname, block, session, jrep + 1) self.products['VERPROFILES'][vprofkey] = verprofs.copy() vprofskeys_v = np.zeros((1),dtype='U50') vprofskeys_v[0] = vprofkey sidd.addColumn(vprofskeys_v, 'VERPROFS_KEY', IndexS) horprofspick = os.path.join(productspath, os.path.split(sidd.products['PROFS_ALROW'])[-1]) horprofs = files.cPickleRead(horprofspick) hprofkey = '%s_%s_%s_%i' % (testname, block, session, jrep + 1) self.products['HORPROFILES'][hprofkey] = horprofs.copy() hprofskeys_v = np.zeros((1),dtype='U50') hprofskeys_v[0] = hprofkey sidd.addColumn(hprofskeys_v, 'HORPROFS_KEY', IndexS) # flatten sidd to table sit = sidd.flattentoTable() return sit def _get_extractor_NOTCH_fromPT(self, units): """ """ def _extract_NOTCH_fromPT(PT, block, CCDk, Q): ixblock = self.get_ixblock(PT, block) column = 'FIT_N_ADU_%s_Quad%s' % (CCDk, Q) if units == 'ADU': unitsConvFactor = 1 elif units == 'E': unitsConvFactor = self.cdps['GAIN'][block][CCDk][Q][0] Notch = np.nanmedian(PT[column][ixblock]) * unitsConvFactor return Notch return _extract_NOTCH_fromPT def _get_injcurve(self, _chfitdf, ixCCD, ixQ, IG1raw, gain): """ """ ixsel = np.where((_chfitdf['CCD'] == ixCCD) & (_chfitdf['Q'] == ixQ)) pars = ['BGD', 'K', 'XT', 'XN', 'A', 'N'] trans = dict(BGD='b', K='k', XT='xt', XN='xN', A='a', N='N') parsdict = dict() for par in pars: parsdict[trans[par]] = _chfitdf[par].values[ixsel][0] parsdict['IG1'] = IG1raw.copy() inj = ilib.f_Inj_vs_IG1_ReLU(**parsdict) * 2.**16 # ADU inj_kel = inj * gain / 1.E3 return inj_kel def _get_CHIG1_MAP_from_PT(self, kind='CAL'): """ """ CHIG1MAP = OrderedDict() CHIG1MAP['labelkeys'] = self.Quads PT = self.ParsedTable['CHINJ01'] column = 'METAFIT' IG1s = [2.5, 6.75] dIG1 = 0.05 NIG1 = (IG1s[1] - IG1s[0]) / dIG1 + 1 IG1raw = np.arange(NIG1) * dIG1 + IG1s[0] for jY in range(self.NSLICES_FPA): for iX in range(self.NCOLS_FPA): Ckey = 'C_%i%i' % (jY + 1, iX + 1) CHIG1MAP[Ckey] = OrderedDict() locator = self.fpa.FPA_MAP[Ckey] block = locator[0] CCDk = locator[1] jCCD = int(CCDk[-1]) ixblock = np.where(PT['BLOCK'] == block) if len(ixblock[0]) == 0: CHIG1MAP[Ckey] = OrderedDict(x=OrderedDict(), y=OrderedDict()) for Q in self.Quads: CHIG1MAP[Ckey]['x'][Q] = [] CHIG1MAP[Ckey]['y'][Q] = [] continue _chkey = PT[column][ixblock][0] _chfitdf = self.products['METAFIT'][_chkey]<|fim▁hole|> _ccd_chfitdict = OrderedDict(x=OrderedDict(), y=OrderedDict()) for kQ, Q in enumerate(self.Quads): roeVCal = self.roeVCals[block] IG1cal = roeVCal.fcal_HK(IG1raw, 'IG1', jCCD, Q) gain = self.cdps['GAIN'][block][CCDk][Q][0] inj_kel = self._get_injcurve(_chfitdf, jCCD, kQ + 1, IG1raw, gain) if kind == 'CAL': _IG1 = IG1cal.copy() elif kind == 'RAW': _IG1 = IG1raw.copy() _ccd_chfitdict['x'][Q] = _IG1.copy() _ccd_chfitdict['y'][Q] = inj_kel.copy() CHIG1MAP[Ckey] = _ccd_chfitdict.copy() return CHIG1MAP def _get_XYdict_INJ(self, kind='CAL'): x = dict() y = dict() PT = self.ParsedTable['CHINJ01'] column = 'METAFIT' IG1s = [2.5, 6.75] dIG1 = 0.05 NIG1 = (IG1s[1] - IG1s[0]) / dIG1 + 1 IG1raw = np.arange(NIG1) * dIG1 + IG1s[0] labelkeys = [] for block in self.flight_blocks: ixblock = np.where(PT['BLOCK'] == block) ch_key = PT[column][ixblock][0] chfitdf = self.products['METAFIT'][ch_key] for iCCD, CCD in enumerate(self.CCDs): CCDk = 'CCD%i' % CCD for kQ, Q in enumerate(self.Quads): roeVCal = self.roeVCals[block] IG1cal = roeVCal.fcal_HK(IG1raw, 'IG1', iCCD + 1, Q) gain = self.cdps['GAIN'][block][CCDk][Q][0] if kind == 'CAL': _IG1 = IG1cal.copy() elif kind == 'RAW': _IG1 = IG1raw.copy() pkey = '%s_%s_%s' % (block, CCDk, Q) inj_kel = self._get_injcurve(chfitdf, iCCD + 1, kQ + 1, IG1raw, gain) x[pkey] = _IG1.copy() y[pkey] = inj_kel.copy() labelkeys.append(pkey) CHdict = dict(x=x, y=y, labelkeys=labelkeys) return CHdict def _extract_INJCURVES_PAR_fromPT(self,PT,block,CCDk,Q): """ """ ixblock = self.get_ixblock(PT,block) column = 'METAFIT' ch_key = PT[column][ixblock][0] chfitdf = self.products['METAFIT'][ch_key] ixCCD = ['CCD1','CCD2','CCD3'].index(CCDk)+1 ixQ = ['E','F','G','H'].index(Q)+1 ixsel = np.where((chfitdf['CCD'] == ixCCD) & (chfitdf['Q'] == ixQ)) pars = ['BGD', 'K', 'XT', 'XN', 'A', 'N'] trans = dict(BGD='b', K='k', XT='xt', XN='xN', A='a', N='N') parsdict = dict() for par in pars: parsdict[trans[par]] = '%.3e' % chfitdf[par].values[ixsel][0] return parsdict def _get_XYdict_PROFS(self,proftype, IG1=4.5, Quads=None, doNorm=False, xrangeNorm=None): """ """ if Quads is None: Quads = self.Quads x = dict() y = dict() labelkeys = [] PT = self.ParsedTable['CHINJ01'] profcol = '%sPROFS_KEY' % proftype.upper() prodkey = '%sPROFILES' % proftype.upper() for block in self.flight_blocks: ixsel = np.where(PT['BLOCK'] == block) prof_key = PT[profcol][ixsel][0] i_Prof = self.products[prodkey][prof_key].copy() IG1key = 'IG1_%.2fV' % IG1 for iCCD, CCD in enumerate(self.CCDs): CCDk = 'CCD%i' % CCD for kQ, Q in enumerate(Quads): pkey = '%s_%s_%s' % (block, CCDk, Q) _pcq = i_Prof['data'][CCDk][Q].copy() _x = _pcq['x'][IG1key].copy() _y = _pcq['y'][IG1key].copy() x[pkey] = _x if doNorm: if xrangeNorm is not None: norm = np.nanmedian(_y[xrangeNorm[0]:xrangeNorm[1]]) else: norm = np.nanmedian(_y) y[pkey] = _y / norm labelkeys.append(pkey) Pdict = dict(x=x,y=y,labelkeys=labelkeys) return Pdict def init_fignames(self): """ """ if not os.path.exists(self.figspath): os.system('mkdir %s' % self.figspath) self.figs['NOTCH_ADU_MAP'] = os.path.join(self.figspath, 'NOTCH_ADU_MAP.png') self.figs['NOTCH_ELE_MAP'] = os.path.join(self.figspath, 'NOTCH_ELE_MAP.png') self.figs['CHINJ01_curves_IG1_RAW'] = os.path.join(self.figspath, 'CHINJ01_CURVES_IG1_RAW.png') self.figs['CHINJ01_curves_IG1_CAL'] = os.path.join(self.figspath, 'CHINJ01_CURVES_IG1_CAL.png') self.figs['CHINJ01_curves_MAP_IG1_CAL'] = os.path.join(self.figspath, 'CHINJ01_CURVES_MAP_IG1_CAL.png') for proftype in ['ver','hor']: for ccdhalf in ['top','bot']: figkey = 'PROFS_%s_%s' % (proftype.upper(),ccdhalf.upper()) self.figs[figkey] = os.path.join(self.figspath, 'CHINJ01_%s_%s_PROFILES.png' % \ (proftype.upper(),ccdhalf.upper())) for ccdhalf in ['top','bot']: figkey = 'PROFS_ver_%s_ZOOM' % (ccdhalf.upper(),) self.figs[figkey] = os.path.join(self.figspath, 'CHINJ01_ver_%s_ZOOM_PROFILES.png' % \ (ccdhalf.upper()),) def init_outcdpnames(self): if not os.path.exists(self.cdpspath): os.system('mkdir %s' % self.cdpspath) self.outcdps['INJCURVES'] = 'CHINJ01_INJCURVES_PAR.json' self.outcdps['INJPROF_XLSX_HOR'] = 'CHINJ01_INJPROFILES_HOR.xlsx' self.outcdps['INJPROF_XLSX_VER'] = 'CHINJ01_INJPROFILES_VER.xlsx' self.outcdps['INJPROF_FITS_HOR'] = 'CHINJ01_INJPROFILES_HOR.fits' self.outcdps['INJPROF_FITS_VER'] = 'CHINJ01_INJPROFILES_VER.fits' def _extract_NUNHOR_fromPT(self, PT, block, CCDk, Q): """ """ IG1 = 4.5 ixblock = self.get_ixblock(PT, block) profcol = 'HORPROFS_KEY' prodkey = 'HORPROFILES' prof_key = PT[profcol][ixblock][0] i_Prof = self.products[prodkey][prof_key].copy() IG1key = 'IG1_%.2fV' % IG1 _pcq = i_Prof['data'][CCDk][Q].copy() _y = _pcq['y'][IG1key].copy() return np.nanstd(_y)/np.nanmean(_y)*100. def _get_injprof_dfdict(self, direction, pandice=False): """ """ injprofs = OrderedDict() Quads = self.Quads PT = self.ParsedTable['CHINJ01'] profcol = '{}PROFS_KEY'.format(direction.upper()) prodkey = '{}PROFILES'.format(direction.upper()) for ib, block in enumerate(self.flight_blocks): injprofs[block] = OrderedDict() ixsel = np.where(PT['BLOCK'] == block) prof_key = PT[profcol][ixsel][0] i_Prof = self.products[prodkey][prof_key].copy() if ib==0: rawIG1keys = list(i_Prof['data']['CCD1']['E']['x'].keys()) IG1values = [float(item.replace('IG1_','').replace('V','')) for item in rawIG1keys] _order = np.argsort(IG1values) IG1keys = np.array(rawIG1keys)[_order].tolist() IG1values = np.array(IG1values)[_order].tolist() for IG1key in IG1keys: for iCCD, CCD in enumerate(self.CCDs): CCDk = 'CCD%i' % CCD Ckey = self.fpa.get_Ckey_from_BlockCCD(block, CCD) for kQ, Q in enumerate(Quads): _pcq = i_Prof['data'][CCDk][Q].copy() _x = _pcq['x'][IG1key].copy() _y = _pcq['y'][IG1key].copy() #_y /= np.nanmedian(_y) if iCCD==0 and kQ==0: injprofs[block]['pixel'] = _x.copy() injprofs[block]['%s_%s_%s' % (Ckey,Q,IG1key)] = _y.copy() if pandice: for block in self.flight_blocks: injprofs[block] = pd.DataFrame.from_dict(injprofs[block]) return injprofs, IG1values def get_injprof_xlsx_cdp(self, direction, inCDP_header=None): """ """ CDP_header = OrderedDict() if CDP_header is not None: CDP_header.update(inCDP_header) cdpname = self.outcdps['INJPROF_XLSX_%s' % direction.upper()] path = self.cdpspath injprof_cdp = cdp.Tables_CDP() injprof_cdp.rootname = os.path.splitext(cdpname)[0] injprof_cdp.path = path injprofs_meta = OrderedDict() injprofs, IG1values = self._get_injprof_dfdict(direction, pandice=True) injprofs_meta['IG1'] = IG1values.__repr__() #injprofs_meta['norm'] = 'median' injprof_cdp.ingest_inputs(data=injprofs.copy(), meta=injprofs_meta.copy(), header=CDP_header.copy()) injprof_cdp.init_wb_and_fillAll( header_title='CHINJ01: INJPROFS-%s' % direction.upper()) return injprof_cdp def get_injprof_fits_cdp(self, direction, inCDP_header=None): """ """ CDP_header = OrderedDict() if inCDP_header is not None: CDP_header.update(inCDP_header) cdpname = self.outcdps['INJPROF_FITS_%s' % direction.upper()] path = self.cdpspath injprof_cdp = cdp.FitsTables_CDP() injprof_cdp.rootname = os.path.splitext(cdpname)[0] injprof_cdp.path = path injprofs_meta = OrderedDict() injprofs, IG1values = self._get_injprof_dfdict(direction, pandice=False) injprofs_meta['IG1'] = IG1values.__repr__() #injprofs_meta['norm'] = 'median' CDP_header = self.FITSify_CDP_header(CDP_header) injprof_cdp.ingest_inputs(data=injprofs.copy(), meta=injprofs_meta.copy(), header=CDP_header.copy()) injprof_cdp.init_HL_and_fillAll() injprof_cdp.hdulist[0].header.insert(list(CDP_header.keys())[0], ('title', 'CHINJ01: INJPROFS-%s' % direction.upper())) return injprof_cdp def dump_aggregated_results(self): """ """ if self.report is not None: self.report.add_Section(keyword='dump', Title='Aggregated Results', level=0) self.add_DataAlbaran2Report() function, module = utils.get_function_module() CDP_header = self.CDP_header.copy() CDP_header.update(dict(function=function, module=module)) CDP_header['DATE'] = self.get_time_tag() # Histogram of Slopes [ADU/electrons] # Histogram of Notch [ADU/electrons] # Histogram of IG1_THRESH # Injection level vs. Calibrated IG1, MAP CURVES_IG1CAL_MAP = self._get_CHIG1_MAP_from_PT(kind='CAL') figkey1 = 'CHINJ01_curves_MAP_IG1_CAL' figname1 = self.figs[figkey1] self.plot_XYMAP(CURVES_IG1CAL_MAP, **dict( suptitle='Charge Injection Curves - Calibrated IG1', doLegend=True, ylabel='Inj [kel]', xlabel='IG1 [V]', corekwargs=dict(E=dict(linestyle='-', marker='', color='r'), F=dict(linestyle='-', marker='', color='g'), G=dict(linestyle='-', marker='', color='b'), H=dict(linestyle='-', marker='', color='m')), figname=figname1 )) if self.report is not None: self.addFigure2Report(figname1, figkey=figkey1, caption='CHINJ01: Charge injection level [ke-] as a function of '+\ 'calibrated IG1 voltage.', texfraction=0.7) # saving charge injection parameters to a json CDP ICURVES_PAR_MAP = self.get_FPAMAP_from_PT( self.ParsedTable['CHINJ01'], extractor=self._extract_INJCURVES_PAR_fromPT) ic_header = OrderedDict() ic_header['title'] = 'Injection Curves Parameters' ic_header['test'] = 'CHINJ01' ic_header.update(CDP_header) ic_meta = OrderedDict() ic_meta['units'] ='/2^16 ADU', ic_meta['model'] = 'I=b+1/(1+exp(-K(IG1-XT))) * (-A*(IG1-XN)[IG1<XN] + N)' ic_meta['structure'] = '' ic_cdp = cdp.Json_CDP(rootname=self.outcdps['INJCURVES'], path=self.cdpspath) ic_cdp.ingest_inputs(data=ICURVES_PAR_MAP, header = ic_header, meta=ic_meta) ic_cdp.savehardcopy() # Injection level vs. Calibrated IG1, single plot IG1CAL_Singledict = self._get_XYdict_INJ(kind='CAL') figkey2 = 'CHINJ01_curves_IG1_CAL' figname2 = self.figs[figkey2] IG1CAL_kwargs = dict( title='Charge Injection Curves - Calibrated IG1', doLegend=False, xlabel='IG1 (Calibrated) [V]', ylabel='Injection [kel]', figname=figname2) corekwargs = dict() for block in self.flight_blocks: for iCCD in self.CCDs: corekwargs['%s_CCD%i_E' % (block, iCCD)] = dict(linestyle='-', marker='', color='#FF4600') # red corekwargs['%s_CCD%i_F' % (block, iCCD)] = dict(linestyle='-', marker='', color='#61FF00') # green corekwargs['%s_CCD%i_G' % (block, iCCD)] = dict(linestyle='-', marker='', color='#00FFE0') # cyan corekwargs['%s_CCD%i_H' % (block, iCCD)] = dict(linestyle='-', marker='', color='#1700FF') # blue IG1CAL_kwargs['corekwargs'] = corekwargs.copy() self.plot_XY(IG1CAL_Singledict, **IG1CAL_kwargs) if self.report is not None: self.addFigure2Report(figname2, figkey=figkey2, caption='CHINJ01: Charge injection level [ke-] as a function of '+\ 'calibrated IG1 voltage.', texfraction=0.7) # Injection level vs. Non-Calibrated IG1, single plot IG1RAW_Singledict = self._get_XYdict_INJ(kind='RAW') figkey3 = 'CHINJ01_curves_IG1_RAW' figname3 = self.figs[figkey3] IG1RAW_kwargs = dict( title='Charge Injection Curves - RAW IG1', doLegend=False, xlabel='IG1 (RAW) [V]', ylabel='Injection [kel]', figname=figname3) corekwargs = dict() for block in self.flight_blocks: for iCCD in self.CCDs: corekwargs['%s_CCD%i_E' % (block, iCCD)] = dict(linestyle='-', marker='', color='#FF4600') # red corekwargs['%s_CCD%i_F' % (block, iCCD)] = dict(linestyle='-', marker='', color='#61FF00') # green corekwargs['%s_CCD%i_G' % (block, iCCD)] = dict(linestyle='-', marker='', color='#00FFE0') # cyan corekwargs['%s_CCD%i_H' % (block, iCCD)] = dict(linestyle='-', marker='', color='#1700FF') # blue IG1RAW_kwargs['corekwargs'] = corekwargs.copy() self.plot_XY(IG1RAW_Singledict, **IG1RAW_kwargs) if self.report is not None: self.addFigure2Report(figname3, figkey=figkey3, caption='CHINJ01: Charge injection level [ke-] as a function of '+\ 'Non-calibrated IG1 voltage.', texfraction=0.7) # Notch level vs. calibrated IG2 # Notch level vs. calibrated IDL # Notch level vs. calibrated OD # Notch injection map, ADUs NOTCHADUMAP = self.get_FPAMAP_from_PT( self.ParsedTable['CHINJ01'], extractor=self._get_extractor_NOTCH_fromPT( units='ADU')) figkey4 = 'NOTCH_ADU_MAP' figname4 = self.figs[figkey4] self.plot_SimpleMAP(NOTCHADUMAP, **dict( suptitle='CHINJ01: NOTCH INJECTION [ADU]', ColorbarText='ADU', figname=figname4)) if self.report is not None: self.addFigure2Report(figname4, figkey=figkey4, caption='CHINJ01: notch injection level, in ADU.', texfraction=0.7) # Notch injection map, ELECTRONs NOTCHEMAP = self.get_FPAMAP_from_PT(self.ParsedTable['CHINJ01'], extractor=self._get_extractor_NOTCH_fromPT(units='E')) figkey5 = 'NOTCH_ELE_MAP' figname5 = self.figs[figkey5] self.plot_SimpleMAP(NOTCHEMAP, **dict( suptitle='CHINJ01: NOTCH INJECTION [ELECTRONS]', ColorbarText='electrons', figname=figname5)) if self.report is not None: self.addFigure2Report(figname5, figkey=figkey5, caption='CHINJ01: notch injection level, in electrons.', texfraction=0.7) # Average injection profiles IG1profs = 4.5 xlabels_profs = dict(hor='column [pix]', ver='row [pix]') ylabels_profs = dict(hor='Injection level [Normalized]', ver='Injection level [ADU]',) proftypes = ['hor','ver'] ccdhalves = ['top','bot'] BLOCKcolors = cm.rainbow(np.linspace(0, 1, len(self.flight_blocks))) pointcorekwargs = dict() for jblock, block in enumerate(self.flight_blocks): jcolor = BLOCKcolors[jblock] for iCCD in self.CCDs: for kQ in self.Quads: pointcorekwargs['%s_CCD%i_%s' % (block, iCCD, kQ)] = dict( linestyle='', marker='.', color=jcolor, ms=2.0) for ccdhalf in ccdhalves: if ccdhalf == 'top': _Quads = ['G','H'] elif ccdhalf == 'bot': _Quads = ['E','F'] for proftype in proftypes: if proftype == 'hor': xrangeNorm = None elif proftype == 'ver': xrangeNorm = [10,20] XY_profs = self._get_XYdict_PROFS(proftype=proftype, IG1=IG1profs,Quads=_Quads, doNorm=True, xrangeNorm=xrangeNorm) figkey6 = 'PROFS_%s_%s' % (proftype.upper(),ccdhalf.upper()) figname6 = self.figs[figkey6] title = 'CHINJ01: Direction: %s, CCDHalf: %s' % \ (proftype.upper(),ccdhalf.upper()), if proftype == 'ver': xlim=[0,50] ylim=None elif proftype == 'hor': xlim=None ylim=[0.5,1.5] profkwargs = dict( title=title, doLegend=False, xlabel=xlabels_profs[proftype], xlim=xlim, ylim=ylim, ylabel=ylabels_profs[proftype], figname=figname6, corekwargs=pointcorekwargs) self.plot_XY(XY_profs, **profkwargs) if proftype == 'ver': captemp = 'CHINJ01: Average (normalized) injection profiles in vertical direction (along CCD columns) '+\ 'for IG1=%.2fV. Only the 2 channels in the CCD %s-half are shown '+\ '(%s, %s). Each colour corresponds to a '+\ 'different block (2x3 quadrant-channels in each colour).' elif proftype == 'hor': captemp = 'CHINJ01: Average injection profiles in horizontal direction (along CCD rows) '+\ 'for IG1=%.2fV. The profiles have been normalized by the median injection level. '+\ 'Only the 2 channels in the CCD %s-half are shown (%s, %s). Each colour corresponds to a '+\ 'different block (2x3 quadrant-channels in each colour).' if self.report is not None: self.addFigure2Report(figname6, figkey=figkey6, caption= captemp % (IG1profs, ccdhalf, _Quads[0],_Quads[1]), texfraction=0.7) # Average injection vertical profiles, zoomed in to highlight # non-perfect charge injection shut-down. pointcorekwargs = dict() for jblock, block in enumerate(self.flight_blocks): jcolor = BLOCKcolors[jblock] for iCCD in self.CCDs: for kQ in self.Quads: pointcorekwargs['%s_CCD%i_%s' % (block, iCCD, kQ)] = dict( linestyle='', marker='.', color=jcolor, ms=2.0) for ccdhalf in ccdhalves: if ccdhalf == 'top': _Quads = ['G','H'] elif ccdhalf == 'bot': _Quads = ['E','F'] XY_profs = self._get_XYdict_PROFS(proftype='ver', IG1=IG1profs,Quads=_Quads, doNorm=True, xrangeNorm=[10,20]) figkey7 = 'PROFS_ver_%s_ZOOM' % (ccdhalf.upper(),) figname7 = self.figs[figkey7] title = 'CHINJ01: Direction: ver, CCDHalf: %s, ZOOM-in' % \ (ccdhalf.upper(),), xlim=[25,50] ylim=[0,4.e-3] profkwargs = dict( title=title, doLegend=False, xlabel=xlabels_profs[proftype], xlim=xlim, ylim=ylim, ylabel=ylabels_profs[proftype], figname=figname7, corekwargs=pointcorekwargs) self.plot_XY(XY_profs, **profkwargs) captemp = 'CHINJ01: Average injection profiles in vertical direction (along CCD columns) '+\ 'for IG1=%.2fV. Only the 2 channels in the CCD %s-half are shown '+\ '(%s, %s). Each colour corresponds to a '+\ 'different block (2x3 quadrant-channels in each colour). Zoomed in '+\ 'to highlight injection shutdown profile.' if self.report is not None: self.addFigure2Report(figname7, figkey=figkey7, caption= captemp % (IG1profs, ccdhalf, _Quads[0],_Quads[1]), texfraction=0.7) # creating and saving INJ PROFILES CDPs. for direction in ['hor','ver']: _injprof_xlsx_cdp = self.get_injprof_xlsx_cdp(direction=direction, inCDP_header=CDP_header) _injprof_xlsx_cdp.savehardcopy() _injprof_fits_cdp = self.get_injprof_fits_cdp(direction=direction, inCDP_header=CDP_header) _injprof_fits_cdp.savehardcopy() # reporting non-uniformity of injection lines to report if self.report is not None: NUN_HOR = self.get_FPAMAP_from_PT(self.ParsedTable['CHINJ01'], extractor=self._extract_NUNHOR_fromPT) nun_cdpdict = dict( caption='CHINJ01: Non-Uniformity of the injection lines, rms, as percentage.', valformat='%.2f') ignore = self.add_StdQuadsTable2Report( Matrix = NUN_HOR, cdpdict = nun_cdpdict)<|fim▁end|>
<|file_name|>launch_default_experiments.py<|end_file_name|><|fim▁begin|>import argparse import os from config import * def main(): parser = argparse.ArgumentParser(prog=os.path.basename(__file__)) globals().update(load_config(parser)) parser.add_argument('--dataset', choices=datasets, required=False) args = parser.parse_args() # override default values if args.dataset: selected_datasets = [args.dataset] else: selected_datasets = datasets for d in selected_datasets:<|fim▁hole|> print(command) os.system(command) if __name__ == "__main__": main()<|fim▁end|>
for m in methods: experiment_name = '%s.%s' % (d, m) command = "qsub -N %s -l q=compute %s/scripts/default_experiment.sh %s %s" % ( experiment_name, os.environ['AUTOWEKA_PATH'], d, m)
<|file_name|>__openerp__.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name' : 'Account Tax Cash Basis', 'version' : '1.1',<|fim▁hole|> 'sequence': 4, 'description': """ Add an option on tax to allow them to be cash based, meaning that during reconciliation, if there is a tax with cash basis involved, a new journal entry will be create containing those taxes value. """, 'category' : 'Accounting & Finance', 'website': 'https://www.odoo.com/page/accounting', 'depends' : ['account'], 'data': [ 'views/tax_cash_basis_view.xml', ], 'installable': True, 'auto_install': False, }<|fim▁end|>
'author' : 'OpenERP SA', 'summary': 'Allow to have cash basis on tax',
<|file_name|>ST_decrypt.java<|end_file_name|><|fim▁begin|>import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; // import org.apache.commons.cli.*; class Dumper { private static FileOutputStream fstream; public Dumper(String filename) { try { fstream = new FileOutputStream(filename); } catch (FileNotFoundException ex) { Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex); } } /** * Dump byte array to a file * * @param dump byte array * @param filename */ static void dump(byte[] dump, String filename) { if (dump == null) { return; } FileOutputStream fos = null; try { fos = new FileOutputStream(filename); } catch (FileNotFoundException ex) { Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex); } try { fos.write(dump, 0, dump.length); fos.flush(); fos.close(); } catch (IOException ex) { Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex); } } void append(byte[] b) { try { fstream.write(b); } catch (IOException ex) { Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex); } } void close() { try { fstream.close(); } catch (IOException ex) { Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex); } } } class Crypto { private static int d(final int n) { final long n2 = n & 0xFFFFFFFFL; return (int) ((n2 & 0x7F7F7F7FL) << 1 ^ ((n2 & 0xFFFFFFFF80808080L) >> 7) * 27L); } private static int a(final int n, final int n2) { final long n3 = n & 0xFFFFFFFFL; return (int) (n3 >> n2 * 8 | n3 << 32 - n2 * 8); } static int polynom2(int n) { final int d3; final int d2; final int d = d(d2 = d(d3 = d(n))); n ^= d; return d3 ^ (d2 ^ d ^ a(d3 ^ n, 3) ^ a(d2 ^ n, 2) ^ a(n, 1)); } static int polynom(int n) { return (d(n) ^ a(n ^ d(n), 3) ^ a(n, 2) ^ a(n, 1)); } } public class ST_decrypt { /** * Encrypt or decrypt input file */ private static boolean encrypt; private static String encryptionKey; private static Dumper dumper; public static void main(String[] args) { // CommandLineParser parser = new DefaultParser(); // Options options = new Options(); // String help = "st_decrypt.jar [-e] -k <key> -i <input> -o <output>"; // options.addOption("k", "key", true, "encryption key"); // options.addOption("e", "encrypt", false, "encrypt binary"); // options.addOption("i", "input", true, "input file"); // options.addOption("o", "output", true, "output file"); // HelpFormatter formatter = new HelpFormatter(); // CommandLine opts = null; // try { // opts = parser.parse(options, args); // if (opts.hasOption("key") // && opts.hasOption("input") // && opts.hasOption("output")) { // encryptionKey = opts.getOptionValue("key"); // } else { // formatter.printHelp(help, options); // System.exit(1); // } // encrypt = opts.hasOption("encrypt"); // } catch (ParseException exp) { // System.out.println(exp.getMessage()); // formatter.printHelp(help, options); // System.exit(1); // } // String output = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java.bin"; // String input = "/home/jonathan/stm_jig/usb_sniff/f2_5.bin"; // String output = "/home/jonathan/stm_jig/usb_sniff/16_encrypted"; // String input = "/home/jonathan/stm_jig/usb_sniff/16_unencrypted"; // String output = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java_enc.bin"; // String input = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java.bin"; // encryptionKey = "I am a key, wawawa"; // // encryptionKey = unHex("496CDB76964E46637CC0237ED87B6B7F"); // // encryptionKey = unHex("E757D2F9F122DEB3FB883ECC1AF4C688"); // // encryptionKey = unHex("8DBDA2460CD8069682D3E9BB755B7FB9"); // encryptionKey = unHex("5F4946053BD9896E8F4CE917A6D2F21A"); // encrypt=true; encryptionKey = "best performance"; int dataLength = 30720;//(int)getFileLen("/home/jonathan/stm_jig/provisioning-jig/fw_update/fw_upgrade/f2_1.bin"); byte[] fw = new byte[dataLength]; byte[] key = new byte[16];//encryptionKey.getBytes(); byte[] data = new byte[dataLength];// {0xF7, 0x72, 0x44, 0xB3, 0xFC, 0x86, 0xE0, 0xDC, 0x20, 0xE1, 0x74, 0x2D, 0x3A, 0x29, 0x0B, 0xD2}; str_to_arr(encryptionKey, key); readFileIntoArr(System.getProperty("user.dir") + "/f2_1.bin", data); decrypt(data, fw, key, dataLength); System.out.println(dataLength); System.out.println(toHexStr(fw).length()); // Write out the decrypted fw for debugging String outf = "fw_decrypted.bin"; dumper = new Dumper(outf); dumper.dump(fw, outf); dumper.close(); // fw now contains our decrypted firmware // Make a key from the first 4 and last 12 bytes returned by f308 encryptionKey = "I am key, wawawa"; byte[] newKey = new byte[16]; byte[] f308 = new byte[16]; str_to_arr(encryptionKey, key); readFileIntoArr("f303_bytes_4_12.bin", f308); encrypt(f308, newKey, key, 16); System.out.print("Using key: "); System.out.println(toHexStr(newKey)); System.out.print("From bytes: "); System.out.println(toHexStr(f308)); byte[] enc_fw = new byte[dataLength]; encrypt(fw, enc_fw, newKey, dataLength); // System.out.println(toHexStr(enc_fw)); // Now for real String outfile = "fw_re_encrypted.bin"; dumper = new Dumper(outfile); dumper.dump(enc_fw, outfile); dumper.close(); byte[] a = new byte[16]; byte[] ans = new byte[16]; str_to_arr(unHex("ffffffffffffffffffffffffd32700a5"), a); encrypt(a, ans, newKey, 16); System.out.println("Final 16 bytes: " + toHexStr(ans)); outfile = "version_thingee_16.bin"; dumper = new Dumper(outfile); dumper.dump(ans, outfile); dumper.close(); // dumper = new Dumper(output); // dump_fw(input); // dumper.close(); // System.out.println("Done!"); } // ***************** MY Code functions ***************** JW static void readFileIntoArr(String file, byte[] data){ FileInputStream fis = null; try { File f = new File(file); fis = new FileInputStream(f); } catch (Exception ex) { System.out.print(file); System.out.println("Invalid file name"); System.exit(1); } try (BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) { long len = getFileLen(file); bufferedInputStream.read(data); } catch (IOException ex) { Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex); } } static String toHexStr(byte[] B){ StringBuilder str = new StringBuilder(); for(int i = 0; i < B.length; i++){ str.append(String.format("%02x", B[i])); } return str.toString(); } static String unHex(String arg) { String str = ""; for(int i=0;i<arg.length();i+=2) { String s = arg.substring(i, (i + 2)); int decimal = Integer.parseInt(s, 16); str = str + (char) decimal; } return str; } // ******************************************************* static long getFileLen(String file) { long n2 = 0L; FileInputStream fis = null; try { File f = new File(file); fis = new FileInputStream(f); } catch (Exception ex) { } try { BufferedInputStream bufferedInputStream = new BufferedInputStream(fis); while (true) { int read; try { read = bufferedInputStream.read(); } catch (IOException ex) { System.out.println("Failure opening file"); read = -1; } if (read == -1) { break; } ++n2; } bufferedInputStream.close(); } catch (IOException ex3) { System.out.println("Failure getting firmware data"); } return n2; } /** * * @param array firmware byte array * @param n length * @param n2 ?? * @return */ static long encodeAndWrite(final byte[] array, long n, final int n2) { long a = 0L; final byte[] array2 = new byte[4 * ((array.length + 3) / 4)]; // Clever hack to get multiple of fourwith padding final byte[] array3 = new byte[16]; str_to_arr(encryptionKey, array3); if (encrypt) { encrypt(array, array2, array3, array.length); } else { decrypt(array, array2, array3, array.length); } <|fim▁hole|> } static long writeFirmware(final BufferedInputStream bufferedInputStream, final long n) { long a = 0L; final byte[] array = new byte[3072]; long n4 = 0L; try { while (n4 < n && a == 0L) { final long n5; if ((n5 = bufferedInputStream.read(array)) != -1L) { encodeAndWrite(array, n4 + 134234112L, 3072); n4 += n5; } } } catch (IOException ex) { System.out.println("Failure reading file: " + ex.getMessage()); System.exit(1); } return a; } static void dump_fw(String file) { FileInputStream fis = null; try { File f = new File(file); fis = new FileInputStream(f); } catch (Exception ex) { System.out.println("Invalid file name"); System.exit(1); } try (BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) { long len = getFileLen(file); writeFirmware(bufferedInputStream, len); } catch (IOException ex) { Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex); } } private static int pack_u32(final int n, final int n2, final int n3, final int n4) { return (n << 24 & 0xFF000000) + (n2 << 16 & 0xFF0000) + (n3 << 8 & 0xFF00) + (n4 & 0xFF); } private static int u32(final int n) { return n >>> 24; } private static int u16(final int n) { return n >> 16 & 0xFF; } private static int u8(final int n) { return n >> 8 & 0xFF; } /** * Converts the key from String to byte array * * @param s input string * @param array destination array */ public static void str_to_arr(final String s, final byte[] array) { final char[] charArray = s.toCharArray(); for (int i = 0; i < 16; ++i) { array[i] = (byte) charArray[i]; } } private static void key_decode(final byte[] array, final int[] array2) { // core.a.a(byte[], byte[]) final int[] array3 = new int[4]; for (int i = 0; i < 4; ++i) { array2[i] = (array3[i] = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * i)); } for (int j = 0; j < 10;) { array3[0] ^= (int) (pack_u32(aes_x[u16(array3[3])], aes_x[u8(array3[3])], aes_x[array3[3] & 0xFF], aes_x[u32(array3[3])]) ^ rcon[j++]); array3[1] ^= array3[0]; array3[2] ^= array3[1]; array3[3] ^= array3[2]; System.arraycopy(array3, 0, array2, 4 * j, 4); } } /** * Encrypt firmware file */ static void encrypt(final byte[] src, final byte[] dest, byte[] key, int len) { final byte[] array3 = new byte[16]; int n = 0; key_decode(key, mystery_key); while (len > 0) { key = null; int n2; if (len >= 16) { key = Arrays.copyOfRange(src, n, n + 16); n2 = 16; } else if ((n2 = len) > 0) { final byte[] array4 = new byte[16]; for (int j = 0; j < len; ++j) { array4[j] = src[n + j]; } for (int k = len; k < 16; ++k) { array4[k] = (byte) Double.doubleToLongBits(Math.random()); } key = array4; } if (len > 0) { final int[] a = mystery_key; final int[] tmp = new int[4]; int n3 = 10; int n4 = 0; for (int l = 0; l < 4; ++l) { tmp[l] = (ByteBuffer.wrap(key).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * l) ^ a[l + 0]); } n4 += 4; do { final int a2 = pack_u32(aes_x[u32(tmp[0])], aes_x[u16(tmp[1])], aes_x[u8(tmp[2])], aes_x[tmp[3] & 0xFF]); final int a3 = pack_u32(aes_x[u32(tmp[1])], aes_x[u16(tmp[2])], aes_x[u8(tmp[3])], aes_x[tmp[0] & 0xFF]); final int a4 = pack_u32(aes_x[u32(tmp[2])], aes_x[u16(tmp[3])], aes_x[u8(tmp[0])], aes_x[tmp[1] & 0xFF]); final int a5 = pack_u32(aes_x[u32(tmp[3])], aes_x[u16(tmp[0])], aes_x[u8(tmp[1])], aes_x[tmp[2] & 0xFF]); tmp[0] = (Crypto.polynom(a2) ^ a[n4]); tmp[1] = (Crypto.polynom(a3) ^ a[n4 + 1]); tmp[2] = (Crypto.polynom(a4) ^ a[n4 + 2]); tmp[3] = (Crypto.polynom(a5) ^ a[n4 + 3]); n4 += 4; } while (--n3 != 1); final int a6 = pack_u32(aes_x[u32(tmp[0])], aes_x[u16(tmp[1])], aes_x[u8(tmp[2])], aes_x[tmp[3] & 0xFF]); final int a7 = pack_u32(aes_x[u32(tmp[1])], aes_x[u16(tmp[2])], aes_x[u8(tmp[3])], aes_x[tmp[0] & 0xFF]); final int a8 = pack_u32(aes_x[u32(tmp[2])], aes_x[u16(tmp[3])], aes_x[u8(tmp[0])], aes_x[tmp[1] & 0xFF]); final int a9 = pack_u32(aes_x[u32(tmp[3])], aes_x[u16(tmp[0])], aes_x[u8(tmp[1])], aes_x[tmp[2] & 0xFF]); final int n5 = a6 ^ a[n4]; final int n6 = a7 ^ a[n4 + 1]; final int n7 = a8 ^ a[n4 + 2]; final int n8 = a9 ^ a[n4 + 3]; ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(n5); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(4, n6); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(8, n7); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(12, n8); } for (int i = 0; i < 16; ++i) { dest[n + i] = array3[i]; } len -= n2; n += n2; } } /** * Decrypt firmware file * * @param src firmware file * @param dest destination array * @param key key * @param len array.length */ static void decrypt(final byte[] src, final byte[] dest, byte[] key, int len) { final byte[] array3 = new byte[16]; int n = 0; key_decode(key, mystery_key); while (len > 0) { key = null; int n2; if (len >= 16) { key = Arrays.copyOfRange(src, n, n + 16); n2 = 16; } else if ((n2 = len) > 0) { final byte[] array4 = new byte[16]; for (int j = 0; j < len; ++j) { array4[j] = src[n + j]; } for (int k = len; k < 16; ++k) { array4[k] = (byte) Double.doubleToLongBits(Math.random()); } key = array4; } if (len > 0) { final int[] a = mystery_key; final int[] tmp = new int[4]; int n3 = 10; int n4 = 40; for (int l = 0; l < 4; ++l) { tmp[l] = (ByteBuffer.wrap(key).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * l) ^ a[l + 40]); } n4 -= 8; do { final int n5 = pack_u32(aes_y[u32(tmp[0])], aes_y[u16(tmp[3])], aes_y[u8(tmp[2])], aes_y[tmp[1] & 0xFF]) ^ a[n4 + 4]; final int n6 = pack_u32(aes_y[u32(tmp[1])], aes_y[u16(tmp[0])], aes_y[u8(tmp[3])], aes_y[tmp[2] & 0xFF]) ^ a[n4 + 5]; final int n7 = pack_u32(aes_y[u32(tmp[2])], aes_y[u16(tmp[1])], aes_y[u8(tmp[0])], aes_y[tmp[3] & 0xFF]) ^ a[n4 + 6]; final int n8 = pack_u32(aes_y[u32(tmp[3])], aes_y[u16(tmp[2])], aes_y[u8(tmp[1])], aes_y[tmp[0] & 0xFF]) ^ a[n4 + 7]; tmp[0] = Crypto.polynom2(n5); tmp[1] = Crypto.polynom2(n6); tmp[2] = Crypto.polynom2(n7); tmp[3] = Crypto.polynom2(n8); n4 -= 4; } while (--n3 != 1); final int n9 = pack_u32(aes_y[u32(tmp[0])], aes_y[u16(tmp[3])], aes_y[u8(tmp[2])], aes_y[tmp[1] & 0xFF]) ^ a[n4 + 4]; final int n10 = pack_u32(aes_y[u32(tmp[1])], aes_y[u16(tmp[0])], aes_y[u8(tmp[3])], aes_y[tmp[2] & 0xFF]) ^ a[n4 + 5]; final int n11 = pack_u32(aes_y[u32(tmp[2])], aes_y[u16(tmp[1])], aes_y[u8(tmp[0])], aes_y[tmp[3] & 0xFF]) ^ a[n4 + 6]; final int n12 = pack_u32(aes_y[u32(tmp[3])], aes_y[u16(tmp[2])], aes_y[u8(tmp[1])], aes_y[tmp[0] & 0xFF]) ^ a[n4 + 7]; ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(n9); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(4, n10); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(8, n11); ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(12, n12); } for (int i = 0; i < n2; ++i) { dest[n + i] = array3[i]; } len -= n2; n += n2; } } static int[] mystery_key = new int[44]; static int[] aes_x = { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }; static int[] aes_y = { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D }; static long[] rcon = { 0x01000000L, 0x02000000L, 0x04000000L, 0x08000000L, 0x10000000L, 0x20000000L, 0x40000000L, 0xFFFFFFFF80000000L, 0x1B000000L, 0x36000000L }; }<|fim▁end|>
/* Send chunk of data to device */ dumper.append(array2); return a;
<|file_name|>syscall_darwin.go<|end_file_name|><|fim▁begin|>// Copyright 2009,2010 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package syscall import "unsafe" func direntIno(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Ino), unsafe.Sizeof(Dirent{}.Ino)) } func direntReclen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Reclen), unsafe.Sizeof(Dirent{}.Reclen)) } func direntNamlen(buf []byte) (uint64, bool) { return readInt(buf, unsafe.Offsetof(Dirent{}.Namlen), unsafe.Sizeof(Dirent{}.Namlen))<|fim▁hole|><|fim▁end|>
}
<|file_name|>integer-test.js<|end_file_name|><|fim▁begin|>import hbs from 'htmlbars-inline-precompile'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('advanced-form/integer', { integration: true }); test('Render component with attributes', function(assert) { this.render( hbs`{{advanced-form/integer min=10 max=20 value=5}}`<|fim▁hole|> var $componentInput = this.$('.integer input'); assert.equal($componentInput.val(), '10'); });<|fim▁end|>
);
<|file_name|>fake_service_repository.go<|end_file_name|><|fim▁begin|>// This file was generated by counterfeiter package fakes import ( "sync" "github.com/cloudfoundry/cli/cf/api" "github.com/cloudfoundry/cli/cf/api/resources" "github.com/cloudfoundry/cli/cf/models" ) type FakeServiceRepository struct { PurgeServiceOfferingStub func(offering models.ServiceOffering) error purgeServiceOfferingMutex sync.RWMutex purgeServiceOfferingArgsForCall []struct { offering models.ServiceOffering } purgeServiceOfferingReturns struct { result1 error } GetServiceOfferingByGuidStub func(serviceGuid string) (offering models.ServiceOffering, apiErr error) getServiceOfferingByGuidMutex sync.RWMutex getServiceOfferingByGuidArgsForCall []struct { serviceGuid string } getServiceOfferingByGuidReturns struct { result1 models.ServiceOffering result2 error } FindServiceOfferingsByLabelStub func(name string) (offering models.ServiceOfferings, apiErr error) findServiceOfferingsByLabelMutex sync.RWMutex findServiceOfferingsByLabelArgsForCall []struct { name string } findServiceOfferingsByLabelReturns struct { result1 models.ServiceOfferings result2 error } FindServiceOfferingByLabelAndProviderStub func(name, provider string) (offering models.ServiceOffering, apiErr error) findServiceOfferingByLabelAndProviderMutex sync.RWMutex findServiceOfferingByLabelAndProviderArgsForCall []struct { name string provider string } findServiceOfferingByLabelAndProviderReturns struct { result1 models.ServiceOffering result2 error } FindServiceOfferingsForSpaceByLabelStub func(spaceGuid, name string) (offering models.ServiceOfferings, apiErr error) findServiceOfferingsForSpaceByLabelMutex sync.RWMutex findServiceOfferingsForSpaceByLabelArgsForCall []struct { spaceGuid string name string } findServiceOfferingsForSpaceByLabelReturns struct { result1 models.ServiceOfferings result2 error } GetAllServiceOfferingsStub func() (offerings models.ServiceOfferings, apiErr error) getAllServiceOfferingsMutex sync.RWMutex getAllServiceOfferingsArgsForCall []struct{} getAllServiceOfferingsReturns struct { result1 models.ServiceOfferings result2 error } GetServiceOfferingsForSpaceStub func(spaceGuid string) (offerings models.ServiceOfferings, apiErr error) getServiceOfferingsForSpaceMutex sync.RWMutex getServiceOfferingsForSpaceArgsForCall []struct { spaceGuid string } getServiceOfferingsForSpaceReturns struct { result1 models.ServiceOfferings result2 error } FindInstanceByNameStub func(name string) (instance models.ServiceInstance, apiErr error) findInstanceByNameMutex sync.RWMutex findInstanceByNameArgsForCall []struct { name string } findInstanceByNameReturns struct { result1 models.ServiceInstance result2 error } PurgeServiceInstanceStub func(instance models.ServiceInstance) error purgeServiceInstanceMutex sync.RWMutex purgeServiceInstanceArgsForCall []struct { instance models.ServiceInstance } purgeServiceInstanceReturns struct { result1 error } CreateServiceInstanceStub func(name, planGuid string, params map[string]interface{}, tags []string) (apiErr error) createServiceInstanceMutex sync.RWMutex createServiceInstanceArgsForCall []struct { name string planGuid string params map[string]interface{} tags []string } createServiceInstanceReturns struct { result1 error } UpdateServiceInstanceStub func(instanceGuid, planGuid string, params map[string]interface{}, tags []string) (apiErr error) updateServiceInstanceMutex sync.RWMutex updateServiceInstanceArgsForCall []struct { instanceGuid string planGuid string params map[string]interface{} tags []string } updateServiceInstanceReturns struct { result1 error } RenameServiceStub func(instance models.ServiceInstance, newName string) (apiErr error) renameServiceMutex sync.RWMutex renameServiceArgsForCall []struct { instance models.ServiceInstance newName string } renameServiceReturns struct { result1 error } DeleteServiceStub func(instance models.ServiceInstance) (apiErr error) deleteServiceMutex sync.RWMutex deleteServiceArgsForCall []struct { instance models.ServiceInstance } deleteServiceReturns struct { result1 error } FindServicePlanByDescriptionStub func(planDescription resources.ServicePlanDescription) (planGuid string, apiErr error) findServicePlanByDescriptionMutex sync.RWMutex findServicePlanByDescriptionArgsForCall []struct { planDescription resources.ServicePlanDescription } findServicePlanByDescriptionReturns struct { result1 string result2 error } ListServicesFromBrokerStub func(brokerGuid string) (services []models.ServiceOffering, err error) listServicesFromBrokerMutex sync.RWMutex listServicesFromBrokerArgsForCall []struct { brokerGuid string } listServicesFromBrokerReturns struct { result1 []models.ServiceOffering result2 error } ListServicesFromManyBrokersStub func(brokerGuids []string) (services []models.ServiceOffering, err error) listServicesFromManyBrokersMutex sync.RWMutex listServicesFromManyBrokersArgsForCall []struct { brokerGuids []string } listServicesFromManyBrokersReturns struct { result1 []models.ServiceOffering result2 error } GetServiceInstanceCountForServicePlanStub func(v1PlanGuid string) (count int, apiErr error) getServiceInstanceCountForServicePlanMutex sync.RWMutex getServiceInstanceCountForServicePlanArgsForCall []struct { v1PlanGuid string } getServiceInstanceCountForServicePlanReturns struct { result1 int result2 error } MigrateServicePlanFromV1ToV2Stub func(v1PlanGuid, v2PlanGuid string) (changedCount int, apiErr error) migrateServicePlanFromV1ToV2Mutex sync.RWMutex migrateServicePlanFromV1ToV2ArgsForCall []struct { v1PlanGuid string v2PlanGuid string } migrateServicePlanFromV1ToV2Returns struct { result1 int result2 error } } func (fake *FakeServiceRepository) PurgeServiceOffering(offering models.ServiceOffering) error { fake.purgeServiceOfferingMutex.Lock() fake.purgeServiceOfferingArgsForCall = append(fake.purgeServiceOfferingArgsForCall, struct { offering models.ServiceOffering }{offering}) fake.purgeServiceOfferingMutex.Unlock() if fake.PurgeServiceOfferingStub != nil { return fake.PurgeServiceOfferingStub(offering) } else { return fake.purgeServiceOfferingReturns.result1 } }<|fim▁hole|> defer fake.purgeServiceOfferingMutex.RUnlock() return len(fake.purgeServiceOfferingArgsForCall) } func (fake *FakeServiceRepository) PurgeServiceOfferingArgsForCall(i int) models.ServiceOffering { fake.purgeServiceOfferingMutex.RLock() defer fake.purgeServiceOfferingMutex.RUnlock() return fake.purgeServiceOfferingArgsForCall[i].offering } func (fake *FakeServiceRepository) PurgeServiceOfferingReturns(result1 error) { fake.PurgeServiceOfferingStub = nil fake.purgeServiceOfferingReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) GetServiceOfferingByGuid(serviceGuid string) (offering models.ServiceOffering, apiErr error) { fake.getServiceOfferingByGuidMutex.Lock() fake.getServiceOfferingByGuidArgsForCall = append(fake.getServiceOfferingByGuidArgsForCall, struct { serviceGuid string }{serviceGuid}) fake.getServiceOfferingByGuidMutex.Unlock() if fake.GetServiceOfferingByGuidStub != nil { return fake.GetServiceOfferingByGuidStub(serviceGuid) } else { return fake.getServiceOfferingByGuidReturns.result1, fake.getServiceOfferingByGuidReturns.result2 } } func (fake *FakeServiceRepository) GetServiceOfferingByGuidCallCount() int { fake.getServiceOfferingByGuidMutex.RLock() defer fake.getServiceOfferingByGuidMutex.RUnlock() return len(fake.getServiceOfferingByGuidArgsForCall) } func (fake *FakeServiceRepository) GetServiceOfferingByGuidArgsForCall(i int) string { fake.getServiceOfferingByGuidMutex.RLock() defer fake.getServiceOfferingByGuidMutex.RUnlock() return fake.getServiceOfferingByGuidArgsForCall[i].serviceGuid } func (fake *FakeServiceRepository) GetServiceOfferingByGuidReturns(result1 models.ServiceOffering, result2 error) { fake.GetServiceOfferingByGuidStub = nil fake.getServiceOfferingByGuidReturns = struct { result1 models.ServiceOffering result2 error }{result1, result2} } func (fake *FakeServiceRepository) FindServiceOfferingsByLabel(name string) (offering models.ServiceOfferings, apiErr error) { fake.findServiceOfferingsByLabelMutex.Lock() fake.findServiceOfferingsByLabelArgsForCall = append(fake.findServiceOfferingsByLabelArgsForCall, struct { name string }{name}) fake.findServiceOfferingsByLabelMutex.Unlock() if fake.FindServiceOfferingsByLabelStub != nil { return fake.FindServiceOfferingsByLabelStub(name) } else { return fake.findServiceOfferingsByLabelReturns.result1, fake.findServiceOfferingsByLabelReturns.result2 } } func (fake *FakeServiceRepository) FindServiceOfferingsByLabelCallCount() int { fake.findServiceOfferingsByLabelMutex.RLock() defer fake.findServiceOfferingsByLabelMutex.RUnlock() return len(fake.findServiceOfferingsByLabelArgsForCall) } func (fake *FakeServiceRepository) FindServiceOfferingsByLabelArgsForCall(i int) string { fake.findServiceOfferingsByLabelMutex.RLock() defer fake.findServiceOfferingsByLabelMutex.RUnlock() return fake.findServiceOfferingsByLabelArgsForCall[i].name } func (fake *FakeServiceRepository) FindServiceOfferingsByLabelReturns(result1 models.ServiceOfferings, result2 error) { fake.FindServiceOfferingsByLabelStub = nil fake.findServiceOfferingsByLabelReturns = struct { result1 models.ServiceOfferings result2 error }{result1, result2} } func (fake *FakeServiceRepository) FindServiceOfferingByLabelAndProvider(name string, provider string) (offering models.ServiceOffering, apiErr error) { fake.findServiceOfferingByLabelAndProviderMutex.Lock() fake.findServiceOfferingByLabelAndProviderArgsForCall = append(fake.findServiceOfferingByLabelAndProviderArgsForCall, struct { name string provider string }{name, provider}) fake.findServiceOfferingByLabelAndProviderMutex.Unlock() if fake.FindServiceOfferingByLabelAndProviderStub != nil { return fake.FindServiceOfferingByLabelAndProviderStub(name, provider) } else { return fake.findServiceOfferingByLabelAndProviderReturns.result1, fake.findServiceOfferingByLabelAndProviderReturns.result2 } } func (fake *FakeServiceRepository) FindServiceOfferingByLabelAndProviderCallCount() int { fake.findServiceOfferingByLabelAndProviderMutex.RLock() defer fake.findServiceOfferingByLabelAndProviderMutex.RUnlock() return len(fake.findServiceOfferingByLabelAndProviderArgsForCall) } func (fake *FakeServiceRepository) FindServiceOfferingByLabelAndProviderArgsForCall(i int) (string, string) { fake.findServiceOfferingByLabelAndProviderMutex.RLock() defer fake.findServiceOfferingByLabelAndProviderMutex.RUnlock() return fake.findServiceOfferingByLabelAndProviderArgsForCall[i].name, fake.findServiceOfferingByLabelAndProviderArgsForCall[i].provider } func (fake *FakeServiceRepository) FindServiceOfferingByLabelAndProviderReturns(result1 models.ServiceOffering, result2 error) { fake.FindServiceOfferingByLabelAndProviderStub = nil fake.findServiceOfferingByLabelAndProviderReturns = struct { result1 models.ServiceOffering result2 error }{result1, result2} } func (fake *FakeServiceRepository) FindServiceOfferingsForSpaceByLabel(spaceGuid string, name string) (offering models.ServiceOfferings, apiErr error) { fake.findServiceOfferingsForSpaceByLabelMutex.Lock() fake.findServiceOfferingsForSpaceByLabelArgsForCall = append(fake.findServiceOfferingsForSpaceByLabelArgsForCall, struct { spaceGuid string name string }{spaceGuid, name}) fake.findServiceOfferingsForSpaceByLabelMutex.Unlock() if fake.FindServiceOfferingsForSpaceByLabelStub != nil { return fake.FindServiceOfferingsForSpaceByLabelStub(spaceGuid, name) } else { return fake.findServiceOfferingsForSpaceByLabelReturns.result1, fake.findServiceOfferingsForSpaceByLabelReturns.result2 } } func (fake *FakeServiceRepository) FindServiceOfferingsForSpaceByLabelCallCount() int { fake.findServiceOfferingsForSpaceByLabelMutex.RLock() defer fake.findServiceOfferingsForSpaceByLabelMutex.RUnlock() return len(fake.findServiceOfferingsForSpaceByLabelArgsForCall) } func (fake *FakeServiceRepository) FindServiceOfferingsForSpaceByLabelArgsForCall(i int) (string, string) { fake.findServiceOfferingsForSpaceByLabelMutex.RLock() defer fake.findServiceOfferingsForSpaceByLabelMutex.RUnlock() return fake.findServiceOfferingsForSpaceByLabelArgsForCall[i].spaceGuid, fake.findServiceOfferingsForSpaceByLabelArgsForCall[i].name } func (fake *FakeServiceRepository) FindServiceOfferingsForSpaceByLabelReturns(result1 models.ServiceOfferings, result2 error) { fake.FindServiceOfferingsForSpaceByLabelStub = nil fake.findServiceOfferingsForSpaceByLabelReturns = struct { result1 models.ServiceOfferings result2 error }{result1, result2} } func (fake *FakeServiceRepository) GetAllServiceOfferings() (offerings models.ServiceOfferings, apiErr error) { fake.getAllServiceOfferingsMutex.Lock() fake.getAllServiceOfferingsArgsForCall = append(fake.getAllServiceOfferingsArgsForCall, struct{}{}) fake.getAllServiceOfferingsMutex.Unlock() if fake.GetAllServiceOfferingsStub != nil { return fake.GetAllServiceOfferingsStub() } else { return fake.getAllServiceOfferingsReturns.result1, fake.getAllServiceOfferingsReturns.result2 } } func (fake *FakeServiceRepository) GetAllServiceOfferingsCallCount() int { fake.getAllServiceOfferingsMutex.RLock() defer fake.getAllServiceOfferingsMutex.RUnlock() return len(fake.getAllServiceOfferingsArgsForCall) } func (fake *FakeServiceRepository) GetAllServiceOfferingsReturns(result1 models.ServiceOfferings, result2 error) { fake.GetAllServiceOfferingsStub = nil fake.getAllServiceOfferingsReturns = struct { result1 models.ServiceOfferings result2 error }{result1, result2} } func (fake *FakeServiceRepository) GetServiceOfferingsForSpace(spaceGuid string) (offerings models.ServiceOfferings, apiErr error) { fake.getServiceOfferingsForSpaceMutex.Lock() fake.getServiceOfferingsForSpaceArgsForCall = append(fake.getServiceOfferingsForSpaceArgsForCall, struct { spaceGuid string }{spaceGuid}) fake.getServiceOfferingsForSpaceMutex.Unlock() if fake.GetServiceOfferingsForSpaceStub != nil { return fake.GetServiceOfferingsForSpaceStub(spaceGuid) } else { return fake.getServiceOfferingsForSpaceReturns.result1, fake.getServiceOfferingsForSpaceReturns.result2 } } func (fake *FakeServiceRepository) GetServiceOfferingsForSpaceCallCount() int { fake.getServiceOfferingsForSpaceMutex.RLock() defer fake.getServiceOfferingsForSpaceMutex.RUnlock() return len(fake.getServiceOfferingsForSpaceArgsForCall) } func (fake *FakeServiceRepository) GetServiceOfferingsForSpaceArgsForCall(i int) string { fake.getServiceOfferingsForSpaceMutex.RLock() defer fake.getServiceOfferingsForSpaceMutex.RUnlock() return fake.getServiceOfferingsForSpaceArgsForCall[i].spaceGuid } func (fake *FakeServiceRepository) GetServiceOfferingsForSpaceReturns(result1 models.ServiceOfferings, result2 error) { fake.GetServiceOfferingsForSpaceStub = nil fake.getServiceOfferingsForSpaceReturns = struct { result1 models.ServiceOfferings result2 error }{result1, result2} } func (fake *FakeServiceRepository) FindInstanceByName(name string) (instance models.ServiceInstance, apiErr error) { fake.findInstanceByNameMutex.Lock() fake.findInstanceByNameArgsForCall = append(fake.findInstanceByNameArgsForCall, struct { name string }{name}) fake.findInstanceByNameMutex.Unlock() if fake.FindInstanceByNameStub != nil { return fake.FindInstanceByNameStub(name) } else { return fake.findInstanceByNameReturns.result1, fake.findInstanceByNameReturns.result2 } } func (fake *FakeServiceRepository) FindInstanceByNameCallCount() int { fake.findInstanceByNameMutex.RLock() defer fake.findInstanceByNameMutex.RUnlock() return len(fake.findInstanceByNameArgsForCall) } func (fake *FakeServiceRepository) FindInstanceByNameArgsForCall(i int) string { fake.findInstanceByNameMutex.RLock() defer fake.findInstanceByNameMutex.RUnlock() return fake.findInstanceByNameArgsForCall[i].name } func (fake *FakeServiceRepository) FindInstanceByNameReturns(result1 models.ServiceInstance, result2 error) { fake.FindInstanceByNameStub = nil fake.findInstanceByNameReturns = struct { result1 models.ServiceInstance result2 error }{result1, result2} } func (fake *FakeServiceRepository) PurgeServiceInstance(instance models.ServiceInstance) error { fake.purgeServiceInstanceMutex.Lock() fake.purgeServiceInstanceArgsForCall = append(fake.purgeServiceInstanceArgsForCall, struct { instance models.ServiceInstance }{instance}) fake.purgeServiceInstanceMutex.Unlock() if fake.PurgeServiceInstanceStub != nil { return fake.PurgeServiceInstanceStub(instance) } else { return fake.purgeServiceInstanceReturns.result1 } } func (fake *FakeServiceRepository) PurgeServiceInstanceCallCount() int { fake.purgeServiceInstanceMutex.RLock() defer fake.purgeServiceInstanceMutex.RUnlock() return len(fake.purgeServiceInstanceArgsForCall) } func (fake *FakeServiceRepository) PurgeServiceInstanceArgsForCall(i int) models.ServiceInstance { fake.purgeServiceInstanceMutex.RLock() defer fake.purgeServiceInstanceMutex.RUnlock() return fake.purgeServiceInstanceArgsForCall[i].instance } func (fake *FakeServiceRepository) PurgeServiceInstanceReturns(result1 error) { fake.PurgeServiceInstanceStub = nil fake.purgeServiceInstanceReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) CreateServiceInstance(name string, planGuid string, params map[string]interface{}, tags []string) (apiErr error) { fake.createServiceInstanceMutex.Lock() fake.createServiceInstanceArgsForCall = append(fake.createServiceInstanceArgsForCall, struct { name string planGuid string params map[string]interface{} tags []string }{name, planGuid, params, tags}) fake.createServiceInstanceMutex.Unlock() if fake.CreateServiceInstanceStub != nil { return fake.CreateServiceInstanceStub(name, planGuid, params, tags) } else { return fake.createServiceInstanceReturns.result1 } } func (fake *FakeServiceRepository) CreateServiceInstanceCallCount() int { fake.createServiceInstanceMutex.RLock() defer fake.createServiceInstanceMutex.RUnlock() return len(fake.createServiceInstanceArgsForCall) } func (fake *FakeServiceRepository) CreateServiceInstanceArgsForCall(i int) (string, string, map[string]interface{}, []string) { fake.createServiceInstanceMutex.RLock() defer fake.createServiceInstanceMutex.RUnlock() return fake.createServiceInstanceArgsForCall[i].name, fake.createServiceInstanceArgsForCall[i].planGuid, fake.createServiceInstanceArgsForCall[i].params, fake.createServiceInstanceArgsForCall[i].tags } func (fake *FakeServiceRepository) CreateServiceInstanceReturns(result1 error) { fake.CreateServiceInstanceStub = nil fake.createServiceInstanceReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) UpdateServiceInstance(instanceGuid string, planGuid string, params map[string]interface{}, tags []string) (apiErr error) { fake.updateServiceInstanceMutex.Lock() fake.updateServiceInstanceArgsForCall = append(fake.updateServiceInstanceArgsForCall, struct { instanceGuid string planGuid string params map[string]interface{} tags []string }{instanceGuid, planGuid, params, tags}) fake.updateServiceInstanceMutex.Unlock() if fake.UpdateServiceInstanceStub != nil { return fake.UpdateServiceInstanceStub(instanceGuid, planGuid, params, tags) } else { return fake.updateServiceInstanceReturns.result1 } } func (fake *FakeServiceRepository) UpdateServiceInstanceCallCount() int { fake.updateServiceInstanceMutex.RLock() defer fake.updateServiceInstanceMutex.RUnlock() return len(fake.updateServiceInstanceArgsForCall) } func (fake *FakeServiceRepository) UpdateServiceInstanceArgsForCall(i int) (string, string, map[string]interface{}, []string) { fake.updateServiceInstanceMutex.RLock() defer fake.updateServiceInstanceMutex.RUnlock() return fake.updateServiceInstanceArgsForCall[i].instanceGuid, fake.updateServiceInstanceArgsForCall[i].planGuid, fake.updateServiceInstanceArgsForCall[i].params, fake.updateServiceInstanceArgsForCall[i].tags } func (fake *FakeServiceRepository) UpdateServiceInstanceReturns(result1 error) { fake.UpdateServiceInstanceStub = nil fake.updateServiceInstanceReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) RenameService(instance models.ServiceInstance, newName string) (apiErr error) { fake.renameServiceMutex.Lock() fake.renameServiceArgsForCall = append(fake.renameServiceArgsForCall, struct { instance models.ServiceInstance newName string }{instance, newName}) fake.renameServiceMutex.Unlock() if fake.RenameServiceStub != nil { return fake.RenameServiceStub(instance, newName) } else { return fake.renameServiceReturns.result1 } } func (fake *FakeServiceRepository) RenameServiceCallCount() int { fake.renameServiceMutex.RLock() defer fake.renameServiceMutex.RUnlock() return len(fake.renameServiceArgsForCall) } func (fake *FakeServiceRepository) RenameServiceArgsForCall(i int) (models.ServiceInstance, string) { fake.renameServiceMutex.RLock() defer fake.renameServiceMutex.RUnlock() return fake.renameServiceArgsForCall[i].instance, fake.renameServiceArgsForCall[i].newName } func (fake *FakeServiceRepository) RenameServiceReturns(result1 error) { fake.RenameServiceStub = nil fake.renameServiceReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) DeleteService(instance models.ServiceInstance) (apiErr error) { fake.deleteServiceMutex.Lock() fake.deleteServiceArgsForCall = append(fake.deleteServiceArgsForCall, struct { instance models.ServiceInstance }{instance}) fake.deleteServiceMutex.Unlock() if fake.DeleteServiceStub != nil { return fake.DeleteServiceStub(instance) } else { return fake.deleteServiceReturns.result1 } } func (fake *FakeServiceRepository) DeleteServiceCallCount() int { fake.deleteServiceMutex.RLock() defer fake.deleteServiceMutex.RUnlock() return len(fake.deleteServiceArgsForCall) } func (fake *FakeServiceRepository) DeleteServiceArgsForCall(i int) models.ServiceInstance { fake.deleteServiceMutex.RLock() defer fake.deleteServiceMutex.RUnlock() return fake.deleteServiceArgsForCall[i].instance } func (fake *FakeServiceRepository) DeleteServiceReturns(result1 error) { fake.DeleteServiceStub = nil fake.deleteServiceReturns = struct { result1 error }{result1} } func (fake *FakeServiceRepository) FindServicePlanByDescription(planDescription resources.ServicePlanDescription) (planGuid string, apiErr error) { fake.findServicePlanByDescriptionMutex.Lock() fake.findServicePlanByDescriptionArgsForCall = append(fake.findServicePlanByDescriptionArgsForCall, struct { planDescription resources.ServicePlanDescription }{planDescription}) fake.findServicePlanByDescriptionMutex.Unlock() if fake.FindServicePlanByDescriptionStub != nil { return fake.FindServicePlanByDescriptionStub(planDescription) } else { return fake.findServicePlanByDescriptionReturns.result1, fake.findServicePlanByDescriptionReturns.result2 } } func (fake *FakeServiceRepository) FindServicePlanByDescriptionCallCount() int { fake.findServicePlanByDescriptionMutex.RLock() defer fake.findServicePlanByDescriptionMutex.RUnlock() return len(fake.findServicePlanByDescriptionArgsForCall) } func (fake *FakeServiceRepository) FindServicePlanByDescriptionArgsForCall(i int) resources.ServicePlanDescription { fake.findServicePlanByDescriptionMutex.RLock() defer fake.findServicePlanByDescriptionMutex.RUnlock() return fake.findServicePlanByDescriptionArgsForCall[i].planDescription } func (fake *FakeServiceRepository) FindServicePlanByDescriptionReturns(result1 string, result2 error) { fake.FindServicePlanByDescriptionStub = nil fake.findServicePlanByDescriptionReturns = struct { result1 string result2 error }{result1, result2} } func (fake *FakeServiceRepository) ListServicesFromBroker(brokerGuid string) (services []models.ServiceOffering, err error) { fake.listServicesFromBrokerMutex.Lock() fake.listServicesFromBrokerArgsForCall = append(fake.listServicesFromBrokerArgsForCall, struct { brokerGuid string }{brokerGuid}) fake.listServicesFromBrokerMutex.Unlock() if fake.ListServicesFromBrokerStub != nil { return fake.ListServicesFromBrokerStub(brokerGuid) } else { return fake.listServicesFromBrokerReturns.result1, fake.listServicesFromBrokerReturns.result2 } } func (fake *FakeServiceRepository) ListServicesFromBrokerCallCount() int { fake.listServicesFromBrokerMutex.RLock() defer fake.listServicesFromBrokerMutex.RUnlock() return len(fake.listServicesFromBrokerArgsForCall) } func (fake *FakeServiceRepository) ListServicesFromBrokerArgsForCall(i int) string { fake.listServicesFromBrokerMutex.RLock() defer fake.listServicesFromBrokerMutex.RUnlock() return fake.listServicesFromBrokerArgsForCall[i].brokerGuid } func (fake *FakeServiceRepository) ListServicesFromBrokerReturns(result1 []models.ServiceOffering, result2 error) { fake.ListServicesFromBrokerStub = nil fake.listServicesFromBrokerReturns = struct { result1 []models.ServiceOffering result2 error }{result1, result2} } func (fake *FakeServiceRepository) ListServicesFromManyBrokers(brokerGuids []string) (services []models.ServiceOffering, err error) { fake.listServicesFromManyBrokersMutex.Lock() fake.listServicesFromManyBrokersArgsForCall = append(fake.listServicesFromManyBrokersArgsForCall, struct { brokerGuids []string }{brokerGuids}) fake.listServicesFromManyBrokersMutex.Unlock() if fake.ListServicesFromManyBrokersStub != nil { return fake.ListServicesFromManyBrokersStub(brokerGuids) } else { return fake.listServicesFromManyBrokersReturns.result1, fake.listServicesFromManyBrokersReturns.result2 } } func (fake *FakeServiceRepository) ListServicesFromManyBrokersCallCount() int { fake.listServicesFromManyBrokersMutex.RLock() defer fake.listServicesFromManyBrokersMutex.RUnlock() return len(fake.listServicesFromManyBrokersArgsForCall) } func (fake *FakeServiceRepository) ListServicesFromManyBrokersArgsForCall(i int) []string { fake.listServicesFromManyBrokersMutex.RLock() defer fake.listServicesFromManyBrokersMutex.RUnlock() return fake.listServicesFromManyBrokersArgsForCall[i].brokerGuids } func (fake *FakeServiceRepository) ListServicesFromManyBrokersReturns(result1 []models.ServiceOffering, result2 error) { fake.ListServicesFromManyBrokersStub = nil fake.listServicesFromManyBrokersReturns = struct { result1 []models.ServiceOffering result2 error }{result1, result2} } func (fake *FakeServiceRepository) GetServiceInstanceCountForServicePlan(v1PlanGuid string) (count int, apiErr error) { fake.getServiceInstanceCountForServicePlanMutex.Lock() fake.getServiceInstanceCountForServicePlanArgsForCall = append(fake.getServiceInstanceCountForServicePlanArgsForCall, struct { v1PlanGuid string }{v1PlanGuid}) fake.getServiceInstanceCountForServicePlanMutex.Unlock() if fake.GetServiceInstanceCountForServicePlanStub != nil { return fake.GetServiceInstanceCountForServicePlanStub(v1PlanGuid) } else { return fake.getServiceInstanceCountForServicePlanReturns.result1, fake.getServiceInstanceCountForServicePlanReturns.result2 } } func (fake *FakeServiceRepository) GetServiceInstanceCountForServicePlanCallCount() int { fake.getServiceInstanceCountForServicePlanMutex.RLock() defer fake.getServiceInstanceCountForServicePlanMutex.RUnlock() return len(fake.getServiceInstanceCountForServicePlanArgsForCall) } func (fake *FakeServiceRepository) GetServiceInstanceCountForServicePlanArgsForCall(i int) string { fake.getServiceInstanceCountForServicePlanMutex.RLock() defer fake.getServiceInstanceCountForServicePlanMutex.RUnlock() return fake.getServiceInstanceCountForServicePlanArgsForCall[i].v1PlanGuid } func (fake *FakeServiceRepository) GetServiceInstanceCountForServicePlanReturns(result1 int, result2 error) { fake.GetServiceInstanceCountForServicePlanStub = nil fake.getServiceInstanceCountForServicePlanReturns = struct { result1 int result2 error }{result1, result2} } func (fake *FakeServiceRepository) MigrateServicePlanFromV1ToV2(v1PlanGuid string, v2PlanGuid string) (changedCount int, apiErr error) { fake.migrateServicePlanFromV1ToV2Mutex.Lock() fake.migrateServicePlanFromV1ToV2ArgsForCall = append(fake.migrateServicePlanFromV1ToV2ArgsForCall, struct { v1PlanGuid string v2PlanGuid string }{v1PlanGuid, v2PlanGuid}) fake.migrateServicePlanFromV1ToV2Mutex.Unlock() if fake.MigrateServicePlanFromV1ToV2Stub != nil { return fake.MigrateServicePlanFromV1ToV2Stub(v1PlanGuid, v2PlanGuid) } else { return fake.migrateServicePlanFromV1ToV2Returns.result1, fake.migrateServicePlanFromV1ToV2Returns.result2 } } func (fake *FakeServiceRepository) MigrateServicePlanFromV1ToV2CallCount() int { fake.migrateServicePlanFromV1ToV2Mutex.RLock() defer fake.migrateServicePlanFromV1ToV2Mutex.RUnlock() return len(fake.migrateServicePlanFromV1ToV2ArgsForCall) } func (fake *FakeServiceRepository) MigrateServicePlanFromV1ToV2ArgsForCall(i int) (string, string) { fake.migrateServicePlanFromV1ToV2Mutex.RLock() defer fake.migrateServicePlanFromV1ToV2Mutex.RUnlock() return fake.migrateServicePlanFromV1ToV2ArgsForCall[i].v1PlanGuid, fake.migrateServicePlanFromV1ToV2ArgsForCall[i].v2PlanGuid } func (fake *FakeServiceRepository) MigrateServicePlanFromV1ToV2Returns(result1 int, result2 error) { fake.MigrateServicePlanFromV1ToV2Stub = nil fake.migrateServicePlanFromV1ToV2Returns = struct { result1 int result2 error }{result1, result2} } var _ api.ServiceRepository = new(FakeServiceRepository)<|fim▁end|>
func (fake *FakeServiceRepository) PurgeServiceOfferingCallCount() int { fake.purgeServiceOfferingMutex.RLock()
<|file_name|>treeadmin.js<|end_file_name|><|fim▁begin|>/* Suppress initial rendering of result list, but only if we can show it with JS later on */ document.write('<style type="text/css">#result_list { display: none }</style>'); treeadmin.jQuery(function($){ // recolor tree after expand/collapse $.extend($.fn.recolorRows = function() { $('tr:visible:even', this).removeClass('row2').addClass('row1'); $('tr:visible:odd', this).removeClass('row1').addClass('row2'); }); function isExpandedNode(id) { return treeadmin.collapsed_nodes.indexOf(id) == -1; } function markNodeAsExpanded(id) { // remove itemId from array of collapsed nodes var idx = treeadmin.collapsed_nodes.indexOf(id); if(idx >= 0) treeadmin.collapsed_nodes.splice(idx, 1); } function markNodeAsCollapsed(id) { if(isExpandedNode(id)) treeadmin.collapsed_nodes.push(id); } // toggle children function doToggle(id, show) { var children = treeadmin.tree_structure[id]; for (var i=0; i<children.length; ++i) { var childId = children[i]; if(show) { $('#item-' + childId).show(); // only reveal children if current node is not collapsed if(isExpandedNode(childId)) { doToggle(childId, show); } } else { $('#item-' + childId).hide(); // always recursively hide children doToggle(childId, show); } } } function rowLevel($row) { return parseInt($row.attr('rel').replace(/[^\d]/ig, '')); } /* * FeinCMS Drag-n-drop tree reordering. * Based upon code by bright4 for Radiant CMS, rewritten for * FeinCMS by Bjorn Post. * * September 2010 * */ $.extend($.fn.feinTree = function() { $('tr', this).each(function(i, el) { // adds 'children' class to all parents var pageId = extract_item_id($('.page_marker', el).attr('id')); $(el).attr('id', 'item-' + pageId); if (treeadmin.tree_structure[pageId].length) { $('.page_marker', el).addClass('children'); } // set 'level' on rel attribute var pixels = $('.page_marker', el).css('width').replace(/[^\d]/ig,""); var rel = Math.round(pixels/18); $(el).attr('rel', rel); }); $('div.drag_handle').bind('mousedown', function(event) { BEFORE = 0; AFTER = 1; CHILD = 2; CHILD_PAD = 20; var originalRow = $(event.target).closest('tr'); var rowHeight = originalRow.height(); var childEdge = $(event.target).offset().left + $(event.target).width(); var moveTo = new Object(); var expandObj = new Object(); $("body").addClass('dragging').disableSelection().bind('mousemove', function(event) { // attach dragged item to mouse var cloned = originalRow.html(); if($('#ghost').length == 0) { $('<div id="ghost"></div>').appendTo('body'); } $('#ghost').html(cloned).css({ 'opacity': .8, 'position': 'absolute', 'top': event.pageY, 'left': event.pageX-30, 'width': 600 }); // check on edge of screen if(event.pageY+100 > $(window).height()+$(window).scrollTop()) { $('html,body').stop().animate({scrollTop: $(window).scrollTop()+250 }, 500); } else if(event.pageY-50 < $(window).scrollTop()) { $('html,body').stop().animate({scrollTop: $(window).scrollTop()-250 }, 500); } // check if drag_line element already exists, else append<|fim▁hole|> } // loop trough all rows $("tr", originalRow.parent()).each(function(index, element) { var element = $(element), top = element.offset().top; // check if mouse is over a row if (event.pageY >= top && event.pageY < top + rowHeight) { var targetRow = null, targetLoc = null, elementLevel = rowLevel(element); if (event.pageY >= top && event.pageY < top + rowHeight / 3) { targetRow = element; targetLoc = BEFORE; } else if (event.pageY >= top + rowHeight / 3 && event.pageY < top + rowHeight * 2 / 3) { var next = element.next(); // there's no point in allowing adding children when there are some already // better move the items to the correct place right away if (!next.length || rowLevel(next) <= elementLevel) { targetRow = element; targetLoc = CHILD; } } else if (event.pageY >= top + rowHeight * 2 / 3 && event.pageY < top + rowHeight) { var next = element.next(); if (!next.length || rowLevel(next) <= elementLevel) { targetRow = element; targetLoc = AFTER; } } if(targetRow) { var padding = 37 + element.attr('rel') * CHILD_PAD + (targetLoc == CHILD ? CHILD_PAD : 0 ); $("#drag_line").css({ 'width': targetRow.width() - padding, 'left': targetRow.offset().left + padding, 'top': targetRow.offset().top + (targetLoc == AFTER || targetLoc == CHILD ? rowHeight: 0) -1 }); // Store the found row and options moveTo.hovering = element; moveTo.relativeTo = targetRow; moveTo.side = targetLoc; return true; } } }); }); $('body').keydown(function(event) { if (event.which == '27') { $("#drag_line").remove(); $("#ghost").remove(); $("body").removeClass('dragging').enableSelection().unbind('mousemove').unbind('mouseup'); event.preventDefault(); } }); $("body").bind('mouseup', function(event) { if(moveTo.relativeTo) { var cutItem = extract_item_id(originalRow.find('.page_marker').attr('id')); var pastedOn = extract_item_id(moveTo.relativeTo.find('.page_marker').attr('id')); // get out early if items are the same if(cutItem != pastedOn) { var isParent = (moveTo.relativeTo.next().attr('rel') > moveTo.relativeTo.attr('rel')); var position = ''; // determine position if(moveTo.side == CHILD && !isParent) { position = 'last-child'; } else if (moveTo.side == BEFORE) { position = 'left'; } else { position = 'right'; } // save $.post('.', { '__cmd': 'move_node', 'position': position, 'cut_item': cutItem, 'pasted_on': pastedOn }, function(data) { window.location.reload(); }); } else { $("#drag_line").remove(); $("#ghost").remove(); } $("body").removeClass('dragging').enableSelection().unbind('mousemove').unbind('mouseup'); } }); }); return this; }); /* Every time the user expands or collapses a part of the tree, we remember the current state of the tree so we can restore it on a reload. Note: We might use html5's session storage? */ function storeCollapsedNodes(nodes) { $.cookie('treeadmin_collapsed_nodes', "[" + nodes.join(",") + "]", { expires: 7 }); } function retrieveCollapsedNodes() { var n = $.cookie('treeadmin_collapsed_nodes'); if(n != null) { try { n = $.parseJSON(n); } catch(e) { n = null; } } return n; } function expandOrCollapseNode(item) { var show = true; if(!item.hasClass('children')) return; var itemId = extract_item_id(item.attr('id')); if(!isExpandedNode(itemId)) { item.removeClass('closed'); markNodeAsExpanded(itemId); } else { item.addClass('closed'); show = false; markNodeAsCollapsed(itemId); } storeCollapsedNodes(treeadmin.collapsed_nodes); doToggle(itemId, show); $('#result_list tbody').recolorRows(); } $.extend($.fn.feinTreeToggleItem = function() { $(this).click(function(event){ expandOrCollapseNode($(this)); if(event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } return false; }); return this; }); // bind the collapse all children event $.extend($.fn.bindCollapseTreeEvent = function() { $(this).click(function() { rlist = $("#result_list"); rlist.hide(); $('tbody tr', rlist).each(function(i, el) { var marker = $('.page_marker', el); if(marker.hasClass('children')) { var itemId = extract_item_id(marker.attr('id')); doToggle(itemId, false); marker.addClass('closed'); markNodeAsCollapsed(itemId); } }); storeCollapsedNodes(treeadmin.collapsed_nodes); rlist.show(); $('tbody', rlist).recolorRows(); }); return this; }); // bind the open all children event $.extend($.fn.bindOpenTreeEvent = function() { $(this).click(function() { rlist = $("#result_list"); rlist.hide(); $('tbody tr', rlist).each(function(i, el) { var marker = $('span.page_marker', el); if(marker.hasClass('children')) { var itemId = extract_item_id($('span.page_marker', el).attr('id')); doToggle(itemId, true); marker.removeClass('closed'); markNodeAsExpanded(itemId); } }); storeCollapsedNodes([]); rlist.show(); $('tbody', rlist).recolorRows(); }); return this; }); var changelist_tab = function(elem, event, direction) { event.preventDefault(); elem = $(elem); var ne = (direction > 0) ? elem.nextAll(':visible:first') : elem.prevAll(':visible:first'); if(ne) { elem.attr('tabindex', -1); ne.attr('tabindex', '0'); ne.focus(); } }; function keyboardNavigationHandler(event) { // console.log('keydown', this, event.keyCode); switch(event.keyCode) { case 40: // down changelist_tab(this, event, 1); break; case 38: // up changelist_tab(this, event, -1); break; case 37: // left case 39: // right expandOrCollapseNode($(this).find('.page_marker')); break; case 13: // return where_to = extract_item_id($('span', this).attr('id')); document.location = document.location.pathname + where_to + '/' break; default: break; }; } // fire! rlist = $("#result_list"); if($('tbody tr', rlist).length > 1) { rlist.hide(); $('tbody', rlist).feinTree(); $('span.page_marker', rlist).feinTreeToggleItem(); $('#collapse_entire_tree').bindCollapseTreeEvent(); $('#open_entire_tree').bindOpenTreeEvent(); // Disable things user cannot do anyway (object level permissions) non_editable_fields = $('.tree-item-not-editable', rlist).parents('tr'); non_editable_fields.addClass('non-editable'); $('input:checkbox', non_editable_fields).attr('disabled', 'disabled'); $('a:first', non_editable_fields).click(function(e){e.preventDefault()}); $('.drag_handle', non_editable_fields).removeClass('drag_handle'); /* Enable focussing, put focus on first result, add handler for keyboard navigation */ $('tr', rlist).attr('tabindex', -1); $('tbody tr:first', rlist).attr('tabindex', 0).focus(); $('tr', rlist).keydown(keyboardNavigationHandler); treeadmin.collapsed_nodes = []; var storedNodes = retrieveCollapsedNodes(); if(storedNodes == null) { $('#collapse_entire_tree').click(); } else { for(var i=0; i<storedNodes.length; i++) { $('#page_marker-' + storedNodes[i]).click(); } } } rlist.show(); $('tbody', rlist).recolorRows(); });<|fim▁end|>
if($("#drag_line").length < 1) { $("body").append('<div id="drag_line" style="position:absolute">line<div></div></div>');
<|file_name|>utils.py<|end_file_name|><|fim▁begin|>#-*- coding:utf8 -*- def crawl_folder(folder): import os os_objects = [] seen = set([folder]) for os_object_name in os.listdir(folder): full_path = os.path.normpath(os.path.join(folder, os_object_name)) if not full_path in seen: os_objects.append((full_path, os_object_name,)) seen.add(full_path) return os_objects<|fim▁hole|> def __init__(self, name, log_stream, verbosity, interval=10): self.name = name self.verbosity = verbosity self.log_stream = log_stream self.interval = interval self.value = 0 def add(self): from datetime import datetime self.value += 1 if self.verbosity and self.value % self.interval == 0: self.log_stream.write("Logger: " + self.name + ", value: " + str(self.value) + ", time: " + str(datetime.now())+ "\n") self.log_stream.flush() def log_state(self): from datetime import datetime self.log_stream.write("Logger: " + self.name + ", value: " + str(self.value) + ", time: " + str(datetime.now())+ "\n") self.log_stream.flush()<|fim▁end|>
class TCustomCounter:
<|file_name|>test_packet.py<|end_file_name|><|fim▁begin|>import struct import numpy import io import pickle import pyctrl.packet as packet def testA(): # test A assert packet.pack('A','C') == b'AC' assert packet.pack('A','B') == b'AB' assert packet.pack('A','C') != b'AB' assert packet.unpack_stream(io.BytesIO(b'AC')) == ('A', 'C') assert packet.unpack_stream(io.BytesIO(b'AB')) == ('A', 'B') assert packet.unpack_stream(io.BytesIO(b'AB')) != ('A', 'C') def testC(): # test C assert packet.pack('C','C') == b'CC' assert packet.pack('C','B') == b'CB' assert packet.pack('C','C') != b'CB' assert packet.unpack_stream(io.BytesIO(b'CC')) == ('C', 'C') assert packet.unpack_stream(io.BytesIO(b'CB')) == ('C', 'B') assert packet.unpack_stream(io.BytesIO(b'CB')) != ('C', 'C') def testS(): # test S assert packet.pack('S','abc') == struct.pack('<cI3s', b'S', 3, b'abc') assert packet.pack('S','abcd') != struct.pack('<cI3s', b'S', 3, b'abc') assert packet.unpack_stream( io.BytesIO(struct.pack('<cI3s', b'S', 3, b'abc'))) == ('S', 'abc') assert packet.unpack_stream( io.BytesIO(struct.pack('<cI3s', b'S', 3, b'abc'))) != ('S', 'abcd') def testIFD(): # test I assert packet.pack('I',3) == struct.pack('<ci', b'I', 3) assert packet.pack('I',3) != struct.pack('<ci', b'I', 4) assert packet.unpack_stream( io.BytesIO(struct.pack('<ci', b'I', 3))) == ('I', 3) assert packet.unpack_stream( io.BytesIO(struct.pack('<ci', b'I', 4))) != ('I', 3) # test F assert packet.pack('F',3.3) == struct.pack('<cf', b'F', 3.3) assert packet.pack('F',3.3) != struct.pack('<cf', b'F', 4.3) assert packet.unpack_stream( io.BytesIO(struct.pack('<cf', b'F', numpy.float32(3.3)))) == ('F', numpy.float32(3.3)) assert packet.unpack_stream( io.BytesIO(struct.pack('<cf', b'F', 4.3))) != ('F', 3.3) # test D assert packet.pack('D',3.3) == struct.pack('<cd', b'D', 3.3) assert packet.pack('D',3.3) != struct.pack('<cd', b'D', 4.3) assert packet.unpack_stream( io.BytesIO(struct.pack('<cd', b'D', 3.3))) == ('D', 3.3) assert packet.unpack_stream( io.BytesIO(struct.pack('<cd', b'D', 4.3))) != ('D', 3.3) def testV(): # test VI vector = numpy.array((1,2,3), int) assert packet.pack('V',vector) == struct.pack('<ccIiii', b'V', b'I', 3, 1, 2, 3) (type, rvector) = packet.unpack_stream( io.BytesIO(struct.pack('<ccIiii', b'V', b'I', 3, 1, 2, 3))) assert type == 'V' assert numpy.all(rvector == vector) vector = numpy.array((1,-2,3), int) assert packet.pack('V',vector) == struct.pack('<ccIiii', b'V', b'I', 3, 1, -2, 3) (type, rvector) = packet.unpack_stream( io.BytesIO(struct.pack('<ccIiii', b'V', b'I', 3, 1, -2, 3))) assert type == 'V' assert numpy.all(rvector == vector) # test VF vector = numpy.array((1.3,-2,3), numpy.float32) assert packet.pack('V',vector) == struct.pack('<ccIfff', b'V', b'F', 3, 1.3, -2, 3) (type, rvector) = packet.unpack_stream( io.BytesIO(struct.pack('<ccIfff', b'V', b'F', 3, 1.3, -2, 3))) assert type == 'V' assert numpy.all(rvector == vector) # test VD vector = numpy.array((1.3,-2,3), float) assert packet.pack('V',vector) == struct.pack('<ccIddd', b'V', b'D', 3, 1.3, -2, 3) (type, rvector) = packet.unpack_stream( io.BytesIO(struct.pack('<ccIddd', b'V', b'D', 3, 1.3, -2, 3))) assert type == 'V' assert numpy.all(rvector == vector) def testM(): # test MI vector = numpy.array(((1,2,3), (3,4,5)), int)<|fim▁hole|> (type, rvector) = packet.unpack_stream( io.BytesIO(struct.pack('<cIccIiiiiii', b'M', 2, b'V', b'I', 6, 1, 2, 3, 3, 4, 5))) assert type == 'M' assert numpy.all(rvector == vector) vector = numpy.array(((1,-2,3), (3,4,-5)), int) assert packet.pack('M',vector) == struct.pack('<cIccIiiiiii', b'M', 2, b'V', b'I', 6, 1, -2, 3, 3, 4, -5) (type, rvector) = packet.unpack_stream( io.BytesIO(struct.pack('<cIccIiiiiii', b'M', 2, b'V', b'I', 6, 1, -2, 3, 3, 4, -5))) assert type == 'M' assert numpy.all(rvector == vector) # test MF vector = numpy.array(((1.3,-2,3), (0,-1,2.5)), numpy.float32) assert packet.pack('M',vector) == struct.pack('<cIccIffffff', b'M', 2, b'V', b'F', 6, 1.3, -2, 3, 0, -1, 2.5) (type, rvector) = packet.unpack_stream( io.BytesIO(struct.pack('<cIccIffffff', b'M', 2, b'V', b'F', 6, 1.3, -2, 3, 0, -1, 2.5))) assert type == 'M' assert numpy.all(rvector == vector) # test MD vector = numpy.array(((1.3,-2,3), (0,-1,2.5)), numpy.float) assert packet.pack('M',vector) == struct.pack('<cIccIdddddd', b'M', 2, b'V', b'D', 6, 1.3, -2, 3, 0, -1, 2.5) (type, rvector) = packet.unpack_stream( io.BytesIO(struct.pack('<cIccIdddddd', b'M', 2, b'V', b'D', 6, 1.3, -2, 3, 0, -1, 2.5))) assert type == 'M' assert numpy.all(rvector == vector) def testP(): vector = numpy.array(((1.3,-2,3), (0,-1,2.5)), numpy.float) string = packet.pack('P', vector) (type, rvector) = packet.unpack_stream(io.BytesIO(string)) assert type == 'P' assert numpy.all(rvector == vector) def testKR(): args = { 'a': 1, 'b': 2 } string = packet.pack('K', args) (type, rargs) = packet.unpack_stream(io.BytesIO(string)) assert type == 'K' assert (args == rargs) args = ('a', 1, 'b', 2) string = packet.pack('R', args) (type, rargs) = packet.unpack_stream(io.BytesIO(string)) assert type == 'R' assert (args == rargs) if __name__ == "__main__": testA() testC() testS() testIFD() testV() testM() testP() testKR()<|fim▁end|>
assert packet.pack('M',vector) == struct.pack('<cIccIiiiiii', b'M', 2, b'V', b'I', 6, 1, 2, 3, 3, 4, 5)
<|file_name|>schemas.py<|end_file_name|><|fim▁begin|>from app.models import EMAIL_TYPES from app.schema_validation.definitions import uuid, datetime, date def email_types(): pattern = '|'.join(EMAIL_TYPES) return { "type": "string", "pattern": pattern, "validationMessage": "is not an email type", } post_create_email_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for creating email", "type": "object", "properties": { "event_id": uuid, "details": {"type": ["string", "null"]}, "extra_txt": {"type": ["string", "null"]}, "replace_all": {"type": "boolean"}, "email_type": email_types(), "send_starts_at": date, "expires": date }, "required": ["email_type"] } post_preview_email_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for preview email", "type": "object", "properties": { "event_id": uuid, "details": {"type": ["string", "null"]}, "extra_txt": {"type": ["string", "null"]}, "replace_all": {"type": "boolean"}, "email_type": email_types() }, "required": ["email_type"] } post_update_email_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for updating email", "type": "object", "properties": { "event_id": uuid, "details": {"type": ["string", "null"]}, "extra_txt": {"type": ["string", "null"]}, "replace_all": {"type": "boolean"}, "email_type": email_types(), "send_starts_at": date, "expires": date, "reject_reason": {"type": ["string", "null"]}, }, } post_import_email_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for importing emails", "type": "object", "properties": { "id": {"format": "number", "type": "string"}, "eventdetails": {"type": "string"}, "extratxt": {"type": "string"}, "replaceAll": {"type": "string"}, "timestamp": datetime }, "required": ["id", "timestamp"] } post_import_emails_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for importing emails", "type": "array", "items": { "type": "object", "$ref": "#/definitions/email" }, "definitions": { "email": post_import_email_schema } } post_import_email_member_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for importing emails", "type": "object", "properties": { "id": {"format": "number", "type": "string"}, "mailinglistid": {"format": "number", "type": "string"}, "timestamp": datetime }, "required": ["id", "mailinglistid", "timestamp"] } post_import_email_members_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for importing emails members",<|fim▁hole|> "items": { "type": "object", "$ref": "#/definitions/email_member" }, "definitions": { "email_member": post_import_email_member_schema } } post_send_message_schema = { "$schema": "http://json-schema.org/draft-04/schema#", "description": "POST schema for send message", "type": "object", "properties": { "name": {"type": "string"}, "email": {"format": "email", "type": "string"}, "reason": {"type": "string"}, "message": {"type": "string"} }, "required": ["name", "email", "reason", "message"] }<|fim▁end|>
"type": "array",
<|file_name|>juce_Viewport.cpp<|end_file_name|><|fim▁begin|>/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2013 - Raw Material Software Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ Viewport::Viewport (const String& name) : Component (name), scrollBarThickness (0), singleStepX (16), singleStepY (16), showHScrollbar (true), showVScrollbar (true), deleteContent (true), allowScrollingWithoutScrollbarV (false), allowScrollingWithoutScrollbarH (false), verticalScrollBar (true), horizontalScrollBar (false) { // content holder is used to clip the contents so they don't overlap the scrollbars addAndMakeVisible (contentHolder); contentHolder.setInterceptsMouseClicks (false, true); addChildComponent (verticalScrollBar); addChildComponent (horizontalScrollBar); verticalScrollBar.addListener (this); horizontalScrollBar.addListener (this); setInterceptsMouseClicks (false, true); setWantsKeyboardFocus (true); } Viewport::~Viewport() { deleteContentComp(); } //============================================================================== void Viewport::visibleAreaChanged (const Rectangle<int>&) {} void Viewport::viewedComponentChanged (Component*) {} //============================================================================== void Viewport::deleteContentComp() { if (contentComp != nullptr) contentComp->removeComponentListener (this); if (deleteContent) { // This sets the content comp to a null pointer before deleting the old one, in case // anything tries to use the old one while it's in mid-deletion.. ScopedPointer<Component> oldCompDeleter (contentComp); } else { contentComp = nullptr; } } void Viewport::setViewedComponent (Component* const newViewedComponent, const bool deleteComponentWhenNoLongerNeeded) { if (contentComp.get() != newViewedComponent) { deleteContentComp(); contentComp = newViewedComponent; deleteContent = deleteComponentWhenNoLongerNeeded; if (contentComp != nullptr) { contentHolder.addAndMakeVisible (contentComp); setViewPosition (Point<int>()); contentComp->addComponentListener (this); } viewedComponentChanged (contentComp); updateVisibleArea(); } } int Viewport::getMaximumVisibleWidth() const { return contentHolder.getWidth(); } int Viewport::getMaximumVisibleHeight() const { return contentHolder.getHeight(); } Point<int> Viewport::viewportPosToCompPos (Point<int> pos) const { jassert (contentComp != nullptr); return Point<int> (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -(pos.x))), jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -(pos.y)))); } void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset) { setViewPosition (Point<int> (xPixelsOffset, yPixelsOffset)); } void Viewport::setViewPosition (Point<int> newPosition) { if (contentComp != nullptr) contentComp->setTopLeftPosition (viewportPosToCompPos (newPosition)); } void Viewport::setViewPositionProportionately (const double x, const double y) { if (contentComp != nullptr) setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))), jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight())))); } bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed) { if (contentComp != nullptr) { int dx = 0, dy = 0; if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth()) { if (mouseX < activeBorderThickness) dx = activeBorderThickness - mouseX; else if (mouseX >= contentHolder.getWidth() - activeBorderThickness) dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX; <|fim▁hole|> dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight()); else dx = jmin (dx, maximumSpeed, -contentComp->getX()); } if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight()) { if (mouseY < activeBorderThickness) dy = activeBorderThickness - mouseY; else if (mouseY >= contentHolder.getHeight() - activeBorderThickness) dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY; if (dy < 0) dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom()); else dy = jmin (dy, maximumSpeed, -contentComp->getY()); } if (dx != 0 || dy != 0) { contentComp->setTopLeftPosition (contentComp->getX() + dx, contentComp->getY() + dy); return true; } } return false; } void Viewport::componentMovedOrResized (Component&, bool, bool) { updateVisibleArea(); } void Viewport::resized() { updateVisibleArea(); } //============================================================================== void Viewport::updateVisibleArea() { const int scrollbarWidth = getScrollBarThickness(); const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth; const bool canShowHBar = showHScrollbar && canShowAnyBars; const bool canShowVBar = showVScrollbar && canShowAnyBars; bool hBarVisible = false, vBarVisible = false; Rectangle<int> contentArea; for (int i = 3; --i >= 0;) { hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides(); vBarVisible = canShowVBar && ! verticalScrollBar.autoHides(); contentArea = getLocalBounds(); if (contentComp != nullptr && ! contentArea.contains (contentComp->getBounds())) { hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth()); vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight()); if (vBarVisible) contentArea.setWidth (getWidth() - scrollbarWidth); if (hBarVisible) contentArea.setHeight (getHeight() - scrollbarWidth); if (! contentArea.contains (contentComp->getBounds())) { hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth()); vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight()); } } if (vBarVisible) contentArea.setWidth (getWidth() - scrollbarWidth); if (hBarVisible) contentArea.setHeight (getHeight() - scrollbarWidth); if (contentComp == nullptr) { contentHolder.setBounds (contentArea); break; } const Rectangle<int> oldContentBounds (contentComp->getBounds()); contentHolder.setBounds (contentArea); // If the content has changed its size, that might affect our scrollbars, so go round again and re-caclulate.. if (oldContentBounds == contentComp->getBounds()) break; } Rectangle<int> contentBounds; if (contentComp != nullptr) contentBounds = contentHolder.getLocalArea (contentComp, contentComp->getLocalBounds()); Point<int> visibleOrigin (-contentBounds.getPosition()); horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth); horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth()); horizontalScrollBar.setCurrentRange (visibleOrigin.x, contentArea.getWidth()); horizontalScrollBar.setSingleStepSize (singleStepX); horizontalScrollBar.cancelPendingUpdate(); if (canShowHBar && ! hBarVisible) visibleOrigin.setX (0); verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight()); verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight()); verticalScrollBar.setCurrentRange (visibleOrigin.y, contentArea.getHeight()); verticalScrollBar.setSingleStepSize (singleStepY); verticalScrollBar.cancelPendingUpdate(); if (canShowVBar && ! vBarVisible) visibleOrigin.setY (0); // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers. horizontalScrollBar.setVisible (hBarVisible); verticalScrollBar.setVisible (vBarVisible); if (contentComp != nullptr) { const Point<int> newContentCompPos (viewportPosToCompPos (visibleOrigin)); if (contentComp->getBounds().getPosition() != newContentCompPos) { contentComp->setTopLeftPosition (newContentCompPos); // (this will re-entrantly call updateVisibleArea again) return; } } const Rectangle<int> visibleArea (visibleOrigin.x, visibleOrigin.y, jmin (contentBounds.getWidth() - visibleOrigin.x, contentArea.getWidth()), jmin (contentBounds.getHeight() - visibleOrigin.y, contentArea.getHeight())); if (lastVisibleArea != visibleArea) { lastVisibleArea = visibleArea; visibleAreaChanged (visibleArea); } horizontalScrollBar.handleUpdateNowIfNeeded(); verticalScrollBar.handleUpdateNowIfNeeded(); } //============================================================================== void Viewport::setSingleStepSizes (const int stepX, const int stepY) { if (singleStepX != stepX || singleStepY != stepY) { singleStepX = stepX; singleStepY = stepY; updateVisibleArea(); } } void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded, const bool showHorizontalScrollbarIfNeeded, const bool allowVerticalScrollingWithoutScrollbar, const bool allowHorizontalScrollingWithoutScrollbar) { allowScrollingWithoutScrollbarV = allowVerticalScrollingWithoutScrollbar; allowScrollingWithoutScrollbarH = allowHorizontalScrollingWithoutScrollbar; if (showVScrollbar != showVerticalScrollbarIfNeeded || showHScrollbar != showHorizontalScrollbarIfNeeded) { showVScrollbar = showVerticalScrollbarIfNeeded; showHScrollbar = showHorizontalScrollbarIfNeeded; updateVisibleArea(); } } void Viewport::setScrollBarThickness (const int thickness) { if (scrollBarThickness != thickness) { scrollBarThickness = thickness; updateVisibleArea(); } } int Viewport::getScrollBarThickness() const { return scrollBarThickness > 0 ? scrollBarThickness : getLookAndFeel().getDefaultScrollbarWidth(); } void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart) { const int newRangeStartInt = roundToInt (newRangeStart); if (scrollBarThatHasMoved == &horizontalScrollBar) { setViewPosition (newRangeStartInt, getViewPositionY()); } else if (scrollBarThatHasMoved == &verticalScrollBar) { setViewPosition (getViewPositionX(), newRangeStartInt); } } void Viewport::mouseWheelMove (const MouseEvent& e, const MouseWheelDetails& wheel) { if (! useMouseWheelMoveIfNeeded (e, wheel)) Component::mouseWheelMove (e, wheel); } static int rescaleMouseWheelDistance (float distance, int singleStepSize) noexcept { if (distance == 0) return 0; distance *= 14.0f * singleStepSize; return roundToInt (distance < 0 ? jmin (distance, -1.0f) : jmax (distance, 1.0f)); } bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, const MouseWheelDetails& wheel) { if (! (e.mods.isAltDown() || e.mods.isCtrlDown() || e.mods.isCommandDown())) { const bool canScrollVert = (allowScrollingWithoutScrollbarV || verticalScrollBar.isVisible()); const bool canScrollHorz = (allowScrollingWithoutScrollbarH || horizontalScrollBar.isVisible()); if (canScrollHorz || canScrollVert) { const int deltaX = rescaleMouseWheelDistance (wheel.deltaX, singleStepX); const int deltaY = rescaleMouseWheelDistance (wheel.deltaY, singleStepY); Point<int> pos (getViewPosition()); if (deltaX != 0 && deltaY != 0 && canScrollHorz && canScrollVert) { pos.x -= deltaX; pos.y -= deltaY; } else if (canScrollHorz && (deltaX != 0 || e.mods.isShiftDown() || ! canScrollVert)) { pos.x -= deltaX != 0 ? deltaX : deltaY; } else if (canScrollVert && deltaY != 0) { pos.y -= deltaY; } if (pos != getViewPosition()) { setViewPosition (pos); return true; } } } return false; } static bool isUpDownKeyPress (const KeyPress& key) { return key == KeyPress::upKey || key == KeyPress::downKey || key == KeyPress::pageUpKey || key == KeyPress::pageDownKey || key == KeyPress::homeKey || key == KeyPress::endKey; } static bool isLeftRightKeyPress (const KeyPress& key) { return key == KeyPress::leftKey || key == KeyPress::rightKey; } bool Viewport::keyPressed (const KeyPress& key) { const bool isUpDownKey = isUpDownKeyPress (key); if (verticalScrollBar.isVisible() && isUpDownKey) return verticalScrollBar.keyPressed (key); const bool isLeftRightKey = isLeftRightKeyPress (key); if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey)) return horizontalScrollBar.keyPressed (key); return false; } bool Viewport::respondsToKey (const KeyPress& key) { return isUpDownKeyPress (key) || isLeftRightKeyPress (key); }<|fim▁end|>
if (dx < 0)
<|file_name|>l476xx--xgen_syscfg.go<|end_file_name|><|fim▁begin|>// +build l476xx package syscfg // DO NOT EDIT THIS FILE. GENERATED BY xgen. import ( "bits" "mmio" "unsafe" "stm32/o/l476xx/mmap" ) type SYSCFG_Periph struct { MEMRMP RMEMRMP CFGR1 RCFGR1 EXTICR [4]REXTICR SCSR RSCSR CFGR2 RCFGR2 SWPR RSWPR SKR RSKR } func (p *SYSCFG_Periph) BaseAddr() uintptr { return uintptr(unsafe.Pointer(p)) } //emgo:const var SYSCFG = (*SYSCFG_Periph)(unsafe.Pointer(uintptr(mmap.SYSCFG_BASE))) type MEMRMP uint32 func (b MEMRMP) Field(mask MEMRMP) int { return bits.Field32(uint32(b), uint32(mask)) } func (mask MEMRMP) J(v int) MEMRMP { return MEMRMP(bits.MakeField32(v, uint32(mask))) } <|fim▁hole|>func (r *RMEMRMP) Bits(mask MEMRMP) MEMRMP { return MEMRMP(r.U32.Bits(uint32(mask))) } func (r *RMEMRMP) StoreBits(mask, b MEMRMP) { r.U32.StoreBits(uint32(mask), uint32(b)) } func (r *RMEMRMP) SetBits(mask MEMRMP) { r.U32.SetBits(uint32(mask)) } func (r *RMEMRMP) ClearBits(mask MEMRMP) { r.U32.ClearBits(uint32(mask)) } func (r *RMEMRMP) Load() MEMRMP { return MEMRMP(r.U32.Load()) } func (r *RMEMRMP) Store(b MEMRMP) { r.U32.Store(uint32(b)) } func (r *RMEMRMP) AtomicStoreBits(mask, b MEMRMP) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) } func (r *RMEMRMP) AtomicSetBits(mask MEMRMP) { r.U32.AtomicSetBits(uint32(mask)) } func (r *RMEMRMP) AtomicClearBits(mask MEMRMP) { r.U32.AtomicClearBits(uint32(mask)) } type RMMEMRMP struct{ mmio.UM32 } func (rm RMMEMRMP) Load() MEMRMP { return MEMRMP(rm.UM32.Load()) } func (rm RMMEMRMP) Store(b MEMRMP) { rm.UM32.Store(uint32(b)) } func (p *SYSCFG_Periph) MEM_MODE() RMMEMRMP { return RMMEMRMP{mmio.UM32{&p.MEMRMP.U32, uint32(MEM_MODE)}} } func (p *SYSCFG_Periph) FB_MODE() RMMEMRMP { return RMMEMRMP{mmio.UM32{&p.MEMRMP.U32, uint32(FB_MODE)}} } type CFGR1 uint32 func (b CFGR1) Field(mask CFGR1) int { return bits.Field32(uint32(b), uint32(mask)) } func (mask CFGR1) J(v int) CFGR1 { return CFGR1(bits.MakeField32(v, uint32(mask))) } type RCFGR1 struct{ mmio.U32 } func (r *RCFGR1) Bits(mask CFGR1) CFGR1 { return CFGR1(r.U32.Bits(uint32(mask))) } func (r *RCFGR1) StoreBits(mask, b CFGR1) { r.U32.StoreBits(uint32(mask), uint32(b)) } func (r *RCFGR1) SetBits(mask CFGR1) { r.U32.SetBits(uint32(mask)) } func (r *RCFGR1) ClearBits(mask CFGR1) { r.U32.ClearBits(uint32(mask)) } func (r *RCFGR1) Load() CFGR1 { return CFGR1(r.U32.Load()) } func (r *RCFGR1) Store(b CFGR1) { r.U32.Store(uint32(b)) } func (r *RCFGR1) AtomicStoreBits(mask, b CFGR1) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) } func (r *RCFGR1) AtomicSetBits(mask CFGR1) { r.U32.AtomicSetBits(uint32(mask)) } func (r *RCFGR1) AtomicClearBits(mask CFGR1) { r.U32.AtomicClearBits(uint32(mask)) } type RMCFGR1 struct{ mmio.UM32 } func (rm RMCFGR1) Load() CFGR1 { return CFGR1(rm.UM32.Load()) } func (rm RMCFGR1) Store(b CFGR1) { rm.UM32.Store(uint32(b)) } func (p *SYSCFG_Periph) FWDIS() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(FWDIS)}} } func (p *SYSCFG_Periph) BOOSTEN() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(BOOSTEN)}} } func (p *SYSCFG_Periph) I2C_PB6_FMP() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(I2C_PB6_FMP)}} } func (p *SYSCFG_Periph) I2C_PB7_FMP() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(I2C_PB7_FMP)}} } func (p *SYSCFG_Periph) I2C_PB8_FMP() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(I2C_PB8_FMP)}} } func (p *SYSCFG_Periph) I2C_PB9_FMP() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(I2C_PB9_FMP)}} } func (p *SYSCFG_Periph) I2C1_FMP() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(I2C1_FMP)}} } func (p *SYSCFG_Periph) I2C2_FMP() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(I2C2_FMP)}} } func (p *SYSCFG_Periph) I2C3_FMP() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(I2C3_FMP)}} } func (p *SYSCFG_Periph) FPU_IE_0() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(FPU_IE_0)}} } func (p *SYSCFG_Periph) FPU_IE_1() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(FPU_IE_1)}} } func (p *SYSCFG_Periph) FPU_IE_2() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(FPU_IE_2)}} } func (p *SYSCFG_Periph) FPU_IE_3() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(FPU_IE_3)}} } func (p *SYSCFG_Periph) FPU_IE_4() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(FPU_IE_4)}} } func (p *SYSCFG_Periph) FPU_IE_5() RMCFGR1 { return RMCFGR1{mmio.UM32{&p.CFGR1.U32, uint32(FPU_IE_5)}} } type EXTICR uint32 func (b EXTICR) Field(mask EXTICR) int { return bits.Field32(uint32(b), uint32(mask)) } func (mask EXTICR) J(v int) EXTICR { return EXTICR(bits.MakeField32(v, uint32(mask))) } type REXTICR struct{ mmio.U32 } func (r *REXTICR) Bits(mask EXTICR) EXTICR { return EXTICR(r.U32.Bits(uint32(mask))) } func (r *REXTICR) StoreBits(mask, b EXTICR) { r.U32.StoreBits(uint32(mask), uint32(b)) } func (r *REXTICR) SetBits(mask EXTICR) { r.U32.SetBits(uint32(mask)) } func (r *REXTICR) ClearBits(mask EXTICR) { r.U32.ClearBits(uint32(mask)) } func (r *REXTICR) Load() EXTICR { return EXTICR(r.U32.Load()) } func (r *REXTICR) Store(b EXTICR) { r.U32.Store(uint32(b)) } func (r *REXTICR) AtomicStoreBits(mask, b EXTICR) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) } func (r *REXTICR) AtomicSetBits(mask EXTICR) { r.U32.AtomicSetBits(uint32(mask)) } func (r *REXTICR) AtomicClearBits(mask EXTICR) { r.U32.AtomicClearBits(uint32(mask)) } type RMEXTICR struct{ mmio.UM32 } func (rm RMEXTICR) Load() EXTICR { return EXTICR(rm.UM32.Load()) } func (rm RMEXTICR) Store(b EXTICR) { rm.UM32.Store(uint32(b)) } func (p *SYSCFG_Periph) EXTI0(n int) RMEXTICR { return RMEXTICR{mmio.UM32{&p.EXTICR[n].U32, uint32(EXTI0)}} } func (p *SYSCFG_Periph) EXTI1(n int) RMEXTICR { return RMEXTICR{mmio.UM32{&p.EXTICR[n].U32, uint32(EXTI1)}} } func (p *SYSCFG_Periph) EXTI2(n int) RMEXTICR { return RMEXTICR{mmio.UM32{&p.EXTICR[n].U32, uint32(EXTI2)}} } func (p *SYSCFG_Periph) EXTI3(n int) RMEXTICR { return RMEXTICR{mmio.UM32{&p.EXTICR[n].U32, uint32(EXTI3)}} } type SCSR uint32 func (b SCSR) Field(mask SCSR) int { return bits.Field32(uint32(b), uint32(mask)) } func (mask SCSR) J(v int) SCSR { return SCSR(bits.MakeField32(v, uint32(mask))) } type RSCSR struct{ mmio.U32 } func (r *RSCSR) Bits(mask SCSR) SCSR { return SCSR(r.U32.Bits(uint32(mask))) } func (r *RSCSR) StoreBits(mask, b SCSR) { r.U32.StoreBits(uint32(mask), uint32(b)) } func (r *RSCSR) SetBits(mask SCSR) { r.U32.SetBits(uint32(mask)) } func (r *RSCSR) ClearBits(mask SCSR) { r.U32.ClearBits(uint32(mask)) } func (r *RSCSR) Load() SCSR { return SCSR(r.U32.Load()) } func (r *RSCSR) Store(b SCSR) { r.U32.Store(uint32(b)) } func (r *RSCSR) AtomicStoreBits(mask, b SCSR) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) } func (r *RSCSR) AtomicSetBits(mask SCSR) { r.U32.AtomicSetBits(uint32(mask)) } func (r *RSCSR) AtomicClearBits(mask SCSR) { r.U32.AtomicClearBits(uint32(mask)) } type RMSCSR struct{ mmio.UM32 } func (rm RMSCSR) Load() SCSR { return SCSR(rm.UM32.Load()) } func (rm RMSCSR) Store(b SCSR) { rm.UM32.Store(uint32(b)) } func (p *SYSCFG_Periph) SRAM2ER() RMSCSR { return RMSCSR{mmio.UM32{&p.SCSR.U32, uint32(SRAM2ER)}} } func (p *SYSCFG_Periph) SRAM2BSY() RMSCSR { return RMSCSR{mmio.UM32{&p.SCSR.U32, uint32(SRAM2BSY)}} } type CFGR2 uint32 func (b CFGR2) Field(mask CFGR2) int { return bits.Field32(uint32(b), uint32(mask)) } func (mask CFGR2) J(v int) CFGR2 { return CFGR2(bits.MakeField32(v, uint32(mask))) } type RCFGR2 struct{ mmio.U32 } func (r *RCFGR2) Bits(mask CFGR2) CFGR2 { return CFGR2(r.U32.Bits(uint32(mask))) } func (r *RCFGR2) StoreBits(mask, b CFGR2) { r.U32.StoreBits(uint32(mask), uint32(b)) } func (r *RCFGR2) SetBits(mask CFGR2) { r.U32.SetBits(uint32(mask)) } func (r *RCFGR2) ClearBits(mask CFGR2) { r.U32.ClearBits(uint32(mask)) } func (r *RCFGR2) Load() CFGR2 { return CFGR2(r.U32.Load()) } func (r *RCFGR2) Store(b CFGR2) { r.U32.Store(uint32(b)) } func (r *RCFGR2) AtomicStoreBits(mask, b CFGR2) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) } func (r *RCFGR2) AtomicSetBits(mask CFGR2) { r.U32.AtomicSetBits(uint32(mask)) } func (r *RCFGR2) AtomicClearBits(mask CFGR2) { r.U32.AtomicClearBits(uint32(mask)) } type RMCFGR2 struct{ mmio.UM32 } func (rm RMCFGR2) Load() CFGR2 { return CFGR2(rm.UM32.Load()) } func (rm RMCFGR2) Store(b CFGR2) { rm.UM32.Store(uint32(b)) } func (p *SYSCFG_Periph) CLL() RMCFGR2 { return RMCFGR2{mmio.UM32{&p.CFGR2.U32, uint32(CLL)}} } func (p *SYSCFG_Periph) SPL() RMCFGR2 { return RMCFGR2{mmio.UM32{&p.CFGR2.U32, uint32(SPL)}} } func (p *SYSCFG_Periph) PVDL() RMCFGR2 { return RMCFGR2{mmio.UM32{&p.CFGR2.U32, uint32(PVDL)}} } func (p *SYSCFG_Periph) ECCL() RMCFGR2 { return RMCFGR2{mmio.UM32{&p.CFGR2.U32, uint32(ECCL)}} } func (p *SYSCFG_Periph) SPF() RMCFGR2 { return RMCFGR2{mmio.UM32{&p.CFGR2.U32, uint32(SPF)}} } type SWPR uint32 func (b SWPR) Field(mask SWPR) int { return bits.Field32(uint32(b), uint32(mask)) } func (mask SWPR) J(v int) SWPR { return SWPR(bits.MakeField32(v, uint32(mask))) } type RSWPR struct{ mmio.U32 } func (r *RSWPR) Bits(mask SWPR) SWPR { return SWPR(r.U32.Bits(uint32(mask))) } func (r *RSWPR) StoreBits(mask, b SWPR) { r.U32.StoreBits(uint32(mask), uint32(b)) } func (r *RSWPR) SetBits(mask SWPR) { r.U32.SetBits(uint32(mask)) } func (r *RSWPR) ClearBits(mask SWPR) { r.U32.ClearBits(uint32(mask)) } func (r *RSWPR) Load() SWPR { return SWPR(r.U32.Load()) } func (r *RSWPR) Store(b SWPR) { r.U32.Store(uint32(b)) } func (r *RSWPR) AtomicStoreBits(mask, b SWPR) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) } func (r *RSWPR) AtomicSetBits(mask SWPR) { r.U32.AtomicSetBits(uint32(mask)) } func (r *RSWPR) AtomicClearBits(mask SWPR) { r.U32.AtomicClearBits(uint32(mask)) } type RMSWPR struct{ mmio.UM32 } func (rm RMSWPR) Load() SWPR { return SWPR(rm.UM32.Load()) } func (rm RMSWPR) Store(b SWPR) { rm.UM32.Store(uint32(b)) } func (p *SYSCFG_Periph) PAGE0() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE0)}} } func (p *SYSCFG_Periph) PAGE1() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE1)}} } func (p *SYSCFG_Periph) PAGE2() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE2)}} } func (p *SYSCFG_Periph) PAGE3() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE3)}} } func (p *SYSCFG_Periph) PAGE4() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE4)}} } func (p *SYSCFG_Periph) PAGE5() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE5)}} } func (p *SYSCFG_Periph) PAGE6() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE6)}} } func (p *SYSCFG_Periph) PAGE7() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE7)}} } func (p *SYSCFG_Periph) PAGE8() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE8)}} } func (p *SYSCFG_Periph) PAGE9() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE9)}} } func (p *SYSCFG_Periph) PAGE10() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE10)}} } func (p *SYSCFG_Periph) PAGE11() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE11)}} } func (p *SYSCFG_Periph) PAGE12() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE12)}} } func (p *SYSCFG_Periph) PAGE13() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE13)}} } func (p *SYSCFG_Periph) PAGE14() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE14)}} } func (p *SYSCFG_Periph) PAGE15() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE15)}} } func (p *SYSCFG_Periph) PAGE16() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE16)}} } func (p *SYSCFG_Periph) PAGE17() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE17)}} } func (p *SYSCFG_Periph) PAGE18() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE18)}} } func (p *SYSCFG_Periph) PAGE19() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE19)}} } func (p *SYSCFG_Periph) PAGE20() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE20)}} } func (p *SYSCFG_Periph) PAGE21() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE21)}} } func (p *SYSCFG_Periph) PAGE22() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE22)}} } func (p *SYSCFG_Periph) PAGE23() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE23)}} } func (p *SYSCFG_Periph) PAGE24() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE24)}} } func (p *SYSCFG_Periph) PAGE25() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE25)}} } func (p *SYSCFG_Periph) PAGE26() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE26)}} } func (p *SYSCFG_Periph) PAGE27() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE27)}} } func (p *SYSCFG_Periph) PAGE28() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE28)}} } func (p *SYSCFG_Periph) PAGE29() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE29)}} } func (p *SYSCFG_Periph) PAGE30() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE30)}} } func (p *SYSCFG_Periph) PAGE31() RMSWPR { return RMSWPR{mmio.UM32{&p.SWPR.U32, uint32(PAGE31)}} } type SKR uint32 func (b SKR) Field(mask SKR) int { return bits.Field32(uint32(b), uint32(mask)) } func (mask SKR) J(v int) SKR { return SKR(bits.MakeField32(v, uint32(mask))) } type RSKR struct{ mmio.U32 } func (r *RSKR) Bits(mask SKR) SKR { return SKR(r.U32.Bits(uint32(mask))) } func (r *RSKR) StoreBits(mask, b SKR) { r.U32.StoreBits(uint32(mask), uint32(b)) } func (r *RSKR) SetBits(mask SKR) { r.U32.SetBits(uint32(mask)) } func (r *RSKR) ClearBits(mask SKR) { r.U32.ClearBits(uint32(mask)) } func (r *RSKR) Load() SKR { return SKR(r.U32.Load()) } func (r *RSKR) Store(b SKR) { r.U32.Store(uint32(b)) } func (r *RSKR) AtomicStoreBits(mask, b SKR) { r.U32.AtomicStoreBits(uint32(mask), uint32(b)) } func (r *RSKR) AtomicSetBits(mask SKR) { r.U32.AtomicSetBits(uint32(mask)) } func (r *RSKR) AtomicClearBits(mask SKR) { r.U32.AtomicClearBits(uint32(mask)) } type RMSKR struct{ mmio.UM32 } func (rm RMSKR) Load() SKR { return SKR(rm.UM32.Load()) } func (rm RMSKR) Store(b SKR) { rm.UM32.Store(uint32(b)) } func (p *SYSCFG_Periph) KEY() RMSKR { return RMSKR{mmio.UM32{&p.SKR.U32, uint32(KEY)}} }<|fim▁end|>
type RMEMRMP struct{ mmio.U32 }
<|file_name|>day_5.rs<|end_file_name|><|fim▁begin|>pub use tdd_kata::directed_graph_kata::day_5::{DirectedGraph, DirectedCycle}; pub use expectest::prelude::{be_equal_to, be_some, be_ok, be_err, be_true, be_false}; describe! directed_graph { before_each { let mut graph = DirectedGraph::default(); } describe! graph { it "should create a new empty directed graph" { expect!(graph.vertices()).to(be_equal_to(0)); expect!(graph.edges()).to(be_equal_to(0)); } it "should add an edge to a graph" { graph.add_edge(1, 2); expect!(graph.vertices()).to(be_equal_to(2)); expect!(graph.edges()).to(be_equal_to(1)); } <|fim▁hole|> graph.add_edge(2, 3); graph.add_edge(1, 4); expect!(graph.vertices()).to(be_equal_to(4)); expect!(graph.edges()).to(be_equal_to(3)); } it "should not be adjacent to each other" { graph.add_edge(1, 2); expect!(graph.adjacent_to(1)).to(be_some().value(&vec![2])); expect!(graph.adjacent_to(2)).to(be_some().value(&vec![])); } } describe! directed_cycle { it "should create a directed cycle" { graph.add_edge(1, 2); expect!(DirectedCycle::new(&graph)).to(be_ok()); } it "should not create a directed cycle from an empty graph" { expect!(DirectedCycle::new(&graph)).to(be_err()); } it "should have a cycle" { graph.add_edge(1, 2); graph.add_edge(2, 3); graph.add_edge(3, 1); let cycle = DirectedCycle::new(&graph).unwrap(); expect!(cycle.has_cycle()).to(be_true()); } it "should not have a cycle" { graph.add_edge(1, 2); graph.add_edge(2, 3); graph.add_edge(1, 4); let cycle = DirectedCycle::new(&graph).unwrap(); expect!(cycle.has_cycle()).to(be_false()); } } }<|fim▁end|>
it "should add edges to a graph" { graph.add_edge(1, 2);
<|file_name|>api.js<|end_file_name|><|fim▁begin|>import * as React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import {<|fim▁hole|> export default function Page() { return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />; }<|fim▁end|>
demos, docs, requireDemo, } from '!@material-ui/markdown/loader!docs/src/pages/guides/api/api.md';
<|file_name|>CRecallRequestInfo.hpp<|end_file_name|><|fim▁begin|>// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <CRecallRequest.hpp> START_ATF_NAMESPACE namespace Info { using CRecallRequestctor_CRecallRequest2_ptr = void (WINAPIV*)(struct CRecallRequest*, uint16_t); using CRecallRequestctor_CRecallRequest2_clbk = void (WINAPIV*)(struct CRecallRequest*, uint16_t, CRecallRequestctor_CRecallRequest2_ptr); using CRecallRequestClear4_ptr = void (WINAPIV*)(struct CRecallRequest*); using CRecallRequestClear4_clbk = void (WINAPIV*)(struct CRecallRequest*, CRecallRequestClear4_ptr); using CRecallRequestClose6_ptr = void (WINAPIV*)(struct CRecallRequest*, bool); using CRecallRequestClose6_clbk = void (WINAPIV*)(struct CRecallRequest*, bool, CRecallRequestClose6_ptr); using CRecallRequestGetID8_ptr = uint16_t (WINAPIV*)(struct CRecallRequest*); using CRecallRequestGetID8_clbk = uint16_t (WINAPIV*)(struct CRecallRequest*, CRecallRequestGetID8_ptr); using CRecallRequestGetOwner10_ptr = struct CPlayer* (WINAPIV*)(struct CRecallRequest*); using CRecallRequestGetOwner10_clbk = struct CPlayer* (WINAPIV*)(struct CRecallRequest*, CRecallRequestGetOwner10_ptr); using CRecallRequestIsBattleModeUse12_ptr = bool (WINAPIV*)(struct CRecallRequest*); using CRecallRequestIsBattleModeUse12_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsBattleModeUse12_ptr); using CRecallRequestIsClose14_ptr = bool (WINAPIV*)(struct CRecallRequest*); using CRecallRequestIsClose14_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsClose14_ptr); using CRecallRequestIsRecallAfterStoneState16_ptr = bool (WINAPIV*)(struct CRecallRequest*); using CRecallRequestIsRecallAfterStoneState16_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsRecallAfterStoneState16_ptr); using CRecallRequestIsRecallParty18_ptr = bool (WINAPIV*)(struct CRecallRequest*); using CRecallRequestIsRecallParty18_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsRecallParty18_ptr); using CRecallRequestIsTimeOut20_ptr = bool (WINAPIV*)(struct CRecallRequest*); using CRecallRequestIsTimeOut20_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsTimeOut20_ptr); using CRecallRequestIsWait22_ptr = bool (WINAPIV*)(struct CRecallRequest*); using CRecallRequestIsWait22_clbk = bool (WINAPIV*)(struct CRecallRequest*, CRecallRequestIsWait22_ptr); using CRecallRequestRecall24_ptr = char (WINAPIV*)(struct CRecallRequest*, struct CPlayer*, bool); using CRecallRequestRecall24_clbk = char (WINAPIV*)(struct CRecallRequest*, struct CPlayer*, bool, CRecallRequestRecall24_ptr); using CRecallRequestRegist26_ptr = char (WINAPIV*)(struct CRecallRequest*, struct CPlayer*, struct CCharacter*, bool, bool, bool);<|fim▁hole|> using CRecallRequestdtor_CRecallRequest30_ptr = void (WINAPIV*)(struct CRecallRequest*); using CRecallRequestdtor_CRecallRequest30_clbk = void (WINAPIV*)(struct CRecallRequest*, CRecallRequestdtor_CRecallRequest30_ptr); }; // end namespace Info END_ATF_NAMESPACE<|fim▁end|>
using CRecallRequestRegist26_clbk = char (WINAPIV*)(struct CRecallRequest*, struct CPlayer*, struct CCharacter*, bool, bool, bool, CRecallRequestRegist26_ptr);
<|file_name|>write.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python<|fim▁hole|>with open('stuck.pkl','rb') as pklfile: stuck = pickle.load(pklfile) TE.makeBasicTable(stuck,TE.workdir+'html/table.html',TE.webdir+'table.html') TE.makeCSV(stuck,TE.webdir+'data.csv') for basis in [-6,-5,-4,-3,-1,1,2]: TE.makeJson(stuck,TE.webdir+('stuck_%i'%basis).replace('-','m')+'.json',basis)<|fim▁end|>
import TransferErrors as TE import cPickle as pickle
<|file_name|>claimant_make_claim_command.go<|end_file_name|><|fim▁begin|>package stake import "strings" // MakeClaim lets a claimant make a claim about a subject. func (claimant *Claimant) MakeClaim(subject string, claim string) (string, error) { if strings.TrimSpace(subject) == "" { return "Subject cannot be blank", nil } claimAlreadyExists := claimant.claimKeyFor(subject, claim) if claimant.claims[claimAlreadyExists] == true { return "Claim already exists", nil } <|fim▁hole|>}<|fim▁end|>
claimant.trackChange(ClaimMade{ClaimantID: claimant.ID, Subject: subject, Claim: claim}) return "Success", nil
<|file_name|>actor.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /// General actor system infrastructure. use devtools_traits::PreciseTime; use rustc_serialize::json; use std::any::{Any, TypeId}; use std::collections::HashMap; use std::cell::{Cell, RefCell}; use std::marker::Reflect; use std::mem::{replace, transmute}; use std::net::TcpStream;<|fim▁hole|>#[derive(PartialEq)] pub enum ActorMessageStatus { Processed, Ignored, } /// A common trait for all devtools actors that encompasses an immutable name /// and the ability to process messages that are directed to particular actors. /// TODO: ensure the name is immutable pub trait Actor: Any { fn handle_message(&self, registry: &ActorRegistry, msg_type: &str, msg: &json::Object, stream: &mut TcpStream) -> Result<ActorMessageStatus, ()>; fn name(&self) -> String; } impl Actor + Send { /// Returns true if the boxed type is the same as `T` #[inline] pub fn is<T: Reflect + 'static>(&self) -> bool { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[inline] #[allow(unsafe_code)] pub fn downcast_ref<T: Reflect + 'static>(&self) -> Option<&T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } /// Returns some mutable reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[inline] #[allow(unsafe_code)] pub fn downcast_mut<T: Reflect + 'static>(&mut self) -> Option<&mut T> { if self.is::<T>() { unsafe { // Get the raw representation of the trait object let to: TraitObject = transmute(self); // Extract the data pointer Some(transmute(to.data)) } } else { None } } } /// A list of known, owned actors. pub struct ActorRegistry { actors: HashMap<String, Box<Actor + Send>>, new_actors: RefCell<Vec<Box<Actor + Send>>>, old_actors: RefCell<Vec<String>>, script_actors: RefCell<HashMap<String, String>>, shareable: Option<Arc<Mutex<ActorRegistry>>>, next: Cell<u32>, start_stamp: PreciseTime, } impl ActorRegistry { /// Create an empty registry. pub fn new() -> ActorRegistry { ActorRegistry { actors: HashMap::new(), new_actors: RefCell::new(vec!()), old_actors: RefCell::new(vec!()), script_actors: RefCell::new(HashMap::new()), shareable: None, next: Cell::new(0), start_stamp: PreciseTime::now(), } } /// Creating shareable registry pub fn create_shareable(self) -> Arc<Mutex<ActorRegistry>>{ if self.shareable.is_some() { return self.shareable.unwrap(); } let shareable = Arc::new(Mutex::new(self)); let mut lock = shareable.lock(); let registry = lock.as_mut().unwrap(); registry.shareable = Some(shareable.clone()); shareable.clone() } /// Get shareable registry through threads pub fn get_shareable(&self) -> Arc<Mutex<ActorRegistry>> { self.shareable.as_ref().unwrap().clone() } /// Get start stamp when registry was started pub fn start_stamp(&self) -> PreciseTime { self.start_stamp.clone() } pub fn register_script_actor(&self, script_id: String, actor: String) { println!("registering {} ({})", actor, script_id); let mut script_actors = self.script_actors.borrow_mut(); script_actors.insert(script_id, actor); } pub fn script_to_actor(&self, script_id: String) -> String { if script_id.is_empty() { return "".to_string(); } self.script_actors.borrow().get(&script_id).unwrap().to_string() } pub fn script_actor_registered(&self, script_id: String) -> bool { self.script_actors.borrow().contains_key(&script_id) } pub fn actor_to_script(&self, actor: String) -> String { for (key, value) in &*self.script_actors.borrow() { println!("checking {}", value); if *value == actor { return key.to_string(); } } panic!("couldn't find actor named {}", actor) } /// Create a unique name based on a monotonically increasing suffix pub fn new_name(&self, prefix: &str) -> String { let suffix = self.next.get(); self.next.set(suffix + 1); format!("{}{}", prefix, suffix) } /// Add an actor to the registry of known actors that can receive messages. pub fn register(&mut self, actor: Box<Actor + Send>) { self.actors.insert(actor.name().to_string(), actor); } pub fn register_later(&self, actor: Box<Actor + Send>) { let mut actors = self.new_actors.borrow_mut(); actors.push(actor); } /// Find an actor by registered name pub fn find<'a, T: Reflect + 'static>(&'a self, name: &str) -> &'a T { let actor = self.actors.get(&name.to_string()).unwrap(); actor.downcast_ref::<T>().unwrap() } /// Find an actor by registered name pub fn find_mut<'a, T: Reflect + 'static>(&'a mut self, name: &str) -> &'a mut T { let actor = self.actors.get_mut(&name.to_string()).unwrap(); actor.downcast_mut::<T>().unwrap() } /// Attempt to process a message as directed by its `to` property. If the actor is not /// found or does not indicate that it knew how to process the message, ignore the failure. pub fn handle_message(&mut self, msg: &json::Object, stream: &mut TcpStream) -> Result<(), ()> { let to = msg.get("to").unwrap().as_string().unwrap(); match self.actors.get(&to.to_string()) { None => println!("message received for unknown actor \"{}\"", to), Some(actor) => { let msg_type = msg.get("type").unwrap().as_string().unwrap(); if try!(actor.handle_message(self, &msg_type.to_string(), msg, stream)) != ActorMessageStatus::Processed { println!("unexpected message type \"{}\" found for actor \"{}\"", msg_type, to); } } } let new_actors = replace(&mut *self.new_actors.borrow_mut(), vec!()); for actor in new_actors.into_iter() { self.actors.insert(actor.name().to_string(), actor); } let old_actors = replace(&mut *self.old_actors.borrow_mut(), vec!()); for name in old_actors { self.drop_actor(name); } Ok(()) } pub fn drop_actor(&mut self, name: String) { self.actors.remove(&name); } pub fn drop_actor_later(&self, name: String) { let mut actors = self.old_actors.borrow_mut(); actors.push(name); } }<|fim▁end|>
use std::raw::TraitObject; use std::sync::{Arc, Mutex};
<|file_name|>SatisfyTool.java<|end_file_name|><|fim▁begin|>/* * Copyright 2015 @author Unai Alegre * * This file is part of R-CASE (Requirements for Context-Aware Systems Engineering), a module * of Modelio that aids the requirements elicitation phase of a Context-Aware System (C-AS). * * R-CASE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * R-CASE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. *<|fim▁hole|>package edu.casetools.rcase.modelio.diagrams.requirements.tools.relations; import org.modelio.api.modelio.diagram.IDiagramGraphic; import org.modelio.api.modelio.diagram.IDiagramHandle; import org.modelio.metamodel.uml.infrastructure.Dependency; import org.modelio.metamodel.uml.infrastructure.ModelElement; import edu.casetools.rcase.modelio.diagrams.RelationTool; import edu.casetools.rcase.module.api.RCaseStereotypes; import edu.casetools.rcase.module.impl.RCaseModule; import edu.casetools.rcase.module.impl.RCasePeerModule; import edu.casetools.rcase.utils.ElementUtils; /** * The Class SatisfyTool is the tool for creating a Satisfy relation. */ public class SatisfyTool extends RelationTool { /* * (non-Javadoc) * * @see * org.modelio.api.diagram.tools.DefaultLinkTool#acceptFirstElement(org. * modelio.api.diagram.IDiagramHandle, * org.modelio.api.diagram.IDiagramGraphic) */ @Override public boolean acceptFirstElement(IDiagramHandle representation, IDiagramGraphic target) { return acceptAnyElement(target); } /* * (non-Javadoc) * * @see * org.modelio.api.diagram.tools.DefaultLinkTool#acceptSecondElement(org * .modelio.api.diagram.IDiagramHandle, * org.modelio.api.diagram.IDiagramGraphic, * org.modelio.api.diagram.IDiagramGraphic) */ @Override public boolean acceptSecondElement(IDiagramHandle representation, IDiagramGraphic source, IDiagramGraphic target) { return acceptElement(RCasePeerModule.MODULE_NAME, target, RCaseStereotypes.STEREOTYPE_REQUIREMENT); } /* * (non-Javadoc) * * @see edu.casesuite.modelio.diagrams.RelationTool# * createDependency(org.modelio.metamodel.uml.infrastructure.ModelElement, * org.modelio.metamodel.uml.infrastructure.ModelElement) */ @Override public Dependency createDependency(ModelElement originElement, ModelElement targetElement) { return ElementUtils.getInstance().createDependency(RCaseModule.getInstance(), RCasePeerModule.MODULE_NAME, originElement, targetElement, RCaseStereotypes.STEREOTYPE_SATISFY); } }<|fim▁end|>
* You should have received a copy of the GNU General Public License * along with Modelio. If not, see <http://www.gnu.org/licenses/>. * */
<|file_name|>requirements.py<|end_file_name|><|fim▁begin|>"""Requirements specific to SQLAlchemy's own unit tests. """ from sqlalchemy import util import sys from sqlalchemy.testing.requirements import SuiteRequirements from sqlalchemy.testing import exclusions from sqlalchemy.testing.exclusions import \ skip, \ skip_if,\ only_if,\ only_on,\ fails_on_everything_except,\ fails_on,\ fails_if,\ succeeds_if,\ SpecPredicate,\ against,\ LambdaPredicate,\ requires_tag def no_support(db, reason): return SpecPredicate(db, description=reason) def exclude(db, op, spec, description=None): return SpecPredicate(db, op, spec, description=description) class DefaultRequirements(SuiteRequirements): @property def deferrable_or_no_constraints(self): """Target database must support deferrable constraints.""" return skip_if([ no_support('firebird', 'not supported by database'), no_support('mysql', 'not supported by database'), no_support('mssql', 'not supported by database'), ]) @property def check_constraints(self): """Target database must support check constraints.""" return exclusions.open() @property def named_constraints(self): """target database must support names for constraints.""" return skip_if([ no_support('sqlite', 'not supported by database'), ]) @property def foreign_keys(self): """Target database must support foreign keys.""" return skip_if( no_support('sqlite', 'not supported by database') ) @property def on_update_cascade(self): """target database must support ON UPDATE..CASCADE behavior in foreign keys.""" return skip_if( ['sqlite', 'oracle'], 'target backend %(doesnt_support)s ON UPDATE CASCADE' ) @property def non_updating_cascade(self): """target database must *not* support ON UPDATE..CASCADE behavior in foreign keys.""" return fails_on_everything_except('sqlite', 'oracle', '+zxjdbc') + \ skip_if('mssql') @property def deferrable_fks(self): """target database must support deferrable fks""" return only_on(['oracle']) @property def unbounded_varchar(self): """Target database must support VARCHAR with no length""" return skip_if([ "firebird", "oracle", "mysql" ], "not supported by database" ) @property def boolean_col_expressions(self): """Target database must support boolean expressions as columns""" return skip_if([ no_support('firebird', 'not supported by database'), no_support('oracle', 'not supported by database'), no_support('mssql', 'not supported by database'), no_support('sybase', 'not supported by database'), ]) @property def standalone_binds(self): """target database/driver supports bound parameters as column expressions without being in the context of a typed column. """ return skip_if(["firebird", "mssql+mxodbc"], "not supported by driver") @property def identity(self): """Target database must support GENERATED AS IDENTITY or a facsimile. Includes GENERATED AS IDENTITY, AUTOINCREMENT, AUTO_INCREMENT, or other column DDL feature that fills in a DB-generated identifier at INSERT-time without requiring pre-execution of a SEQUENCE or other artifact. """ return skip_if(["firebird", "oracle", "postgresql", "sybase"], "not supported by database" ) @property def temporary_tables(self): """target database supports temporary tables""" return skip_if( ["mssql", "firebird"], "not supported (?)" ) @property def temp_table_reflection(self): return self.temporary_tables @property def reflectable_autoincrement(self): """Target database must support tables that can automatically generate PKs assuming they were reflected. this is essentially all the DBs in "identity" plus Postgresql, which has SERIAL support. FB and Oracle (and sybase?) require the Sequence to be explicitly added, including if the table was reflected. """ return skip_if(["firebird", "oracle", "sybase"], "not supported by database" ) @property def insert_from_select(self): return skip_if( ["firebird"], "crashes for unknown reason" ) @property def fetch_rows_post_commit(self): return skip_if( ["firebird"], "not supported" ) @property def binary_comparisons(self): """target database/driver can allow BLOB/BINARY fields to be compared against a bound parameter value. """ return skip_if(["oracle", "mssql"], "not supported by database/driver" ) @property def binary_literals(self): """target backend supports simple binary literals, e.g. an expression like:: SELECT CAST('foo' AS BINARY) Where ``BINARY`` is the type emitted from :class:`.LargeBinary`, e.g. it could be ``BLOB`` or similar. Basically fails on Oracle. """ # adding mssql here since it doesn't support comparisons either, # have observed generally bad behavior with binary / mssql. return skip_if(["oracle", "mssql"], "not supported by database/driver" ) @property def independent_cursors(self): """Target must support simultaneous, independent database cursors on a single connection.""" return skip_if(["mssql+pyodbc", "mssql+mxodbc"], "no driver support") @property def independent_connections(self): """Target must support simultaneous, independent database connections.""" # This is also true of some configurations of UnixODBC and probably win32 # ODBC as well. return skip_if([ no_support("sqlite", "independent connections disabled " "when :memory: connections are used"), exclude("mssql", "<", (9, 0, 0), "SQL Server 2005+ is required for " "independent connections" ) ] ) @property def updateable_autoincrement_pks(self): """Target must support UPDATE on autoincrement/integer primary key.""" return skip_if(["mssql", "sybase"], "IDENTITY columns can't be updated") @property def isolation_level(self): return only_on( ('postgresql', 'sqlite', 'mysql'), "DBAPI has no isolation level support" ) + fails_on('postgresql+pypostgresql', 'pypostgresql bombs on multiple isolation level calls') @property def row_triggers(self): """Target must support standard statement-running EACH ROW triggers.""" return skip_if([ # no access to same table no_support('mysql', 'requires SUPER priv'), exclude('mysql', '<', (5, 0, 10), 'not supported by database'), # huh? TODO: implement triggers for PG tests, remove this no_support('postgresql', 'PG triggers need to be implemented for tests'), ]) @property def correlated_outer_joins(self): """Target must support an outer join to a subquery which correlates to the parent.""" return skip_if("oracle", 'Raises "ORA-01799: a column may not be ' 'outer-joined to a subquery"') @property def update_from(self): """Target must support UPDATE..FROM syntax""" return only_on(['postgresql', 'mssql', 'mysql'], "Backend does not support UPDATE..FROM") @property def update_where_target_in_subquery(self): """Target must support UPDATE where the same table is present in a subquery in the WHERE clause. This is an ANSI-standard syntax that apparently MySQL can't handle, such as: UPDATE documents SET flag=1 WHERE documents.title IN (SELECT max(documents.title) AS title FROM documents GROUP BY documents.user_id ) """ return fails_if('mysql', 'MySQL error 1093 "Cant specify target table ' 'for update in FROM clause"') @property def savepoints(self): """Target database must support savepoints.""" return skip_if([ "sqlite", "sybase", ("mysql", "<", (5, 0, 3)), ], "savepoints not supported") @property def schemas(self): """Target database must support external schemas, and have one named 'test_schema'.""" return skip_if([ "sqlite", "firebird" ], "no schema support") @property def cross_schema_fk_reflection(self): """target system must support reflection of inter-schema foreign keys """ return only_on([ "postgresql" ]) @property def unique_constraint_reflection(self): return fails_on_everything_except( "postgresql", "mysql", "sqlite" ) @property def temp_table_names(self): """target dialect supports listing of temporary table names""" return only_on(['sqlite', 'oracle']) @property def temporary_views(self): """target database supports temporary views""" return only_on(['sqlite', 'postgresql']) @property def update_nowait(self): """Target database must support SELECT...FOR UPDATE NOWAIT""" return skip_if(["firebird", "mssql", "mysql", "sqlite", "sybase"], "no FOR UPDATE NOWAIT support" ) @property def subqueries(self): """Target database must support subqueries.""" return skip_if(exclude('mysql', '<', (4, 1, 1)), 'no subquery support') @property def mod_operator_as_percent_sign(self): """target database must use a plain percent '%' as the 'modulus' operator.""" return only_if( ['mysql', 'sqlite', 'postgresql+psycopg2', 'mssql'] ) @property def intersect(self): """Target database must support INTERSECT or equivalent.""" return fails_if([ "firebird", "mysql", "sybase", ], 'no support for INTERSECT') @property def except_(self): """Target database must support EXCEPT or equivalent (i.e. MINUS).""" return fails_if([ "firebird", "mysql", "sybase", ], 'no support for EXCEPT') @property def parens_in_union_contained_select(self): """Target database must support parenthesized SELECT in UNION. E.g. (SELECT ...) UNION (SELECT ..) """ return fails_if('sqlite') @property def offset(self): """Target database must support some method of adding OFFSET or equivalent to a result set.""" return fails_if([ "sybase" ], 'no support for OFFSET or equivalent') @property def window_functions(self): return only_if([ "postgresql>=8.4", "mssql", "oracle" ], "Backend does not support window functions") @property def two_phase_transactions(self): """Target database must support two-phase transactions.""" return skip_if([ no_support('firebird', 'no SA implementation'), no_support('mssql', 'two-phase xact not supported by drivers'), no_support('oracle', 'two-phase xact not implemented in SQLA/oracle'), no_support('drizzle', 'two-phase xact not supported by database'), no_support('sqlite', 'two-phase xact not supported by database'), no_support('sybase', 'two-phase xact not supported by drivers/SQLA'), no_support('postgresql+zxjdbc', 'FIXME: JDBC driver confuses the transaction state, may ' 'need separate XA implementation'), exclude('mysql', '<', (5, 0, 3), 'two-phase xact not supported by database'), ]) @property def views(self): """Target database must support VIEWs.""" return skip_if("drizzle", "no VIEW support") @property def empty_strings_varchar(self): """target database can persist/return an empty string with a varchar.""" return fails_if(["oracle"], 'oracle converts empty strings to a blank space') @property def empty_strings_text(self): """target database can persist/return an empty string with an unbounded text.""" return exclusions.open() @property def unicode_data(self): """target drive must support unicode data stored in columns.""" return skip_if([ no_support("sybase", "no unicode driver support") ]) @property def unicode_connections(self): """Target driver must support some encoding of Unicode across the wire.""" # TODO: expand to exclude MySQLdb versions w/ broken unicode return skip_if([ exclude('mysql', '<', (4, 1, 1), 'no unicode connection support'), ]) @property def unicode_ddl(self): """Target driver must support some degree of non-ascii symbol names.""" # TODO: expand to exclude MySQLdb versions w/ broken unicode return skip_if([ no_support('oracle', 'FIXME: no support in database?'), no_support('sybase', 'FIXME: guessing, needs confirmation'), no_support('mssql+pymssql', 'no FreeTDS support'), LambdaPredicate( lambda config: against(config, "mysql+mysqlconnector") and config.db.dialect._mysqlconnector_version_info > (2, 0) and util.py2k, "bug in mysqlconnector 2.0" ), LambdaPredicate( lambda config: against(config, 'mssql+pyodbc') and config.db.dialect.freetds and config.db.dialect.freetds_driver_version < "0.91", "older freetds doesn't support unicode DDL" ), exclude('mysql', '<', (4, 1, 1), 'no unicode connection support'), ]) @property def sane_rowcount(self): return skip_if( lambda config: not config.db.dialect.supports_sane_rowcount, "driver doesn't support 'sane' rowcount" ) @property def emulated_lastrowid(self): """"target dialect retrieves cursor.lastrowid or an equivalent after an insert() construct executes. """ return fails_on_everything_except('mysql', 'sqlite+pysqlite', 'sqlite+pysqlcipher', 'sybase', 'mssql') @property def implements_get_lastrowid(self): return skip_if([ no_support('sybase', 'not supported by database'), ]) @property def dbapi_lastrowid(self): """"target backend includes a 'lastrowid' accessor on the DBAPI cursor object. """ return skip_if('mssql+pymssql', 'crashes on pymssql') + \ fails_on_everything_except('mysql', 'sqlite+pysqlite', 'sqlite+pysqlcipher') @property def sane_multi_rowcount(self): return fails_if( lambda config: not config.db.dialect.supports_sane_multi_rowcount, "driver %(driver)s %(doesnt_support)s 'sane' multi row count" ) @property def nullsordering(self): """Target backends that support nulls ordering.""" return fails_on_everything_except('postgresql', 'oracle', 'firebird') @property def reflects_pk_names(self): """Target driver reflects the name of primary key constraints.""" return fails_on_everything_except('postgresql', 'oracle', 'mssql', 'sybase') @property def datetime_literals(self): """target dialect supports rendering of a date, time, or datetime as a literal string, e.g. via the TypeEngine.literal_processor() method. """ return fails_on_everything_except("sqlite") @property def datetime(self): """target dialect supports representation of Python datetime.datetime() objects.""" return exclusions.open() @property def datetime_microseconds(self): """target dialect supports representation of Python datetime.datetime() with microsecond objects.""" return skip_if(['mssql', 'mysql', 'firebird', '+zxjdbc', 'oracle', 'sybase']) @property def datetime_historic(self): """target dialect supports representation of Python datetime.datetime() objects with historic (pre 1900) values.""" return succeeds_if(['sqlite', 'postgresql', 'firebird']) @property def date(self): """target dialect supports representation of Python datetime.date() objects.""" return exclusions.open() @property def date_coerces_from_datetime(self): """target dialect accepts a datetime object as the target of a date column.""" return fails_on('mysql+mysqlconnector') @property def date_historic(self): """target dialect supports representation of Python datetime.datetime() objects with historic (pre 1900) values.""" return succeeds_if(['sqlite', 'postgresql', 'firebird']) @property def time(self): """target dialect supports representation of Python datetime.time() objects.""" return skip_if(['oracle']) @property def time_microseconds(self): """target dialect supports representation of Python datetime.time() with microsecond objects.""" return skip_if(['mssql', 'mysql', 'firebird', '+zxjdbc', 'oracle', 'sybase']) @property def precision_numerics_general(self): """target backend has general support for moderately high-precision numerics.""" return exclusions.open() @property def precision_numerics_enotation_small(self): """target backend supports Decimal() objects using E notation to represent very small values.""" # NOTE: this exclusion isn't used in current tests. return exclusions.open() @property def precision_numerics_enotation_large(self): """target backend supports Decimal() objects using E notation to represent very large values.""" return skip_if( [("sybase+pyodbc", None, None, "Don't know how do get these values through FreeTDS + Sybase"), ("firebird", None, None, "Precision must be from 1 to 18"),] ) @property def precision_numerics_many_significant_digits(self): """target backend supports values with many digits on both sides, such as 319438950232418390.273596, 87673.594069654243 """ return fails_if( [('sqlite', None, None, 'TODO'), ("firebird", None, None, "Precision must be from 1 to 18"), ("sybase+pysybase", None, None, "TODO"), ('mssql+pymssql', None, None, 'FIXME: improve pymssql dec handling')] ) @property def precision_numerics_retains_significant_digits(self): """A precision numeric type will return empty significant digits, i.e. a value such as 10.000 will come back in Decimal form with the .000 maintained.""" return fails_if( [ ('oracle', None, None, "this may be a bug due to the difficulty in handling " "oracle precision numerics"), ("firebird", None, None, "database and/or driver truncates decimal places.") ] ) @property def precision_generic_float_type(self): """target backend will return native floating point numbers with at least seven decimal places when using the generic Float type.""" return fails_if([ ('mysql', None, None, 'mysql FLOAT type only returns 4 decimals'), ('firebird', None, None, "firebird FLOAT type isn't high precision"), ]) @property def floats_to_four_decimals(self): return fails_if([ ("mysql+oursql", None, None, "Floating point error"), ("firebird", None, None, "Firebird still has FP inaccuracy even " "with only four decimal places"), ('mssql+pyodbc', None, None, 'mssql+pyodbc has FP inaccuracy even with ' 'only four decimal places ' ), ('mssql+pymssql', None, None, 'mssql+pymssql has FP inaccuracy even with ' 'only four decimal places '), ( 'postgresql+pg8000', None, None, 'postgresql+pg8000 has FP inaccuracy even with ' 'only four decimal places '), ( 'postgresql+psycopg2cffi', None, None, 'postgresql+psycopg2cffi has FP inaccuracy even with ' 'only four decimal places '), ]) @property def fetch_null_from_numeric(self): return skip_if( ("mssql+pyodbc", None, None, "crashes due to bug #351"), ) @property def duplicate_key_raises_integrity_error(self): return fails_on("postgresql+pg8000") @property def python2(self): return skip_if( lambda: sys.version_info >= (3,), "Python version 2.xx is required." ) @property def python3(self): return skip_if( lambda: sys.version_info < (3,), "Python version 3.xx is required." ) @property def cpython(self): return only_if(lambda: util.cpython, "cPython interpreter needed" ) @property def non_broken_pickle(self): from sqlalchemy.util import pickle return only_if( lambda: not util.pypy and pickle.__name__ == 'cPickle' or sys.version_info >= (3, 2), "Needs cPickle+cPython or newer Python 3 pickle" ) @property def predictable_gc(self): """target platform must remove all cycles unconditionally when gc.collect() is called, as well as clean out unreferenced subclasses. """ return self.cpython @property def hstore(self): def check_hstore(config): if not against(config, "postgresql"): return False try: config.db.execute("SELECT 'a=>1,a=>2'::hstore;") return True except: return False return only_if(check_hstore) @property def range_types(self): def check_range_types(config): if not against( config, ["postgresql+psycopg2", "postgresql+psycopg2cffi"]): return False try: config.db.scalar("select '[1,2)'::int4range;") return True except: return False return only_if(check_range_types) @property def oracle_test_dblink(self): return skip_if( lambda config: not config.file_config.has_option( 'sqla_testing', 'oracle_db_link'), "oracle_db_link option not specified in config" ) @property def postgresql_test_dblink(self): return skip_if( lambda config: not config.file_config.has_option( 'sqla_testing', 'postgres_test_db_link'), "postgres_test_db_link option not specified in config" ) @property def postgresql_jsonb(self): return skip_if( lambda config: config.db.dialect.driver == "pg8000" and config.db.dialect._dbapi_version <= (1, 10, 1) ) @property def psycopg2_native_json(self): return self.psycopg2_compatibility <|fim▁hole|> return self.psycopg2_compatibility @property def psycopg2_compatibility(self): return only_on( ["postgresql+psycopg2", "postgresql+psycopg2cffi"] ) @property def psycopg2_or_pg8000_compatibility(self): return only_on( ["postgresql+psycopg2", "postgresql+psycopg2cffi", "postgresql+pg8000"] ) @property def percent_schema_names(self): return skip_if( [ ( "+psycopg2", None, None, "psycopg2 2.4 no longer accepts percent " "sign in bind placeholders"), ( "+psycopg2cffi", None, None, "psycopg2cffi does not accept percent signs in " "bind placeholders"), ("mysql", None, None, "executemany() doesn't work here") ] ) @property def order_by_label_with_expression(self): return fails_if([ ('firebird', None, None, "kinterbasdb doesn't send full type information"), ('postgresql', None, None, 'only simple labels allowed'), ('sybase', None, None, 'only simple labels allowed'), ('mssql', None, None, 'only simple labels allowed') ]) @property def skip_mysql_on_windows(self): """Catchall for a large variety of MySQL on Windows failures""" return skip_if(self._has_mysql_on_windows, "Not supported on MySQL + Windows" ) @property def mssql_freetds(self): return only_on( LambdaPredicate( lambda config: ( (against(config, 'mssql+pyodbc') and config.db.dialect.freetds) or against(config, 'mssql+pymssql') ) ) ) @property def no_mssql_freetds(self): return self.mssql_freetds.not_() @property def selectone(self): """target driver must support the literal statement 'select 1'""" return skip_if(["oracle", "firebird"], "non-standard SELECT scalar syntax") @property def mysql_fully_case_sensitive(self): return only_if(self._has_mysql_fully_case_sensitive) def _has_mysql_on_windows(self, config): return against(config, 'mysql') and \ config.db.dialect._detect_casing(config.db) == 1 def _has_mysql_fully_case_sensitive(self, config): return against(config, 'mysql') and \ config.db.dialect._detect_casing(config.db) == 0 @property def postgresql_utf8_server_encoding(self): return only_if( lambda config: against(config, 'postgresql') and config.db.scalar("show server_encoding").lower() == "utf8" )<|fim▁end|>
@property def psycopg2_native_hstore(self):
<|file_name|>Appearance.py<|end_file_name|><|fim▁begin|># Generated from 'Appearance.h' def FOUR_CHAR_CODE(x): return x kAppearanceEventClass = FOUR_CHAR_CODE('appr') kAEAppearanceChanged = FOUR_CHAR_CODE('thme') kAESystemFontChanged = FOUR_CHAR_CODE('sysf') kAESmallSystemFontChanged = FOUR_CHAR_CODE('ssfn') kAEViewsFontChanged = FOUR_CHAR_CODE('vfnt') kThemeDataFileType = FOUR_CHAR_CODE('thme') kThemePlatinumFileType = FOUR_CHAR_CODE('pltn') kThemeCustomThemesFileType = FOUR_CHAR_CODE('scen') kThemeSoundTrackFileType = FOUR_CHAR_CODE('tsnd') kThemeBrushDialogBackgroundActive = 1 kThemeBrushDialogBackgroundInactive = 2 kThemeBrushAlertBackgroundActive = 3 kThemeBrushAlertBackgroundInactive = 4 kThemeBrushModelessDialogBackgroundActive = 5 kThemeBrushModelessDialogBackgroundInactive = 6 kThemeBrushUtilityWindowBackgroundActive = 7 kThemeBrushUtilityWindowBackgroundInactive = 8 kThemeBrushListViewSortColumnBackground = 9 kThemeBrushListViewBackground = 10 kThemeBrushIconLabelBackground = 11 kThemeBrushListViewSeparator = 12 kThemeBrushChasingArrows = 13 kThemeBrushDragHilite = 14 kThemeBrushDocumentWindowBackground = 15 kThemeBrushFinderWindowBackground = 16 kThemeBrushScrollBarDelimiterActive = 17 kThemeBrushScrollBarDelimiterInactive = 18 kThemeBrushFocusHighlight = 19 kThemeBrushPopupArrowActive = 20 kThemeBrushPopupArrowPressed = 21 kThemeBrushPopupArrowInactive = 22 kThemeBrushAppleGuideCoachmark = 23 kThemeBrushIconLabelBackgroundSelected = 24 kThemeBrushStaticAreaFill = 25 kThemeBrushActiveAreaFill = 26 kThemeBrushButtonFrameActive = 27 kThemeBrushButtonFrameInactive = 28 kThemeBrushButtonFaceActive = 29 kThemeBrushButtonFaceInactive = 30 kThemeBrushButtonFacePressed = 31 kThemeBrushButtonActiveDarkShadow = 32 kThemeBrushButtonActiveDarkHighlight = 33 kThemeBrushButtonActiveLightShadow = 34 kThemeBrushButtonActiveLightHighlight = 35 kThemeBrushButtonInactiveDarkShadow = 36 kThemeBrushButtonInactiveDarkHighlight = 37 kThemeBrushButtonInactiveLightShadow = 38 kThemeBrushButtonInactiveLightHighlight = 39 kThemeBrushButtonPressedDarkShadow = 40 kThemeBrushButtonPressedDarkHighlight = 41 kThemeBrushButtonPressedLightShadow = 42 kThemeBrushButtonPressedLightHighlight = 43 kThemeBrushBevelActiveLight = 44 kThemeBrushBevelActiveDark = 45 kThemeBrushBevelInactiveLight = 46 kThemeBrushBevelInactiveDark = 47 kThemeBrushNotificationWindowBackground = 48 kThemeBrushMovableModalBackground = 49 kThemeBrushSheetBackground = 50 kThemeBrushDrawerBackground = 51 kThemeBrushBlack = -1 kThemeBrushWhite = -2 kThemeTextColorDialogActive = 1 kThemeTextColorDialogInactive = 2 kThemeTextColorAlertActive = 3 kThemeTextColorAlertInactive = 4 kThemeTextColorModelessDialogActive = 5 kThemeTextColorModelessDialogInactive = 6 kThemeTextColorWindowHeaderActive = 7 kThemeTextColorWindowHeaderInactive = 8 kThemeTextColorPlacardActive = 9 kThemeTextColorPlacardInactive = 10 kThemeTextColorPlacardPressed = 11 kThemeTextColorPushButtonActive = 12 kThemeTextColorPushButtonInactive = 13 kThemeTextColorPushButtonPressed = 14 kThemeTextColorBevelButtonActive = 15 kThemeTextColorBevelButtonInactive = 16 kThemeTextColorBevelButtonPressed = 17 kThemeTextColorPopupButtonActive = 18 kThemeTextColorPopupButtonInactive = 19 kThemeTextColorPopupButtonPressed = 20 kThemeTextColorIconLabel = 21 kThemeTextColorListView = 22 kThemeTextColorDocumentWindowTitleActive = 23 kThemeTextColorDocumentWindowTitleInactive = 24 kThemeTextColorMovableModalWindowTitleActive = 25 kThemeTextColorMovableModalWindowTitleInactive = 26 kThemeTextColorUtilityWindowTitleActive = 27 kThemeTextColorUtilityWindowTitleInactive = 28 kThemeTextColorPopupWindowTitleActive = 29 kThemeTextColorPopupWindowTitleInactive = 30 kThemeTextColorRootMenuActive = 31 kThemeTextColorRootMenuSelected = 32 kThemeTextColorRootMenuDisabled = 33 kThemeTextColorMenuItemActive = 34 kThemeTextColorMenuItemSelected = 35 kThemeTextColorMenuItemDisabled = 36 kThemeTextColorPopupLabelActive = 37 kThemeTextColorPopupLabelInactive = 38 kThemeTextColorTabFrontActive = 39 kThemeTextColorTabNonFrontActive = 40 kThemeTextColorTabNonFrontPressed = 41 kThemeTextColorTabFrontInactive = 42 kThemeTextColorTabNonFrontInactive = 43 kThemeTextColorIconLabelSelected = 44 kThemeTextColorBevelButtonStickyActive = 45 kThemeTextColorBevelButtonStickyInactive = 46 kThemeTextColorNotification = 47 kThemeTextColorBlack = -1 kThemeTextColorWhite = -2 kThemeStateInactive = 0 kThemeStateActive = 1 kThemeStatePressed = 2 kThemeStateRollover = 6 kThemeStateUnavailable = 7 kThemeStateUnavailableInactive = 8 kThemeStateDisabled = 0 kThemeStatePressedUp = 2 kThemeStatePressedDown = 3 kThemeArrowCursor = 0 kThemeCopyArrowCursor = 1 kThemeAliasArrowCursor = 2 kThemeContextualMenuArrowCursor = 3 kThemeIBeamCursor = 4 kThemeCrossCursor = 5 kThemePlusCursor = 6 kThemeWatchCursor = 7 kThemeClosedHandCursor = 8 kThemeOpenHandCursor = 9 kThemePointingHandCursor = 10 kThemeCountingUpHandCursor = 11 kThemeCountingDownHandCursor = 12 kThemeCountingUpAndDownHandCursor = 13 kThemeSpinningCursor = 14 kThemeResizeLeftCursor = 15 kThemeResizeRightCursor = 16 kThemeResizeLeftRightCursor = 17 kThemeMenuBarNormal = 0 kThemeMenuBarSelected = 1 kThemeMenuSquareMenuBar = (1 << 0) kThemeMenuActive = 0 kThemeMenuSelected = 1 kThemeMenuDisabled = 3 kThemeMenuTypePullDown = 0 kThemeMenuTypePopUp = 1 kThemeMenuTypeHierarchical = 2 kThemeMenuTypeInactive = 0x0100 kThemeMenuItemPlain = 0 kThemeMenuItemHierarchical = 1 kThemeMenuItemScrollUpArrow = 2 kThemeMenuItemScrollDownArrow = 3 kThemeMenuItemAtTop = 0x0100 kThemeMenuItemAtBottom = 0x0200 kThemeMenuItemHierBackground = 0x0400 kThemeMenuItemPopUpBackground = 0x0800 kThemeMenuItemHasIcon = 0x8000 kThemeBackgroundTabPane = 1 kThemeBackgroundPlacard = 2 kThemeBackgroundWindowHeader = 3 kThemeBackgroundListViewWindowHeader = 4 kThemeBackgroundSecondaryGroupBox = 5 kThemeNameTag = FOUR_CHAR_CODE('name') kThemeVariantNameTag = FOUR_CHAR_CODE('varn') kThemeHighlightColorTag = FOUR_CHAR_CODE('hcol') kThemeScrollBarArrowStyleTag = FOUR_CHAR_CODE('sbar') kThemeScrollBarThumbStyleTag = FOUR_CHAR_CODE('sbth') kThemeSoundsEnabledTag = FOUR_CHAR_CODE('snds') kThemeDblClickCollapseTag = FOUR_CHAR_CODE('coll') kThemeAppearanceFileNameTag = FOUR_CHAR_CODE('thme') kThemeSystemFontTag = FOUR_CHAR_CODE('lgsf') kThemeSmallSystemFontTag = FOUR_CHAR_CODE('smsf') kThemeViewsFontTag = FOUR_CHAR_CODE('vfnt') kThemeViewsFontSizeTag = FOUR_CHAR_CODE('vfsz') kThemeDesktopPatternNameTag = FOUR_CHAR_CODE('patn') kThemeDesktopPatternTag = FOUR_CHAR_CODE('patt') kThemeDesktopPictureNameTag = FOUR_CHAR_CODE('dpnm') kThemeDesktopPictureAliasTag = FOUR_CHAR_CODE('dpal') kThemeDesktopPictureAlignmentTag = FOUR_CHAR_CODE('dpan') kThemeHighlightColorNameTag = FOUR_CHAR_CODE('hcnm') kThemeExamplePictureIDTag = FOUR_CHAR_CODE('epic') kThemeSoundTrackNameTag = FOUR_CHAR_CODE('sndt') kThemeSoundMaskTag = FOUR_CHAR_CODE('smsk') kThemeUserDefinedTag = FOUR_CHAR_CODE('user') kThemeSmoothFontEnabledTag = FOUR_CHAR_CODE('smoo') kThemeSmoothFontMinSizeTag = FOUR_CHAR_CODE('smos') kThemeCheckBoxClassicX = 0 kThemeCheckBoxCheckMark = 1 kThemeScrollBarArrowsSingle = 0 kThemeScrollBarArrowsLowerRight = 1 kThemeScrollBarThumbNormal = 0 kThemeScrollBarThumbProportional = 1 kThemeSystemFont = 0 kThemeSmallSystemFont = 1 kThemeSmallEmphasizedSystemFont = 2 kThemeViewsFont = 3 kThemeEmphasizedSystemFont = 4 kThemeApplicationFont = 5 kThemeLabelFont = 6 kThemeMenuTitleFont = 100 kThemeMenuItemFont = 101 kThemeMenuItemMarkFont = 102 kThemeMenuItemCmdKeyFont = 103 kThemeWindowTitleFont = 104 kThemePushButtonFont = 105 kThemeUtilityWindowTitleFont = 106 kThemeAlertHeaderFont = 107 kThemeCurrentPortFont = 200 kThemeTabNonFront = 0 kThemeTabNonFrontPressed = 1 kThemeTabNonFrontInactive = 2 kThemeTabFront = 3 kThemeTabFrontInactive = 4 kThemeTabNonFrontUnavailable = 5 kThemeTabFrontUnavailable = 6 kThemeTabNorth = 0 kThemeTabSouth = 1 kThemeTabEast = 2 kThemeTabWest = 3 kThemeSmallTabHeight = 16 kThemeLargeTabHeight = 21 kThemeTabPaneOverlap = 3 kThemeSmallTabHeightMax = 19 kThemeLargeTabHeightMax = 24 kThemeMediumScrollBar = 0 kThemeSmallScrollBar = 1 kThemeMediumSlider = 2 kThemeMediumProgressBar = 3 kThemeMediumIndeterminateBar = 4 kThemeRelevanceBar = 5 kThemeSmallSlider = 6 kThemeLargeProgressBar = 7 kThemeLargeIndeterminateBar = 8 kThemeTrackActive = 0 kThemeTrackDisabled = 1 kThemeTrackNothingToScroll = 2 kThemeTrackInactive = 3 kThemeLeftOutsideArrowPressed = 0x01 kThemeLeftInsideArrowPressed = 0x02 kThemeLeftTrackPressed = 0x04 kThemeThumbPressed = 0x08 kThemeRightTrackPressed = 0x10 kThemeRightInsideArrowPressed = 0x20 kThemeRightOutsideArrowPressed = 0x40 kThemeTopOutsideArrowPressed = kThemeLeftOutsideArrowPressed kThemeTopInsideArrowPressed = kThemeLeftInsideArrowPressed kThemeTopTrackPressed = kThemeLeftTrackPressed kThemeBottomTrackPressed = kThemeRightTrackPressed kThemeBottomInsideArrowPressed = kThemeRightInsideArrowPressed kThemeBottomOutsideArrowPressed = kThemeRightOutsideArrowPressed kThemeThumbPlain = 0 kThemeThumbUpward = 1 kThemeThumbDownward = 2 kThemeTrackHorizontal = (1 << 0) kThemeTrackRightToLeft = (1 << 1) kThemeTrackShowThumb = (1 << 2) kThemeTrackThumbRgnIsNotGhost = (1 << 3) kThemeTrackNoScrollBarArrows = (1 << 4) kThemeWindowHasGrow = (1 << 0) kThemeWindowHasHorizontalZoom = (1 << 3) kThemeWindowHasVerticalZoom = (1 << 4) kThemeWindowHasFullZoom = kThemeWindowHasHorizontalZoom + kThemeWindowHasVerticalZoom kThemeWindowHasCloseBox = (1 << 5) kThemeWindowHasCollapseBox = (1 << 6) kThemeWindowHasTitleText = (1 << 7) kThemeWindowIsCollapsed = (1 << 8) kThemeWindowHasDirty = (1 << 9) kThemeDocumentWindow = 0 kThemeDialogWindow = 1 kThemeMovableDialogWindow = 2 kThemeAlertWindow = 3 kThemeMovableAlertWindow = 4 kThemePlainDialogWindow = 5 kThemeShadowDialogWindow = 6 kThemePopupWindow = 7 kThemeUtilityWindow = 8 kThemeUtilitySideWindow = 9 kThemeSheetWindow = 10 kThemeWidgetCloseBox = 0 kThemeWidgetZoomBox = 1 kThemeWidgetCollapseBox = 2 kThemeWidgetDirtyCloseBox = 6 kThemeArrowLeft = 0 kThemeArrowDown = 1 kThemeArrowRight = 2 kThemeArrowUp = 3 kThemeArrow3pt = 0 kThemeArrow5pt = 1 kThemeArrow7pt = 2 kThemeArrow9pt = 3 kThemeGrowLeft = (1 << 0) kThemeGrowRight = (1 << 1) kThemeGrowUp = (1 << 2) kThemeGrowDown = (1 << 3) kThemePushButton = 0 kThemeCheckBox = 1 kThemeRadioButton = 2 kThemeBevelButton = 3 kThemeArrowButton = 4 kThemePopupButton = 5 kThemeDisclosureButton = 6 kThemeIncDecButton = 7 kThemeSmallBevelButton = 8 kThemeMediumBevelButton = 3 kThemeLargeBevelButton = 9 kThemeListHeaderButton = 10 kThemeRoundButton = 11 kThemeLargeRoundButton = 12 kThemeSmallCheckBox = 13 kThemeSmallRadioButton = 14 kThemeRoundedBevelButton = 15 kThemeNormalCheckBox = kThemeCheckBox kThemeNormalRadioButton = kThemeRadioButton kThemeButtonOff = 0 kThemeButtonOn = 1 kThemeButtonMixed = 2 kThemeDisclosureRight = 0 kThemeDisclosureDown = 1 kThemeDisclosureLeft = 2 kThemeAdornmentNone = 0 kThemeAdornmentDefault = (1 << 0) kThemeAdornmentFocus = (1 << 2) kThemeAdornmentRightToLeft = (1 << 4) kThemeAdornmentDrawIndicatorOnly = (1 << 5) kThemeAdornmentHeaderButtonLeftNeighborSelected = (1 << 6) kThemeAdornmentHeaderButtonRightNeighborSelected = (1 << 7) kThemeAdornmentHeaderButtonSortUp = (1 << 8) kThemeAdornmentHeaderMenuButton = (1 << 9) kThemeAdornmentHeaderButtonNoShadow = (1 << 10) kThemeAdornmentHeaderButtonShadowOnly = (1 << 11) kThemeAdornmentNoShadow = kThemeAdornmentHeaderButtonNoShadow kThemeAdornmentShadowOnly = kThemeAdornmentHeaderButtonShadowOnly kThemeAdornmentArrowLeftArrow = (1 << 6) kThemeAdornmentArrowDownArrow = (1 << 7) kThemeAdornmentArrowDoubleArrow = (1 << 8) kThemeAdornmentArrowUpArrow = (1 << 9) kThemeNoSounds = 0 kThemeWindowSoundsMask = (1 << 0) kThemeMenuSoundsMask = (1 << 1) kThemeControlSoundsMask = (1 << 2) kThemeFinderSoundsMask = (1 << 3) kThemeDragSoundNone = 0 kThemeDragSoundMoveWindow = FOUR_CHAR_CODE('wmov') kThemeDragSoundGrowWindow = FOUR_CHAR_CODE('wgro') kThemeDragSoundMoveUtilWindow = FOUR_CHAR_CODE('umov') kThemeDragSoundGrowUtilWindow = FOUR_CHAR_CODE('ugro') kThemeDragSoundMoveDialog = FOUR_CHAR_CODE('dmov') kThemeDragSoundMoveAlert = FOUR_CHAR_CODE('amov') kThemeDragSoundMoveIcon = FOUR_CHAR_CODE('imov') kThemeDragSoundSliderThumb = FOUR_CHAR_CODE('slth') kThemeDragSoundSliderGhost = FOUR_CHAR_CODE('slgh') kThemeDragSoundScrollBarThumb = FOUR_CHAR_CODE('sbth') kThemeDragSoundScrollBarGhost = FOUR_CHAR_CODE('sbgh') kThemeDragSoundScrollBarArrowDecreasing = FOUR_CHAR_CODE('sbad') kThemeDragSoundScrollBarArrowIncreasing = FOUR_CHAR_CODE('sbai') kThemeDragSoundDragging = FOUR_CHAR_CODE('drag') kThemeSoundNone = 0 kThemeSoundMenuOpen = FOUR_CHAR_CODE('mnuo') kThemeSoundMenuClose = FOUR_CHAR_CODE('mnuc') kThemeSoundMenuItemHilite = FOUR_CHAR_CODE('mnui') kThemeSoundMenuItemRelease = FOUR_CHAR_CODE('mnus') kThemeSoundWindowClosePress = FOUR_CHAR_CODE('wclp') kThemeSoundWindowCloseEnter = FOUR_CHAR_CODE('wcle') kThemeSoundWindowCloseExit = FOUR_CHAR_CODE('wclx') kThemeSoundWindowCloseRelease = FOUR_CHAR_CODE('wclr') kThemeSoundWindowZoomPress = FOUR_CHAR_CODE('wzmp') kThemeSoundWindowZoomEnter = FOUR_CHAR_CODE('wzme') kThemeSoundWindowZoomExit = FOUR_CHAR_CODE('wzmx') kThemeSoundWindowZoomRelease = FOUR_CHAR_CODE('wzmr') kThemeSoundWindowCollapsePress = FOUR_CHAR_CODE('wcop') kThemeSoundWindowCollapseEnter = FOUR_CHAR_CODE('wcoe') kThemeSoundWindowCollapseExit = FOUR_CHAR_CODE('wcox') kThemeSoundWindowCollapseRelease = FOUR_CHAR_CODE('wcor') kThemeSoundWindowDragBoundary = FOUR_CHAR_CODE('wdbd') kThemeSoundUtilWinClosePress = FOUR_CHAR_CODE('uclp') kThemeSoundUtilWinCloseEnter = FOUR_CHAR_CODE('ucle') kThemeSoundUtilWinCloseExit = FOUR_CHAR_CODE('uclx') kThemeSoundUtilWinCloseRelease = FOUR_CHAR_CODE('uclr') kThemeSoundUtilWinZoomPress = FOUR_CHAR_CODE('uzmp') kThemeSoundUtilWinZoomEnter = FOUR_CHAR_CODE('uzme') kThemeSoundUtilWinZoomExit = FOUR_CHAR_CODE('uzmx') kThemeSoundUtilWinZoomRelease = FOUR_CHAR_CODE('uzmr') kThemeSoundUtilWinCollapsePress = FOUR_CHAR_CODE('ucop') kThemeSoundUtilWinCollapseEnter = FOUR_CHAR_CODE('ucoe') kThemeSoundUtilWinCollapseExit = FOUR_CHAR_CODE('ucox') kThemeSoundUtilWinCollapseRelease = FOUR_CHAR_CODE('ucor') kThemeSoundUtilWinDragBoundary = FOUR_CHAR_CODE('udbd') kThemeSoundWindowOpen = FOUR_CHAR_CODE('wopn') kThemeSoundWindowClose = FOUR_CHAR_CODE('wcls') kThemeSoundWindowZoomIn = FOUR_CHAR_CODE('wzmi') kThemeSoundWindowZoomOut = FOUR_CHAR_CODE('wzmo') kThemeSoundWindowCollapseUp = FOUR_CHAR_CODE('wcol') kThemeSoundWindowCollapseDown = FOUR_CHAR_CODE('wexp') kThemeSoundWindowActivate = FOUR_CHAR_CODE('wact') kThemeSoundUtilWindowOpen = FOUR_CHAR_CODE('uopn') kThemeSoundUtilWindowClose = FOUR_CHAR_CODE('ucls') kThemeSoundUtilWindowZoomIn = FOUR_CHAR_CODE('uzmi') kThemeSoundUtilWindowZoomOut = FOUR_CHAR_CODE('uzmo') kThemeSoundUtilWindowCollapseUp = FOUR_CHAR_CODE('ucol') kThemeSoundUtilWindowCollapseDown = FOUR_CHAR_CODE('uexp')<|fim▁hole|>kThemeSoundDialogOpen = FOUR_CHAR_CODE('dopn') kThemeSoundDialogClose = FOUR_CHAR_CODE('dlgc') kThemeSoundAlertOpen = FOUR_CHAR_CODE('aopn') kThemeSoundAlertClose = FOUR_CHAR_CODE('altc') kThemeSoundPopupWindowOpen = FOUR_CHAR_CODE('pwop') kThemeSoundPopupWindowClose = FOUR_CHAR_CODE('pwcl') kThemeSoundButtonPress = FOUR_CHAR_CODE('btnp') kThemeSoundButtonEnter = FOUR_CHAR_CODE('btne') kThemeSoundButtonExit = FOUR_CHAR_CODE('btnx') kThemeSoundButtonRelease = FOUR_CHAR_CODE('btnr') kThemeSoundDefaultButtonPress = FOUR_CHAR_CODE('dbtp') kThemeSoundDefaultButtonEnter = FOUR_CHAR_CODE('dbte') kThemeSoundDefaultButtonExit = FOUR_CHAR_CODE('dbtx') kThemeSoundDefaultButtonRelease = FOUR_CHAR_CODE('dbtr') kThemeSoundCancelButtonPress = FOUR_CHAR_CODE('cbtp') kThemeSoundCancelButtonEnter = FOUR_CHAR_CODE('cbte') kThemeSoundCancelButtonExit = FOUR_CHAR_CODE('cbtx') kThemeSoundCancelButtonRelease = FOUR_CHAR_CODE('cbtr') kThemeSoundCheckboxPress = FOUR_CHAR_CODE('chkp') kThemeSoundCheckboxEnter = FOUR_CHAR_CODE('chke') kThemeSoundCheckboxExit = FOUR_CHAR_CODE('chkx') kThemeSoundCheckboxRelease = FOUR_CHAR_CODE('chkr') kThemeSoundRadioPress = FOUR_CHAR_CODE('radp') kThemeSoundRadioEnter = FOUR_CHAR_CODE('rade') kThemeSoundRadioExit = FOUR_CHAR_CODE('radx') kThemeSoundRadioRelease = FOUR_CHAR_CODE('radr') kThemeSoundScrollArrowPress = FOUR_CHAR_CODE('sbap') kThemeSoundScrollArrowEnter = FOUR_CHAR_CODE('sbae') kThemeSoundScrollArrowExit = FOUR_CHAR_CODE('sbax') kThemeSoundScrollArrowRelease = FOUR_CHAR_CODE('sbar') kThemeSoundScrollEndOfTrack = FOUR_CHAR_CODE('sbte') kThemeSoundScrollTrackPress = FOUR_CHAR_CODE('sbtp') kThemeSoundSliderEndOfTrack = FOUR_CHAR_CODE('slte') kThemeSoundSliderTrackPress = FOUR_CHAR_CODE('sltp') kThemeSoundBalloonOpen = FOUR_CHAR_CODE('blno') kThemeSoundBalloonClose = FOUR_CHAR_CODE('blnc') kThemeSoundBevelPress = FOUR_CHAR_CODE('bevp') kThemeSoundBevelEnter = FOUR_CHAR_CODE('beve') kThemeSoundBevelExit = FOUR_CHAR_CODE('bevx') kThemeSoundBevelRelease = FOUR_CHAR_CODE('bevr') kThemeSoundLittleArrowUpPress = FOUR_CHAR_CODE('laup') kThemeSoundLittleArrowDnPress = FOUR_CHAR_CODE('ladp') kThemeSoundLittleArrowEnter = FOUR_CHAR_CODE('lare') kThemeSoundLittleArrowExit = FOUR_CHAR_CODE('larx') kThemeSoundLittleArrowUpRelease = FOUR_CHAR_CODE('laur') kThemeSoundLittleArrowDnRelease = FOUR_CHAR_CODE('ladr') kThemeSoundPopupPress = FOUR_CHAR_CODE('popp') kThemeSoundPopupEnter = FOUR_CHAR_CODE('pope') kThemeSoundPopupExit = FOUR_CHAR_CODE('popx') kThemeSoundPopupRelease = FOUR_CHAR_CODE('popr') kThemeSoundDisclosurePress = FOUR_CHAR_CODE('dscp') kThemeSoundDisclosureEnter = FOUR_CHAR_CODE('dsce') kThemeSoundDisclosureExit = FOUR_CHAR_CODE('dscx') kThemeSoundDisclosureRelease = FOUR_CHAR_CODE('dscr') kThemeSoundTabPressed = FOUR_CHAR_CODE('tabp') kThemeSoundTabEnter = FOUR_CHAR_CODE('tabe') kThemeSoundTabExit = FOUR_CHAR_CODE('tabx') kThemeSoundTabRelease = FOUR_CHAR_CODE('tabr') kThemeSoundDragTargetHilite = FOUR_CHAR_CODE('dthi') kThemeSoundDragTargetUnhilite = FOUR_CHAR_CODE('dtuh') kThemeSoundDragTargetDrop = FOUR_CHAR_CODE('dtdr') kThemeSoundEmptyTrash = FOUR_CHAR_CODE('ftrs') kThemeSoundSelectItem = FOUR_CHAR_CODE('fsel') kThemeSoundNewItem = FOUR_CHAR_CODE('fnew') kThemeSoundReceiveDrop = FOUR_CHAR_CODE('fdrp') kThemeSoundCopyDone = FOUR_CHAR_CODE('fcpd') kThemeSoundResolveAlias = FOUR_CHAR_CODE('fral') kThemeSoundLaunchApp = FOUR_CHAR_CODE('flap') kThemeSoundDiskInsert = FOUR_CHAR_CODE('dski') kThemeSoundDiskEject = FOUR_CHAR_CODE('dske') kThemeSoundFinderDragOnIcon = FOUR_CHAR_CODE('fdon') kThemeSoundFinderDragOffIcon = FOUR_CHAR_CODE('fdof') kThemePopupTabNormalPosition = 0 kThemePopupTabCenterOnWindow = 1 kThemePopupTabCenterOnOffset = 2 kThemeMetricScrollBarWidth = 0 kThemeMetricSmallScrollBarWidth = 1 kThemeMetricCheckBoxHeight = 2 kThemeMetricRadioButtonHeight = 3 kThemeMetricEditTextWhitespace = 4 kThemeMetricEditTextFrameOutset = 5 kThemeMetricListBoxFrameOutset = 6 kThemeMetricFocusRectOutset = 7 kThemeMetricImageWellThickness = 8 kThemeMetricScrollBarOverlap = 9 kThemeMetricLargeTabHeight = 10 kThemeMetricLargeTabCapsWidth = 11 kThemeMetricTabFrameOverlap = 12 kThemeMetricTabIndentOrStyle = 13 kThemeMetricTabOverlap = 14 kThemeMetricSmallTabHeight = 15 kThemeMetricSmallTabCapsWidth = 16 kThemeMetricDisclosureButtonHeight = 17 kThemeMetricRoundButtonSize = 18 kThemeMetricPushButtonHeight = 19 kThemeMetricListHeaderHeight = 20 kThemeMetricSmallCheckBoxHeight = 21 kThemeMetricDisclosureButtonWidth = 22 kThemeMetricSmallDisclosureButtonHeight = 23 kThemeMetricSmallDisclosureButtonWidth = 24 kThemeMetricDisclosureTriangleHeight = 25 kThemeMetricDisclosureTriangleWidth = 26 kThemeMetricLittleArrowsHeight = 27 kThemeMetricLittleArrowsWidth = 28 kThemeMetricPaneSplitterHeight = 29 kThemeMetricPopupButtonHeight = 30 kThemeMetricSmallPopupButtonHeight = 31 kThemeMetricLargeProgressBarThickness = 32 kThemeMetricPullDownHeight = 33 kThemeMetricSmallPullDownHeight = 34 kThemeMetricSmallPushButtonHeight = 35 kThemeMetricSmallRadioButtonHeight = 36 kThemeMetricRelevanceIndicatorHeight = 37 kThemeMetricResizeControlHeight = 38 kThemeMetricSmallResizeControlHeight = 39 kThemeMetricLargeRoundButtonSize = 40 kThemeMetricHSliderHeight = 41 kThemeMetricHSliderTickHeight = 42 kThemeMetricSmallHSliderHeight = 43 kThemeMetricSmallHSliderTickHeight = 44 kThemeMetricVSliderWidth = 45 kThemeMetricVSliderTickWidth = 46 kThemeMetricSmallVSliderWidth = 47 kThemeMetricSmallVSliderTickWidth = 48 kThemeMetricTitleBarControlsHeight = 49 kThemeMetricCheckBoxWidth = 50 kThemeMetricSmallCheckBoxWidth = 51 kThemeMetricRadioButtonWidth = 52 kThemeMetricSmallRadioButtonWidth = 53 kThemeMetricSmallHSliderMinThumbWidth = 54 kThemeMetricSmallVSliderMinThumbHeight = 55 kThemeMetricSmallHSliderTickOffset = 56 kThemeMetricSmallVSliderTickOffset = 57 kThemeMetricNormalProgressBarThickness = 58 kThemeMetricProgressBarShadowOutset = 59 kThemeMetricSmallProgressBarShadowOutset = 60 kThemeMetricPrimaryGroupBoxContentInset = 61 kThemeMetricSecondaryGroupBoxContentInset = 62 # appearanceBadBrushIndexErr = themeInvalidBrushErr # appearanceProcessRegisteredErr = themeProcessRegisteredErr # appearanceProcessNotRegisteredErr = themeProcessNotRegisteredErr # appearanceBadTextColorIndexErr = themeBadTextColorErr # appearanceThemeHasNoAccents = themeHasNoAccentsErr # appearanceBadCursorIndexErr = themeBadCursorIndexErr kThemeActiveDialogBackgroundBrush = kThemeBrushDialogBackgroundActive kThemeInactiveDialogBackgroundBrush = kThemeBrushDialogBackgroundInactive kThemeActiveAlertBackgroundBrush = kThemeBrushAlertBackgroundActive kThemeInactiveAlertBackgroundBrush = kThemeBrushAlertBackgroundInactive kThemeActiveModelessDialogBackgroundBrush = kThemeBrushModelessDialogBackgroundActive kThemeInactiveModelessDialogBackgroundBrush = kThemeBrushModelessDialogBackgroundInactive kThemeActiveUtilityWindowBackgroundBrush = kThemeBrushUtilityWindowBackgroundActive kThemeInactiveUtilityWindowBackgroundBrush = kThemeBrushUtilityWindowBackgroundInactive kThemeListViewSortColumnBackgroundBrush = kThemeBrushListViewSortColumnBackground kThemeListViewBackgroundBrush = kThemeBrushListViewBackground kThemeIconLabelBackgroundBrush = kThemeBrushIconLabelBackground kThemeListViewSeparatorBrush = kThemeBrushListViewSeparator kThemeChasingArrowsBrush = kThemeBrushChasingArrows kThemeDragHiliteBrush = kThemeBrushDragHilite kThemeDocumentWindowBackgroundBrush = kThemeBrushDocumentWindowBackground kThemeFinderWindowBackgroundBrush = kThemeBrushFinderWindowBackground kThemeActiveScrollBarDelimiterBrush = kThemeBrushScrollBarDelimiterActive kThemeInactiveScrollBarDelimiterBrush = kThemeBrushScrollBarDelimiterInactive kThemeFocusHighlightBrush = kThemeBrushFocusHighlight kThemeActivePopupArrowBrush = kThemeBrushPopupArrowActive kThemePressedPopupArrowBrush = kThemeBrushPopupArrowPressed kThemeInactivePopupArrowBrush = kThemeBrushPopupArrowInactive kThemeAppleGuideCoachmarkBrush = kThemeBrushAppleGuideCoachmark kThemeActiveDialogTextColor = kThemeTextColorDialogActive kThemeInactiveDialogTextColor = kThemeTextColorDialogInactive kThemeActiveAlertTextColor = kThemeTextColorAlertActive kThemeInactiveAlertTextColor = kThemeTextColorAlertInactive kThemeActiveModelessDialogTextColor = kThemeTextColorModelessDialogActive kThemeInactiveModelessDialogTextColor = kThemeTextColorModelessDialogInactive kThemeActiveWindowHeaderTextColor = kThemeTextColorWindowHeaderActive kThemeInactiveWindowHeaderTextColor = kThemeTextColorWindowHeaderInactive kThemeActivePlacardTextColor = kThemeTextColorPlacardActive kThemeInactivePlacardTextColor = kThemeTextColorPlacardInactive kThemePressedPlacardTextColor = kThemeTextColorPlacardPressed kThemeActivePushButtonTextColor = kThemeTextColorPushButtonActive kThemeInactivePushButtonTextColor = kThemeTextColorPushButtonInactive kThemePressedPushButtonTextColor = kThemeTextColorPushButtonPressed kThemeActiveBevelButtonTextColor = kThemeTextColorBevelButtonActive kThemeInactiveBevelButtonTextColor = kThemeTextColorBevelButtonInactive kThemePressedBevelButtonTextColor = kThemeTextColorBevelButtonPressed kThemeActivePopupButtonTextColor = kThemeTextColorPopupButtonActive kThemeInactivePopupButtonTextColor = kThemeTextColorPopupButtonInactive kThemePressedPopupButtonTextColor = kThemeTextColorPopupButtonPressed kThemeIconLabelTextColor = kThemeTextColorIconLabel kThemeListViewTextColor = kThemeTextColorListView kThemeActiveDocumentWindowTitleTextColor = kThemeTextColorDocumentWindowTitleActive kThemeInactiveDocumentWindowTitleTextColor = kThemeTextColorDocumentWindowTitleInactive kThemeActiveMovableModalWindowTitleTextColor = kThemeTextColorMovableModalWindowTitleActive kThemeInactiveMovableModalWindowTitleTextColor = kThemeTextColorMovableModalWindowTitleInactive kThemeActiveUtilityWindowTitleTextColor = kThemeTextColorUtilityWindowTitleActive kThemeInactiveUtilityWindowTitleTextColor = kThemeTextColorUtilityWindowTitleInactive kThemeActivePopupWindowTitleColor = kThemeTextColorPopupWindowTitleActive kThemeInactivePopupWindowTitleColor = kThemeTextColorPopupWindowTitleInactive kThemeActiveRootMenuTextColor = kThemeTextColorRootMenuActive kThemeSelectedRootMenuTextColor = kThemeTextColorRootMenuSelected kThemeDisabledRootMenuTextColor = kThemeTextColorRootMenuDisabled kThemeActiveMenuItemTextColor = kThemeTextColorMenuItemActive kThemeSelectedMenuItemTextColor = kThemeTextColorMenuItemSelected kThemeDisabledMenuItemTextColor = kThemeTextColorMenuItemDisabled kThemeActivePopupLabelTextColor = kThemeTextColorPopupLabelActive kThemeInactivePopupLabelTextColor = kThemeTextColorPopupLabelInactive kAEThemeSwitch = kAEAppearanceChanged kThemeNoAdornment = kThemeAdornmentNone kThemeDefaultAdornment = kThemeAdornmentDefault kThemeFocusAdornment = kThemeAdornmentFocus kThemeRightToLeftAdornment = kThemeAdornmentRightToLeft kThemeDrawIndicatorOnly = kThemeAdornmentDrawIndicatorOnly kThemeBrushPassiveAreaFill = kThemeBrushStaticAreaFill kThemeMetricCheckBoxGlyphHeight = kThemeMetricCheckBoxHeight kThemeMetricRadioButtonGlyphHeight = kThemeMetricRadioButtonHeight kThemeMetricDisclosureButtonSize = kThemeMetricDisclosureButtonHeight kThemeMetricBestListHeaderHeight = kThemeMetricListHeaderHeight kThemeMetricSmallProgressBarThickness = kThemeMetricNormalProgressBarThickness kThemeMetricProgressBarThickness = kThemeMetricLargeProgressBarThickness kThemeScrollBar = kThemeMediumScrollBar kThemeSlider = kThemeMediumSlider kThemeProgressBar = kThemeMediumProgressBar kThemeIndeterminateBar = kThemeMediumIndeterminateBar<|fim▁end|>
kThemeSoundUtilWindowActivate = FOUR_CHAR_CODE('uact')
<|file_name|>helper.py<|end_file_name|><|fim▁begin|>import datetime import io import logging import logging.handlers import os import sys from collections import deque from time import perf_counter import colorlog class LogHelper: FORMATTER_COLOR = colorlog.ColoredFormatter('{log_color}{asctime} {name}: {levelname} {message}', style='{') FORMATTER = logging.Formatter('{asctime} {name}: {levelname} {message}', style='{') @classmethod def generate_color_handler(cls, stream=sys.stdout): handler = logging.StreamHandler(stream) handler.setFormatter(cls.FORMATTER_COLOR) return handler @classmethod def get_script_name(cls): script_name = os.path.basename(sys.argv[0]) script_name, _ = os.path.splitext(script_name) return script_name @classmethod def generate_simple_rotating_file_handler(cls, path_log_file=None, when='midnight', files_count=7): if path_log_file is None: path_dir = os.path.dirname(sys.argv[0]) path_log_file = cls.suggest_script_log_name(path_dir) handler = logging.handlers.TimedRotatingFileHandler(path_log_file, when=when, backupCount=files_count) handler.setLevel(logging.DEBUG) handler.setFormatter(cls.FORMATTER) return handler @classmethod def suggest_script_log_name(cls, path_dir): return os.path.join(path_dir, cls.get_script_name() + '.log') @staticmethod def timestamp(with_ms=False, time=None): if time is None: time = datetime.datetime.now() if with_ms: return time.strftime('%Y%m%d_%H%M%S.%f')[:-3] else: return time.strftime('%Y%m%d_%H%M%S') class PerformanceMetric: def __init__(self, *, n_samples=1000, units_suffix='', units_format='.2f', name=None): super().__init__() self.name: str = name self.queue_samples = deque(maxlen=n_samples) self.total = 0 self.last = 0 self.units_str = units_suffix self.units_format = units_format def reset(self): self.total = 0 self.last = 0 self.queue_samples.clear() @property def n_samples(self): return len(self.queue_samples) def __str__(self): str_name = f'[{self.name}] ' if self.name else '' if self.n_samples == 0: return f'{str_name}No measurements' return '{}Average: {:{}} {}; Last: {:{}} {}; Samples: {};'.format( str_name, self.average, self.units_format, self.units_str, self.last, self.units_format, self.units_str, self.n_samples ) def last_str(self): str_name = f'[{self.name}] ' if self.name else '' return f'{str_name}{self.last:{self.units_format}} {self.units_str}' @property def average(self): if self.n_samples == 0: return None return self.total / self.n_samples def submit_sample(self, sample: float): sample_popped = 0 if self.n_samples == self.queue_samples.maxlen: sample_popped = self.queue_samples.popleft() self.last = sample self.total += self.last - sample_popped self.queue_samples.append(self.last) class PerformanceTimer(PerformanceMetric): def __init__(self, n_samples=1000, units_format='.1f', **kwargs) -> None: super().__init__(n_samples=n_samples, units_suffix='sec', units_format=units_format, **kwargs) self.time_last_start = 0 def __enter__(self): self.begin() return self def __exit__(self, t, value, tb): self.end() def begin(self): self.time_last_start = perf_counter() def end(self): self.submit_sample(self.peek()) def peek(self): return perf_counter() - self.time_last_start class PrintStream: """ Shortcut for using `StringIO` printf = PrintStream() printf('Case Results:') printf(...) string = str(printf) """ def __init__(self, stream=None): if not stream: stream = io.StringIO() self.stream = stream def __call__(self, *args, **kwargs): print(*args, file=self.stream, **kwargs) <|fim▁hole|><|fim▁end|>
def __str__(self): return self.stream.getvalue()
<|file_name|>PointerData.ts<|end_file_name|><|fim▁begin|>/* * Point * Visit http://createjs.com/ for documentation, updates and examples. * * Copyright (c) 2010 gskinner.com, inc. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ import IPoint from "./../../interface/IVector2"; import NumberUtil from "./../../util/NumberUtil"; /** * @module easelts */ /** * Represents a point on a 2 dimensional x / y coordinate system. * * <h4>Example</h4> * * var point = new createjs.Point(0, 100); * * @class Point * @param {Number} [x=0] X position. * @param {Number} [y=0] Y position. * @constructor **/ class PointerData implements IPoint { /** * X position. * @property x<|fim▁hole|> public x:number; /** * Y position. * @property y * @type number **/ public y:number; /** * @property inBounds * @type boolean */ public inBounds:boolean = false; public target:any = null; posEvtObj:any = null; rawX = 0; rawY = 0; constructor(x:number, y:number) { this.x = x; this.y = y; } } export default PointerData;<|fim▁end|>
* @type Number **/
<|file_name|>extern.rs<|end_file_name|><|fim▁begin|>#[macro_use] extern crate fomat_macros; #[test] fn macro_use() { let c: Vec<String> = vec!["a".into()]; let _ = fomat!( "<ul>" for x in &c { "<li>" (x) "</li>" } "</ul>" );<|fim▁hole|><|fim▁end|>
}
<|file_name|>SampleLights.py<|end_file_name|><|fim▁begin|>"""This sample demonstrates some very simple lightning effects.""" import math import d3d11 import d3d11x from d3d11c import * def heightCallback(x, z, byteIndex, data): return data[byteIndex] * 0.03 class SampleLights(d3d11x.Frame): def onCreate(self): #Heightmap. #self.heightmap = d3d11x.HeightMap(self.device, None, (64, 64), heightCallback, (2, 1, 2), (8, 8), False) self.heightmap = d3d11x.HeightMap(self.device, d3d11x.getResourceDir("Textures", "heightmap.dds"), (64, 64), heightCallback, (2, 1, 2), (8, 8), False) self.heightmap.textureView = self.loadTextureView("ground-marble.dds") #Sphere mesh. meshPath = d3d11x.getResourceDir("Mesh", "sphere.obj") self.sphere = d3d11x.Mesh(self.device, meshPath) self.sphere.textureView = self.loadTextureView("misc-white.bmp") def createLights(self): #Add 7 lights (maximum defined in 'Shared.fx'). lights = [] for i in range(1, 8): #Each light is little farther than the previous one. distance = i * 5 lightTime = self.time * (i * 0.5) #Use sin() and cos() to create a nice little movement pattern. x = math.sin(lightTime) * distance z = math.cos(lightTime) * distance y = self.heightmap.getHeight(x, z) pos = d3d11.Vector(x, y + 1, z) #Set color (RGBA) (from 0.0 to 1.0). 30.0 is just a magic value which looks good. red = i / 30.0 green = (7 - i) / 30.0 color = (red, green, 0, 0) lights.append((pos, color)) return lights def onRender(self): #View- and projectionmatrix. view = self.createLookAt((-50, 25, -50), (0, 0, 0)) projection = self.createProjection(45, 0.1, 300.0) lights = self.createLights() #First the heightmap. self.heightmap.setLights(lights) #Add some ambient lightning so that it is not so dark. self.heightmap.effect.set("lightAmbient", (0.5, 0.5, 0.5, 0)) self.heightmap.render(d3d11.Matrix(), view, projection) #Then our "light spheres". self.sphere.setLights(lights) <|fim▁hole|> meshWorld = d3d11.Matrix() lightPos = light[0] #Add little to y to lift the sphere off the ground. meshWorld.translate((lightPos.x, lightPos.y + 1, lightPos.z)) #Set ambient to light color. self.sphere.effect.set("lightAmbient", light[1]) self.sphere.render(meshWorld, view, projection) if __name__ == "__main__": sample = SampleLights("Lights - DirectPython 11", __doc__) sample.mainloop()<|fim▁end|>
for light in lights: #World matrix.
<|file_name|>Brocfile.js<|end_file_name|><|fim▁begin|><|fim▁hole|>/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var app = new EmberApp(); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/modernizr/modernizr.js'); module.exports = app.toTree();<|fim▁end|>
<|file_name|>slide.core.js<|end_file_name|><|fim▁begin|>var Drag={ obj: null, leftTime: null, rightTime: null, init: function (o,minX,maxX,btnRight,btnLeft) { o.onmousedown=Drag.start; o.hmode=true; if(o.hmode&&isNaN(parseInt(o.style.left))) { o.style.left="0px"; } if(!o.hmode&&isNaN(parseInt(o.style.right))) { o.style.right="0px"; } o.minX=typeof minX!='undefined'?minX:null; o.maxX=typeof maxX!='undefined'?maxX:null; o.onDragStart=new Function(); o.onDragEnd=new Function(); o.onDrag=new Function(); btnLeft.onmousedown=Drag.startLeft; btnRight.onmousedown=Drag.startRight; btnLeft.onmouseup=Drag.stopLeft; btnRight.onmouseup=Drag.stopRight; }, start: function (e) { var o=Drag.obj=this; e=Drag.fixE(e); var x=parseInt(o.hmode?o.style.left:o.style.right); o.onDragStart(x); o.lastMouseX=e.clientX; if(o.hmode) { if(o.minX!=null) { o.minMouseX=e.clientX-x+o.minX; } if(o.maxX!=null) { o.maxMouseX=o.minMouseX+o.maxX-o.minX; } } else { if(o.minX!=null) { o.maxMouseX= -o.minX+e.clientX+x; } if(o.maxX!=null) { o.minMouseX= -o.maxX+e.clientX+x; } } document.onmousemove=Drag.drag; document.onmouseup=Drag.end; return false; }, drag: function (e) { e=Drag.fixE(e); var o=Drag.obj; var ex=e.clientX; var x=parseInt(o.hmode?o.style.left:o.style.right); var nx; if(o.minX!=null) { ex=o.hmode?Math.max(ex,o.minMouseX):Math.min(ex,o.maxMouseX); } if(o.maxX!=null) { ex=o.hmode?Math.min(ex,o.maxMouseX):Math.max(ex,o.minMouseX); } nx=x+((ex-o.lastMouseX)*(o.hmode?1:-1)); $i("scrollcontent").style[o.hmode?"left":"right"]=(-nx*barUnitWidth)+"px"; Drag.obj.style[o.hmode?"left":"right"]=nx+"px"; Drag.obj.lastMouseX=ex; Drag.obj.onDrag(nx); return false; }, startLeft: function () { Drag.leftTime=setInterval("Drag.scrollLeft()",1); }, scrollLeft: function () {<|fim▁hole|> var o=$i("scrollbar"); if((parseInt(o.style.left.replace("px",""))<(590-162-10))&&(parseInt(o.style.left.replace("px",""))>=0)) { o.style.left=(parseInt(o.style.left.replace("px",""))+1)+"px"; c.style.left=(-(parseInt(o.style.left.replace("px",""))+1)*barUnitWidth)+"px"; } else { Drag.stopLeft(); } }, stopLeft: function () { clearInterval(Drag.leftTime); }, startRight: function () { Drag.rightTime=setInterval("Drag.scrollRight()",1); }, scrollRight: function () { var c=$i("scrollcontent"); var o=$i("scrollbar"); if((parseInt(o.style.left.replace("px",""))<=(590-162-10))&&(parseInt(o.style.left.replace("px",""))>0)) { o.style.left=(parseInt(o.style.left.replace("px",""))-1)+"px"; c.style.left=(-(parseInt(o.style.left.replace("px",""))-1)*barUnitWidth)+"px"; } else { Drag.stopRight(); } }, stopRight: function () { clearInterval(Drag.rightTime); }, end: function () { document.onmousemove=null; document.onmouseup=null; Drag.obj.onDragEnd(parseInt(Drag.obj.style[Drag.obj.hmode?"left":"right"])); Drag.obj=null; }, fixE: function (e) { if(typeof e=='undefined') { e=window.event; } if(typeof e.layerX=='undefined') { e.layerX=e.offsetX; } return e; } }; var scrollbar = $i('scrollbar'); var scrollleft = $i('scrollleft'); var scrollright = $i('scrollright'); $("#scrollcontent").css({ width: '600px', left: '-0px', position:'absolute'}); var _tmp1="",_tmp2="",data=slideJSON; $.each(data,function(i){ _tmp1+='<li><a href="'+data[i].link+'"><img title="'+data[i].title+'" src="'+data[i].img+'"></a></li>'; if(i==$CurrentPage-1){ _tmp2+='<li><a href="'+data[i].link+'"><img title="'+data[i].title+'" src="'+data[i].img+'" class="current"></a></li>'; }else{ _tmp2+='<li><a href="'+data[i].link+'"><img title="'+data[i].title+'" src="'+data[i].img+'"></a></li>'; } }); $("#imagelist").html(_tmp1); $("#scrollcontent").html(_tmp2); if($TotalPage>5){ if(scrollbar&&scrollright){ Drag.init(scrollbar,0,418,scrollleft,scrollright); } var scrollcontentWidth = (118*$TotalPage+120)+'px'; var scrollcontentLeft = '-0px'; var scroolbarLeft = '0px'; if($CurrentPage>3){ var $$CurrentPage = ($CurrentPage+2>$TotalPage)? ($TotalPage-5): ($CurrentPage-3); scrollcontentLeft = '-'+(118*$$CurrentPage)+'px'; scroolbarLeft = ((118*$$CurrentPage)/barUnitWidth)+'px'; } $("#scrollcontent").css({ width: scrollcontentWidth, left: scrollcontentLeft}); $("#scrollbar").css({ left: scroolbarLeft}); } else{ $("#scrollleft").hide(); $("#scrollright").hide(); $("#scrollbar img").hide(); }<|fim▁end|>
var c=$i("scrollcontent");