code stringlengths 281 23.7M |
|---|
class DEOK(DeltaE):
NAME = 'ok'
def __init__(self, scalar: float=1) -> None:
self.scalar = scalar
def distance(self, color: Color, sample: Color, scalar: (float | None)=None, **kwargs: Any) -> float:
if (scalar is None):
scalar = self.scalar
return (scalar * distance_euclidean(color, sample, space='oklab')) |
def convolve_weighted(window, signal, weights, n_iter=1):
assert (len(weights) == len(signal)), f'len(weights) = {len(weights)}, len(signal) = {len(signal)}, window_size = {len(window)}'
(y, w) = (signal, weights)
window /= window.sum()
for _i in range(n_iter):
logging.debug('Iteration %d: len(y)=%d, len(w)=%d', _i, len(y), len(w))
D = np.convolve((w * y), window, mode='same')
N = np.convolve(w, window, mode='same')
y = (D / N)
w = np.convolve(window, w, mode='same')
return (y, w) |
def main():
(csvfilename, graphfilename) = parse_argv()
csvr = csv.reader(open(csvfilename, 'rb'), delimiter=',', quotechar='"')
graph_fd = open(graphfilename, 'w')
graph_fd.write('digraph reqdeps {\nrankdir=BT;\nmclimit=10.0;\nnslimit=10.0;ranksep=1;\n')
rows = []
for row in csvr:
rows.append(row)
dep_costs = {}
rows.reverse()
for row in rows:
nodeparams = []
if (row[1] == 'none'):
nodeparams.append('color=red')
elif (row[1] == 'partial'):
nodeparams.append('color=orange')
elif (row[1] == 'fully'):
nodeparams.append('color=green')
dayrate = float(Encoding.to_unicode(row[2])[:(- 2)].replace(',', ''))
days = float(row[3])
material = float(Encoding.to_unicode(row[4])[:(- 2)].replace(',', ''))
lcosts = ((dayrate * days) + material)
dcosts = 0.0
if (row[0] in dep_costs):
dcosts = dep_costs[row[0]]
ocosts = (lcosts + dcosts)
nodeparams.append(('label="%s\\n%9.2f\\n%9.2f"' % (row[0], ocosts, lcosts)))
graph_fd.write(('%s [%s];\n' % (row[0], ','.join(nodeparams))))
acosts = 0.0
if (row[5] in dep_costs):
acosts = dep_costs[row[5]]
dep_costs[row[5]] = (acosts + ocosts)
for row in rows:
if (row[5] != '0'):
graph_fd.write(('%s -> %s;\n' % (row[0], row[5])))
graph_fd.write('}')
graph_fd.close() |
class SerialGroup(Group):
def _do(self, method, *args, **kwargs):
results = GroupResult()
excepted = False
for cxn in self:
try:
results[cxn] = getattr(cxn, method)(*args, **kwargs)
except Exception as e:
results[cxn] = e
excepted = True
if excepted:
raise GroupException(results)
return results |
def extractSaehan01Com(item):
badwords = ['Spanish translation']
if any([(bad in item['tags']) for bad in badwords]):
return None
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Li Yu', 'In Love with an Idiot', 'translated'), ('Shameless', 'Shameless Gangster', 'translated'), ('Intoxication', 'Intoxication', 'translated'), ('Lawless', 'Lawless Gangster', 'translated'), ('saye', 'SAYE', 'translated'), ('Lawless Gangster', 'Lawless Gangster', 'translated'), ('Advance Bravely', 'Advance Bravely', 'translated'), ('addicted', 'Are you Addicted?', 'translated')]
for (tagname, name, tl_type) in tagmap:
if (tagname in item['tags']):
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
if (('Lawless' in item['tags']) and ('Gangster' in item['tags'])):
return buildReleaseMessageWithType(item, 'Lawless Gangster', vol, chp, frag=frag, postfix=postfix)
return False |
def livereload(c):
from livereload import Server
build(c)
server = Server()
server.watch(CONFIG['settings_base'], (lambda : build(c)))
content_file_extensions = ['.md', '.rst']
for extension in content_file_extensions:
content_blob = '{0}/**/*{1}'.format(SETTINGS['PATH'], extension)
server.watch(content_blob, (lambda : build(c)))
theme_path = SETTINGS['THEME']
server.watch('{}/templates/*.html'.format(theme_path), (lambda : build(c)))
static_file_extensions = ['.css', '.js']
for extension in static_file_extensions:
static_file = '{0}/static/**/*{1}'.format(theme_path, extension)
server.watch(static_file, (lambda : build(c)))
server.serve(host=CONFIG['host'], port=CONFIG['port'], root=CONFIG['deploy_path']) |
def mount(directory, path):
mounts = list(remove.getMounted(path))
mounted = (((path + '/') + directory).replace('//', '/') in mounts)
if (not mounted):
os.system('mount --bind {} {}/{}'.format(directory, path, directory))
print(text.mounted.format(directory))
else:
print(text.alreadyMounted.format(directory)) |
def create_sales_invoice(patient, service_request, template, type):
sales_invoice = frappe.new_doc('Sales Invoice')
sales_invoice.patient = patient
sales_invoice.customer = frappe.db.get_value('Patient', patient, 'customer')
sales_invoice.due_date = getdate()
sales_invoice.currency = 'INR'
sales_invoice.company = '_Test Company'
sales_invoice.debit_to = get_receivable_account('_Test Company')
if (type == 'lab_test_prescription'):
sales_invoice.append('items', {'qty': 1, 'uom': 'Nos', 'conversion_factor': 1, 'income_account': get_income_account(None, '_Test Company'), 'rate': template.lab_test_rate, 'amount': template.lab_test_rate, 'reference_dt': service_request.doctype, 'reference_dn': service_request.name, 'cost_center': erpnext.get_default_cost_center('_Test Company'), 'item_code': template.item, 'item_name': template.lab_test_name, 'description': template.lab_test_description})
elif (type == 'drug_prescription'):
sales_invoice.append('items', {'qty': 1, 'uom': 'Nos', 'conversion_factor': 1, 'income_account': get_income_account(None, '_Test Company'), 'reference_dt': service_request.doctype, 'reference_dn': service_request.name, 'cost_center': erpnext.get_default_cost_center('_Test Company'), 'item_name': template.name, 'description': template.name})
elif (type == 'observation'):
sales_invoice.append('items', {'qty': 1, 'uom': 'Nos', 'conversion_factor': 1, 'income_account': get_income_account(None, '_Test Company'), 'rate': template.rate, 'amount': template.rate, 'reference_dt': service_request.doctype, 'reference_dn': service_request.name, 'cost_center': erpnext.get_default_cost_center('_Test Company'), 'item_code': template.item, 'item_name': template.item_code, 'description': template.description})
sales_invoice.set_missing_values()
sales_invoice.submit()
return sales_invoice |
def client(asgi, tmp_path):
file = (tmp_path / 'file.txt')
file.write_text('foo bar')
def make(sink_before_static_route):
app = create_app(asgi=asgi, sink_before_static_route=sink_before_static_route)
app.add_sink((sink_async if asgi else sink), '/sink')
app.add_static_route('/sink/static', str(tmp_path))
return testing.TestClient(app)
return make |
class OptionPlotoptionsErrorbarSonificationContexttracksMappingNoteduration(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
self._config(text, js_type=False)
def max(self):
return self._config_get(None)
def max(self, num: float):
self._config(num, js_type=False)
def min(self):
return self._config_get(None)
def min(self, num: float):
self._config(num, js_type=False)
def within(self):
return self._config_get(None)
def within(self, value: Any):
self._config(value, js_type=False) |
class TestHighlightAnchorLinenumNameInline(util.MdCase):
extension = ['pymdownx.highlight', 'pymdownx.superfences']
extension_configs = {'pymdownx.highlight': {'anchor_linenums': True, 'line_anchors': '__my_span', 'linenums_style': 'inline'}}
def test_linespans(self):
self.check_markdown('\n ```python linenums="2"\n import test\n ```\n ', '\n <div class="highlight"><pre><span></span><code><a id="__my_span-0-2" name="__my_span-0-2"></a><a href="#__my_span-0-2"><span class="linenos">2</span></a><span class="kn">import</span> <span class="nn">test</span>\n </code></pre></div>\n ', True) |
class Labels():
def __init__(self, labels, positions, colors, visible):
self.labels = labels
self.positions = positions
self.colors = colors
self.visible = visible
def get_properties(self, binary_filename):
positions = np.array(self.positions)
colors = np.array(self.colors)
json_dict = {'type': 'labels', 'labels': self.labels, 'positions': positions.tolist(), 'colors': colors.tolist(), 'visible': self.visible}
return json_dict
def write_binary(self, path):
return |
def test_check_consistency_raises_exception_when_type_not_recognized():
message = DefaultMessage(dialogue_reference=('', ''), message_id=1, target=0, performative=DefaultMessage.Performative.BYTES, content=b'hello')
with mock.patch.object(DefaultMessage.Performative, '__eq__', return_value=False):
assert (not message._is_consistent()) |
def init(quiet=False, assume_tty=True):
global QUIET, ASSUME_TTY, RALLY_RUNNING_IN_DOCKER, PLAIN, format
QUIET = quiet
ASSUME_TTY = assume_tty
RALLY_RUNNING_IN_DOCKER = (os.environ.get('RALLY_RUNNING_IN_DOCKER', '').upper() == 'TRUE')
if ((os.environ.get('TERM') == 'dumb') or (sys.platform == 'win32')):
PLAIN = True
format = PlainFormat
else:
PLAIN = False
format = RichFormat
try:
int(os.environ['COLUMNS'])
except (KeyError, ValueError):
try:
os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns)
except BaseException:
pass |
_os(*metadata.platforms)
def main():
common.log('Writing dummy shortcut file')
shortcut_path = 'C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\evil.lnk'
common.execute(['cmd', '/c', 'echo', 'dummy_shortcut', '>', shortcut_path])
common.log('Deleting dummy shortcut file')
common.remove_file(shortcut_path) |
class OptionSeriesSolidgaugeSonificationDefaultinstrumentoptionsMappingVolume(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
self._config(text, js_type=False)
def max(self):
return self._config_get(None)
def max(self, num: float):
self._config(num, js_type=False)
def min(self):
return self._config_get(None)
def min(self, num: float):
self._config(num, js_type=False)
def within(self):
return self._config_get(None)
def within(self, value: Any):
self._config(value, js_type=False) |
class OptionSeriesErrorbarSonificationDefaultinstrumentoptionsMappingTremoloSpeed(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
self._config(text, js_type=False)
def max(self):
return self._config_get(None)
def max(self, num: float):
self._config(num, js_type=False)
def min(self):
return self._config_get(None)
def min(self, num: float):
self._config(num, js_type=False)
def within(self):
return self._config_get(None)
def within(self, value: Any):
self._config(value, js_type=False) |
(name='api.mon.base.tasks.mon_user_group_changed', base=MonInternalTask, max_retries=1, default_retry_delay=5, bind=True)
def mon_user_group_changed(self, task_id, sender, group_name=None, dc_name=None, *args, **kwargs):
logger.info('mon_user_group_changed task has started with dc_name %s, and group_name %s', dc_name, group_name)
try:
_user_group_changed(sender, group_name, dc_name)
except MonitoringError as exc:
logger.exception(exc)
logger.error("mon_user_group_changed task crashed, it's going to be retried")
self.retry(exc=exc) |
_frequency(timedelta(days=1))
def fetch_consumption(zone_key: ZoneKey, session: (Session | None)=None, target_datetime: (datetime | None)=None, logger: Logger=getLogger(__name__)):
r = (session or Session())
consumption_list = TotalConsumptionList(logger)
if (target_datetime is None):
start_date = ((datetime.now(tz=TIMEZONE) - PUBLICATION_DELAY) - timedelta(days=1))
end_date = datetime.now(tz=TIMEZONE)
else:
start_date = (target_datetime - timedelta(days=1))
end_date = target_datetime
for year in range(start_date.year, (end_date.year + 1)):
url = HISTORICAL_LOAD_REPORTS.format(year)
response: Response = r.get(url)
if (not response.ok):
raise ParserException('CA_BC.py', f'Could not fetch load report for year {year}', zone_key)
df = pd.read_excel(response.content, skiprows=3)
df = df.rename(columns={'Date ?': 'Date'})
df['datetime'] = pd.to_datetime(((df['Date'] + ' ') + (df['HE'] - 1).astype('str')), format='%m/%d/%Y %H').dt.tz_localize(TIMEZONE, nonexistent='shift_backward')
df = df.set_index('datetime')
selected_times = df[start_date:end_date]
for row in selected_times.iterrows():
consumption_list.append(zoneKey=zone_key, datetime=row[0].to_pydatetime(), source=SOURCE, consumption=row[1]['Control Area Load'])
return consumption_list.to_list() |
class Solution():
def countVowelPermutation(self, n: int) -> int:
map = {'.': ['a', 'e', 'i', 'o', 'u'], 'a': ['e'], 'e': ['a', 'i'], 'i': ['a', 'e', 'o', 'u'], 'o': ['i', 'u'], 'u': ['a']}
_cache(None)
def dp(i, last):
if (i == n):
return 1
ans = 0
for nxt in map[last]:
ans = ((ans + dp((i + 1), nxt)) % )
return ans
return dp(0, '.') |
class Splicing_shots(object):
def __init__(self):
self.img = []
self.img_list = []
self.images_data = []
self.images_data_list = []
self.images_data_line_list = []
self.img_width = 0
self.img_height = 0
self.compare_row = 50
self.cut_width = 0
self.rate = 0.85
self.left_border = 0
self.min_head = 0
self.min_left = 0
self.min_right = 0
self.right_border = 0
self.head_pos = {}
self.head_data = None
def open_img(self):
for i in self.img:
img = Image.open(i)
if (self.img_width == 0):
(self.img_width, self.img_height) = img.size
self.img_list.append(img)
img_data = list(img.convert('L').getdata())
self.images_data_list.append(img_data)
an_imgdata = []
for line in range(img.height):
an_imgdata.append(img_data[(line * img.width):((line + 1) * img.width)])
self.images_data_line_list.append(an_imgdata)
def find_left_side(self):
images_data_list = []
for img in self.img_list[:2]:
rotate_img = img.rotate(270, expand=1)
rotate_img_data = list(rotate_img.convert('L').getdata())
an_imgdata = []
for line in range((rotate_img.height - 1)):
an_imgdata.append(rotate_img_data[(line * rotate_img.width):((line + 1) * rotate_img.width)])
images_data_list.append(an_imgdata)
rotate_height = len(images_data_list[0])
min_head = rotate_height
for i in range(1):
for j in range(1, rotate_height):
img1 = images_data_list[i][:j]
img2 = images_data_list[(i + 1)][:j]
if (img2 != img1):
if (j == 1):
print('!')
return
elif (j < (min_head + 1)):
min_head = (j - 1)
break
self.min_left = min_head
print('minleft', min_head)
def find_right_size(self):
images_data_list = []
for img in self.img_list[:2]:
rotate_img = img.rotate(90, expand=1)
rotate_img_data = list(rotate_img.convert('L').getdata())
an_imgdata = []
for line in range((rotate_img.height - 1)):
an_imgdata.append(rotate_img_data[(line * rotate_img.width):((line + 1) * rotate_img.width)])
images_data_list.append(an_imgdata)
rotate_height = len(images_data_list[0])
min_head = rotate_height
for i in range(1):
for j in range(1, rotate_height):
img1 = images_data_list[i][:j]
img2 = images_data_list[(i + 1)][:j]
if (img2 != img1):
if (j == 1):
print('!')
self.min_right = self.img_width
return
elif (j < (min_head + 1)):
min_head = (j - 1)
break
self.min_right = (self.img_width - min_head)
print('minright', min_head)
def find_the_same_head_to_remove(self):
min_head = self.img_height
for i in range((len(self.img) - 1)):
for j in range(1, self.img_height):
img1 = self.images_data_line_list[i][:j]
img2 = self.images_data_line_list[(i + 1)][:j]
if (img2 != img1):
if (j == 1):
print('!')
return
elif (j < (min_head + 1)):
min_head = (j - 1)
break
self.min_head = min_head
print('minhead', min_head)
def majority_color(self, classList):
count_dict = {}
for label in classList:
if (label not in count_dict.keys()):
count_dict[label] = 0
count_dict[label] += 1
return max(zip(count_dict.values(), count_dict.keys()))
def isthesameline(self, line1, line2):
same = 0
line1_majority_color = self.majority_color(line1)
line2_majority_color = self.majority_color(line2)
if (line2_majority_color[1] != line1_majority_color[1]):
return 0
elif (abs((line1_majority_color[0] - line2_majority_color[0])) > (self.img_width * 0.05)):
return 0
else:
(majority_color_count, majority_color) = line2_majority_color
if (majority_color_count > int((self.cut_width * 0.9))):
return 1
for i in range(self.cut_width):
if ((line1[i] == majority_color) or (line2[i] == majority_color)):
continue
elif (abs((line1[i] - line2[i])) < 10):
same += 1
if (same >= ((self.cut_width - majority_color_count) * self.rate)):
return 1
else:
return 0
def find_the_pos(self):
self.head_pos = {}
min_head = self.min_head
left = self.min_left
right = self.min_right
self.cut_width = (right - left)
images_data_line_list = self.images_data_line_list
compare_row = self.compare_row
for i in range((len(self.img) - 1)):
img1 = images_data_line_list[i]
img2 = images_data_line_list[(i + 1)]
max_line = [0, 0]
for k in range(min_head, (self.img_height - compare_row)):
sameline = 0
chance_count = 0
chance = 0
for j in range(min_head, (min_head + compare_row)):
st1 = (k + sameline)
dt2 = (min_head + sameline)
lin1 = img1[(k + sameline)][left:right]
lin2 = img2[(min_head + sameline)][left:right]
res = self.isthesameline(lin1, lin2)
if res:
sameline += 1
chance_count += 1
if (chance_count >= 7):
chance_count = 0
chance += 1
if (sameline > max_line[1]):
max_line[0] = k
max_line[1] = sameline
elif (chance <= 0):
break
else:
chance -= 1
sameline += 1
if (sameline >= (compare_row - (compare_row // 20))):
self.head_pos[i] = k
print(i, k)
print(self.head_pos)
break
if (i not in self.head_pos.keys()):
if (max_line[1] >= 1):
self.head_pos[i] = max_line[0]
print('max_line', i, max_line)
def merge_all(self):
try:
majority_pos = self.majority_color(self.head_pos.values())
for i in range((len(self.img) - 1)):
if (i not in self.head_pos.keys()):
self.head_pos[i] = majority_pos[1]
print(i, ',', majority_pos)
img_width = self.img_width
img_height = 0
for i in self.head_pos.keys():
img_height += (self.head_pos[i] - self.min_head)
img_height += self.img_height
newpic = Image.new(self.img_list[0].mode, (img_width, img_height))
height = 0
if self.min_head:
height += self.min_head
newpic.paste(self.img_list[0].crop((0, 0, img_width, self.min_head)), (0, 0))
for i in range((len(self.img_list) - 1)):
if self.min_head:
newpic.paste(self.img_list[i].crop((0, self.min_head, self.img_width, self.head_pos[i])), (0, height))
height += (self.head_pos[i] - self.min_head)
else:
newpic.paste(self.img_list[i].crop((0, self.min_head, self.img_width, self.head_pos[i])), (0, height))
height += self.head_pos[i]
if self.min_head:
newpic.paste(self.img_list[(- 1)].crop((0, self.min_head, img_width, img_height)), (0, height))
else:
newpic.paste(self.img_list[(- 1)], (0, height))
newpic.save('new.png')
except:
print('error')
def splicing(self, imagePaths=[]):
st = time.process_time()
self.img = imagePaths
self.open_img()
st1 = time.process_time()
self.find_the_same_head_to_remove()
self.find_left_side()
self.find_right_size()
st2 = time.process_time()
self.find_the_pos()
st3 = time.process_time()
self.merge_all()
print((st1 - st))
print((st2 - st1))
print((st3 - st2))
print((time.process_time() - st3))
print(':', (time.process_time() - st)) |
class flip(_coconut_base_callable):
__slots__ = ('func', 'nargs')
def __init__(self, func, nargs=None):
self.func = func
if (nargs is None):
self.nargs = None
else:
self.nargs = _coconut.operator.index(nargs)
if (self.nargs < 0):
raise _coconut.ValueError('flip: nargs cannot be negative')
def __reduce__(self):
return (self.__class__, (self.func, self.nargs))
def __call__(self, *args, **kwargs):
if (self.nargs is None):
return self.func(*args[::(- 1)], **kwargs)
if (self.nargs == 0):
return self.func(*args, **kwargs)
return self.func(*(args[(self.nargs - 1)::(- 1)] + args[self.nargs:]), **kwargs)
def __repr__(self):
return ('flip(%r%s)' % (self.func, ('' if (self.nargs is None) else (', ' + _coconut.repr(self.nargs))))) |
_bad_request
def all_england_price_per_unit_by_presentation(request, bnf_code):
date = _specified_or_last_date(request, 'prescribing')
presentation = get_object_or_404(Presentation, pk=bnf_code)
primary_code = _get_primary_substitutable_bnf_code(bnf_code)
if (bnf_code != primary_code):
url = request.get_full_path().replace(bnf_code, primary_code)
return HttpResponseRedirect(url)
params = {'format': 'json', 'bnf_code': presentation.bnf_code, 'date': date.strftime('%Y-%m-%d')}
bubble_data_url = _build_api_url('bubble', params)
context = {'name': presentation.product_name, 'bnf_code': presentation.bnf_code, 'presentation': presentation, 'dmd_info': presentation.dmd_info(), 'date': date, 'by_presentation': True, 'bubble_data_url': bubble_data_url, 'entity_name': 'NHS England', 'entity_name_and_status': 'NHS England', 'entity_type': 'CCG'}
return render(request, 'price_per_unit.html', context) |
class OFPBucket(StringifyMixin):
def __init__(self, weight=0, watch_port=ofproto.OFPP_ANY, watch_group=ofproto.OFPG_ANY, actions=None, len_=None):
super(OFPBucket, self).__init__()
self.weight = weight
self.watch_port = watch_port
self.watch_group = watch_group
self.actions = actions
def parser(cls, buf, offset):
(len_, weigth, watch_port, watch_group) = struct.unpack_from(ofproto.OFP_BUCKET_PACK_STR, buf, offset)
length = ofproto.OFP_BUCKET_SIZE
offset += ofproto.OFP_BUCKET_SIZE
actions = []
while (length < len_):
action = OFPAction.parser(buf, offset)
actions.append(action)
offset += action.len
length += action.len
m = cls(weigth, watch_port, watch_group, actions)
m.len = len_
return m
def serialize(self, buf, offset):
action_offset = (offset + ofproto.OFP_BUCKET_SIZE)
action_len = 0
for a in self.actions:
a.serialize(buf, action_offset)
action_offset += a.len
action_len += a.len
self.len = utils.round_up((ofproto.OFP_BUCKET_SIZE + action_len), 8)
msg_pack_into(ofproto.OFP_BUCKET_PACK_STR, buf, offset, self.len, self.weight, self.watch_port, self.watch_group) |
class WindowsGoPacketCapturer():
def __init__(self, device, interface):
if (device.device_id() != 'localhost'):
raise XVEx('Packet capture on Windows can currently only be done if the Windows device is thetest orchestrator, i.e. the current device')
self._device = device
self._interface = interface
self._capture_file = 'capture.{}.json'.format(self._interface)
self._popen = None
self._pid = None
def _random_pid_file():
return 'xv_packet_capture_{}.pid'.format(''.join((random.choice(string.ascii_uppercase) for _ in range(10))))
def _get_packets(self):
dst = os.path.join(self._device.temp_directory(), self._capture_file)
timeup = TimeUp(5)
while (not timeup):
if os.path.exists(dst):
break
L.warning('Waiting for capture file to be written: {}'.format(dst))
time.sleep(1)
if (not os.path.exists(dst)):
raise XVEx("Couldn't get capture file from capture device")
return object_from_json_file(dst, 'attribute')['data']
def _find_windows_pid(self):
timeup = TimeUp(5)
while (not timeup):
pids = self._device.pgrep('xv_packet_capture.exe')
L.debug('Found the following PIDs matching xv_packet_capture.exe: {}'.format(pids))
for pid in pids:
cmd_line = self._device.command_line_for_pid(pid)
L.debug('Command line for PID {} was: {}'.format(pid, cmd_line))
for arg in cmd_line:
if (self._capture_file in arg):
return pid
raise XVEx("Couldn't find PID for xv_packet_capture.exe with capture file {}".format(self._capture_file))
def start(self):
L.debug('Starting packet capture on interface {}'.format(self._interface))
if self._popen:
raise XVEx('Packet capture already started!')
binary = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'bin', 'xv_packet_capture.exe')
os.path.join(self._device.temp_directory(), WindowsGoPacketCapturer._random_pid_file())
binary = windows_real_path(binary)
output_directory = windows_real_path(self._device.temp_directory())
cmd = ['cmd.exe', '/c', binary, '-i', str(self._interface), '-o', output_directory, '-f', self._capture_file, '-m', 'windump', '--preserve', '--debug']
stdout = os.path.join(self._device.temp_directory(), '{}.stdout'.format(self._capture_file))
stderr = os.path.join(self._device.temp_directory(), '{}.stderr'.format(self._capture_file))
L.debug('Starting packet capture: {}'.format(cmd))
makedirs_safe(self._device.temp_directory())
with open(stdout, 'w') as out, open(stderr, 'w') as err:
self._popen = subprocess.Popen(cmd, stdout=out, stderr=err)
self._pid = self._find_windows_pid()
def stop(self):
L.debug('Stopping packet capture on interface {} and getting packets'.format(self._interface))
if (not self._popen):
raise XVEx('Packet capture not started!')
old_handler = None
def interrupt_func(_, __):
L.debug('Ignoring interrupt in main process when killing packet capture')
signal.signal(signal.SIGINT, old_handler)
old_handler = signal.signal(signal.SIGINT, interrupt_func)
subprocess.Popen(['windows-kill', '-SIGINT', str(self._pid)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self._pid = None
self._popen.wait()
self._popen = None
return self._get_packets() |
class ACCESS_ALLOWED_OBJECT_ACE(object):
ACE_OBJECT_TYPE_PRESENT = 1
ACE_INHERITED_OBJECT_TYPE_PRESENT = 2
ADS_RIGHT_DS_CONTROL_ACCESS = 256
ADS_RIGHT_DS_CREATE_CHILD = 1
ADS_RIGHT_DS_DELETE_CHILD = 2
ADS_RIGHT_DS_READ_PROP = 16
ADS_RIGHT_DS_WRITE_PROP = 32
ADS_RIGHT_DS_SELF = 8
def __init__(self, fh):
self.fh = fh
self.data = c_secd.ACCESS_ALLOWED_OBJECT_ACE(fh)
self.sid = LdapSid(in_obj=self.data.Sid) |
class SuperFencesCodeExtension(Extension):
def __init__(self, *args, **kwargs):
self.superfences = []
self.config = {'disable_indented_code_blocks': [False, 'Disable indented code blocks - Default: False'], 'custom_fences': [[], 'Specify custom fences. Default: See documentation.'], 'highlight_code': [True, 'Deprecated and does nothing'], 'css_class': ['', "Set class name for wrapper element. The default of CodeHilite or Highlight will be usedif nothing is set. - Default: ''"], 'preserve_tabs': [False, 'Preserve tabs in fences - Default: False']}
super().__init__(*args, **kwargs)
def extend_super_fences(self, name, formatter, validator):
obj = {'name': name, 'test': functools.partial(_test, test_language=name), 'formatter': formatter, 'validator': validator}
if (name == '*'):
self.superfences[0] = obj
else:
self.superfences.append(obj)
def extendMarkdown(self, md):
md.registerExtension(self)
config = self.getConfigs()
self.superfences.insert(0, {'name': 'superfences', 'test': _test, 'formatter': None, 'validator': functools.partial(_validator, validator=highlight_validator)})
custom_fences = config.get('custom_fences', [])
for custom in custom_fences:
name = custom.get('name')
class_name = custom.get('class')
fence_format = custom.get('format', fence_code_format)
validator = custom.get('validator', default_validator)
legacy = False
if ((name is not None) and (class_name is not None)):
sig = signature(validator)
if (len(sig.parameters) == 2):
legacy = True
warnings.warn('Old format of custom validators is deprectated, please migrate to the new format: validator(language, inputs, options, attrs, md)', PymdownxDeprecationWarning)
self.extend_super_fences(name, functools.partial(_formatter, class_name=class_name, _fmt=fence_format), functools.partial(_validator, validator=validator, _legacy=legacy))
self.md = md
self.patch_fenced_rule()
self.stash = CodeStash()
def patch_fenced_rule(self):
config = self.getConfigs()
fenced = SuperFencesBlockPreprocessor(self.md)
fenced.config = config
fenced.extension = self
if (self.superfences[0]['name'] == 'superfences'):
self.superfences[0]['formatter'] = fenced.highlight
self.md.preprocessors.register(fenced, 'fenced_code_block', 25)
indented_code = SuperFencesCodeBlockProcessor(self.md.parser)
indented_code.config = config
indented_code.extension = self
self.md.parser.blockprocessors.register(indented_code, 'code', 80)
if config['preserve_tabs']:
raw_fenced = SuperFencesRawBlockPreprocessor(self.md)
raw_fenced.config = config
raw_fenced.extension = self
self.md.preprocessors.register(raw_fenced, 'fenced_raw_block', 31.05)
self.md.registerExtensions(['pymdownx._bypassnorm'], {})
self.md.registerExtensions(['pymdownx.highlight'], {'pymdownx.highlight': {'_enabled': False}})
def reset(self):
self.stash.clear_stash() |
class OptionSeriesPieSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionSeriesPieSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionSeriesPieSonificationDefaultinstrumentoptionsMappingTremoloDepth)
def speed(self) -> 'OptionSeriesPieSonificationDefaultinstrumentoptionsMappingTremoloSpeed':
return self._config_sub_data('speed', OptionSeriesPieSonificationDefaultinstrumentoptionsMappingTremoloSpeed) |
class OptionSeriesTreegraphStatesHover(Options):
def animation(self) -> 'OptionSeriesTreegraphStatesHoverAnimation':
return self._config_sub_data('animation', OptionSeriesTreegraphStatesHoverAnimation)
def brightness(self):
return self._config_get('undefined')
def brightness(self, num: float):
self._config(num, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def halo(self) -> 'OptionSeriesTreegraphStatesHoverHalo':
return self._config_sub_data('halo', OptionSeriesTreegraphStatesHoverHalo)
def lineWidth(self):
return self._config_get(None)
def lineWidth(self, num: float):
self._config(num, js_type=False)
def lineWidthPlus(self):
return self._config_get(1)
def lineWidthPlus(self, num: float):
self._config(num, js_type=False)
def marker(self) -> 'OptionSeriesTreegraphStatesHoverMarker':
return self._config_sub_data('marker', OptionSeriesTreegraphStatesHoverMarker)
def opacity(self):
return self._config_get(0.75)
def opacity(self, num: float):
self._config(num, js_type=False)
def shadow(self):
return self._config_get(False)
def shadow(self, flag: bool):
self._config(flag, js_type=False) |
def load_test_transaction(test_dir: str, test_file: str, network: str) -> Dict[(str, Any)]:
pure_test_file = os.path.basename(test_file)
test_name = os.path.splitext(pure_test_file)[0]
path = os.path.join(test_dir, test_file)
with open(path, 'r') as fp:
json_data = json.load(fp)[f'{test_name}']
tx_rlp = hex_to_bytes(json_data['txbytes'])
test_result = json_data['result'][network]
return {'tx_rlp': tx_rlp, 'test_result': test_result} |
def set_diagnostic_status(doc):
if doc.get('__islocal'):
return
observations = frappe.db.get_all('Observation', {'sales_invoice': doc.docname, 'docstatus': 0, 'status': ['!=', 'Approved'], 'has_component': 0})
workflow_name = get_workflow_name('Diagnostic Report')
workflow_state_field = get_workflow_state_field(workflow_name)
if (observations and (len(observations) > 0)):
set_status = 'Partially Approved'
else:
set_status = 'Approved'
doc.status = set_status
doc.set(workflow_state_field, set_status) |
def test_missing_count(dbt_project: DbtProject, test_id: str):
missing_values = [None, ' ', 'null', 'NULL']
data = [{COLUMN_NAME: value} for value in (['a', 'b', 'c', ' a '] + missing_values)]
dbt_project.seed(data, test_id)
result = dbt_project.run_query(f"select {{{{ elementary.missing_count('{COLUMN_NAME}') }}}} as missing_count from {{{{ generate_schema_name() }}}}.{test_id}")[0]
assert (result['missing_count'] == len(missing_values)) |
class OptionSeriesLollipopLowmarkerStatesHover(Options):
def animation(self) -> 'OptionSeriesLollipopLowmarkerStatesHoverAnimation':
return self._config_sub_data('animation', OptionSeriesLollipopLowmarkerStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def fillColor(self):
return self._config_get(None)
def fillColor(self, text: str):
self._config(text, js_type=False)
def lineColor(self):
return self._config_get(None)
def lineColor(self, text: str):
self._config(text, js_type=False)
def lineWidth(self):
return self._config_get(None)
def lineWidth(self, num: float):
self._config(num, js_type=False)
def lineWidthPlus(self):
return self._config_get(1)
def lineWidthPlus(self, num: float):
self._config(num, js_type=False)
def radius(self):
return self._config_get(None)
def radius(self, num: float):
self._config(num, js_type=False)
def radiusPlus(self):
return self._config_get(2)
def radiusPlus(self, num: float):
self._config(num, js_type=False) |
def upgrade():
op.execute('alter type messagingservicetype rename to messagingservicetype_old')
op.alter_column('messagingconfig', 'service_type', new_column_name='service_type_old')
op.execute('alter table messagingconfig alter column service_type_old type messagingservicetype_old using service_type_old::text::messagingservicetype_old')
messagingservicetype = postgresql.ENUM('mailgun', 'twilio_text', 'twilio_email', 'mailchimp_transactional', name='messagingservicetype', create_type=True)
messagingservicetype.create(op.get_bind())
op.add_column('messagingconfig', sa.Column('service_type', messagingservicetype, nullable=True, unique=True))
session = Session(bind=op.get_bind())
conn = session.connection()
statement = text('SELECT distinct LOWER(service_type_old::text) AS lower_service_type_old, id\nFROM messagingconfig')
result = conn.execute(statement)
for row in result:
op.execute(f"UPDATE messagingconfig SET service_type = '{row[0]}' WHERE id = '{row[1]}';")
op.alter_column('messagingconfig', 'service_type', nullable=False)
op.drop_column('messagingconfig', 'service_type_old')
op.execute('drop type messagingservicetype_old') |
class Device():
CHECK_MARK = ''
def __init__(self, cast_info_or_none=None):
self.__device = cast_info_or_none
self.is_cast_info = isinstance(self.__device, CastInfo)
def id(self):
return (str(self.__device.uuid) if isinstance(self.__device, CastInfo) else None)
def LOCAL_DEVICE(cls):
return t('Local device')
def name(self):
if self.is_cast_info:
return self.__device.friendly_name
return self.LOCAL_DEVICE()
def as_tray_name(self, active_id):
if (active_id == self.id):
return f'{self.CHECK_MARK} {self.name}'
return f' {self.name}'
def tray_key(self):
return (f'device:{self.id}' if self.is_cast_info else 'device:0')
def gui_key(self):
return (f'device::{self.id}' if self.is_cast_info else 'device::0')
def as_tray_item(self, active_id) -> tuple:
return (self.as_tray_name(active_id), self.tray_key)
def __eq__(self, other):
return (self.id == other.id)
def __str__(self):
return self.name
def __repr__(self):
return f'Device(id={self.id}, name={self.name})' |
class TestApiView(QuartAppTestCase):
async def test_valid_raw(self):
content = b'test valid api view content'
paste_id = (await write_test_paste(content))
client = self.new_client()
response = (await client.get(f'/api/pastes/{paste_id}'))
data = (await response.get_data(as_text=False))
self.assertEqual(content, data)
async def test_valid_meta(self):
content = b'test valid api view meta'
paste_id = (await write_test_paste(content))
client = self.new_client()
response = (await client.get(f'/api/pastes/{paste_id}/meta'))
data = (await response.get_data(as_text=True))
self.assertIn(paste_id, data)
async def test_invalid_not_found(self):
paste_id = 'testing123'
routes = (f'/api/pastes/{paste_id}', f'/api/pastes/{paste_id}/meta', f'/api/pastes/{paste_id}/content')
for route in routes:
with self.subTest():
client = self.new_client()
response = (await client.get(route))
self.assertEqual(404, response.status_code)
async def test_invalid_too_short(self):
paste_id = '1'
routes = (f'/api/pastes/{paste_id}', f'/api/pastes/{paste_id}/meta', f'/api/pastes/{paste_id}/content')
for route in routes:
with self.subTest():
client = self.new_client()
response = (await client.get(route))
self.assertEqual(404, response.status_code) |
class Commit(base_tests.SimpleProtocol):
def runTest(self):
request = ofp.message.bundle_ctrl_msg(bundle_ctrl_type=ofp.OFPBCT_OPEN_REQUEST, bundle_id=1)
(response, _) = self.controller.transact(request)
self.assertIsInstance(response, ofp.message.bundle_ctrl_msg)
self.assertEqual(response.bundle_ctrl_type, ofp.OFPBCT_OPEN_REPLY)
self.assertEqual(response.bundle_id, 1)
for i in xrange(0, 10):
request = ofp.message.bundle_add_msg(xid=i, bundle_id=1, data=ofp.message.echo_request(xid=i).pack())
self.controller.message_send(request)
(msg, _) = self.controller.poll(ofp.message.echo_reply)
self.assertIsNone(msg)
request = ofp.message.bundle_ctrl_msg(bundle_ctrl_type=ofp.OFPBCT_COMMIT_REQUEST, bundle_id=1)
(response, _) = self.controller.transact(request)
self.assertIsInstance(response, ofp.message.bundle_ctrl_msg)
self.assertEqual(response.bundle_ctrl_type, ofp.OFPBCT_COMMIT_REPLY)
self.assertEqual(response.bundle_id, 1)
for i in xrange(0, 10):
(response, _) = self.controller.poll(ofp.message.echo_reply)
self.assertIsNotNone(response)
self.assertEquals(response.xid, i) |
.compilertest
def test_lightstep_not_supported(tmp_path: Path):
yaml = '\n---\napiVersion: getambassador.io/v3alpha1\nkind: TracingService\nmetadata:\n name: tracing\n namespace: ambassador\nspec:\n service: lightstep:80\n driver: lightstep\n custom_tags:\n - tag: ltag\n literal:\n value: avalue\n - tag: etag\n environment:\n name: UNKNOWN_ENV_VAR\n default_value: efallback\n - tag: htag\n request_header:\n name: x-does-not-exist\n default_value: hfallback\n config:\n access_token_file: /lightstep-credentials/access-token\n propagation_modes: ["ENVOY", "TRACE_CONTEXT"]\n'
econf = _get_envoy_config(yaml)
assert ('ir.tracing' in econf.ir.aconf.errors)
tracing_error = econf.ir.aconf.errors['ir.tracing'][0]['error']
assert ("'lightstep' driver is no longer supported" in tracing_error)
(bootstrap_config, _, _) = econf.split_config()
assert ('tracing' not in bootstrap_config) |
class TestCompose(BasePyTestCase):
def _generate_compose(self, request, security):
uid = uuid.uuid4()
release = model.Release(name='F27-{}'.format(uid), long_name='Fedora 27 {}'.format(uid), id_prefix='FEDORA', version='27', dist_tag='f27', stable_tag='f27-updates', testing_tag='f27-updates-testing', candidate_tag='f27-updates-candidate', pending_signing_tag='f27-updates-testing-signing', pending_testing_tag='f27-updates-testing-pending', pending_stable_tag='f27-updates-pending', override_tag='f27-override', state=ReleaseState.current, branch='f27-{}'.format(uid))
self.db.add(release)
update = self.create_update(['bodhi-{}-1.fc27'.format(uuid.uuid4())])
update.release = release
update.request = request
update.locked = True
if security:
update.type = model.UpdateType.security
compose = model.Compose(request=request, release=update.release)
self.db.add(compose)
self.db.flush()
return compose
def test_content_type_no_updates(self):
compose = self._generate_compose(model.UpdateRequest.stable, False)
compose.updates[0].locked = False
self.db.flush()
self.db.refresh(compose)
assert (compose.content_type is None)
def test_content_type_with_updates(self):
compose = self._generate_compose(model.UpdateRequest.stable, False)
assert (compose.content_type == model.ContentType.rpm)
def test_from_dict(self):
compose = self._generate_compose(model.UpdateRequest.stable, False)
reloaded_compose = model.Compose.from_dict(self.db, compose.__json__())
assert (reloaded_compose.request == compose.request)
assert (reloaded_compose.release == compose.release)
def test_from_updates(self):
update_1 = self.create_update(['bodhi-{}-1.fc27'.format(uuid.uuid4())])
update_2 = self.create_update(['bodhi-{}-1.fc27'.format(uuid.uuid4())])
update_2.request = None
release = model.Release(name='F27', long_name='Fedora 27', id_prefix='FEDORA', version='27', dist_tag='f27', stable_tag='f27-updates', testing_tag='f27-updates-testing', candidate_tag='f27-updates-candidate', pending_signing_tag='f27-updates-testing-signing', pending_testing_tag='f27-updates-testing-pending', pending_stable_tag='f27-updates-pending', override_tag='f27-override', state=ReleaseState.current, branch='f27')
self.db.add(release)
update_3 = self.create_update(['bodhi-{}-1.fc27'.format(uuid.uuid4())])
update_3.release = release
update_3.type = model.UpdateType.security
update_4 = self.create_update(['bodhi-{}-1.fc27'.format(uuid.uuid4())])
update_4.status = model.UpdateStatus.testing
update_4.request = model.UpdateRequest.stable
composes = model.Compose.from_updates([update_1, update_2, update_3, update_4])
assert isinstance(composes, list)
for c in composes:
self.db.add(c)
self.db.flush()
self.db.refresh(c)
composes = sorted(composes)
assert (len(composes) == 3)
def assert_compose_has_update(compose, update):
assert (compose.updates == [update])
assert (compose.release == update.release)
assert (compose.request == update.request)
assert_compose_has_update(composes[0], update_3)
assert_compose_has_update(composes[1], update_4)
assert_compose_has_update(composes[2], update_1)
def test_from_updates_no_builds(self):
update = self.create_update(['bodhi-{}-1.fc27'.format(uuid.uuid4())])
update.builds = []
composes = model.Compose.from_updates([update])
assert isinstance(composes, list)
assert (len(composes) == 0)
def test_security_false(self):
compose = self._generate_compose(model.UpdateRequest.stable, False)
assert (not compose.security)
def test_security_true(self):
compose = self._generate_compose(model.UpdateRequest.stable, True)
assert compose.security
def test_update_state_date(self):
compose = self._generate_compose(model.UpdateRequest.stable, True)
before = datetime.utcnow()
compose.state = model.ComposeState.notifying
assert (compose.state_date > before)
assert (datetime.utcnow() > compose.state_date)
def test_update_summary(self):
compose = self._generate_compose(model.UpdateRequest.stable, True)
update = compose.updates[0]
assert (compose.update_summary == [{'alias': update.alias, 'title': update.get_title(nvr=True, beautify=True)}])
def test___json___composer_flag(self):
compose = self._generate_compose(model.UpdateRequest.stable, True)
normal_json = compose.__json__()
j = compose.__json__(composer=True)
assert set(j.keys()), {'security', 'release_id', ('request' == 'content_type')}
for k in (set(normal_json.keys()) - set(j.keys())):
del normal_json[k]
assert (j == normal_json)
def test___lt___false_fallthrough(self):
compose_1 = self._generate_compose(model.UpdateRequest.stable, True)
compose_2 = self._generate_compose(model.UpdateRequest.stable, True)
assert (not (compose_1 < compose_2))
assert (not (compose_2 < compose_1))
assert (not (compose_1 > compose_2))
assert (not (compose_2 > compose_1))
def test___lt___security_prioritized(self):
compose_1 = self._generate_compose(model.UpdateRequest.testing, True)
compose_2 = self._generate_compose(model.UpdateRequest.testing, False)
assert (compose_1 < compose_2)
assert (not (compose_2 < compose_1))
assert (not (compose_1 > compose_2))
assert (compose_2 > compose_1)
assert (sorted([compose_1, compose_2]) == [compose_1, compose_2])
def test___lt___security_prioritized_over_stable(self):
compose_1 = self._generate_compose(model.UpdateRequest.testing, True)
compose_2 = self._generate_compose(model.UpdateRequest.stable, False)
assert (compose_1 < compose_2)
assert (not (compose_2 < compose_1))
assert (not (compose_1 > compose_2))
assert (compose_2 > compose_1)
assert (sorted([compose_1, compose_2]) == [compose_1, compose_2])
def test___lt___stable_prioritized(self):
compose_1 = self._generate_compose(model.UpdateRequest.testing, False)
compose_2 = self._generate_compose(model.UpdateRequest.stable, False)
assert (not (compose_1 < compose_2))
assert (compose_2 < compose_1)
assert (compose_1 > compose_2)
assert (not (compose_2 > compose_1))
assert (sorted([compose_1, compose_2]) == [compose_2, compose_1])
def test___str__(self):
compose = self._generate_compose(model.UpdateRequest.stable, False)
assert (str(compose) == '<Compose: {} stable>'.format(compose.release.name)) |
_meta(inputlets.ActionInputlet)
class ActionInputlet():
_disp_func
def passive_action_disp(self, ilet, skills, rawcards, params, players):
me = self.me
usage = getattr(ilet.initiator, 'card_usage', 'none')
if skills:
if any(((not me.has_skill(s)) for s in skills)):
raise ActionDisplayResult(False, '', False, [], [])
cards = [actions.skill_wrap(me, skills, rawcards, params)]
usage = (cards[0].usage if (usage == 'launch') else usage)
else:
cards = rawcards
(cards, prompt_card) = self.pasv_handle_card_selection(ilet, cards)
(plsel, disables, players, prompt_target) = self.pasv_handle_player_selection(ilet, players)
verify = getattr(ilet.initiator, 'ask_for_action_verify', None)
rst = ((not verify) or verify(me, cards, players))
if (not rst):
raise ActionDisplayResult(False, rst.ui_meta.shootdown_message, plsel, disables, players)
raise ActionDisplayResult(True, (prompt_target or prompt_card), plsel, disables, players)
def pasv_handle_card_selection(self, ilet, cards):
g = self.game
if (not ilet.categories):
return ([], '')
if cards:
walk_wrapped(g, cards, True)
from thb.cards.base import Skill
if (cards[0].is_card(Skill) and (not actions.skill_check(cards[0]))):
raise ActionDisplayResult(False, '', False, [], [])
c = ilet.initiator.cond(cards)
(c1, text) = ilet.initiator.ui_meta.choose_card_text(ilet.initiator, cards)
assert (c == c1), ('cond = %s, meta = %s' % (c, c1))
if (not c):
raise ActionDisplayResult(False, text, False, [], [])
return (cards, text)
def pasv_handle_player_selection(self, ilet, players):
g = self.game
if (not ilet.candidates):
return (False, [], [], '')
disables = [p for p in g.players if (p not in ilet.candidates)]
players = [p for p in players if (p not in disables)]
(players, logic_valid) = ilet.initiator.choose_player_target(players)
try:
(ui_meta_valid, reason) = ilet.initiator.ui_meta.target(players)
assert (bool(logic_valid) == bool(ui_meta_valid)), ('logic: %s, ui: %s' % (logic_valid, ui_meta_valid))
except Exception:
log.exception('act.ui_meta.target error')
raise ActionDisplayResult(False, '[act.ui_meta.target ]', bool(ilet.candidates), disables, players)
if (not logic_valid):
raise ActionDisplayResult(False, reason, True, disables, players)
return (True, disables, players, reason)
def passive_action_recommend(self, ilet):
if (not ilet.categories):
return
me = self.me
for c in me.showncards:
if (not ilet.initiator.cond([c])):
continue
return view.card(c)
for c in me.cards:
if (not ilet.initiator.cond([c])):
continue
return view.card(c)
def get_selectable_cards(self, ilet, for_skill):
cards = []
actor = ilet.actor
if for_skill:
cards += actor.cards
cards += actor.showncards
cards += actor.equips
else:
for cat in ilet.categories:
cards += getattr(actor, cat)
return [view.card(c) for c in cards]
_disp_func
def active_action_disp(self, ilet, skills, rawcards, params, players):
me = self.me
stage = ilet.initiator
if ((not skills) and (not rawcards)):
raise ActionDisplayResult(False, stage.ui_meta.idle_prompt, False, [], [])
usage = getattr(ilet.initiator, 'card_usage', 'none')
if skills:
if any(((not me.has_skill(s)) for s in skills)):
raise ActionDisplayResult(False, '', False, [], [])
cards = [actions.skill_wrap(me, skills, rawcards, params)]
usage = (cards[0].usage if (usage == 'launch') else usage)
else:
cards = rawcards
card = self.actv_handle_card_selection(stage, cards)
(players, disables, prompt) = self.actv_handle_target_selection(stage, card, players)
act = stage.launch_card_cls(me, players, card)
shootdown = act.action_shootdown()
if (shootdown is not None):
raise ActionDisplayResult(False, shootdown.ui_meta.shootdown_message, True, disables, players)
raise ActionDisplayResult(True, prompt, True, disables, players)
def actv_handle_card_selection(self, act, cards):
g = self.game
if (len(cards) != 1):
raise ActionDisplayResult(False, '', False, [], [])
walk_wrapped(g, cards, False)
card = cards[0]
c = act.cond(cards)
(c1, text) = act.ui_meta.choose_card_text(act, cards)
assert (c == c1), ('cond = %s, meta = %s' % (c, c1))
if (not c):
raise ActionDisplayResult(False, text, False, [], [])
return card
def actv_handle_target_selection(self, stage: BaseActionStage, card: Card, players: Sequence[Character]):
plsel = False
selected: List[Character] = []
disables: List[Character] = []
g = self.game
me = self.me
(tl, tl_valid) = card.target(me, players)
if (tl is not None):
selected = list(tl)
if (card.target.__name__.split('.')[(- 1)] in ('t_One', 't_OtherOne')):
for p in g.players:
act = stage.launch_card_cls(me, [p], card)
shootdown = act.action_shootdown()
if (shootdown is not None):
if shootdown.ui_meta.target_independent:
reason = shootdown.ui_meta.shootdown_message
raise ActionDisplayResult(False, reason, False, [], [])
disables.append(p)
plsel = True
for i in disables:
try:
tl.remove(i)
except ValueError:
pass
try:
(rst, reason) = card.ui_meta.is_action_valid(card, tl)
except Exception:
log.exception('card.ui_meta.is_action_valid error')
raise ActionDisplayResult(False, '[card.ui_meta.is_action_valid ]', False, [], [])
if (not rst):
raise ActionDisplayResult(False, reason, plsel, disables, selected)
if (not tl_valid):
raise ActionDisplayResult(False, '', plsel, disables, selected)
return (tl, disables, reason)
def handle_reject_autoresponse(self, trans, ilet):
from thb.actions import ForEach
from thb.cards.definition import RejectCard
act = ilet.initiator.target_act
if (not RejectCard.ui_meta.has_reject_card(ilet.actor)):
return {'cancel': True, 'no_reject_card': True}
pact = ForEach.get_actual_action(act)
if ((pact is not None) and pact._.get('__dont_care')):
return {'cancel': True, 'dont_care_clicked': True}
return {'has_dont_care': (pact is not None)}
def set_reject_dontcare(self, trans, ilet):
from thb.actions import ForEach
act = ilet.initiator.target_act
pact = ForEach.get_actual_action(act)
if (pact is not None):
pact._['__dont_care'] = True |
def cmd_wait(jobs: Jobs, reqid: Optional[RequestID]=None) -> None:
try:
try:
(job, pid) = jobs.wait_until_job_started(reqid)
except NoRunningJobError:
logger.error('no current request to wait for')
sys.exit(1)
except JobAlreadyFinishedError as exc:
logger.warning(f'job {exc.reqid} was already done')
else:
assert pid, (job and job.reqid)
job.wait_until_finished(pid)
except JobNeverStartedError:
logger.warning('job not started')
except JobFinishedError:
pass |
class ScrubberDemo(HasTraits):
simple_integer = Range(0, 100)
rollover_float = Range((- 10.0), 10.0)
bordered_unbounded = Float()
dynamic_low = Range(high=(- 0.01), value=(- 10.0))
dynamic_high = Range(low=0.01, value=10.0)
dynamic_value = Range('dynamic_low', 'dynamic_high', 0.0)
view = View(HGroup(VGroup(Item('simple_integer', editor=ScrubberEditor()), Item('rollover_float', editor=ScrubberEditor(hover_color=, active_color=)), Item('bordered_unbounded', editor=ScrubberEditor(hover_color=, active_color=, border_color=8421504)), Item('dynamic_low', editor=ScrubberEditor()), Item('dynamic_high', editor=ScrubberEditor()), Item('dynamic_value', editor=ScrubberEditor()), show_border=True, label='Scrubber Editors'), VGroup(Item('simple_integer'), Item('rollover_float'), Item('bordered_unbounded'), Item('dynamic_low'), Item('dynamic_high'), Item('dynamic_value'), show_border=True, label='Default Editors'), spring), title='Scrubber Editor Demo') |
class LifeCycle():
def on_init(self):
pass
async def async_on_init(self):
pass
def before_start(self):
pass
async def async_before_start(self):
pass
def after_start(self):
pass
async def async_after_start(self):
pass
def before_stop(self):
pass
async def async_before_stop(self):
pass |
class TestHasTraitsPropertyObserves(unittest.TestCase):
def setUp(self):
push_exception_handler(reraise_exceptions=True)
self.addCleanup(pop_exception_handler)
def test_property_observe_extended_trait(self):
instance_observe = ClassWithPropertyObservesDefault()
handler_observe = mock.Mock()
instance_observe.observe(handler_observe, 'extended_age')
instance_depends_on = ClassWithPropertyDependsOnDefault()
handler_otc = mock.Mock()
instance_depends_on.on_trait_change(get_otc_handler(handler_otc), 'extended_age')
instances = [instance_observe, instance_depends_on]
handlers = [handler_observe, handler_otc]
for (instance, handler) in zip(instances, handlers):
with self.subTest(instance=instance, handler=handler):
instance.info_with_default.age = 70
self.assertEqual(handler.call_count, 1)
self.assertEqual(instance.extended_age_n_calculations, 1)
def test_property_observe_does_not_fire_default(self):
instance_observe = ClassWithPropertyObservesDefault()
handler_observe = mock.Mock()
instance_observe.observe(handler_observe, 'extended_age')
instance_depends_on = ClassWithPropertyDependsOnDefault()
instance_depends_on.on_trait_change(get_otc_handler(mock.Mock()), 'extended_age')
self.assertFalse(instance_observe.info_with_default_computed)
self.assertTrue(instance_depends_on.info_with_default_computed)
def test_property_multi_observe(self):
instance_observe = ClassWithPropertyMultipleObserves()
handler_observe = mock.Mock()
instance_observe.observe(handler_observe, 'computed_value')
self.assertEqual(instance_observe.computed_value_n_calculations, 0)
instance_depends_on = ClassWithPropertyMultipleDependsOn()
instance_depends_on.on_trait_change(get_otc_handler(mock.Mock()), 'computed_value')
self.assertEqual(instance_depends_on.computed_value_n_calculations, 0)
for instance in [instance_observe, instance_depends_on]:
with self.subTest(instance=instance):
instance.age = 1
self.assertEqual(instance.computed_value_n_calculations, 1)
instance.gender = 'male'
self.assertEqual(instance.computed_value_n_calculations, 2)
def test_property_observe_container(self):
instance_observe = ClassWithPropertyObservesItems()
handler_observe = mock.Mock()
instance_observe.observe(handler_observe, 'discounted')
instance_depends_on = ClassWithPropertyDependsOnItems()
instance_depends_on.on_trait_change(get_otc_handler(mock.Mock()), 'discounted')
for instance in [instance_observe, instance_depends_on]:
with self.subTest(instance=instance):
self.assertEqual(instance.discounted_n_calculations, 0)
instance.list_of_infos.append(PersonInfo(age=30))
self.assertEqual(instance.discounted_n_calculations, 1)
instance.list_of_infos[(- 1)].age = 80
self.assertEqual(instance.discounted_n_calculations, 2)
def test_property_old_value_uncached(self):
instance = ClassWithPropertyMultipleObserves()
handler = mock.Mock()
instance.observe(handler, 'computed_value')
instance.age = 1
(((event,), _),) = handler.call_args_list
self.assertIs(event.object, instance)
self.assertEqual(event.name, 'computed_value')
self.assertIs(event.old, Undefined)
self.assertIs(event.new, 1)
handler.reset_mock()
instance.gender = 'male'
(((event,), _),) = handler.call_args_list
self.assertIs(event.object, instance)
self.assertEqual(event.name, 'computed_value')
self.assertIs(event.old, Undefined)
self.assertIs(event.new, 5)
def test_property_with_cache(self):
instance = ClassWithPropertyObservesWithCache()
handler = mock.Mock()
instance.observe(handler, 'discounted')
instance.age = 1
((event,), _) = handler.call_args_list[(- 1)]
self.assertIs(event.object, instance)
self.assertEqual(event.name, 'discounted')
self.assertIs(event.old, Undefined)
self.assertIs(event.new, False)
handler.reset_mock()
instance.age = 80
((event,), _) = handler.call_args_list[(- 1)]
self.assertIs(event.object, instance)
self.assertEqual(event.name, 'discounted')
self.assertIs(event.old, False)
self.assertIs(event.new, True)
def test_property_default_initializer_with_value_in_init(self):
with self.assertRaises(AttributeError):
ClassWithPropertyDependsOnInit(info_without_default=PersonInfo(age=30))
instance = ClassWithPropertyObservesInit(info_without_default=PersonInfo(age=30))
handler = mock.Mock()
instance.observe(handler, 'extended_age')
self.assertFalse(instance.sample_info_default_computed)
self.assertEqual(instance.sample_info.age, 30)
self.assertEqual(instance.extended_age, 30)
self.assertEqual(handler.call_count, 0)
instance.sample_info.age = 40
self.assertEqual(handler.call_count, 1)
instance_no_property = ClassWithInstanceDefaultInit(info_without_default=PersonInfo(age=30))
self.assertFalse(instance_no_property.sample_info_default_computed)
self.assertEqual(instance_no_property.sample_info.age, 30)
def test_property_decorated_observer(self):
instance_observe = ClassWithPropertyObservesDecorated(age=30)
instance_depends_on = ClassWithPropertyDependsOnDecorated(age=30)
for instance in [instance_observe, instance_depends_on]:
with self.subTest(instance=instance):
self.assertEqual(len(instance.discounted_events), 1)
def test_garbage_collectable(self):
instance = ClassWithPropertyObservesDefault()
instance_ref = weakref.ref(instance)
del instance
self.assertIsNone(instance_ref())
def test_property_with_no_getter(self):
instance = ClassWithPropertyMissingGetter()
try:
instance.age += 1
except Exception:
self.fail('Having property with undefined getter/setter should not prevent the observed traits from being changed.')
def test_property_with_missing_dependent(self):
instance = ClassWithPropertyTraitNotFound()
with self.assertRaises(ValueError) as exception_context:
instance.person = PersonInfo()
self.assertIn("Trait named 'last_name' not found", str(exception_context.exception))
def test_pickle_has_traits_with_property_observe(self):
instance = ClassWithPropertyMultipleObserves()
for protocol in range((pickle.HIGHEST_PROTOCOL + 1)):
serialized = pickle.dumps(instance, protocol=protocol)
deserialized = pickle.loads(serialized)
handler = mock.Mock()
deserialized.observe(handler, 'computed_value')
deserialized.age = 1
self.assertEqual(handler.call_count, 1) |
def extractMjnovelsBlogspotCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap:
if (tagname in item['tags']):
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
class FlicketDepartment(PaginatedAPIMixin, Base):
__tablename__ = 'flicket_department'
id = db.Column(db.Integer, primary_key=True)
department = db.Column(db.String(field_size['department_max_length']))
categories = db.relationship('FlicketCategory', back_populates='department')
def __init__(self, department):
self.department = department
def to_dict(self):
data = {'id': self.id, 'department': self.department, 'links': {'self': (app.config['base_url'] + url_for('bp_api.get_department', id=self.id)), 'departments': (app.config['base_url'] + url_for('bp_api.get_departments'))}}
return data
def __repr__(self):
return '<FlicketDepartment: id={}, department={}>'.format(self.id, self.department) |
class GetBlockHeadersV65(BaseCommand[BlockHeadersQuery]):
protocol_command_id = 3
serialization_codec: RLPCodec[BlockHeadersQuery] = RLPCodec(sedes=sedes.List((HashOrNumber(), sedes.big_endian_int, sedes.big_endian_int, sedes.boolean)), process_inbound_payload_fn=(lambda args: BlockHeadersQuery(*args))) |
def test_that_having_no_refcase_but_history_observations_causes_exception(tmpdir):
with tmpdir.as_cwd():
config = dedent('\n ECLBASE my_name%d\n NUM_REALIZATIONS 10\n OBS_CONFIG observations\n ')
with open('config.ert', 'w', encoding='utf-8') as fh:
fh.writelines(config)
with open('observations', 'w', encoding='utf-8') as fo:
fo.writelines('HISTORY_OBSERVATION FOPR;')
with open('time_map.txt', 'w', encoding='utf-8') as fo:
fo.writelines('2023-02-01')
with pytest.raises(expected_exception=ObservationConfigError, match='Missing REFCASE or TIME_MAP'):
ErtConfig.from_file('config.ert') |
def run():
print('\nmodule top(input clk, stb, di, output do);\n localparam integer DIN_N = 8;\n localparam integer DOUT_N = 8;\n\n reg [DIN_N-1:0] din;\n wire [DOUT_N-1:0] dout;\n\n reg [DIN_N-1:0] din_shr;\n reg [DOUT_N-1:0] dout_shr;\n\n always (posedge clk) begin\n din_shr <= {din_shr, di};\n dout_shr <= {dout_shr, din_shr[DIN_N-1]};\n if (stb) begin\n din <= din_shr;\n dout_shr <= dout;\n end\n end\n\n assign do = dout_shr[DOUT_N-1];\n ')
params = {}
database = os.getenv('XRAY_DATABASE')
int_tile = os.getenv('XRAY_PS7_INT')
assert (database == 'zynq7'), database
for isone in util.gen_fuzz_states(1):
params[int_tile] = isone
print(('\n (* KEEP, DONT_TOUCH *)\n\n PS7 dut_%(dut)s(\n\t.DMA0DATYPE\t\t\t(),\n\t.DMA0DAVALID\t\t\t(),\n\t.DMA0DRREADY\t\t\t(),\n\t.DMA0RSTN\t\t\t(),\n\t.DMA1DATYPE\t \t(),\n\t.DMA1DAVALID\t\t\t(),\n\t.DMA1DRREADY\t\t\t(),\n\t.DMA1RSTN\t\t\t(),\n\t.DMA2DATYPE\t\t\t(),\n\t.DMA2DAVALID\t\t\t(),\n\t.DMA2DRREADY\t\t\t(),\n\t.DMA2RSTN\t\t\t(),\n\t.DMA3DATYPE\t\t\t(),\n\t.DMA3DAVALID\t\t\t(),\n\t.DMA3DRREADY\t\t\t(),\n\t.DMA3RSTN\t\t\t(),\n\t.EMIOCAN0PHYTX\t\t\t(),\n\t.EMIOCAN1PHYTX\t\t\t(),\n\t.EMIOENET0GMIITXD\t\t(),\n\t.EMIOENET0GMIITXEN\t\t(),\n\t.EMIOENET0GMIITXER\t\t(),\n\t.EMIOENET0MDIOMDC\t\t(),\n\t.EMIOENET0MDIOO\t\t\t(),\n\t.EMIOENET0MDIOTN\t\t(),\n\t.EMIOENET0PTPDELAYREQRX\t\t(),\n\t.EMIOENET0PTPDELAYREQTX\t\t(),\n\t.EMIOENET0PTPPDELAYREQRX\t(),\n\t.EMIOENET0PTPPDELAYREQTX\t(),\n\t.EMIOENET0PTPPDELAYRESPRX\t(),\n\t.EMIOENET0PTPPDELAYRESPTX\t(),\n\t.EMIOENET0PTPSYNCFRAMERX\t(),\n\t.EMIOENET0PTPSYNCFR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XIGP1ARQOS\t\t\t(),\n\t.MAXIGP1ARSIZE\t\t\t(),\n\t.MAXIGP1ARVALID\t\t\t(),\n\t.MAXIGP1AWADDR\t\t\t(),\n\t.MAXIGP1AWBURST\t\t\t(),\n\t.MAXIGP1AWCACHE\t\t\t(),\n\t.MAXIGP1AWID\t\t\t(),\n\t.MAXIGP1AWLEN\t\t\t(),\n\t.MAXIGP1AWLOCK\t\t\t(),\n\t.MAXIGP1AWPROT\t\t\t(),\n\t.MAXIGP1AWQOS\t\t\t(),\n\t.MAXIGP1AWSIZE\t\t\t(),\n\t.MAXIGP1AWVALID\t\t\t(),\n\t.MAXIGP1BREADY\t\t\t(),\n\t.MAXIGP1RREADY\t\t\t(),\n\t.MAXIGP1WDATA\t\t\t(),\n\t.MAXIGP1WID\t\t\t(),\n\t.MAXIGP1WLAST\t\t\t(),\n\t.MAXIGP1WSTRB\t\t\t(),\n\t.MAXIGP1WVALID\t\t\t(),\n\t.SAXIACPARESETN\t\t\t(),\n\t.SAXIACPARREADY\t\t\t(),\n\t.SAXIACPAWREADY\t\t\t(),\n\t.SAXIACPBID\t\t\t(),\n\t.SAXIACPBRESP\t\t\t(),\n\t.SAXIACPBVALID\t\t\t(),\n\t.SAXIACPRDATA\t\t\t(),\n\t.SAXIACPRID\t\t\t(),\n\t.SAXIACPRLAST\t\t\t(),\n\t.SAXIACPRRESP\t\t\t(),\n\t.SAXIACPRVALID\t\t\t(),\n\t.SAXIACPWREADY\t\t\t(),\n\t.SAXIGP0ARESETN\t\t\t(),\n\t.SAXIGP0ARREADY\t\t\t(),\n\t.SAXIGP0AWREADY\t\t\t(),\n\t.SAXIGP0BID\t\t\t(),\n\t.SAXIGP0BRESP\t\t\t(),\n\t.SAXIGP0BVALID\t\t\t(),\n\t.SAXIGP0RDATA\t\t\t(),\n\t.SAXIGP0RID\t\t\t(),\n\t.SAXIGP0RLAST\t\t\t(),\n\t.SAXIGP0RRESP\t\t\t(),\n\t.SAXIGP0RVALID\t\t\t(),\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UART0RIN\t\t\t(),\n\t.EMIOUART0RX\t\t\t(),\n\t.EMIOUART1CTSN\t\t\t(),\n\t.EMIOUART1DCDN\t\t\t(),\n\t.EMIOUART1DSRN\t\t\t(),\n\t.EMIOUART1RIN\t\t\t(),\n\t.EMIOUART1RX\t\t\t(),\n\t.EMIOUSB0VBUSPWRFAULT\t\t(),\n\t.EMIOUSB1VBUSPWRFAULT\t\t(),\n\t.EMIOWDTCLKI\t\t\t(),\n\t.EVENTEVENTI\t\t\t(),\n\t.FCLKCLKTRIGN\t\t\t(),\n\t.FPGAIDLEN\t\t\t(),\n\t.FTMDTRACEINATID\t\t(),\n\t.FTMDTRACEINCLOCK\t\t(),\n\t.FTMDTRACEINDATA\t\t(),\n\t.FTMDTRACEINVALID\t\t(),\n\t.FTMTF2PDEBUG\t\t\t(),\n\t.FTMTF2PTRIG\t\t\t(),\n\t.FTMTP2FTRIGACK\t\t\t(),\n\t.IRQF2P\t\t\t\t(),\n\t.MAXIGP0ACLK\t\t\t(),\n\t.MAXIGP0ARREADY\t\t\t(),\n\t.MAXIGP0AWREADY\t\t\t(),\n\t.MAXIGP0BID\t\t\t(),\n\t.MAXIGP0BRESP\t\t\t(),\n\t.MAXIGP0BVALID\t\t\t(),\n\t.MAXIGP0RDATA\t\t\t(),\n\t.MAXIGP0RID\t\t\t(),\n\t.MAXIGP0RLAST\t\t\t(),\n\t.MAXIGP0RRESP\t\t\t(),\n\t.MAXIGP0RVALID\t\t\t(),\n\t.MAXIGP0WREADY\t\t\t(),\n\t.MAXIGP1ACLK\t\t\t(),\n\t.MAXIGP1ARREADY\t\t\t(),\n\t.MAXIGP1AWREADY\t\t\t(),\n\t.MAXIGP1BID\t\t\t(),\n\t.MAXIGP1BRESP\t\t\t(),\n\t.MAXIGP1BVALID\t\t\t(),\n\t.MAXIGP1RDATA\t\t\t(),\n\t.MAXIGP1RID\t\t\t(),\n\t.MAXIGP1RLAST\t\t\t(),\n\t.MAXIGP1RRESP\t\t\t(),\n\t.MAXIGP1RVALID\t\t\t(),\n\t.MAXIGP1WREADY\t\t\t(),\n\t.SAXIACPACLK\t\t\t(),\n\t.SAXIACPARADDR\t\t\t(),\n\t.SAXIACPARBURST\t\t\t(),\n\t.SAXIACPARCACHE\t\t\t(),\n\t.SAXIACPARID\t\t\t(),\n\t.SAXIACPARLEN\t\t\t(),\n\t.SAXIACPARLOCK\t\t\t(),\n\t.SAXIACPARPROT\t\t\t(),\n\t.SAXIACPARQOS\t\t\t(),\n\t.SAXIACPARSIZE\t\t\t(),\n\t.SAXIACPARUSER\t\t\t(),\n\t.SAXIACPARVALID\t\t\t(),\n\t.SAXIACPAWADDR\t\t\t(),\n\t.SAXIACPAWBURST\t\t\t(),\n\t.SAXIACPAWCACHE\t\t\t(),\n\t.SAXIACPAWID\t\t\t(),\n\t.SAXIACPAWLEN\t\t\t(),\n\t.SAXIACPAWLOCK\t\t\t(),\n\t.SAXIACPAWPROT\t\t\t(),\n\t.SAXIACPAWQOS\t\t\t(),\n\t.SAXIACPAWSIZE\t\t\t(),\n\t.SAXIACPAWUSER\t\t\t(),\n\t.SAXIACPAWVALID\t\t\t(),\n\t.SAXIACPBREADY\t\t\t(),\n\t.SAXIACPRREADY\t\t\t(),\n\t.SAXIACPWDATA\t\t\t(),\n\t.SAXIACPWID\t\t\t(),\n\t.SAXIACPWLAST\t\t\t(),\n\t.SAXIACPWSTRB\t\t\t(),\n\t.SAXIACPWVALID\t\t\t(),\n\t.SAXIGP0ACLK\t\t\t(),\n\t.SAXIGP0ARADDR\t\t\t(),\n\t.SAXIGP0ARBURST\t\t\t(),\n\t.SAXIGP0ARCACHE\t\t\t(),\n\t.SAXIGP0ARID\t\t\t(),\n\t.SAXIGP0ARLEN\t\t\t(),\n\t.SAXIGP0ARLOCK\t\t\t(),\n\t.SAXIGP0ARPROT\t\t\t(),\n\t.SAXIGP0ARQOS\t\t\t(),\n\t.SAXIGP0ARSIZE\t\t\t(),\n\t.SAXIGP0ARVALID\t\t\t(),\n\t.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P3WVALID\t\t\t()\n\t);\n ' % {'dut': 'site_name', 'dout': isone}))
print('endmodule')
write_params(params) |
class I18NMiddleware(I18N):
def process_update_types(self) -> list:
return ['message', 'callback_query']
async def get_user_language(self, obj: Union[(types.Message, types.CallbackQuery)]):
user_id = obj.from_user.id
if (user_id not in users_lang):
users_lang[user_id] = 'en'
return users_lang[user_id] |
def extractFantasywebfictionWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap:
if (tagname in item['tags']):
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
def extractAdoseoflove4MeWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap:
if (tagname in item['tags']):
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
class Alphabet():
def __init__(self, chars, encoding=None, mask=False, missing=255):
self.chars = np.frombuffer(chars, dtype=np.uint8)
self.encoding = (np.zeros(256, dtype=np.uint8) + missing)
if (encoding is None):
self.encoding[self.chars] = np.arange(len(self.chars))
self.size = len(self.chars)
else:
self.encoding[self.chars] = encoding
self.size = (encoding.max() + 1)
self.mask = mask
if mask:
self.size -= 1
def __len__(self):
return self.size
def __getitem__(self, i):
return chr(self.chars[i])
def encode(self, x):
x = np.frombuffer(x, dtype=np.uint8)
z = self.encoding[x]
return z
def decode(self, x):
string = self.chars[x]
return string.tobytes()
def unpack(self, h, k):
n = self.size
kmer = np.zeros(k, dtype=np.uint8)
for i in reversed(range(k)):
c = (h % n)
kmer[i] = c
h = (h // n)
return kmer
def get_kmer(self, h, k):
kmer = self.unpack(h, k)
return self.decode(kmer) |
def test_widget_info(lfs_manager, manager_nospawn):
manager_nospawn.start(lfs_manager)
matches_loaded(manager_nospawn)
info = manager_nospawn.c.widget['livefootballscores'].info()
assert (info == {'matches': {0: 'Chelsea 1-1 Burnley (FT)', 1: 'West Ham United 3-2 Liverpool (FT)', 2: 'Aston Villa 0-0 Brighton & Hove Albion (15:00)', 3: 'Burnley 0-0 Crystal Palace (15:00)', 4: 'Newcastle United 0-0 Brentford (15:00)', 5: 'Norwich City 0-0 Southampton (15:00)', 6: 'Watford 0-0 Manchester United (15:00)', 7: 'Wolverhampton Wanderers 0-0 West Ham United (15:00)', 8: 'Liverpool 0-0 Arsenal (17:30)'}, 'name': 'livefootballscores', 'objects': {'leagues': {'premier-league': {0: 'Aston Villa 0-0 Brighton & Hove Albion (15:00)', 1: 'Burnley 0-0 Crystal Palace (15:00)', 2: 'Newcastle United 0-0 Brentford (15:00)', 3: 'Norwich City 0-0 Southampton (15:00)', 4: 'Watford 0-0 Manchester United (15:00)', 5: 'Wolverhampton Wanderers 0-0 West Ham United (15:00)', 6: 'Liverpool 0-0 Arsenal (17:30)'}, 'FIFA World Cup': {}}, 'team': 'Chelsea 1-1 Burnley (FT)', 'teams': {'Liverpool': 'West Ham United 3-2 Liverpool (FT)', 'Real Madrid': 'Real Madrid are not playing today.'}}, 'sources': {'leagues': 'premier-league, FIFA World Cup', 'team': 'Chelsea', 'teams': 'Liverpool, Real Madrid'}}) |
def test_general_rotation():
assert np.allclose(td.Transformed.rotation(0.1, 0), td.Transformed.rotation(0.1, [2, 0, 0]))
assert np.allclose(td.Transformed.rotation(0.2, 1), td.Transformed.rotation(0.2, [0, 3, 0]))
assert np.allclose(td.Transformed.rotation(0.3, 2), td.Transformed.rotation(0.3, [0, 0, 4])) |
.requires_window_manager
def test_that_loading_gui_creates_no_storage_in_read_only_mode(monkeypatch, tmp_path, qapp, source_root):
shutil.copytree(os.path.join(source_root, 'test-data', 'poly_example'), os.path.join(tmp_path, 'poly_example'))
monkeypatch.chdir(tmp_path)
args = argparse.Namespace(config='poly_example/poly.ert', read_only=True)
qapp.exec_ = (lambda : None)
monkeypatch.setattr(ert.gui.main, 'QApplication', Mock(return_value=qapp))
monkeypatch.setattr(ert.gui.main.LibresFacade, 'enspath', tmp_path)
run_gui(args)
assert ([p.stem for p in tmp_path.glob('**/*')].count('storage') == 0) |
class qb_audio_device(Gtk.MenuButton):
def __init__(self, setting, qb_instance):
self._setting = setting
self._qb = qb_instance
self._settings = QuickButtons.options[setting]
self._devices = {}
self._current_device = None
self._button_group = None
self._devices_to = None
self.popover = Gtk.Popover()
self.vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.vbox.show_all()
self.popover.add(self.vbox)
super().__init__(label=self._settings['label'], popover=self.popover)
self.set_tooltip_text(self._settings['tooltip'])
self.connect('toggled', self._on_cb_popup)
def _set_audio_device(self, button: Gtk.RadioButton) -> None:
self._qb.self_triggered = True
if (button.get_active() and (button.device_id != self._current_device)):
settings.set_option(self._setting, button.device_id)
def _on_cb_popup(self, widget: Gtk.RadioButton) -> None:
if widget.get_active():
self._set_devices()
elif self._devices_to:
GObject.source_remove(self._devices_to)
def _set_devices(self) -> None:
self._current_device = settings.get_option(self._setting, self._settings['default'])
actual_devices = {}
from xl.player.gst.sink import get_devices
for (name, device_id, _unused) in reversed(list(get_devices())):
actual_devices[device_id] = name
if (device_id not in self._devices):
widget = self._add_toggle(name, device_id)
self._devices[device_id] = {'name': name, 'widget': widget}
for child in self.vbox.get_children():
if (child.device_id not in actual_devices):
self._devices.pop(child.device_id, None)
self.vbox.remove(child)
if (self._current_device not in actual_devices):
self._current_device = 'auto'
self._devices[self._current_device]['widget'].set_active(True)
self.vbox.show_all()
self.vbox.reorder_child(self._devices['auto']['widget'], (- 1))
self._devices_to = GObject.timeout_add(1000, self._set_devices)
def _add_toggle(self, label: str, device_id: str) -> None:
btn = Gtk.RadioButton(label=label)
btn.connect('toggled', self._set_audio_device)
btn.device_id = device_id
if self._button_group:
btn.join_group(self._button_group)
self._button_group = btn
self.vbox.pack_start(btn, False, True, 10)
return btn
def show_all(self) -> None:
if (('depends_on' in self._settings) and (self._settings['depends_on'] not in self._qb.exaile.plugins.enabled_plugins)):
super().hide()
else:
super().show_all() |
def test_save_as_calls_publishers_for_published_versions(setup_publishers, create_test_data, create_pymel, create_maya_env):
data = create_test_data
pm = create_pymel
maya_env = create_maya_env
publishers_called = []
('LookDev')
def publisher1():
publishers_called.append('publisher1')
('Model')
def publisher2():
publishers_called.append('publisher2')
pm.newFile(force=True)
data['task6'].type = Type(name='LookDev', code='LookDev', target_entity_type='Task')
v = Version(task=data['task6'])
v.is_published = True
DBSession.add(v)
assert (publishers_called == [])
maya_env.save_as(v)
assert (publishers_called == ['publisher1']) |
class Model():
def __init__(self, f):
self.seq = undo.Sequence()
self.callback_in_progress = False
self.f = f
self.old_f = self.f.serialize()
self.f.connect('parameters-changed', self.onParametersChanged)
def block_callbacks(self):
self.callback_in_progress = True
def unblock_callbacks(self):
self.callback_in_progress = False
def callbacks_allowed(self):
return (not self.callback_in_progress)
def onParametersChanged(self, *args):
if (not self.callbacks_allowed()):
return
current = self.f.serialize()
def set_fractal(val):
self.f.freeze()
self.f.deserialize(val)
if self.f.thaw():
self.block_callbacks()
self.f.changed()
self.unblock_callbacks()
self.seq.do(set_fractal, current, set_fractal, self.old_f)
self.old_f = current
def extract_x_from_dump(self, dump):
x_re = re.compile('x=.*')
m = x_re.search(dump)
if m:
return m.group()
return 'eek'
def dump_history(self):
i = 0
print('(redo,undo)')
for he in self.seq.history:
if (i == self.seq.pos):
print('-->', end=' ')
else:
print(' ', end=' ')
print(('(%s,%s)' % (self.extract_x_from_dump(he.redo_data), self.extract_x_from_dump(he.undo_data))))
i += 1
def undo(self):
if self.seq.can_undo():
self.seq.undo()
def redo(self):
if self.seq.can_redo():
self.seq.redo() |
def init_logging(log_filename):
if (log_filename is not None):
logging.basicConfig(filename=log_filename, level=logging.DEBUG, filemode='w', format='%(asctime)s %(levelname)s - %(message)s', datefmt='%m-%d-%Y %H:%M:%S')
logging.info('program started')
logging.info('command line: {0}'.format(' '.join(sys.argv))) |
class OptionPlotoptionsDependencywheelStatesHover(Options):
def animation(self) -> 'OptionPlotoptionsDependencywheelStatesHoverAnimation':
return self._config_sub_data('animation', OptionPlotoptionsDependencywheelStatesHoverAnimation)
def borderColor(self):
return self._config_get(None)
def borderColor(self, text: str):
self._config(text, js_type=False)
def brightness(self):
return self._config_get(0.1)
def brightness(self, num: float):
self._config(num, js_type=False)
def color(self):
return self._config_get(None)
def color(self, text: str):
self._config(text, js_type=False)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def linkOpacity(self):
return self._config_get(1)
def linkOpacity(self, num: float):
self._config(num, js_type=False)
def opacity(self):
return self._config_get(1)
def opacity(self, num: float):
self._config(num, js_type=False) |
class InventorySummary(object):
def __init__(self, service_config, inventory_index_id, progress_queue):
self.service_config = service_config
self.inventory_index_id = inventory_index_id
self.progress_queue = progress_queue
self.notifier_config = self.service_config.get_notifier_config()
def _get_output_filename(self, filename_template):
utc_now_datetime = date_time.get_utc_now_datetime()
output_timestamp = utc_now_datetime.strftime(string_formats.TIMESTAMP_TIMEZONE_FILES)
return filename_template.format(str(self.inventory_index_id), output_timestamp)
def _upload_to_gcs(self, summary_data):
gcs_upload_path = ''
LOGGER.debug('Uploading inventory summary data to GCS.')
gcs_summary_config = self.notifier_config.get('inventory').get('gcs_summary')
if (not gcs_summary_config.get('gcs_path')):
LOGGER.error('gcs_path not set for inventory summary notifier.')
return
if (not gcs_summary_config['gcs_path'].startswith('gs://')):
LOGGER.error('Invalid GCS path: %s', gcs_summary_config['gcs_path'])
return
data_format = gcs_summary_config.get('data_format', 'csv')
base_notification.BaseNotification.check_data_format(data_format)
try:
if (data_format == 'csv'):
gcs_upload_path = '{}/{}'.format(gcs_summary_config.get('gcs_path'), self._get_output_filename(string_formats.INVENTORY_SUMMARY_CSV_FMT))
file_uploader.upload_csv('inv_summary', summary_data, gcs_upload_path)
else:
gcs_upload_path = '{}/{}'.format(gcs_summary_config.get('gcs_path'), self._get_output_filename(string_formats.INVENTORY_SUMMARY_JSON_FMT))
file_uploader.upload_json(summary_data, gcs_upload_path)
log_message = f'Inventory Summary file saved to GCS path: {gcs_upload_path}'
self.progress_queue.put(log_message)
LOGGER.info(log_message)
except HttpError:
LOGGER.exception('Unable to upload inventory summary in bucket %s:', gcs_upload_path)
def _send_email(self, summary_data, details_data, root_resources):
LOGGER.debug(f'Sending inventory summary by email for inventory id {self.inventory_index_id}.')
email_summary_config = self.notifier_config.get('inventory').get('email_summary')
try:
if self.notifier_config.get('email_connector'):
email_connector = EmailFactory(self.notifier_config).get_connector()
else:
email_connector = EmailFactory(email_summary_config).get_connector()
except:
LOGGER.exception('Error occurred to instantiate connector.')
raise InvalidInputError(self.notifier_config)
email_subject = 'Inventory Summary: {0}'.format(self.inventory_index_id)
inventory_index_datetime = date_time.get_date_from_microtimestamp(self.inventory_index_id)
timestamp = inventory_index_datetime.strftime(string_formats.DEFAULT_FORSETI_TIMESTAMP)
gsuite_dwd_status = self._get_gsuite_dwd_status(summary_data)
email_content = email_connector.render_from_template('inventory_summary.jinja', {'inventory_index_id': self.inventory_index_id, 'timestamp': timestamp, 'gsuite_dwd_status': gsuite_dwd_status, 'summary_data': summary_data, 'details_data': details_data, 'root_resources': root_resources})
if self.notifier_config.get('email_connector'):
sender = self.notifier_config.get('email_connector').get('sender')
recipient = self.notifier_config.get('email_connector').get('recipient')
else:
sender = email_summary_config.get('sender')
recipient = email_summary_config.get('recipient')
try:
email_connector.send(email_sender=sender, email_recipient=recipient, email_subject=email_subject, email_content=email_content, content_type='text/html')
log_message = f'Inventory summary email successfully sent for inventory id {self.inventory_index_id}.'
LOGGER.debug(log_message)
self.progress_queue.put(log_message)
except util_errors.EmailSendError as e:
log_message = f'Unable to send Inventory summary email for inventory id {self.inventory_index_id}. {e}'
LOGGER.exception(log_message)
self.progress_queue.put(log_message)
def transform_to_template(data):
template_data = []
for (key, value) in data.items():
template_data.append(dict(resource_type=key, count=value))
return sorted(template_data, key=(lambda k: ((k['resource_type'] is None), k['resource_type'])))
def _get_gsuite_dwd_status(summary_data):
gsuite_types = set(['gsuite_user'])
summary_data_keys = set()
if (summary_data is None):
return 'disabled'
for resource in summary_data:
summary_data_keys.add(resource['resource_type'])
if gsuite_types.issubset(summary_data_keys):
return 'enabled'
return 'disabled'
def _get_summary_data(self):
LOGGER.debug('Getting inventory summary data.')
with self.service_config.scoped_session() as session:
inventory_index = session.query(InventoryIndex).get(self.inventory_index_id)
summary = inventory_index.get_summary(session)
if (not summary):
LOGGER.error('No inventory summary data found for inventory index id: %s.', self.inventory_index_id)
raise util_errors.NoDataError
summary_data = self.transform_to_template(summary)
return summary_data
def _get_details_data(self):
LOGGER.debug('Getting inventory summary details data.')
with self.service_config.scoped_session() as session:
inventory_index = session.query(InventoryIndex).get(self.inventory_index_id)
details = inventory_index.get_details(session)
if (not details):
LOGGER.error('No inventory summary detail data found for inventory index id: %s.', self.inventory_index_id)
raise util_errors.NoDataError
details_data = self.transform_to_template(details)
return details_data
def _get_root_resources(self):
root_resources = []
composite_roots = self.service_config.inventory_config.composite_root_resources
if composite_roots:
root_resources.extend(composite_roots)
else:
root_resources.append(self.service_config.inventory_config.root_resource_id)
return root_resources
def run(self):
LOGGER.info('Running inventory summary notifier.')
inventory_notifier_config = self.notifier_config.get('inventory')
if (not inventory_notifier_config):
LOGGER.info('No inventory configuration for notifier.')
return
try:
is_gcs_summary_enabled = inventory_notifier_config.get('gcs_summary').get('enabled')
is_email_summary_enabled = inventory_notifier_config.get('email_summary').get('enabled')
except AttributeError:
LOGGER.exception('Inventory summary can not be created because unable to get inventory summary configuration.')
return
if ((not is_gcs_summary_enabled) and (not is_email_summary_enabled)):
LOGGER.info('All inventory summaries are disabled.')
return
try:
summary_data = self._get_summary_data()
details_data = self._get_details_data()
root_resources = self._get_root_resources()
except util_errors.NoDataError:
LOGGER.exception('Inventory summary can not be created because no summary data is found for index id: %s.', self.inventory_index_id)
return
if is_gcs_summary_enabled:
summary_and_details_data = sorted((summary_data + details_data), key=(lambda k: k['resource_type']))
self._upload_to_gcs(summary_and_details_data)
if is_email_summary_enabled:
self._send_email(summary_data, details_data, root_resources)
LOGGER.info('Completed running inventory summary.') |
class PerformanceReport():
json: Optional[str] = None
def _str(self, indent: str) -> str:
s = ''
for (k, v) in vars(self).items():
if ((k == 'json') or (k == 'profiler_data')):
continue
s += ((indent + k) + ':')
if isinstance(v, PerformanceReport):
s += ('\n' + v._str((indent + ' ')))
elif isinstance(v, list):
s += ((' [' + ','.join((str(i) for i in v))) + ']\n')
else:
s += ((' ' + str(v)) + '\n')
return s
def __str__(self) -> str:
return self._str('') |
def build_goods_description(quantities_by_good_id: Dict[(str, int)], currency_id: str, ledger_id: str, is_supply: bool) -> Description:
data_model = _build_goods_datamodel(good_ids=list(quantities_by_good_id.keys()), is_supply=is_supply)
values = cast(Dict[(str, Union[(int, str)])], copy.copy(quantities_by_good_id))
values.update({'currency_id': currency_id})
values.update({'ledger_id': ledger_id})
desc = Description(values, data_model=data_model)
return desc |
def test_lifespan_state():
async def app(scope, receive, send):
message = (await receive())
assert (message['type'] == 'lifespan.startup')
(await send({'type': 'lifespan.startup.complete'}))
scope['state']['foo'] = 123
message = (await receive())
assert (message['type'] == 'lifespan.shutdown')
(await send({'type': 'lifespan.shutdown.complete'}))
async def test():
config = Config(app=app, lifespan='on')
lifespan = LifespanOn(config)
(await lifespan.startup())
assert (lifespan.state == {'foo': 123})
(await lifespan.shutdown())
loop = asyncio.new_event_loop()
loop.run_until_complete(test())
loop.close() |
def make_invoice(invoice_details):
doc = frappe.new_doc('Sales Invoice')
doc.is_pos = 1
doc.set_posting_time = 1
doc.zenoti_invoice_no = invoice_details['invoice_no']
doc.zenoti_receipt_no = invoice_details['receipt_no']
doc.is_return = invoice_details['is_return']
doc.customer = invoice_details['customer']
doc.posting_date = invoice_details['posting_date']
doc.posting_time = invoice_details['posting_time']
doc.due_date = invoice_details['posting_date']
doc.cost_center = invoice_details['cost_center']
doc.selling_price_list = frappe.db.get_single_value('Zenoti Settings', 'default_selling_price_list')
doc.set_warehouse = invoice_details['set_warehouse']
doc.update_stock = 1
doc.rounding_adjustment = invoice_details['rounding_adjustment']
doc.set('items', [])
add_items(doc, invoice_details['item_data'])
add_taxes(doc)
doc.set('payments', [])
add_payments(doc, invoice_details['payments'])
doc.insert() |
def verify_ping(fledge_url, skip_verify_north_interface, wait_time, retries):
get_url = '/fledge/ping'
ping_result = utils.get_request(fledge_url, get_url)
assert ('dataRead' in ping_result)
assert ('dataSent' in ping_result)
assert (0 < ping_result['dataRead']), 'South data NOT seen in ping header'
retry_count = 1
sent = 0
if (not skip_verify_north_interface):
while (retries > retry_count):
sent = ping_result['dataSent']
if (sent >= 1):
break
else:
time.sleep(wait_time)
retry_count += 1
ping_result = utils.get_request(fledge_url, get_url)
assert (1 <= sent), 'Failed to send data to Edge Data Store'
return ping_result |
def load_cases(case_type, case_no=None):
if (case_type in ('MUR', 'ADR', 'AF')):
es_client = create_es_client()
if es_client.indices.exists(index=CASE_ALIAS):
logger.info('Loading {0}(s)'.format(case_type))
case_count = 0
for case in get_cases(case_type, case_no):
if (case is not None):
if case.get('published_flg'):
logger.info('Loading {0}: {1}'.format(case_type, case['no']))
es_client.index(CASE_ALIAS, case, id=case['doc_id'])
case_count += 1
logger.info('{0} {1}(s) loaded'.format(case_count, case_type))
else:
try:
logger.info('Found an unpublished case - deleting {0}: {1} from ES'.format(case_type, case['no']))
es_client.delete(index=CASE_ALIAS, id=case['doc_id'])
logger.info('Successfully deleted {} {} from ES'.format(case_type, case['no']))
except Exception as err:
logger.error('An error occurred while deteting an unpublished case.{0} {1} {2}'.format(case_type, case['no'], err))
debug_case_data = case
del debug_case_data['documents']
logger.debug(('case_data count=' + str(case_count)))
logger.debug(('debug_case_data =' + json.dumps(debug_case_data, indent=3, cls=DateTimeEncoder)))
else:
logger.error(" The index alias '{0}' is not found, cannot load cases (mur/adr/af)".format(CASE_ALIAS))
else:
logger.error("Invalid case type: must be 'MUR', 'ADR', or 'AF'.") |
()
('mode', [nox.param('fix', id='fix'), nox.param('check', id='check')])
def black(session: nox.Session, mode: str) -> None:
install_requirements(session)
command = ('black', 'src', 'tests', 'noxfiles', 'scripts', 'noxfile.py')
if (mode == 'check'):
command = (*command, '--check')
session.run(*command) |
def test_events():
(demo, 'increment')
def handler(this, fn, num, obj):
print('Handler caled', fn, num, obj)
if (num == 7):
off(demo, 'increment', handler)
(demo, 'increment')
def onceIncrement(this, *args):
print("Hey, I'm only called once !")
demo.increment() |
class Text():
lines: List[str]
def _print_text(self, indent, inline=False):
if (not self.lines):
return
s = indent_str(indent)
if inline:
(yield (self.lines[0] + '\n'))
else:
(yield ((s + self.lines[0]) + '\n'))
for line in self.lines[1:]:
(yield ((s + line) + '\n'))
def _print_html(self):
for line in self.lines:
(yield line)
(yield '<br/>\n')
def _print_rst(self, section=None):
(yield from self._print_text(8)) |
def js(fn: Callable) -> Callable:
from .output import UI
def _eval_js_dec(*args, **kwargs):
if ((UI._editor is not None) and (UI._editor.web is not None)):
UI.js(fn(*args, **kwargs))
else:
w = mw.app.activeWindow()
if ((w is not None) and hasattr(w, 'editor')):
w.editor.web.eval(fn(*args, **kwargs))
return _eval_js_dec |
class WorkbenchWindowLayout(MWorkbenchWindowLayout):
_qt4_editor_area = Instance(SplitTabWidget)
def activate_editor(self, editor):
if (editor.control is not None):
editor.control.show()
self._qt4_editor_area.setCurrentWidget(editor.control)
editor.set_focus()
return editor
def activate_view(self, view):
view.control.raise_()
view.set_focus()
return view
def add_editor(self, editor, title):
if (editor is None):
return None
try:
self._qt4_editor_area.addTab(self._qt4_get_editor_control(editor), title)
if editor._loading_on_open:
self._qt4_editor_tab_spinner(editor, '', True)
except Exception:
logger.exception('error creating editor control [%s]', editor.id)
return editor
def add_view(self, view, position=None, relative_to=None, size=((- 1), (- 1))):
if (view is None):
return None
try:
self._qt4_add_view(view, position, relative_to, size)
view.visible = True
except Exception:
logger.exception('error creating view control [%s]', view.id)
view.destroy_control()
error(self.window.control, ('Unable to add view [%s]' % view.id), 'Workbench Plugin Error')
return view
def close_editor(self, editor):
if (editor.control is not None):
editor.control.close()
return editor
def close_view(self, view):
self.hide_view(view)
return view
def close(self):
self._qt4_editor_area.editor_has_focus.disconnect(self._qt4_editor_focus)
self._qt4_editor_area.clear()
for v in self.window.views:
if self.contains_view(v):
self._qt4_delete_view_dock_widget(v)
def create_initial_layout(self, parent):
self._qt4_editor_area = editor_area = SplitTabWidget(parent)
editor_area.editor_has_focus.connect(self._qt4_editor_focus)
editor_area.focus_changed.connect(self._qt4_view_focus_changed)
editor_area.tabTextChanged.connect(self._qt4_editor_title_changed)
editor_area.new_window_request.connect(self._qt4_new_window_request)
editor_area.tab_close_request.connect(self._qt4_tab_close_request)
editor_area.tab_window_changed.connect(self._qt4_tab_window_changed)
return editor_area
def contains_view(self, view):
return hasattr(view, '_qt4_dock')
def hide_editor_area(self):
self._qt4_editor_area.hide()
def hide_view(self, view):
view._qt4_dock.hide()
view.visible = False
return view
def refresh(self):
pass
def reset_editors(self):
self._qt4_editor_area.setCurrentIndex(0)
def reset_views(self):
pass
def show_editor_area(self):
self._qt4_editor_area.show()
def show_view(self, view):
view._qt4_dock.show()
view.visible = True
def get_view_memento(self):
view_ids = [v.id for v in self.window.views if self.contains_view(v)]
state = self.window.control.saveState().data()
return (0, (view_ids, state))
def set_view_memento(self, memento):
(version, mdata) = memento
assert (version == 0)
(view_ids, state) = mdata
dock_views = [v for v in self.window.views if self.contains_view(v)]
for v in dock_views:
v._qt4_gone = True
for v in self.window.views:
v.visible = False
for vid in view_ids:
if (vid == v.id):
self._qt4_create_view_dock_widget(v).setVisible(False)
if (v in dock_views):
delattr(v, '_qt4_gone')
break
for v in dock_views:
try:
delattr(v, '_qt4_gone')
except AttributeError:
pass
else:
self._qt4_delete_view_dock_widget(v)
self.window.control.restoreState(state)
def get_editor_memento(self):
editor_layout = self._qt4_editor_area.saveState()
editor_references = self._get_editor_references()
return (0, (editor_layout, editor_references))
def set_editor_memento(self, memento):
(version, mdata) = memento
assert (version == 0)
(editor_layout, editor_references) = mdata
def resolve_id(id):
editor_memento = editor_references.get(id)
if (editor_memento is None):
return None
editor = self.window.editor_manager.set_editor_memento(editor_memento)
if (editor is None):
return None
self.window.editors.append(editor)
return self._qt4_get_editor_control(editor)
self._qt4_editor_area.restoreState(editor_layout, resolve_id)
def get_toolkit_memento(self):
return (0, {'geometry': self.window.control.saveGeometry()})
def set_toolkit_memento(self, memento):
if hasattr(memento, 'toolkit_data'):
data = memento.toolkit_data
if (isinstance(data, tuple) and (len(data) == 2)):
(version, datadict) = data
if (version == 0):
geometry = datadict.pop('geometry', None)
if (geometry is not None):
self.window.control.restoreGeometry(geometry)
def is_editor_area_visible(self):
return self._qt4_editor_area.isVisible()
def _qt4_editor_focus(self, new):
for editor in self.window.editors:
control = editor.control
editor.has_focus = ((control is new) or ((control is not None) and (new in control.children())))
def _qt4_editor_title_changed(self, control, title):
for editor in self.window.editors:
if (editor.control == control):
editor.name = str(title)
def _qt4_editor_tab_spinner(self, event):
editor = event.object
(tw, tidx) = self._qt4_editor_area._tab_widget(editor.control)
if event.new:
tw.show_button(tidx)
else:
tw.hide_button(tidx)
if ((not event.new) and (not (editor == self.window.active_editor))):
self._qt4_editor_area.setTabTextColor(editor.control, QtCore.Qt.GlobalColor.red)
('window:active_editor')
def _qt4_active_editor_changed(self, event):
editor = event.new
if (editor is not None):
self._qt4_editor_area.setTabTextColor(editor.control)
def _qt4_view_focus_changed(self, old, new):
focus_part = None
if (new is not None):
for view in self.window.views:
if ((view.control is not None) and view.control.isAncestorOf(new)):
view.has_focus = True
focus_part = view
break
if (old is not None):
for view in self.window.views:
if ((view is not focus_part) and (view.control is not None) and view.control.isAncestorOf(old)):
view.has_focus = False
break
def _qt4_new_window_request(self, pos, control):
editor = self._qt4_remove_editor_with_control(control)
kind = self.window.editor_manager.get_editor_kind(editor)
window = self.window.workbench.create_window()
window.open()
window.add_editor(editor)
window.editor_manager.add_editor(editor, kind)
window.position = (pos.x(), pos.y())
window.size = self.window.size
window.activate_editor(editor)
editor.window = window
def _qt4_tab_close_request(self, control):
for editor in self.window.editors:
if (editor.control == control):
editor.close()
break
def _qt4_tab_window_changed(self, control):
editor = self._qt4_remove_editor_with_control(control)
kind = self.window.editor_manager.get_editor_kind(editor)
while (not control.isWindow()):
control = control.parent()
for window in self.window.workbench.windows:
if (window.control == control):
window.editors.append(editor)
window.editor_manager.add_editor(editor, kind)
window.layout._qt4_get_editor_control(editor)
window.activate_editor(editor)
editor.window = window
break
def _qt4_remove_editor_with_control(self, control):
for editor in self.window.editors:
if (editor.control == control):
self.editor_closing = editor
control.removeEventFilter(self._qt4_mon)
self.editor_closed = editor
editor.has_focus = False
return editor
def _qt4_get_editor_control(self, editor):
if (editor.control is None):
self.editor_opening = editor
editor.control = editor.create_control(self.window.control)
editor.control.setObjectName(editor.id)
editor.observe(self._qt4_editor_tab_spinner, '_loading')
self.editor_opened = editor
def on_name_changed(event):
editor = event.object
self._qt4_editor_area.setWidgetTitle(editor.control, editor.name)
editor.observe(on_name_changed, 'name')
self._qt4_monitor(editor.control)
return editor.control
def _qt4_add_view(self, view, position, relative_to, size):
if (position is None):
position = view.position
dw = self._qt4_create_view_dock_widget(view, size)
mw = self.window.control
try:
rel_dw = relative_to._qt4_dock
except AttributeError:
rel_dw = None
if (rel_dw is None):
if (position == 'with'):
position = 'left'
try:
dwa = _EDIT_AREA_MAP[position]
except KeyError:
raise ValueError(('unknown view position: %s' % position))
mw.addDockWidget(dwa, dw)
elif (position == 'with'):
mw.tabifyDockWidget(rel_dw, dw)
else:
try:
(orient, swap) = _VIEW_AREA_MAP[position]
except KeyError:
raise ValueError(('unknown view position: %s' % position))
mw.splitDockWidget(rel_dw, dw, orient)
if swap:
mw.removeDockWidget(rel_dw)
mw.splitDockWidget(dw, rel_dw, orient)
rel_dw.show()
def _qt4_create_view_dock_widget(self, view, size=((- 1), (- 1))):
try:
dw = view._qt4_dock
except AttributeError:
dw = QtGui.QDockWidget(view.name, self.window.control)
dw.setWidget(_ViewContainer(size, self.window.control))
dw.setObjectName(view.id)
dw.toggleViewAction().toggled.connect(self._qt4_handle_dock_visibility)
dw.visibilityChanged.connect(self._qt4_handle_dock_visibility)
view._qt4_dock = dw
def on_name_changed(event):
view._qt4_dock.setWindowTitle(view.name)
view.observe(on_name_changed, 'name')
if (view.control is None):
view.window = self.window
try:
view.control = view.create_control(dw.widget())
except:
delattr(view, '_qt4_dock')
self.window.control.removeDockWidget(dw)
dw.deleteLater()
del dw
raise
dw.widget().setCentralWidget(view.control)
return dw
def _qt4_delete_view_dock_widget(self, view):
dw = view._qt4_dock
if (view.control is not None):
view.control.setParent(None)
delattr(view, '_qt4_dock')
self.window.control.removeDockWidget(dw)
dw.deleteLater()
def _qt4_handle_dock_visibility(self, checked):
for v in self.window.views:
try:
dw = v._qt4_dock
except AttributeError:
continue
sender = dw.sender()
if ((sender is dw.toggleViewAction()) or (sender in dw.children())):
v.visible = checked
def _qt4_monitor(self, control):
try:
mon = self._qt4_mon
except AttributeError:
mon = self._qt4_mon = _Monitor(self)
control.installEventFilter(mon) |
def from_uri(uri: str) -> Tuple[(str, str)]:
try:
(spotify, type_, id_) = uri.split(':')
if (spotify != 'spotify'):
raise ValueError()
except ValueError as e:
msg = f'Invalid URI: expected format "spotify:{{type}}:{{id}}", got {uri!r}!'
raise ConversionError(msg) from e
check_type(type_)
if (type_ != IdentifierType.user):
check_id(id_)
return (type_, id_) |
('Panel Permissions > Get Panel Permission Details for a Custom System Role > Get Panel Permission Details for a Custom System Role')
def panel_permissions_custom_system_role(transaction):
with stash['app'].app_context():
CustomSysRoleFactory()
PanelPermissionFactory()
db.session.commit() |
def test_dependency_resolution_3():
a1 = Thing('a1.js', ['b1.js'])
b1 = Thing('b1.js', ['bar.js', 'c1.js'])
c1 = Thing('c1.js', ['d1.js', 'foo.js'])
d1 = Thing('d1.js', ['e1.js'])
e1 = Thing('e1.js', [])
aa = (a1, b1, c1, d1, e1)
with capture_log('warning') as logs:
aa = solve_dependencies(aa, warn_missing=True)
assert (logs and ('missing dependency' in logs[0]))
assert ([a.name for a in aa] == ['e1.js', 'd1.js', 'c1.js', 'b1.js', 'a1.js']) |
.unit
class TestHandleDatabaseCredentialsOptions():
def test_neither_option_supplied_raises(self, test_config: FidesConfig) -> None:
with pytest.raises(click.UsageError):
input_connection_string = ''
input_credentials_id = ''
utils.handle_database_credentials_options(fides_config=test_config, connection_string=input_connection_string, credentials_id=input_credentials_id)
def test_both_options_supplied_raises(self, test_config: FidesConfig) -> None:
with pytest.raises(click.UsageError):
input_connection_string = 'my_connection_string'
input_credentials_id = 'postgres_1'
utils.handle_database_credentials_options(fides_config=test_config, connection_string=input_connection_string, credentials_id=input_credentials_id)
def test_config_does_not_exist_raises(self, test_config: FidesConfig) -> None:
with pytest.raises(click.UsageError):
input_connection_string = ''
input_credentials_id = 'UNKNOWN'
utils.handle_database_credentials_options(fides_config=test_config, connection_string=input_connection_string, credentials_id=input_credentials_id)
def test_returns_input_connection_string(self, test_config: FidesConfig) -> None:
input_connection_string = 'my_connection_string'
input_credentials_id = ''
connection_string = utils.handle_database_credentials_options(fides_config=test_config, connection_string=input_connection_string, credentials_id=input_credentials_id)
assert (connection_string == input_connection_string)
def test_returns_config_connection_string(self, test_config: FidesConfig) -> None:
input_connection_string = ''
input_credentials_id = 'postgres_1'
connection_string = utils.handle_database_credentials_options(fides_config=test_config, connection_string=input_connection_string, credentials_id=input_credentials_id)
assert (connection_string == 'postgresql+psycopg2://postgres:-db:5432/fides_test') |
class AdminSalesDiscountedList(ResourceList):
def query(self, _):
pending = sales_per_marketer_and_discount_by_status('pending')
completed = sales_per_marketer_and_discount_by_status('completed')
placed = sales_per_marketer_and_discount_by_status('placed')
discounts = self.session.query(Event.id.label('event_id'), Event.name.label('event_name'), DiscountCode.id.label('discount_code_id'), DiscountCode.code.label('code'), User.id.label('marketer_id'), User.email.label('email')).filter((Event.id == Order.event_id)).filter((Order.marketer_id == User.id)).filter((Order.discount_code_id == DiscountCode.id)).cte()
return self.session.query(discounts, pending, completed, placed).outerjoin(pending, (((pending.c.event_id == discounts.c.event_id) & (pending.c.discount_code_id == discounts.c.discount_code_id)) & (pending.c.marketer_id == discounts.c.marketer_id))).outerjoin(completed, (((completed.c.event_id == discounts.c.event_id) & (completed.c.discount_code_id == discounts.c.discount_code_id)) & (completed.c.marketer_id == discounts.c.marketer_id))).outerjoin(placed, (((placed.c.event_id == discounts.c.event_id) & (placed.c.discount_code_id == discounts.c.discount_code_id)) & (placed.c.marketer_id == discounts.c.marketer_id)))
methods = ['GET']
decorators = (api.has_permission('is_admin'),)
schema = AdminSalesDiscountedSchema
data_layer = {'model': Event, 'session': db.session, 'methods': {'query': query}} |
class OptionSeriesScatter3dDragdropGuideboxDefault(Options):
def className(self):
return self._config_get('highcharts-drag-box-default')
def className(self, text: str):
self._config(text, js_type=False)
def color(self):
return self._config_get('rgba(0, 0, 0, 0.1)')
def color(self, text: str):
self._config(text, js_type=False)
def cursor(self):
return self._config_get('move')
def cursor(self, text: str):
self._config(text, js_type=False)
def lineColor(self):
return self._config_get('#888')
def lineColor(self, text: str):
self._config(text, js_type=False)
def lineWidth(self):
return self._config_get(1)
def lineWidth(self, num: float):
self._config(num, js_type=False)
def zIndex(self):
return self._config_get(900)
def zIndex(self, num: float):
self._config(num, js_type=False) |
class PowerLineDecoration(_Decoration):
defaults = [('size', 15, 'Width of shape'), ('path', 'arrow_left', 'Shape of decoration. See docstring for more info.'), ('shift', 0, 'Number of pixels to shift the decoration back by.'), ('override_colour', None, 'Force background colour.'), ('override_next_colour', None, 'Force background colour for the next part of the decoration.')]
_screenshots = [('powerline_example2.png', "path='arrow_right'"), ('powerline_example3.png', "path='rounded_left'"), ('powerline_example4.png', "path='rounded_right'"), ('powerline_example5.png', "path='forward_slash'"), ('powerline_example6.png', "path='back_slash'"), ('powerline_example7.png', "path='zig_zag'"), ('powerline_example8.png', 'path=[(0, 0), (0.5, 0), (0.5, 0.25), (1, 0.25), (1, 0.75), (0.5, 0.75), (0.5, 1), (0, 1)]')]
paths = {'arrow_left': [(0, 0), (1, 0.5), (0, 1)], 'arrow_right': [(0, 0), (1, 0), (0, 0.5), (1, 1), (0, 1)], 'forward_slash': [(0, 0), (1, 0), (0, 1)], 'back_slash': [(0, 0), (1, 1), (0, 1)], 'zig_zag': [(0, 0), (1, 0.2), (0, 0.4), (1, 0.6), (0, 0.8), (1, 1), (0, 1)]}
def __init__(self, **config):
_Decoration.__init__(self, **config)
self.add_defaults(PowerLineDecoration.defaults)
self.shift = max(min(self.shift, self.size), 0)
self._extrawidth += (self.size - self.shift)
self.group = False
def _configure(self, parent):
_Decoration._configure(self, parent)
self.paths['rounded_left'] = self.draw_rounded
self.paths['rounded_right'] = partial(self.draw_rounded, rotate=True)
if isinstance(self.path, str):
shape_path = self.paths.get(self.path, False)
if callable(shape_path):
self.draw_func = shape_path
elif isinstance(shape_path, list):
self.draw_func = partial(self.draw_path, path=shape_path)
else:
raise ConfigError(f'Unknown `path` ({self.path}) for PowerLineDecoration.')
elif isinstance(self.path, list):
self.draw_func = partial(self.draw_path, path=self.path)
else:
raise ConfigError(f'Unexpected value for PowerLineDecoration `path`: {self.path}.')
self.parent_background = (self.override_colour or self.parent.background or self.parent.bar.background)
self.next_background = (self.override_next_colour or self.set_next_colour())
def set_next_colour(self):
try:
index = self.parent.bar.widgets.index(self.parent)
widgets = self.parent.bar.widgets
next_widget = next((w for w in widgets if (hasattr(w, 'length') and w.length and (widgets.index(w) > index))))
return (next_widget.background or self.parent.bar.background)
except (ValueError, IndexError, StopIteration):
return self.parent.bar.background
def paint_background(self, background, foreground):
self.ctx.save()
self.ctx.set_operator(cairocffi.OPERATOR_SOURCE)
if self.padding_y:
self.ctx.rectangle(0, 0, self.parent.length, self.parent.bar.height)
self.set_source_rgb(self.parent.bar.background)
self.ctx.fill()
self.drawer.clear_rect(0, self.padding_y, self.parent.length, (self.parent.bar.height - (2 * self.padding_y)))
self.ctx.rectangle(0, self.padding_y, (self.parent_length - self.shift), (self.parent.bar.height - (2 * self.padding_y)))
self.set_source_rgb(background)
self.ctx.fill()
self.ctx.rectangle((self.parent_length - self.shift), self.padding_y, self.size, (self.parent.bar.height - (2 * self.padding_y)))
self.set_source_rgb(foreground)
self.ctx.fill()
self.ctx.restore()
def draw_rounded(self, rotate=False):
self.fg = (self.parent_background if (not rotate) else self.next_background)
self.bg = (self.next_background if (not rotate) else self.parent_background)
self.paint_background(self.parent_background, self.bg)
self.ctx.save()
self.ctx.set_operator(cairocffi.OPERATOR_SOURCE)
start = (((self.parent_length - self.shift) + self.extrawidth) if (not rotate) else self.parent.length)
self.ctx.translate(start, (self.parent.bar.height // 2))
if rotate:
self.ctx.rotate(math.pi)
x_scale = ((self.parent.length - (self.parent_length - self.shift)) - self.extrawidth)
y_scale = ((self.parent.bar.height / 2) - self.padding_y)
self.ctx.scale(x_scale, y_scale)
self.set_source_rgb(self.fg)
self.ctx.arc(0, 0, 1, ((- math.pi) / 2), (math.pi / 2))
self.ctx.close_path()
self.ctx.fill()
self.ctx.restore()
def draw_path(self, path=list()):
if (not path):
return
path = path.copy()
self.fg = self.parent_background
self.bg = self.next_background
self.paint_background(self.fg, self.bg)
width = self.size
height = (self.parent.bar.height - (2 * self.padding_y))
self.ctx.save()
self.ctx.set_operator(cairocffi.OPERATOR_SOURCE)
self.ctx.translate(((self.parent_length - self.shift) + self.extrawidth), self.padding_y)
(x, y) = path.pop(0)
self.ctx.move_to((x * width), (y * height))
for (x, y) in path:
self.ctx.line_to((x * width), (y * height))
self.ctx.close_path()
self.set_source_rgb(self.fg)
self.ctx.fill()
self.ctx.restore()
def draw(self) -> None:
if (self.width == 0):
return
self.next_background = (self.override_next_colour or self.set_next_colour())
self.ctx.save()
self.draw_func()
self.ctx.restore() |
class OptionPlotoptionsWindbarbSonificationDefaultinstrumentoptionsMappingPitch(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get('y')
def mapTo(self, text: str):
self._config(text, js_type=False)
def max(self):
return self._config_get('c6')
def max(self, text: str):
self._config(text, js_type=False)
def min(self):
return self._config_get('c2')
def min(self, text: str):
self._config(text, js_type=False)
def scale(self):
return self._config_get(None)
def scale(self, value: Any):
self._config(value, js_type=False)
def within(self):
return self._config_get('yAxis')
def within(self, text: str):
self._config(text, js_type=False) |
def _eliminate_split_full_idx(sorted_graph: List[Tensor]) -> List[Tensor]:
for tensor in sorted_graph:
src_ops = tensor._attrs['src_ops']
if (len(src_ops) != 1):
continue
src_op = list(src_ops)[0]
if (src_op._attrs['op'] != 'split'):
continue
split_op = src_op
dim = split_op._attrs['split_dim']
split_sizes = split_op._attrs['split_sizes']
assert (len(split_op._attrs['inputs']) == 1)
shape = split_op._attrs['inputs'][0]._attrs['shape']
if ((len(split_sizes) == 1) and shape_utils.is_static_dimension(shape, dim) and (shape[dim]._attrs['values'][0] == split_sizes[0])):
input_tensor = split_op._attrs['inputs'][0]
output_tensor = split_op._attrs['outputs'][0]
if (output_tensor._attrs['is_output'] and input_tensor._attrs['is_input']):
continue
transform_utils.remove_single_tensor_op_from_sorted_graph(split_op)
sorted_graph = transform_utils.sanitize_sorted_graph(sorted_graph)
return transform_utils.sanitize_sorted_graph(sorted_graph) |
def start_wandb(config, wandb):
resume = 'allow'
wandb_id = wandb.util.generate_id()
if (('dir' in config.wandb) and (config.wandb.dir is not None)):
wandb_filename = os.path.join(config.wandb.dir, 'wandb', 'wandb_id.txt')
if os.path.exists(wandb_filename):
with open(wandb_filename, 'r') as file:
wandb_id = file.read().rstrip('\n')
resume = 'must'
else:
os.makedirs(os.path.dirname(wandb_filename), exist_ok=True)
with open(wandb_filename, 'w') as file:
file.write(wandb_id)
if isinstance(config, omegaconf.DictConfig):
config = omegaconf.OmegaConf.to_container(config, resolve=True, throw_on_missing=True)
wandb_cfg_dict = config['wandb']
return wandb.init(id=wandb_id, config=config, resume=resume, **wandb_cfg_dict) |
def generate_beacon_file_fixture(filename):
()
def my_fixture(request):
testpath = Path(request.fspath.dirname)
beacon_zip_path = ((testpath / 'beacons') / filename)
if (not beacon_zip_path.exists()):
pytest.skip(f'Beacon {beacon_zip_path!r} not found')
with unzip_beacon_as_fh(beacon_zip_path) as beacon_file:
try:
beacon_file.seek(0)
(yield beacon_file)
except io.UnsupportedOperation:
with io.BytesIO(beacon_file.read()) as fh:
(yield fh)
return my_fixture |
def test_command_line_autocomplete_options():
args = parser.parse_args('--autocomplete_no_prefix --autocomplete_no_snippets --autocomplete_name_only --lowercase_intrinsics --use_signature_help'.split())
assert args.autocomplete_no_prefix
assert args.autocomplete_no_snippets
assert args.autocomplete_name_only
assert args.lowercase_intrinsics
assert args.use_signature_help |
def encode_defunct(primitive: bytes=None, *, hexstr: str=None, text: str=None) -> SignableMessage:
message_bytes = to_bytes(primitive, hexstr=hexstr, text=text)
msg_length = str(len(message_bytes)).encode('utf-8')
return SignableMessage(b'E', (b'thereum Signed Message:\n' + msg_length), message_bytes) |
class RecVote(models.Model):
user = models.ForeignKey(auth_models.User, related_name='rec_votes', on_delete=models.CASCADE)
product = models.ForeignKey(RecProduct, on_delete=models.CASCADE)
site = models.ForeignKey(Site, on_delete=models.CASCADE)
score = models.FloatField()
class Meta():
app_label = 'recommends'
def __str__(self):
return 'Vote' |
class IntegrityBuilder():
def __init__(self, algorithm: str='sha256') -> None:
self.algorithm = algorithm
self._hasher = hashlib.new(algorithm)
def update(self, data: Union[(str, bytes)]) -> None:
data_bytes: bytes
if isinstance(data, str):
data_bytes = data.encode()
else:
data_bytes = data
self._hasher.update(data_bytes)
def build(self) -> Integrity:
return Integrity(algorithm=self.algorithm, digest=self._hasher.hexdigest()) |
_renderer(wrap_type=TopKMetric)
class TopKMetricRenderer(MetricRenderer):
yaxis_name: str
header: str
def render_html(self, obj: TopKMetric) -> List[BaseWidgetInfo]:
metric_result = obj.get_result()
k = metric_result.k
counters = [CounterData.float(label='current', value=metric_result.current[k], precision=3)]
if (metric_result.reference is not None):
counters.append(CounterData.float(label='reference', value=metric_result.reference[k], precision=3))
fig = plot_metric_k(metric_result.current, metric_result.reference, self.yaxis_name)
header_part = ' No feedback users included.'
if (not obj.no_feedback_users):
header_part = ' No feedback users excluded.'
return [header_text(label=((self.header + f' (top-{k}).') + header_part)), counter(counters=counters), plotly_figure(title='', figure=fig)] |
.skipif((blinker is None), reason='blinker is not installed')
def test_client_json_no_app_context(app, client):
('/hello', methods=['POST'])
def hello():
return f"Hello, {flask.request.json['name']}!"
class Namespace():
count = 0
def add(self, app):
self.count += 1
ns = Namespace()
with appcontext_popped.connected_to(ns.add, app):
rv = client.post('/hello', json={'name': 'Flask'})
assert (rv.get_data(as_text=True) == 'Hello, Flask!')
assert (ns.count == 1) |
def example():
def items(count):
items = []
for i in range(1, (count + 1)):
items.append(ft.Container(content=ft.Text(value=str(i)), alignment=ft.alignment.center, width=50, height=50, bgcolor=ft.colors.AMBER, border_radius=ft.border_radius.all(5)))
return items
async def gap_slider_change(e):
row.spacing = int(e.control.value)
(await row.update_async())
gap_slider = ft.Slider(min=0, max=50, divisions=50, value=0, label='{value}', on_change=gap_slider_change)
row = ft.Row(spacing=0, controls=items(10))
return ft.Column([ft.Column([ft.Text('Spacing between items'), gap_slider]), row]) |
class Cykleo(BikeShareSystem):
headers = {'Content-Type': 'application/json; charset=utf-8', 'User-Agent': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2', 'Referer': ' 'Authority': 'portail.cykleo.fr'}
meta = {'system': 'Cykleo', 'company': ['Cykleo SAS']}
def __init__(self, tag, meta, organization):
super(Cykleo, self).__init__(tag, meta)
self.url = BASE_URL.format(organization=organization)
def update(self, scraper=None):
scraper = (scraper or PyBikesScraper())
places = json.loads(scraper.request(self.url, method='GET', headers=Cykleo.headers, ssl_verification=False))
self.stations = list(map(CykleoStation, places)) |
class OptionPlotoptionsScatterSonificationTracksMappingGapbetweennotes(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
self._config(text, js_type=False)
def max(self):
return self._config_get(None)
def max(self, num: float):
self._config(num, js_type=False)
def min(self):
return self._config_get(None)
def min(self, num: float):
self._config(num, js_type=False)
def within(self):
return self._config_get(None)
def within(self, value: Any):
self._config(value, js_type=False) |
class OptionSeriesArearangeStatesHover(Options):
def animation(self) -> 'OptionSeriesArearangeStatesHoverAnimation':
return self._config_sub_data('animation', OptionSeriesArearangeStatesHoverAnimation)
def enabled(self):
return self._config_get(True)
def enabled(self, flag: bool):
self._config(flag, js_type=False)
def halo(self) -> 'OptionSeriesArearangeStatesHoverHalo':
return self._config_sub_data('halo', OptionSeriesArearangeStatesHoverHalo)
def lineWidth(self):
return self._config_get(None)
def lineWidth(self, num: float):
self._config(num, js_type=False)
def lineWidthPlus(self):
return self._config_get(1)
def lineWidthPlus(self, num: float):
self._config(num, js_type=False)
def marker(self) -> 'OptionSeriesArearangeStatesHoverMarker':
return self._config_sub_data('marker', OptionSeriesArearangeStatesHoverMarker) |
def filter_log_memory_global_setting_data(json):
option_list = ['full_final_warning_threshold', 'full_first_warning_threshold', 'full_second_warning_threshold', 'max_size']
json = remove_invalid_fields(json)
dictionary = {}
for attribute in option_list:
if ((attribute in json) and (json[attribute] is not None)):
dictionary[attribute] = json[attribute]
return dictionary |
class MockStorageItem(StorageItem):
def merge(self, other: 'StorageItem') -> None:
if (not isinstance(other, MockStorageItem)):
raise ValueError('other must be a MockStorageItem')
self.data = other.data
def __init__(self, identifier: ResourceIdentifier, data: str):
self._identifier = identifier
self.data = data
def identifier(self) -> ResourceIdentifier:
return self._identifier
def to_dict(self) -> Dict:
return {'identifier': self._identifier, 'data': self.data}
def serialize(self) -> bytes:
return str(self.data).encode() |
class CoursesList(viewsets.ReadOnlyModelViewSet):
queryset = Courses.objects.filter(is_delete=False)
serializer_class = CourseSerializers
permission_classes = (IsAuthenticated, IsOwnerOrReadOnly)
authentication_classes = [JSONWebTokenAuthentication]
pagination_class = StandardResultsSetPagination |
class SliderDates(SliderDate):
_js__builder__ = ('const minDt = new Date(options.min).getTime() / 1000; \nconst maxDt = new Date(options.max).getTime() / 1000; options.min = minDt; options.max = maxDt; \noptions.values = [new Date(data[0]).getTime() / 1000, new Date(data[1]).getTime() / 1000];\n%(jqId)s.slider(options).css(options.css)' % {'jqId': JsQuery.decorate_var('jQuery(htmlObj)', convert_var=False)})
def dom(self) -> JsHtmlJqueryUI.JsHtmlSliderDates:
if (self._dom is None):
self._dom = JsHtmlJqueryUI.JsHtmlSliderDates(self, page=self.page)
return self._dom |
class ProductFeedDocsTestCase(DocsTestCase):
def setUp(self):
product_catalog = self.create_product_catalog()
DocsDataStore.set('dpa_catalog_id', product_catalog.get_id())
product_feed = self.create_product_feed(product_catalog.get_id())
DocsDataStore.set('dpa_feed_id', product_feed.get_id())
def test_get_products(self):
feed = ProductFeed(DocsDataStore.get('dpa_feed_id'))
products = feed.get_products(fields=[Product.Field.title, Product.Field.price])
self.store_response(products) |
()
def okta_list_applications_with_inactive() -> Generator:
okta_applications = [OktaApplication(config={'id': 'okta_id_1', 'name': 'okta_id_1', 'label': 'okta_label_1', 'status': 'ACTIVE'}), OktaApplication(config={'id': 'okta_id_2', 'name': 'okta_id_2', 'label': 'okta_label_2', 'status': 'INACTIVE'})]
(yield okta_applications) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.