max_stars_repo_path
stringlengths 4
286
| max_stars_repo_name
stringlengths 5
119
| max_stars_count
int64 0
191k
| id
stringlengths 1
7
| content
stringlengths 6
1.03M
| content_cleaned
stringlengths 6
1.03M
| language
stringclasses 111
values | language_score
float64 0.03
1
| comments
stringlengths 0
556k
| edu_score
float64 0.32
5.03
| edu_int_score
int64 0
5
|
|---|---|---|---|---|---|---|---|---|---|---|
views.py
|
CharlieMinaya/Musify-Backend
| 0
|
6626251
|
<gh_stars>0
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import UserSerializer, RatingSerializer, SongSerializer
from .models import User, Rating, Song
class UserView(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
class RatingView(viewsets.ModelViewSet):
serializer_class = RatingSerializer
queryset = Rating.objects.all()
class SongView(viewsets.ModelViewSet):
serializer_class = SongSerializer
queryset = Song.objects.all()
|
from django.shortcuts import render
from rest_framework import viewsets
from .serializers import UserSerializer, RatingSerializer, SongSerializer
from .models import User, Rating, Song
class UserView(viewsets.ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
class RatingView(viewsets.ModelViewSet):
serializer_class = RatingSerializer
queryset = Rating.objects.all()
class SongView(viewsets.ModelViewSet):
serializer_class = SongSerializer
queryset = Song.objects.all()
|
none
| 1
| 1.987816
| 2
|
|
Python Basics/5. While Loop/01. Old Books.py
|
a-shiro/SoftUni-Courses
| 0
|
6626252
|
searched_book = input()
command = input()
book_count = 0
book_found = False
while command != "No More Books":
if command == searched_book:
book_found = True
break
book_count += 1
command = input()
if not book_found:
print("The book you search is not here!")
print(f"You checked {book_count} books.")
else:
print(f"You checked {book_count} books and found it.")
|
searched_book = input()
command = input()
book_count = 0
book_found = False
while command != "No More Books":
if command == searched_book:
book_found = True
break
book_count += 1
command = input()
if not book_found:
print("The book you search is not here!")
print(f"You checked {book_count} books.")
else:
print(f"You checked {book_count} books and found it.")
|
none
| 1
| 4.004835
| 4
|
|
FRemover/env/Lib/site-packages/pygame/examples/setmodescale.py
|
hardikbassi/FRemover
| 3
|
6626253
|
<filename>FRemover/env/Lib/site-packages/pygame/examples/setmodescale.py
#!/usr/bin/env python
""" pygame.examples.setmodescale
On high resolution displays(4k, 1080p) and tiny graphics games (640x480)
show up very small so that they are unplayable. SCALED scales up the window
for you. The game thinks it's a 640x480 window, but really it can be bigger.
Mouse events are scaled for you, so your game doesn't need to do it.
Passing SCALED to pygame.display.set_mode means the resolution depends
on desktop size and the graphics are scaled.
"""
from __future__ import print_function
import pygame as pg
pg.init()
RES = (160, 120)
FPS = 30
clock = pg.time.Clock()
print("desktops", pg.display.get_desktop_sizes())
screen = pg.display.set_mode(RES, pg.SCALED | pg.RESIZABLE)
# MAIN LOOP
done = False
i = 0
j = 0
r_name, r_flags = pg.display._get_renderer_info()
print("renderer:", r_name, "flags:", bin(r_flags))
for flag, name in [
(1, "software"),
(2, "accelerated"),
(4, "VSync"),
(8, "render to texture"),
]:
if flag & r_flags:
print(name)
while not done:
for event in pg.event.get():
if event.type == pg.KEYDOWN and event.key == pg.K_q:
done = True
if event.type == pg.QUIT:
done = True
if event.type == pg.KEYDOWN and event.key == pg.K_f:
pg.display.toggle_fullscreen()
if event.type == pg.VIDEORESIZE:
pg.display._resize_event(event)
i += 1
i = i % screen.get_width()
j += i % 2
j = j % screen.get_height()
screen.fill((255, 0, 255))
pg.draw.circle(screen, (0, 0, 0), (100, 100), 20)
pg.draw.circle(screen, (0, 0, 200), (0, 0), 10)
pg.draw.circle(screen, (200, 0, 0), (160, 120), 30)
pg.draw.line(screen, (250, 250, 0), (0, 120), (160, 0))
pg.draw.circle(screen, (255, 255, 255), (i, j), 5)
pg.display.flip()
clock.tick(FPS)
pg.quit()
|
<filename>FRemover/env/Lib/site-packages/pygame/examples/setmodescale.py
#!/usr/bin/env python
""" pygame.examples.setmodescale
On high resolution displays(4k, 1080p) and tiny graphics games (640x480)
show up very small so that they are unplayable. SCALED scales up the window
for you. The game thinks it's a 640x480 window, but really it can be bigger.
Mouse events are scaled for you, so your game doesn't need to do it.
Passing SCALED to pygame.display.set_mode means the resolution depends
on desktop size and the graphics are scaled.
"""
from __future__ import print_function
import pygame as pg
pg.init()
RES = (160, 120)
FPS = 30
clock = pg.time.Clock()
print("desktops", pg.display.get_desktop_sizes())
screen = pg.display.set_mode(RES, pg.SCALED | pg.RESIZABLE)
# MAIN LOOP
done = False
i = 0
j = 0
r_name, r_flags = pg.display._get_renderer_info()
print("renderer:", r_name, "flags:", bin(r_flags))
for flag, name in [
(1, "software"),
(2, "accelerated"),
(4, "VSync"),
(8, "render to texture"),
]:
if flag & r_flags:
print(name)
while not done:
for event in pg.event.get():
if event.type == pg.KEYDOWN and event.key == pg.K_q:
done = True
if event.type == pg.QUIT:
done = True
if event.type == pg.KEYDOWN and event.key == pg.K_f:
pg.display.toggle_fullscreen()
if event.type == pg.VIDEORESIZE:
pg.display._resize_event(event)
i += 1
i = i % screen.get_width()
j += i % 2
j = j % screen.get_height()
screen.fill((255, 0, 255))
pg.draw.circle(screen, (0, 0, 0), (100, 100), 20)
pg.draw.circle(screen, (0, 0, 200), (0, 0), 10)
pg.draw.circle(screen, (200, 0, 0), (160, 120), 30)
pg.draw.line(screen, (250, 250, 0), (0, 120), (160, 0))
pg.draw.circle(screen, (255, 255, 255), (i, j), 5)
pg.display.flip()
clock.tick(FPS)
pg.quit()
|
en
| 0.902286
|
#!/usr/bin/env python pygame.examples.setmodescale On high resolution displays(4k, 1080p) and tiny graphics games (640x480) show up very small so that they are unplayable. SCALED scales up the window for you. The game thinks it's a 640x480 window, but really it can be bigger. Mouse events are scaled for you, so your game doesn't need to do it. Passing SCALED to pygame.display.set_mode means the resolution depends on desktop size and the graphics are scaled. # MAIN LOOP
| 3.261934
| 3
|
minigame1/Entity.py
|
Tdallau/HRO_project2_minigames
| 0
|
6626254
|
import pygame
from pygame import *
class Entity(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
|
import pygame
from pygame import *
class Entity(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
|
none
| 1
| 2.712113
| 3
|
|
experiments/yago3-10/preprocessed_files/preprocess.py
|
nluedema/kge
| 0
|
6626255
|
import pandas as pd
entities_path = "/work-ceph/nluedema/kge/data/yago3-10/entity_ids.del"
with open(entities_path, "r") as f:
entities = list(
map(lambda s: s.strip().split("\t")[1], f.readlines())
)
data_path = "/work-ceph/nluedema/kge/experiments/yago3-10/"
text_path = f"{data_path}original_files/Textual data.txt"
with open(text_path, "r") as f:
text_data = list(
map(lambda s: s.strip().split("\t"), f.readlines())
)
# Remove duplicates
# Remove entities that are not in yago3-10
ent_set = set()
text_path_preprocessed = f"{data_path}preprocessed_files/text_data.txt"
with open(text_path_preprocessed, "w") as f:
for t in text_data:
ent = t[0]
text = t[1]
# deal with unicode in text description
text = text.encode("utf-8").decode("unicode-escape")
# remove newlines that were introduced by decoding
text = text.replace("\n", " ")
if ent not in ent_set:
ent_set.add(ent)
else:
continue
if ent not in entities:
continue
f.write(f"{ent}\thasDescription\t{text}\n")
numeric_path = f"{data_path}original_files/numerical_data_merged.txt"
with open(numeric_path, "r") as f:
numeric_data = list(
map(lambda s: s.strip().split("\t"), f.readlines())
)
# Remove entities that are not in yago3-10
# Count the occurences of each relation
numeric_data_removed = []
rel_counts = {}
for t in numeric_data:
ent = t[0]
rel = t[1]
if ent not in entities:
continue
numeric_data_removed.append(t)
if rel not in rel_counts:
rel_counts[rel] = 1
else:
rel_counts[rel] += 1
# Remove triples with relations that have less than 5 occurences
numeric_path_preprocessed = f"{data_path}preprocessed_files/numeric_data.txt"
with open(numeric_path_preprocessed, "w") as f:
for t in numeric_data_removed:
ent = t[0]
rel = t[1]
val = t[2]
if rel_counts[rel] < 5:
continue
f.write(f"{ent}\t{rel}\t{val}\n")
|
import pandas as pd
entities_path = "/work-ceph/nluedema/kge/data/yago3-10/entity_ids.del"
with open(entities_path, "r") as f:
entities = list(
map(lambda s: s.strip().split("\t")[1], f.readlines())
)
data_path = "/work-ceph/nluedema/kge/experiments/yago3-10/"
text_path = f"{data_path}original_files/Textual data.txt"
with open(text_path, "r") as f:
text_data = list(
map(lambda s: s.strip().split("\t"), f.readlines())
)
# Remove duplicates
# Remove entities that are not in yago3-10
ent_set = set()
text_path_preprocessed = f"{data_path}preprocessed_files/text_data.txt"
with open(text_path_preprocessed, "w") as f:
for t in text_data:
ent = t[0]
text = t[1]
# deal with unicode in text description
text = text.encode("utf-8").decode("unicode-escape")
# remove newlines that were introduced by decoding
text = text.replace("\n", " ")
if ent not in ent_set:
ent_set.add(ent)
else:
continue
if ent not in entities:
continue
f.write(f"{ent}\thasDescription\t{text}\n")
numeric_path = f"{data_path}original_files/numerical_data_merged.txt"
with open(numeric_path, "r") as f:
numeric_data = list(
map(lambda s: s.strip().split("\t"), f.readlines())
)
# Remove entities that are not in yago3-10
# Count the occurences of each relation
numeric_data_removed = []
rel_counts = {}
for t in numeric_data:
ent = t[0]
rel = t[1]
if ent not in entities:
continue
numeric_data_removed.append(t)
if rel not in rel_counts:
rel_counts[rel] = 1
else:
rel_counts[rel] += 1
# Remove triples with relations that have less than 5 occurences
numeric_path_preprocessed = f"{data_path}preprocessed_files/numeric_data.txt"
with open(numeric_path_preprocessed, "w") as f:
for t in numeric_data_removed:
ent = t[0]
rel = t[1]
val = t[2]
if rel_counts[rel] < 5:
continue
f.write(f"{ent}\t{rel}\t{val}\n")
|
en
| 0.966457
|
# Remove duplicates # Remove entities that are not in yago3-10 # deal with unicode in text description # remove newlines that were introduced by decoding # Remove entities that are not in yago3-10 # Count the occurences of each relation # Remove triples with relations that have less than 5 occurences
| 2.638886
| 3
|
tests/python/pants_test/engine/legacy/test_graph.py
|
tpasternak/pants
| 1
|
6626256
|
<filename>tests/python/pants_test/engine/legacy/test_graph.py<gh_stars>1-10
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import functools
import os
from typing import cast
from pants.build_graph.address_lookup_error import AddressLookupError
from pants.build_graph.build_file_aliases import BuildFileAliases, TargetMacro
from pants.build_graph.files import Files
from pants.testutil.test_base import TestBase
# Macro that adds the specified tag.
def macro(target_cls, tag, parse_context, tags=None, **kwargs):
tags = tags or set()
tags.add(tag)
parse_context.create_object(target_cls, tags=tags, **kwargs)
class GraphTest(TestBase):
_TAG = "tag_added_by_macro"
@classmethod
def alias_groups(cls) -> BuildFileAliases:
return cast(
BuildFileAliases,
super()
.alias_groups()
.merge(
BuildFileAliases(
targets={
"files": Files,
"tagged_files": TargetMacro.Factory.wrap(
functools.partial(macro, Files, cls._TAG), Files
),
}
)
),
)
def test_with_missing_target_in_existing_build_file(self) -> None:
self.create_library("3rdparty/python", "target", "Markdown")
self.create_library("3rdparty/python", "target", "Pygments")
# When a target is missing,
# the suggestions should be in order
# and there should only be one copy of the error if tracing is off.
expected_message = (
'"rutabaga" was not found in namespace "3rdparty/python".'
".*Did you mean one of:\n"
".*:Markdown\n"
".*:Pygments\n"
)
with self.assertRaisesRegex(AddressLookupError, expected_message):
self.targets("3rdparty/python:rutabaga")
def test_with_missing_directory_fails(self) -> None:
with self.assertRaises(AddressLookupError) as cm:
self.targets("no-such-path:")
self.assertIn('Path "no-such-path" does not contain any BUILD files', str(cm.exception))
def test_invalidate_fsnode(self) -> None:
# NB: Invalidation is now more directly tested in unit tests in the `graph` crate.
self.create_library("src/example", "target", "things")
self.targets("src/example::")
invalidated_count = self.invalidate_for("src/example/BUILD")
self.assertGreater(invalidated_count, 0)
def test_sources_ordering(self) -> None:
input_sources = ["p", "a", "n", "t", "s", "b", "u", "i", "l", "d"]
expected_sources = sorted(input_sources)
self.create_library("src/example", "files", "things", sources=input_sources)
target = self.target("src/example:things")
sources = [os.path.basename(s) for s in target.sources_relative_to_buildroot()]
self.assertEqual(expected_sources, sources)
def test_target_macro_override(self) -> None:
"""Tests that we can "wrap" an existing target type with additional functionality.
Installs an additional TargetMacro that wraps `target` aliases to add a tag to all
definitions.
"""
files = self.create_library("src/example", "tagged_files", "things")
self.assertIn(self._TAG, files.tags)
self.assertEqual(type(files), Files)
|
<filename>tests/python/pants_test/engine/legacy/test_graph.py<gh_stars>1-10
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import functools
import os
from typing import cast
from pants.build_graph.address_lookup_error import AddressLookupError
from pants.build_graph.build_file_aliases import BuildFileAliases, TargetMacro
from pants.build_graph.files import Files
from pants.testutil.test_base import TestBase
# Macro that adds the specified tag.
def macro(target_cls, tag, parse_context, tags=None, **kwargs):
tags = tags or set()
tags.add(tag)
parse_context.create_object(target_cls, tags=tags, **kwargs)
class GraphTest(TestBase):
_TAG = "tag_added_by_macro"
@classmethod
def alias_groups(cls) -> BuildFileAliases:
return cast(
BuildFileAliases,
super()
.alias_groups()
.merge(
BuildFileAliases(
targets={
"files": Files,
"tagged_files": TargetMacro.Factory.wrap(
functools.partial(macro, Files, cls._TAG), Files
),
}
)
),
)
def test_with_missing_target_in_existing_build_file(self) -> None:
self.create_library("3rdparty/python", "target", "Markdown")
self.create_library("3rdparty/python", "target", "Pygments")
# When a target is missing,
# the suggestions should be in order
# and there should only be one copy of the error if tracing is off.
expected_message = (
'"rutabaga" was not found in namespace "3rdparty/python".'
".*Did you mean one of:\n"
".*:Markdown\n"
".*:Pygments\n"
)
with self.assertRaisesRegex(AddressLookupError, expected_message):
self.targets("3rdparty/python:rutabaga")
def test_with_missing_directory_fails(self) -> None:
with self.assertRaises(AddressLookupError) as cm:
self.targets("no-such-path:")
self.assertIn('Path "no-such-path" does not contain any BUILD files', str(cm.exception))
def test_invalidate_fsnode(self) -> None:
# NB: Invalidation is now more directly tested in unit tests in the `graph` crate.
self.create_library("src/example", "target", "things")
self.targets("src/example::")
invalidated_count = self.invalidate_for("src/example/BUILD")
self.assertGreater(invalidated_count, 0)
def test_sources_ordering(self) -> None:
input_sources = ["p", "a", "n", "t", "s", "b", "u", "i", "l", "d"]
expected_sources = sorted(input_sources)
self.create_library("src/example", "files", "things", sources=input_sources)
target = self.target("src/example:things")
sources = [os.path.basename(s) for s in target.sources_relative_to_buildroot()]
self.assertEqual(expected_sources, sources)
def test_target_macro_override(self) -> None:
"""Tests that we can "wrap" an existing target type with additional functionality.
Installs an additional TargetMacro that wraps `target` aliases to add a tag to all
definitions.
"""
files = self.create_library("src/example", "tagged_files", "things")
self.assertIn(self._TAG, files.tags)
self.assertEqual(type(files), Files)
|
en
| 0.790353
|
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). # Macro that adds the specified tag. # When a target is missing, # the suggestions should be in order # and there should only be one copy of the error if tracing is off. # NB: Invalidation is now more directly tested in unit tests in the `graph` crate. Tests that we can "wrap" an existing target type with additional functionality. Installs an additional TargetMacro that wraps `target` aliases to add a tag to all definitions.
| 2.065625
| 2
|
navoica_enroll/users/migrations/0005_auto_20200313_1332.py
|
hoffmannkrzysztof/navoica-enroll-web
| 0
|
6626257
|
<filename>navoica_enroll/users/migrations/0005_auto_20200313_1332.py
# Generated by Django 2.2.10 on 2020-03-13 13:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20200223_1927'),
]
operations = [
migrations.AlterField(
model_name='userregistrationcourse',
name='pesel',
field=models.CharField(
help_text='For people who do not have a PESEL number, type in NONE.',
max_length=11, verbose_name='PESEL'),
),
]
|
<filename>navoica_enroll/users/migrations/0005_auto_20200313_1332.py
# Generated by Django 2.2.10 on 2020-03-13 13:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0004_auto_20200223_1927'),
]
operations = [
migrations.AlterField(
model_name='userregistrationcourse',
name='pesel',
field=models.CharField(
help_text='For people who do not have a PESEL number, type in NONE.',
max_length=11, verbose_name='PESEL'),
),
]
|
en
| 0.64136
|
# Generated by Django 2.2.10 on 2020-03-13 13:32
| 1.590781
| 2
|
Types & Operations/Integers-&-Floating-Point-Numbers/Exponentiation-Remainder.py
|
PableraShow/python-exercises
| 8
|
6626258
|
<filename>Types & Operations/Integers-&-Floating-Point-Numbers/Exponentiation-Remainder.py
"""
Given a number m, this returns the remainder of x to the power of y, divided by m. Given no m, this returns x to the power of y, just like x ** y.
Syntax:
pow(x, y)
pow(x, y, m)
"""
print pow(3, 4)
# 81
print pow(3, 4, 2)
# 1
|
<filename>Types & Operations/Integers-&-Floating-Point-Numbers/Exponentiation-Remainder.py
"""
Given a number m, this returns the remainder of x to the power of y, divided by m. Given no m, this returns x to the power of y, just like x ** y.
Syntax:
pow(x, y)
pow(x, y, m)
"""
print pow(3, 4)
# 81
print pow(3, 4, 2)
# 1
|
en
| 0.605479
|
Given a number m, this returns the remainder of x to the power of y, divided by m. Given no m, this returns x to the power of y, just like x ** y.
Syntax:
pow(x, y)
pow(x, y, m) # 81 # 1
| 4.560841
| 5
|
setup.py
|
onkelbeh/simplehound
| 0
|
6626259
|
from setuptools import setup, find_packages
VERSION = "0.3"
REQUIRES = ["requests"]
setup(
name="simplehound",
version=VERSION,
url="https://github.com/robmarkcole/simplehound",
author="<NAME>",
author_email="<EMAIL>",
description="Unofficial python API for Sighthound",
install_requires=REQUIRES,
packages=find_packages(),
license="Apache License, Version 2.0",
python_requires=">=3.6",
classifiers=[
"Intended Audience :: Developers",
"Natural Language :: English",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
],
)
|
from setuptools import setup, find_packages
VERSION = "0.3"
REQUIRES = ["requests"]
setup(
name="simplehound",
version=VERSION,
url="https://github.com/robmarkcole/simplehound",
author="<NAME>",
author_email="<EMAIL>",
description="Unofficial python API for Sighthound",
install_requires=REQUIRES,
packages=find_packages(),
license="Apache License, Version 2.0",
python_requires=">=3.6",
classifiers=[
"Intended Audience :: Developers",
"Natural Language :: English",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
],
)
|
none
| 1
| 1.213507
| 1
|
|
src/graspnet_baseline/dataset/graspnet_dataset.py
|
1heart/graspnet-baseline
| 0
|
6626260
|
""" GraspNet dataset processing.
Author: chenxi-wang
"""
import os
import sys
import numpy as np
import scipy.io as scio
from PIL import Image
import torch
from collections import abc as container_abcs
from torch.utils.data import Dataset
from tqdm import tqdm
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'utils'))
from data_utils import CameraInfo, transform_point_cloud, create_point_cloud_from_depth_image,\
get_workspace_mask, remove_invisible_grasp_points
class GraspNetDataset(Dataset):
def __init__(self, root, valid_obj_idxs, grasp_labels, camera='kinect', split='train', num_points=20000,
remove_outlier=False, remove_invisible=True, augment=False, load_label=True):
assert(num_points<=50000)
self.root = root
self.split = split
self.num_points = num_points
self.remove_outlier = remove_outlier
self.remove_invisible = remove_invisible
self.valid_obj_idxs = valid_obj_idxs
self.grasp_labels = grasp_labels
self.camera = camera
self.augment = augment
self.load_label = load_label
self.collision_labels = {}
if split == 'train':
self.sceneIds = list( range(100) )
elif split == 'test':
self.sceneIds = list( range(100,190) )
elif split == 'test_seen':
self.sceneIds = list( range(100,130) )
elif split == 'test_similar':
self.sceneIds = list( range(130,160) )
elif split == 'test_novel':
self.sceneIds = list( range(160,190) )
self.sceneIds = ['scene_{}'.format(str(x).zfill(4)) for x in self.sceneIds]
self.colorpath = []
self.depthpath = []
self.labelpath = []
self.metapath = []
self.scenename = []
self.frameid = []
for x in tqdm(self.sceneIds, desc = 'Loading data path and collision labels...'):
for img_num in range(256):
self.colorpath.append(os.path.join(root, 'scenes', x, camera, 'rgb', str(img_num).zfill(4)+'.png'))
self.depthpath.append(os.path.join(root, 'scenes', x, camera, 'depth', str(img_num).zfill(4)+'.png'))
self.labelpath.append(os.path.join(root, 'scenes', x, camera, 'label', str(img_num).zfill(4)+'.png'))
self.metapath.append(os.path.join(root, 'scenes', x, camera, 'meta', str(img_num).zfill(4)+'.mat'))
self.scenename.append(x.strip())
self.frameid.append(img_num)
if self.load_label:
collision_labels = np.load(os.path.join(root, 'collision_label', x.strip(), 'collision_labels.npz'))
self.collision_labels[x.strip()] = {}
for i in range(len(collision_labels)):
self.collision_labels[x.strip()][i] = collision_labels['arr_{}'.format(i)]
def scene_list(self):
return self.scenename
def __len__(self):
return len(self.depthpath)
def augment_data(self, point_clouds, object_poses_list):
# Flipping along the YZ plane
if np.random.random() > 0.5:
flip_mat = np.array([[-1, 0, 0],
[ 0, 1, 0],
[ 0, 0, 1]])
point_clouds = transform_point_cloud(point_clouds, flip_mat, '3x3')
for i in range(len(object_poses_list)):
object_poses_list[i] = np.dot(flip_mat, object_poses_list[i]).astype(np.float32)
# Rotation along up-axis/Z-axis
rot_angle = (np.random.random()*np.pi/3) - np.pi/6 # -30 ~ +30 degree
c, s = np.cos(rot_angle), np.sin(rot_angle)
rot_mat = np.array([[1, 0, 0],
[0, c,-s],
[0, s, c]])
point_clouds = transform_point_cloud(point_clouds, rot_mat, '3x3')
for i in range(len(object_poses_list)):
object_poses_list[i] = np.dot(rot_mat, object_poses_list[i]).astype(np.float32)
return point_clouds, object_poses_list
def __getitem__(self, index):
if self.load_label:
return self.get_data_label(index)
else:
return self.get_data(index)
def get_data(self, index, return_raw_cloud=False):
color = np.array(Image.open(self.colorpath[index]), dtype=np.float32) / 255.0
depth = np.array(Image.open(self.depthpath[index]))
seg = np.array(Image.open(self.labelpath[index]))
meta = scio.loadmat(self.metapath[index])
scene = self.scenename[index]
try:
intrinsic = meta['intrinsic_matrix']
factor_depth = meta['factor_depth']
except Exception as e:
print(repr(e))
print(scene)
camera = CameraInfo(1280.0, 720.0, intrinsic[0][0], intrinsic[1][1], intrinsic[0][2], intrinsic[1][2], factor_depth)
# generate cloud
cloud = create_point_cloud_from_depth_image(depth, camera, organized=True)
# get valid points
depth_mask = (depth > 0)
seg_mask = (seg > 0)
if self.remove_outlier:
camera_poses = np.load(os.path.join(self.root, 'scenes', scene, self.camera, 'camera_poses.npy'))
align_mat = np.load(os.path.join(self.root, 'scenes', scene, self.camera, 'cam0_wrt_table.npy'))
trans = np.dot(align_mat, camera_poses[self.frameid[index]])
workspace_mask = get_workspace_mask(cloud, seg, trans=trans, organized=True, outlier=0.02)
mask = (depth_mask & workspace_mask)
else:
mask = depth_mask
cloud_masked = cloud[mask]
color_masked = color[mask]
seg_masked = seg[mask]
if return_raw_cloud:
return cloud_masked, color_masked
# sample points
if len(cloud_masked) >= self.num_points:
idxs = np.random.choice(len(cloud_masked), self.num_points, replace=False)
else:
idxs1 = np.arange(len(cloud_masked))
idxs2 = np.random.choice(len(cloud_masked), self.num_points-len(cloud_masked), replace=True)
idxs = np.concatenate([idxs1, idxs2], axis=0)
cloud_sampled = cloud_masked[idxs]
color_sampled = color_masked[idxs]
ret_dict = {}
ret_dict['point_clouds'] = cloud_sampled.astype(np.float32)
ret_dict['cloud_colors'] = color_sampled.astype(np.float32)
return ret_dict
def get_data_label(self, index):
color = np.array(Image.open(self.colorpath[index]), dtype=np.float32) / 255.0
depth = np.array(Image.open(self.depthpath[index]))
seg = np.array(Image.open(self.labelpath[index]))
meta = scio.loadmat(self.metapath[index])
scene = self.scenename[index]
try:
obj_idxs = meta['cls_indexes'].flatten().astype(np.int32)
poses = meta['poses']
intrinsic = meta['intrinsic_matrix']
factor_depth = meta['factor_depth']
except Exception as e:
print(repr(e))
print(scene)
camera = CameraInfo(1280.0, 720.0, intrinsic[0][0], intrinsic[1][1], intrinsic[0][2], intrinsic[1][2], factor_depth)
# generate cloud
cloud = create_point_cloud_from_depth_image(depth, camera, organized=True)
# get valid points
depth_mask = (depth > 0)
seg_mask = (seg > 0)
if self.remove_outlier:
camera_poses = np.load(os.path.join(self.root, 'scenes', scene, self.camera, 'camera_poses.npy'))
align_mat = np.load(os.path.join(self.root, 'scenes', scene, self.camera, 'cam0_wrt_table.npy'))
trans = np.dot(align_mat, camera_poses[self.frameid[index]])
workspace_mask = get_workspace_mask(cloud, seg, trans=trans, organized=True, outlier=0.02)
mask = (depth_mask & workspace_mask)
else:
mask = depth_mask
cloud_masked = cloud[mask]
color_masked = color[mask]
seg_masked = seg[mask]
# sample points
if len(cloud_masked) >= self.num_points:
idxs = np.random.choice(len(cloud_masked), self.num_points, replace=False)
else:
idxs1 = np.arange(len(cloud_masked))
idxs2 = np.random.choice(len(cloud_masked), self.num_points-len(cloud_masked), replace=True)
idxs = np.concatenate([idxs1, idxs2], axis=0)
cloud_sampled = cloud_masked[idxs]
color_sampled = color_masked[idxs]
seg_sampled = seg_masked[idxs]
objectness_label = seg_sampled.copy()
objectness_label[objectness_label>1] = 1
object_poses_list = []
grasp_points_list = []
grasp_offsets_list = []
grasp_scores_list = []
grasp_tolerance_list = []
for i, obj_idx in enumerate(obj_idxs):
if obj_idx not in self.valid_obj_idxs:
continue
if (seg_sampled == obj_idx).sum() < 50:
continue
object_poses_list.append(poses[:, :, i])
points, offsets, scores, tolerance = self.grasp_labels[obj_idx]
collision = self.collision_labels[scene][i] #(Np, V, A, D)
# remove invisible grasp points
if self.remove_invisible:
visible_mask = remove_invisible_grasp_points(cloud_sampled[seg_sampled==obj_idx], points, poses[:,:,i], th=0.01)
points = points[visible_mask]
offsets = offsets[visible_mask]
scores = scores[visible_mask]
tolerance = tolerance[visible_mask]
collision = collision[visible_mask]
idxs = np.random.choice(len(points), min(max(int(len(points)/4),300),len(points)), replace=False)
grasp_points_list.append(points[idxs])
grasp_offsets_list.append(offsets[idxs])
collision = collision[idxs].copy()
scores = scores[idxs].copy()
scores[collision] = 0
grasp_scores_list.append(scores)
tolerance = tolerance[idxs].copy()
tolerance[collision] = 0
grasp_tolerance_list.append(tolerance)
if self.augment:
cloud_sampled, object_poses_list = self.augment_data(cloud_sampled, object_poses_list)
ret_dict = {}
ret_dict['point_clouds'] = cloud_sampled.astype(np.float32)
ret_dict['cloud_colors'] = color_sampled.astype(np.float32)
ret_dict['objectness_label'] = objectness_label.astype(np.int64)
ret_dict['object_poses_list'] = object_poses_list
ret_dict['grasp_points_list'] = grasp_points_list
ret_dict['grasp_offsets_list'] = grasp_offsets_list
ret_dict['grasp_labels_list'] = grasp_scores_list
ret_dict['grasp_tolerance_list'] = grasp_tolerance_list
return ret_dict
def load_grasp_labels(root):
obj_names = list(range(88))
valid_obj_idxs = []
grasp_labels = {}
for i, obj_name in enumerate(tqdm(obj_names, desc='Loading grasping labels...')):
if i == 18: continue
valid_obj_idxs.append(i + 1) #here align with label png
label = np.load(os.path.join(root, 'grasp_label', '{}_labels.npz'.format(str(i).zfill(3))))
tolerance = np.load(os.path.join(BASE_DIR, 'tolerance', '{}_tolerance.npy'.format(str(i).zfill(3))))
grasp_labels[i + 1] = (label['points'].astype(np.float32), label['offsets'].astype(np.float32),
label['scores'].astype(np.float32), tolerance)
return valid_obj_idxs, grasp_labels
def collate_fn(batch):
if type(batch[0]).__module__ == 'numpy':
return torch.stack([torch.from_numpy(b) for b in batch], 0)
elif isinstance(batch[0], container_abcs.Mapping):
return {key:collate_fn([d[key] for d in batch]) for key in batch[0]}
elif isinstance(batch[0], container_abcs.Sequence):
return [[torch.from_numpy(sample) for sample in b] for b in batch]
raise TypeError("batch must contain tensors, dicts or lists; found {}".format(type(batch[0])))
if __name__ == "__main__":
root = '/data/Benchmark/graspnet'
valid_obj_idxs, grasp_labels = load_grasp_labels(root)
train_dataset = GraspNetDataset(root, valid_obj_idxs, grasp_labels, split='train', remove_outlier=True, remove_invisible=True, num_points=20000)
print(len(train_dataset))
end_points = train_dataset[233]
cloud = end_points['point_clouds']
seg = end_points['objectness_label']
print(cloud.shape)
print(cloud.dtype)
print(cloud[:,0].min(), cloud[:,0].max())
print(cloud[:,1].min(), cloud[:,1].max())
print(cloud[:,2].min(), cloud[:,2].max())
print(seg.shape)
print((seg>0).sum())
print(seg.dtype)
print(np.unique(seg))
|
""" GraspNet dataset processing.
Author: chenxi-wang
"""
import os
import sys
import numpy as np
import scipy.io as scio
from PIL import Image
import torch
from collections import abc as container_abcs
from torch.utils.data import Dataset
from tqdm import tqdm
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'utils'))
from data_utils import CameraInfo, transform_point_cloud, create_point_cloud_from_depth_image,\
get_workspace_mask, remove_invisible_grasp_points
class GraspNetDataset(Dataset):
def __init__(self, root, valid_obj_idxs, grasp_labels, camera='kinect', split='train', num_points=20000,
remove_outlier=False, remove_invisible=True, augment=False, load_label=True):
assert(num_points<=50000)
self.root = root
self.split = split
self.num_points = num_points
self.remove_outlier = remove_outlier
self.remove_invisible = remove_invisible
self.valid_obj_idxs = valid_obj_idxs
self.grasp_labels = grasp_labels
self.camera = camera
self.augment = augment
self.load_label = load_label
self.collision_labels = {}
if split == 'train':
self.sceneIds = list( range(100) )
elif split == 'test':
self.sceneIds = list( range(100,190) )
elif split == 'test_seen':
self.sceneIds = list( range(100,130) )
elif split == 'test_similar':
self.sceneIds = list( range(130,160) )
elif split == 'test_novel':
self.sceneIds = list( range(160,190) )
self.sceneIds = ['scene_{}'.format(str(x).zfill(4)) for x in self.sceneIds]
self.colorpath = []
self.depthpath = []
self.labelpath = []
self.metapath = []
self.scenename = []
self.frameid = []
for x in tqdm(self.sceneIds, desc = 'Loading data path and collision labels...'):
for img_num in range(256):
self.colorpath.append(os.path.join(root, 'scenes', x, camera, 'rgb', str(img_num).zfill(4)+'.png'))
self.depthpath.append(os.path.join(root, 'scenes', x, camera, 'depth', str(img_num).zfill(4)+'.png'))
self.labelpath.append(os.path.join(root, 'scenes', x, camera, 'label', str(img_num).zfill(4)+'.png'))
self.metapath.append(os.path.join(root, 'scenes', x, camera, 'meta', str(img_num).zfill(4)+'.mat'))
self.scenename.append(x.strip())
self.frameid.append(img_num)
if self.load_label:
collision_labels = np.load(os.path.join(root, 'collision_label', x.strip(), 'collision_labels.npz'))
self.collision_labels[x.strip()] = {}
for i in range(len(collision_labels)):
self.collision_labels[x.strip()][i] = collision_labels['arr_{}'.format(i)]
def scene_list(self):
return self.scenename
def __len__(self):
return len(self.depthpath)
def augment_data(self, point_clouds, object_poses_list):
# Flipping along the YZ plane
if np.random.random() > 0.5:
flip_mat = np.array([[-1, 0, 0],
[ 0, 1, 0],
[ 0, 0, 1]])
point_clouds = transform_point_cloud(point_clouds, flip_mat, '3x3')
for i in range(len(object_poses_list)):
object_poses_list[i] = np.dot(flip_mat, object_poses_list[i]).astype(np.float32)
# Rotation along up-axis/Z-axis
rot_angle = (np.random.random()*np.pi/3) - np.pi/6 # -30 ~ +30 degree
c, s = np.cos(rot_angle), np.sin(rot_angle)
rot_mat = np.array([[1, 0, 0],
[0, c,-s],
[0, s, c]])
point_clouds = transform_point_cloud(point_clouds, rot_mat, '3x3')
for i in range(len(object_poses_list)):
object_poses_list[i] = np.dot(rot_mat, object_poses_list[i]).astype(np.float32)
return point_clouds, object_poses_list
def __getitem__(self, index):
if self.load_label:
return self.get_data_label(index)
else:
return self.get_data(index)
def get_data(self, index, return_raw_cloud=False):
color = np.array(Image.open(self.colorpath[index]), dtype=np.float32) / 255.0
depth = np.array(Image.open(self.depthpath[index]))
seg = np.array(Image.open(self.labelpath[index]))
meta = scio.loadmat(self.metapath[index])
scene = self.scenename[index]
try:
intrinsic = meta['intrinsic_matrix']
factor_depth = meta['factor_depth']
except Exception as e:
print(repr(e))
print(scene)
camera = CameraInfo(1280.0, 720.0, intrinsic[0][0], intrinsic[1][1], intrinsic[0][2], intrinsic[1][2], factor_depth)
# generate cloud
cloud = create_point_cloud_from_depth_image(depth, camera, organized=True)
# get valid points
depth_mask = (depth > 0)
seg_mask = (seg > 0)
if self.remove_outlier:
camera_poses = np.load(os.path.join(self.root, 'scenes', scene, self.camera, 'camera_poses.npy'))
align_mat = np.load(os.path.join(self.root, 'scenes', scene, self.camera, 'cam0_wrt_table.npy'))
trans = np.dot(align_mat, camera_poses[self.frameid[index]])
workspace_mask = get_workspace_mask(cloud, seg, trans=trans, organized=True, outlier=0.02)
mask = (depth_mask & workspace_mask)
else:
mask = depth_mask
cloud_masked = cloud[mask]
color_masked = color[mask]
seg_masked = seg[mask]
if return_raw_cloud:
return cloud_masked, color_masked
# sample points
if len(cloud_masked) >= self.num_points:
idxs = np.random.choice(len(cloud_masked), self.num_points, replace=False)
else:
idxs1 = np.arange(len(cloud_masked))
idxs2 = np.random.choice(len(cloud_masked), self.num_points-len(cloud_masked), replace=True)
idxs = np.concatenate([idxs1, idxs2], axis=0)
cloud_sampled = cloud_masked[idxs]
color_sampled = color_masked[idxs]
ret_dict = {}
ret_dict['point_clouds'] = cloud_sampled.astype(np.float32)
ret_dict['cloud_colors'] = color_sampled.astype(np.float32)
return ret_dict
def get_data_label(self, index):
color = np.array(Image.open(self.colorpath[index]), dtype=np.float32) / 255.0
depth = np.array(Image.open(self.depthpath[index]))
seg = np.array(Image.open(self.labelpath[index]))
meta = scio.loadmat(self.metapath[index])
scene = self.scenename[index]
try:
obj_idxs = meta['cls_indexes'].flatten().astype(np.int32)
poses = meta['poses']
intrinsic = meta['intrinsic_matrix']
factor_depth = meta['factor_depth']
except Exception as e:
print(repr(e))
print(scene)
camera = CameraInfo(1280.0, 720.0, intrinsic[0][0], intrinsic[1][1], intrinsic[0][2], intrinsic[1][2], factor_depth)
# generate cloud
cloud = create_point_cloud_from_depth_image(depth, camera, organized=True)
# get valid points
depth_mask = (depth > 0)
seg_mask = (seg > 0)
if self.remove_outlier:
camera_poses = np.load(os.path.join(self.root, 'scenes', scene, self.camera, 'camera_poses.npy'))
align_mat = np.load(os.path.join(self.root, 'scenes', scene, self.camera, 'cam0_wrt_table.npy'))
trans = np.dot(align_mat, camera_poses[self.frameid[index]])
workspace_mask = get_workspace_mask(cloud, seg, trans=trans, organized=True, outlier=0.02)
mask = (depth_mask & workspace_mask)
else:
mask = depth_mask
cloud_masked = cloud[mask]
color_masked = color[mask]
seg_masked = seg[mask]
# sample points
if len(cloud_masked) >= self.num_points:
idxs = np.random.choice(len(cloud_masked), self.num_points, replace=False)
else:
idxs1 = np.arange(len(cloud_masked))
idxs2 = np.random.choice(len(cloud_masked), self.num_points-len(cloud_masked), replace=True)
idxs = np.concatenate([idxs1, idxs2], axis=0)
cloud_sampled = cloud_masked[idxs]
color_sampled = color_masked[idxs]
seg_sampled = seg_masked[idxs]
objectness_label = seg_sampled.copy()
objectness_label[objectness_label>1] = 1
object_poses_list = []
grasp_points_list = []
grasp_offsets_list = []
grasp_scores_list = []
grasp_tolerance_list = []
for i, obj_idx in enumerate(obj_idxs):
if obj_idx not in self.valid_obj_idxs:
continue
if (seg_sampled == obj_idx).sum() < 50:
continue
object_poses_list.append(poses[:, :, i])
points, offsets, scores, tolerance = self.grasp_labels[obj_idx]
collision = self.collision_labels[scene][i] #(Np, V, A, D)
# remove invisible grasp points
if self.remove_invisible:
visible_mask = remove_invisible_grasp_points(cloud_sampled[seg_sampled==obj_idx], points, poses[:,:,i], th=0.01)
points = points[visible_mask]
offsets = offsets[visible_mask]
scores = scores[visible_mask]
tolerance = tolerance[visible_mask]
collision = collision[visible_mask]
idxs = np.random.choice(len(points), min(max(int(len(points)/4),300),len(points)), replace=False)
grasp_points_list.append(points[idxs])
grasp_offsets_list.append(offsets[idxs])
collision = collision[idxs].copy()
scores = scores[idxs].copy()
scores[collision] = 0
grasp_scores_list.append(scores)
tolerance = tolerance[idxs].copy()
tolerance[collision] = 0
grasp_tolerance_list.append(tolerance)
if self.augment:
cloud_sampled, object_poses_list = self.augment_data(cloud_sampled, object_poses_list)
ret_dict = {}
ret_dict['point_clouds'] = cloud_sampled.astype(np.float32)
ret_dict['cloud_colors'] = color_sampled.astype(np.float32)
ret_dict['objectness_label'] = objectness_label.astype(np.int64)
ret_dict['object_poses_list'] = object_poses_list
ret_dict['grasp_points_list'] = grasp_points_list
ret_dict['grasp_offsets_list'] = grasp_offsets_list
ret_dict['grasp_labels_list'] = grasp_scores_list
ret_dict['grasp_tolerance_list'] = grasp_tolerance_list
return ret_dict
def load_grasp_labels(root):
obj_names = list(range(88))
valid_obj_idxs = []
grasp_labels = {}
for i, obj_name in enumerate(tqdm(obj_names, desc='Loading grasping labels...')):
if i == 18: continue
valid_obj_idxs.append(i + 1) #here align with label png
label = np.load(os.path.join(root, 'grasp_label', '{}_labels.npz'.format(str(i).zfill(3))))
tolerance = np.load(os.path.join(BASE_DIR, 'tolerance', '{}_tolerance.npy'.format(str(i).zfill(3))))
grasp_labels[i + 1] = (label['points'].astype(np.float32), label['offsets'].astype(np.float32),
label['scores'].astype(np.float32), tolerance)
return valid_obj_idxs, grasp_labels
def collate_fn(batch):
if type(batch[0]).__module__ == 'numpy':
return torch.stack([torch.from_numpy(b) for b in batch], 0)
elif isinstance(batch[0], container_abcs.Mapping):
return {key:collate_fn([d[key] for d in batch]) for key in batch[0]}
elif isinstance(batch[0], container_abcs.Sequence):
return [[torch.from_numpy(sample) for sample in b] for b in batch]
raise TypeError("batch must contain tensors, dicts or lists; found {}".format(type(batch[0])))
if __name__ == "__main__":
root = '/data/Benchmark/graspnet'
valid_obj_idxs, grasp_labels = load_grasp_labels(root)
train_dataset = GraspNetDataset(root, valid_obj_idxs, grasp_labels, split='train', remove_outlier=True, remove_invisible=True, num_points=20000)
print(len(train_dataset))
end_points = train_dataset[233]
cloud = end_points['point_clouds']
seg = end_points['objectness_label']
print(cloud.shape)
print(cloud.dtype)
print(cloud[:,0].min(), cloud[:,0].max())
print(cloud[:,1].min(), cloud[:,1].max())
print(cloud[:,2].min(), cloud[:,2].max())
print(seg.shape)
print((seg>0).sum())
print(seg.dtype)
print(np.unique(seg))
|
en
| 0.636553
|
GraspNet dataset processing.
Author: chenxi-wang # Flipping along the YZ plane # Rotation along up-axis/Z-axis # -30 ~ +30 degree # generate cloud # get valid points # sample points # generate cloud # get valid points # sample points #(Np, V, A, D) # remove invisible grasp points #here align with label png
| 2.12675
| 2
|
tests/test_pysoundfile.py
|
a-hurst/SoundFile
| 0
|
6626261
|
import soundfile as sf
import numpy as np
import os
import io
import shutil
import pytest
import cffi
import sys
import gc
import weakref
# floating point data is typically limited to the interval [-1.0, 1.0],
# but smaller/larger values are supported as well
data_stereo = np.array([[1.75, -1.75],
[1.0, -1.0],
[0.5, -0.5],
[0.25, -0.25]])
data_mono = np.array([0, 1, 2, -2, -1], dtype='int16')
filename_stereo = 'tests/stereo.wav'
filename_mono = 'tests/mono.wav'
filename_raw = 'tests/mono.raw'
filename_new = 'tests/delme.please'
if sys.version_info >= (3, 6):
import pathlib
open_variants = 'name', 'fd', 'obj', 'pathlib'
else:
open_variants = 'name', 'fd', 'obj'
xfail_from_buffer = pytest.mark.xfail(cffi.__version_info__ < (0, 9),
reason="from_buffer() since CFFI 0.9")
def _file_existing(request, filename, fdarg, objarg=None):
if request.param == 'name':
return filename
if request.param == 'pathlib':
return pathlib.Path(filename)
elif request.param == 'fd':
fd = os.open(filename, fdarg)
def finalizer():
with pytest.raises(OSError):
os.close(fd)
request.addfinalizer(finalizer)
return fd
elif request.param == 'obj':
obj = open(filename, objarg, buffering=False)
request.addfinalizer(obj.close)
return obj
def _file_new(request, fdarg, objarg=None):
filename = filename_new
request.addfinalizer(lambda: os.remove(filename))
return _file_existing(request, filename, fdarg, objarg)
def _file_copy(request, filename, fdarg, objarg=None):
shutil.copy(filename, filename_new)
request.addfinalizer(lambda: os.remove(filename_new))
return _file_existing(request, filename_new, fdarg, objarg)
@pytest.fixture(params=open_variants)
def file_stereo_r(request):
return _file_existing(request, filename_stereo, os.O_RDONLY, 'rb')
@pytest.fixture(params=open_variants)
def file_mono_r(request):
return _file_existing(request, filename_mono, os.O_RDONLY, 'rb')
@pytest.fixture(params=open_variants)
def file_w(request):
return _file_new(request, os.O_CREAT | os.O_WRONLY, 'wb')
@pytest.fixture(params=open_variants)
def file_stereo_rplus(request):
return _file_copy(request, filename_stereo, os.O_RDWR, 'r+b')
@pytest.fixture(params=['obj'])
def file_obj_stereo_rplus(request):
return _file_copy(request, filename_stereo, os.O_RDWR, 'r+b')
@pytest.fixture(params=['obj'])
def file_obj_w(request):
return _file_new(request, os.O_CREAT | os.O_WRONLY, 'wb')
@pytest.fixture(params=open_variants)
def file_wplus(request):
return _file_new(request, os.O_CREAT | os.O_RDWR, 'w+b')
@pytest.yield_fixture
def file_inmemory():
with io.BytesIO() as f:
yield f
@pytest.yield_fixture
def sf_stereo_r(file_stereo_r):
with sf.SoundFile(file_stereo_r) as f:
yield f
@pytest.yield_fixture
def sf_stereo_w(file_w):
with sf.SoundFile(file_w, 'w', 44100, 2, format='WAV') as f:
yield f
@pytest.yield_fixture
def sf_stereo_rplus(file_stereo_rplus):
with sf.SoundFile(file_stereo_rplus, 'r+') as f:
yield f
@pytest.yield_fixture
def sf_stereo_wplus(file_wplus):
with sf.SoundFile(file_wplus, 'w+', 44100, 2,
format='WAV', subtype='FLOAT') as f:
yield f
# -----------------------------------------------------------------------------
# Test read() function
# -----------------------------------------------------------------------------
def test_if_read_returns_float64_data(file_stereo_r):
data, fs = sf.read(file_stereo_r)
assert fs == 44100
assert np.all(data == data_stereo)
assert data.dtype == np.float64
def test_read_float32(file_stereo_r):
data, fs = sf.read(file_stereo_r, dtype='float32')
assert np.all(data == data_stereo)
assert data.dtype == np.float32
def test_read_int16(file_mono_r):
data, fs = sf.read(file_mono_r, dtype='int16')
assert np.all(data == data_mono)
assert data.dtype == np.int16
def test_read_int32(file_mono_r):
data, fs = sf.read(file_mono_r, dtype='int32')
assert np.all(data // 2**16 == data_mono)
assert data.dtype == np.int32
def test_read_into_out(file_stereo_r):
out = np.empty((3, 2), dtype='float64')
data, fs = sf.read(file_stereo_r, out=out)
assert data is out
assert np.all(data == data_stereo[:3])
def test_if_read_into_malformed_out_fails(file_stereo_r):
out = np.empty((2, 3), dtype='float64')
with pytest.raises(ValueError):
sf.read(file_stereo_r, out=out)
def test_if_read_into_out_with_too_many_dimensions_fails(file_stereo_r):
out = np.empty((3, 2, 1), dtype='float64')
with pytest.raises(ValueError):
sf.read(file_stereo_r, out=out)
def test_if_read_into_zero_len_out_works(file_stereo_r):
out = np.empty((0, 2), dtype='float64')
data, fs = sf.read(file_stereo_r, out=out)
assert data is out
assert len(out) == 0
def test_read_into_non_contiguous_out(file_stereo_r):
out = np.empty(data_stereo.shape[::-1], dtype='float64')
if getattr(sys, 'pypy_version_info', (999,)) < (2, 6):
# The test for C-contiguous doesn't work with PyPy 2.5.0
sf.read(file_stereo_r, out=out.T)
else:
with pytest.raises(ValueError) as excinfo:
sf.read(file_stereo_r, out=out.T)
assert "C-contiguous" in str(excinfo.value)
def test_read_into_out_with_invalid_dtype(file_stereo_r):
out = np.empty((3, 2), dtype='int64')
with pytest.raises(ValueError) as excinfo:
sf.read(file_stereo_r, out=out)
assert "dtype must be one of" in str(excinfo.value)
def test_read_mono(file_mono_r):
data, fs = sf.read(file_mono_r, dtype='int16')
assert data.ndim == 1
assert np.all(data == data_mono)
def test_if_read_mono_with_always2d_returns_2d_array(file_mono_r):
data, fs = sf.read(file_mono_r, dtype='int16', always_2d=True)
assert data.ndim == 2
assert np.all(data == data_mono.reshape(-1, 1))
def test_read_mono_into_1d_out(file_mono_r):
out = np.empty(len(data_mono), dtype='int16')
data, fs = sf.read(file_mono_r, out=out)
assert data is out
assert np.all(data == data_mono)
def test_read_mono_into_2d_out(file_mono_r):
out = np.empty((len(data_mono), 1), dtype='int16')
data, fs = sf.read(file_mono_r, out=out)
assert data is out
assert np.all(data == data_mono.reshape(-1, 1))
def test_read_non_existing_file():
with pytest.raises(RuntimeError) as excinfo:
sf.read("i_do_not_exist.wav")
assert "Error opening 'i_do_not_exist.wav'" in str(excinfo.value)
# -----------------------------------------------------------------------------
# Test write() function
# -----------------------------------------------------------------------------
# The read() function is tested above, we assume here that it is working.
def test_write_float_data_to_float_file(file_inmemory):
sf.write(file_inmemory, data_stereo, 44100, format='WAV', subtype='FLOAT')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory)
assert np.all(read == data_stereo)
assert fs == 44100
def test_write_float_data_to_pcm_file(file_inmemory):
float_to_clipped_int16 = [
(-1.0 - 2**-15, -2**15 ),
(-1.0 , -2**15 ),
(-1.0 + 2**-15, -2**15 + 1),
( 0.0 , 0 ),
( 1.0 - 2**-14, 2**15 - 2),
( 1.0 - 2**-15, 2**15 - 1),
( 1.0 , 2**15 - 1),
]
written, expected = zip(*float_to_clipped_int16)
sf.write(file_inmemory, written, 44100, format='WAV', subtype='PCM_16')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory, dtype='int16')
assert np.all(read == expected)
assert fs == 44100
def test_write_int_data_to_pcm_file(file_inmemory):
sf.write(file_inmemory, data_mono, 44100, format='WAV')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory, dtype='int16')
assert fs == 44100
assert np.all(read == data_mono)
def test_write_int_data_to_float_file(file_inmemory):
"""This is a very uncommon use case."""
sf.write(file_inmemory, data_mono, 44100, format='WAV', subtype='FLOAT')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory, always_2d=False, dtype='float32')
assert np.all(read == data_mono)
assert fs == 44100
@pytest.mark.parametrize("filename", ["wav", ".wav", "wav.py"])
def test_write_with_unknown_extension(filename):
with pytest.raises(TypeError) as excinfo:
sf.write(filename, [0.0], 44100)
assert "file extension" in str(excinfo.value)
# -----------------------------------------------------------------------------
# Test blocks() function
# -----------------------------------------------------------------------------
def assert_equal_list_of_arrays(list1, list2):
"""Helper function to assert equality of all list items."""
for item1, item2 in zip(list1, list2):
assert np.all(item1 == item2)
def test_blocks_without_blocksize():
with pytest.raises(TypeError):
list(sf.blocks(filename_stereo))
def test_blocks_full_last_block(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2))
assert_equal_list_of_arrays(blocks, [data_stereo[0:2], data_stereo[2:4]])
def test_blocks_partial_last_block(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=3))
assert_equal_list_of_arrays(blocks, [data_stereo[0:3], data_stereo[3:4]])
def test_blocks_fill_last_block(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=3, fill_value=0))
last_block = np.row_stack((data_stereo[3:4], np.zeros((2, 2))))
assert_equal_list_of_arrays(blocks, [data_stereo[0:3], last_block])
def test_blocks_with_overlap(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=3, overlap=2))
assert_equal_list_of_arrays(blocks, [data_stereo[0:3], data_stereo[1:4]])
def test_blocks_with_start(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, start=2))
assert_equal_list_of_arrays(blocks, [data_stereo[2:4]])
def test_blocks_with_stop(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, stop=2))
assert_equal_list_of_arrays(blocks, [data_stereo[0:2]])
with pytest.raises(TypeError):
list(sf.blocks(filename_stereo, blocksize=2, frames=2, stop=2))
def test_blocks_with_too_large_start(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, start=666))
assert_equal_list_of_arrays(blocks, [[]])
def test_blocks_with_too_large_stop(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=3, stop=666))
assert_equal_list_of_arrays(blocks, [data_stereo[0:3], data_stereo[3:4]])
def test_blocks_with_negative_start_and_stop(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, start=-2, stop=-1))
assert_equal_list_of_arrays(blocks, [data_stereo[-2:-1]])
def test_blocks_with_stop_smaller_than_start(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, start=2, stop=1))
assert blocks == []
def test_blocks_with_frames(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, frames=3))
assert_equal_list_of_arrays(blocks, [data_stereo[0:2], data_stereo[2:3]])
def test_blocks_with_frames_and_fill_value(file_stereo_r):
blocks = list(
sf.blocks(file_stereo_r, blocksize=2, frames=3, fill_value=0))
last_block = np.row_stack((data_stereo[2:3], np.zeros((1, 2))))
assert_equal_list_of_arrays(blocks, [data_stereo[0:2], last_block])
def test_blocks_with_out(file_stereo_r):
out = np.empty((3, 2))
blocks = list(sf.blocks(file_stereo_r, out=out))
assert blocks[0] is out
# First frame was overwritten by second block:
assert np.all(blocks[0] == data_stereo[[3, 1, 2]])
assert blocks[1].base is out
assert np.all(blocks[1] == data_stereo[[3]])
with pytest.raises(TypeError):
list(sf.blocks(filename_stereo, blocksize=3, out=out))
def test_blocks_inplace_modification(file_stereo_r):
out = np.empty((3, 2))
blocks = []
for block in sf.blocks(file_stereo_r, out=out, overlap=1):
blocks.append(np.copy(block))
block *= 2
expected_blocks = [data_stereo[0:3], data_stereo[2:5]]
assert_equal_list_of_arrays(blocks, expected_blocks)
def test_blocks_mono():
blocks = list(sf.blocks(filename_mono, blocksize=3, dtype='int16',
fill_value=0))
assert_equal_list_of_arrays(blocks, [[0, 1, 2], [-2, -1, 0]])
def test_blocks_rplus(sf_stereo_rplus):
blocks = list(sf_stereo_rplus.blocks(blocksize=2))
assert_equal_list_of_arrays(blocks, [data_stereo[0:2], data_stereo[2:4]])
def test_blocks_wplus(sf_stereo_wplus):
"""There is nothing to yield in a 'w+' file."""
blocks = list(sf_stereo_wplus.blocks(blocksize=2, frames=666))
assert blocks == []
def test_blocks_write(sf_stereo_w):
with pytest.raises(RuntimeError):
list(sf_stereo_w.blocks(blocksize=2))
# -----------------------------------------------------------------------------
# Test SoundFile.__init__()
# -----------------------------------------------------------------------------
def test_open_bytes_filename():
with sf.SoundFile(filename_stereo.encode()) as f:
assert np.all(f.read() == data_stereo)
def test_open_with_invalid_file():
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(3.1415)
assert "Invalid file" in str(excinfo.value)
def test_open_with_invalid_mode():
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, 42)
assert "Invalid mode: 42" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf.SoundFile(filename_stereo, 'rr')
assert "Invalid mode: 'rr'" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf.SoundFile(filename_stereo, 'rw')
assert "exactly one of 'xrw'" in str(excinfo.value)
def test_open_with_more_invalid_arguments():
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, 'w', 3.1415, 2, format='WAV')
assert "integer" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 3.1415, format='WAV')
assert "integer" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 2, format='WAF')
assert "Unknown format" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 2, 'PCM16', format='WAV')
assert "Unknown subtype" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 2, 666, format='WAV')
assert "Invalid subtype" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 2, endian='BOTH', format='WAV')
assert "Unknown endian-ness" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 2, endian=True, format='WAV')
assert "Invalid endian-ness" in str(excinfo.value)
def test_open_r_and_rplus_with_too_many_arguments():
for mode in 'r', 'r+':
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode, samplerate=44100)
assert "Not allowed" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode, channels=2)
assert "Not allowed" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode, format='WAV')
assert "Not allowed" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode, subtype='FLOAT')
assert "Not allowed" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode, endian='FILE')
assert "Not allowed" in str(excinfo.value)
def test_open_w_and_wplus_with_too_few_arguments():
for mode in 'w', 'w+':
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, mode, samplerate=44100, channels=2)
assert "No format specified" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, mode, samplerate=44100, format='WAV')
assert "channels" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, mode, channels=2, format='WAV')
assert "samplerate" in str(excinfo.value)
def test_open_with_mode_is_none():
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode=None)
assert "Invalid mode: None" in str(excinfo.value)
with open(filename_stereo, 'rb') as fobj:
with sf.SoundFile(fobj, mode=None) as f:
assert f.mode == 'rb'
def test_open_with_mode_is_x():
with pytest.raises(OSError) as excinfo:
sf.SoundFile(filename_stereo, 'x', 44100, 2)
assert "exists" in str(excinfo.value)
with pytest.raises(OSError) as excinfo:
sf.SoundFile(filename_stereo, 'x+', 44100, 2)
assert "exists" in str(excinfo.value)
@pytest.mark.parametrize("mode", ['w', 'w+'])
def test_if_open_with_mode_w_truncates(file_stereo_rplus, mode):
with sf.SoundFile(file_stereo_rplus, mode, 48000, 6, format='AIFF') as f:
pass
with sf.SoundFile(filename_new) as f:
if isinstance(file_stereo_rplus, str):
assert f.samplerate == 48000
assert f.channels == 6
assert f.format == 'AIFF'
assert f.frames == 0
else:
# This doesn't really work for file descriptors and file objects
pass
class LimitedFile(object):
def __init__(self, file, attrs):
for attr in attrs:
setattr(self, attr, getattr(file, attr))
@pytest.mark.parametrize("readmethod", ['read', 'readinto'])
def test_virtual_io_readonly(file_obj_stereo_rplus, readmethod):
limitedfile = LimitedFile(file_obj_stereo_rplus,
['seek', 'tell', readmethod])
data, fs = sf.read(limitedfile)
assert fs == 44100
assert np.all(data == data_stereo)
def test_virtual_io_writeonly(file_obj_w):
limitedfile = LimitedFile(file_obj_w, ['seek', 'tell', 'write'])
sf.write(limitedfile, [0.5], 48000, format='WAV')
data, fs = sf.read(filename_new)
assert fs == 48000
assert data == [0.5]
VIRTUAL_IO_ATTRS = 'seek', 'tell', 'read', 'write'
@pytest.mark.parametrize("missing", VIRTUAL_IO_ATTRS)
def test_virtual_io_missing_attr(file_obj_stereo_rplus, missing):
attrs = list(VIRTUAL_IO_ATTRS)
goodfile = LimitedFile(file_obj_stereo_rplus, attrs)
success = sf.SoundFile(goodfile, 'r+')
attrs.remove(missing)
badfile = LimitedFile(file_obj_stereo_rplus, attrs)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(badfile, 'r+')
assert "Invalid file" in str(excinfo.value)
assert np.all(success.read() == data_stereo)
# -----------------------------------------------------------------------------
# Test file metadata
# -----------------------------------------------------------------------------
def test_file_content(sf_stereo_r):
assert np.all(data_stereo == sf_stereo_r.read())
def test_file_attributes_in_read_mode(sf_stereo_r):
if isinstance(sf_stereo_r.name, str):
assert sf_stereo_r.name == filename_stereo
elif not isinstance(sf_stereo_r.name, int):
assert sf_stereo_r.name.name == filename_stereo
assert sf_stereo_r.mode == 'r'
assert sf_stereo_r.samplerate == 44100
assert sf_stereo_r.channels == 2
assert sf_stereo_r.format == 'WAV'
assert sf_stereo_r.subtype == 'FLOAT'
assert sf_stereo_r.endian == 'FILE'
assert sf_stereo_r.format_info == 'WAV (Microsoft)'
assert sf_stereo_r.subtype_info == '32 bit float'
assert sf_stereo_r.sections == 1
assert sf_stereo_r.closed is False
assert sf_stereo_r.seekable() is True
assert sf_stereo_r.frames == len(data_stereo)
def test__repr__(sf_stereo_r):
assert repr(sf_stereo_r) == ("SoundFile({0.name!r}, mode='r', "
"samplerate=44100, channels=2, "
"format='WAV', subtype='FLOAT', "
"endian='FILE')").format(sf_stereo_r)
def test_extra_info(sf_stereo_r):
assert 'WAVE_FORMAT_IEEE_FLOAT' in sf_stereo_r.extra_info
def test_mode_should_be_in_write_mode(sf_stereo_w):
assert sf_stereo_w.mode == 'w'
assert sf_stereo_w.frames == 0
def test_mode_should_be_in_readwrite_mode(sf_stereo_rplus):
assert sf_stereo_rplus.mode == 'r+'
def test_file_truthiness(file_w):
with sf.SoundFile(file_w, 'w', 44100, 2, format='WAV') as f:
assert f
# -----------------------------------------------------------------------------
# Test seek/tell
# -----------------------------------------------------------------------------
def test_seek_in_read_mode(sf_stereo_r):
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 0
assert sf_stereo_r.tell() == 0
assert sf_stereo_r.seek(2) == 2
assert sf_stereo_r.tell() == 2
assert sf_stereo_r.seek(2, sf.SEEK_CUR) == 4
assert sf_stereo_r.seek(-2, sf.SEEK_END) == len(data_stereo) - 2
with pytest.raises(RuntimeError):
sf_stereo_r.seek(666)
with pytest.raises(RuntimeError):
sf_stereo_r.seek(-666)
def test_seek_in_write_mode(sf_stereo_w):
assert sf_stereo_w.seek(0, sf.SEEK_CUR) == 0
assert sf_stereo_w.tell() == 0
assert sf_stereo_w.seek(2) == 2
assert sf_stereo_w.tell() == 2
def test_seek_in_rplus_mode(sf_stereo_rplus):
assert sf_stereo_rplus.seek(0, sf.SEEK_CUR) == 0
assert sf_stereo_rplus.tell() == 0
assert sf_stereo_rplus.seek(2) == 2
assert sf_stereo_rplus.seek(0, sf.SEEK_CUR) == 2
assert sf_stereo_rplus.tell() == 2
@pytest.mark.parametrize("use_default", [True, False])
def test_truncate(file_stereo_rplus, use_default):
if (isinstance(file_stereo_rplus, (str, int))
or hasattr(file_stereo_rplus, '__fspath__')):
with sf.SoundFile(file_stereo_rplus, 'r+', closefd=False) as f:
if use_default:
f.seek(2)
f.truncate()
else:
f.truncate(2)
assert f.tell() == 2
assert f.frames == 2
if isinstance(file_stereo_rplus, int):
os.lseek(file_stereo_rplus, 0, os.SEEK_SET)
data, fs = sf.read(file_stereo_rplus)
assert np.all(data == data_stereo[:2])
assert fs == 44100
else:
# file objects don't support truncate()
with sf.SoundFile(file_stereo_rplus, 'r+', closefd=False) as f:
with pytest.raises(RuntimeError) as excinfo:
f.truncate()
assert "Error truncating" in str(excinfo.value)
# -----------------------------------------------------------------------------
# Test read
# -----------------------------------------------------------------------------
def test_read_write_only(sf_stereo_w):
with pytest.raises(RuntimeError):
sf_stereo_w.read(2)
def test_read_should_read_data_and_advance_read_pointer(sf_stereo_r):
data = sf_stereo_r.read(2)
assert np.all(data == data_stereo[:2])
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 2
def test_read_n_frames_should_return_n_frames(sf_stereo_r):
assert len(sf_stereo_r.read(2)) == 2
def test_read_all_frames_should_read_all_remaining_frames(sf_stereo_r):
sf_stereo_r.seek(-2, sf.SEEK_END)
assert np.all(sf_stereo_r.read() == data_stereo[-2:])
def test_read_over_end_should_return_only_remaining_frames(sf_stereo_r):
sf_stereo_r.seek(-2, sf.SEEK_END)
assert np.all(sf_stereo_r.read(4) == data_stereo[-2:])
def test_read_over_end_with_fill_should_reaturn_asked_frames(sf_stereo_r):
sf_stereo_r.seek(-2, sf.SEEK_END)
data = sf_stereo_r.read(4, fill_value=0)
assert np.all(data[:2] == data_stereo[-2:])
assert np.all(data[2:] == 0)
assert len(data) == 4
def test_read_into_out_over_end_should_return_shorter_data_and_write_into_out(
sf_stereo_r):
out = np.ones((4, sf_stereo_r.channels), dtype='float64')
sf_stereo_r.seek(-2, sf.SEEK_END)
data = sf_stereo_r.read(out=out)
assert np.all(data[:2] == out[:2])
assert np.all(data[2:] == 1)
assert out.shape == (4, sf_stereo_r.channels)
assert data.shape == (2, sf_stereo_r.channels)
def test_read_into_out_over_end_with_fill_should_return_full_data_and_write_into_out(
sf_stereo_r):
out = np.ones((4, sf_stereo_r.channels), dtype='float64')
sf_stereo_r.seek(-2, sf.SEEK_END)
data = sf_stereo_r.read(out=out, fill_value=0)
assert np.all(data == out)
assert np.all(data[2:] == 0)
assert out.shape == (4, sf_stereo_r.channels)
# -----------------------------------------------------------------------------
# Test buffer read
# -----------------------------------------------------------------------------
def test_buffer_read(sf_stereo_r):
buf = sf_stereo_r.buffer_read(2, dtype='float64')
assert len(buf) == 2 * 2 * 8
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 2
data = np.frombuffer(buf, dtype='float64').reshape(-1, 2)
assert np.all(data == data_stereo[:2])
buf = sf_stereo_r.buffer_read(dtype='float32')
assert len(buf) == 2 * 2 * 4
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 4
data = np.frombuffer(buf, dtype='float32').reshape(-1, 2)
assert np.all(data == data_stereo[2:])
buf = sf_stereo_r.buffer_read(dtype='float32')
assert len(buf) == 0
buf = sf_stereo_r.buffer_read(666, dtype='float32')
assert len(buf) == 0
with pytest.raises(ValueError) as excinfo:
sf_stereo_r.buffer_read(dtype='int8')
assert "dtype must be one of" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf_stereo_r.buffer_read()
assert "dtype must be one of" in str(excinfo.value)
@xfail_from_buffer
def test_buffer_read_into(sf_stereo_r):
out = np.ones((3, 2))
frames = sf_stereo_r.buffer_read_into(out, dtype='float64')
assert frames == 3
assert np.all(out == data_stereo[:3])
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 3
frames = sf_stereo_r.buffer_read_into(out, dtype='float64')
assert frames == 1
assert np.all(out[:1] == data_stereo[3:])
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 4
# -----------------------------------------------------------------------------
# Test write
# -----------------------------------------------------------------------------
def test_write_to_read_only_file_should_fail(sf_stereo_r):
with pytest.raises(RuntimeError):
sf_stereo_r.write(data_stereo)
def test_if_write_advances_write_pointer(sf_stereo_w):
position = sf_stereo_w.seek(0, sf.SEEK_CUR)
sf_stereo_w.write(data_stereo)
assert sf_stereo_w.seek(0, sf.SEEK_CUR) == position + len(data_stereo)
def test_write_flush_should_write_to_disk(sf_stereo_w):
sf_stereo_w.flush()
size = os.path.getsize(filename_new)
sf_stereo_w.write(data_stereo)
sf_stereo_w.flush()
assert os.path.getsize(filename_new) == size + data_stereo.size * 2
def test_wplus_read_written_data(sf_stereo_wplus):
sf_stereo_wplus.write(data_stereo)
assert sf_stereo_wplus.seek(0, sf.SEEK_CUR) == len(data_stereo)
sf_stereo_wplus.seek(0)
assert np.all(sf_stereo_wplus.read() == data_stereo)
assert sf_stereo_wplus.seek(0, sf.SEEK_CUR) == len(data_stereo)
sf_stereo_wplus.close()
data, fs = sf.read(filename_new)
assert np.all(data == data_stereo)
def test_rplus_append_data(sf_stereo_rplus):
sf_stereo_rplus.seek(0, sf.SEEK_END)
sf_stereo_rplus.write(data_stereo / 2)
sf_stereo_rplus.close()
data, fs = sf.read(filename_new)
assert np.all(data[:len(data_stereo)] == data_stereo)
assert np.all(data[len(data_stereo):] == data_stereo / 2)
# -----------------------------------------------------------------------------
# Test buffer write
# -----------------------------------------------------------------------------
@xfail_from_buffer
def test_buffer_write(sf_stereo_w):
buf = np.array([[1, 2], [-1, -2]], dtype='int16')
sf_stereo_w.buffer_write(buf, dtype='int16')
sf_stereo_w.close()
data, fs = sf.read(filename_new, dtype='int16')
assert np.all(data == buf)
assert fs == 44100
def test_buffer_write_with_bytes(sf_stereo_w):
b = b"\x01\x00\xFF\xFF\xFF\x00\x00\xFF"
sf_stereo_w.buffer_write(b, dtype='int16')
sf_stereo_w.close()
data, fs = sf.read(filename_new, dtype='int16')
assert np.all(data == [[1, -1], [255, -256]])
assert fs == 44100
@xfail_from_buffer
def test_buffer_write_with_wrong_size(sf_stereo_w):
buf = np.array([1, 2, 3], dtype='int16')
with pytest.raises(ValueError) as excinfo:
sf_stereo_w.buffer_write(buf, dtype='int16')
assert "multiple of frame size" in str(excinfo.value)
# -----------------------------------------------------------------------------
# Other tests
# -----------------------------------------------------------------------------
def test_context_manager_should_open_and_close_file(file_stereo_r):
with sf.SoundFile(file_stereo_r) as f:
assert not f.closed
assert f.closed
def test_closing_should_close_file(file_stereo_r):
f = sf.SoundFile(file_stereo_r)
assert not f.closed
f.close()
assert f.closed
def test_anything_on_closed_file(file_stereo_r):
with sf.SoundFile(file_stereo_r) as f:
pass
with pytest.raises(RuntimeError) as excinfo:
f.seek(0)
assert "closed" in str(excinfo.value)
def test_garbage(file_stereo_r):
f = sf.SoundFile(file_stereo_r)
ref = weakref.ref(f)
f = None
gc.collect()
assert ref() is None
def test_file_attributes_should_save_to_disk(file_w):
with sf.SoundFile(file_w, 'w', 44100, 2, format='WAV') as f:
f.title = 'testing'
with sf.SoundFile(filename_new) as f:
assert f.title == 'testing'
def test_non_file_attributes_should_not_save_to_disk(file_w):
with sf.SoundFile(file_w, 'w', 44100, 2, format='WAV') as f:
f.foobar = 'testing'
with sf.SoundFile(filename_new) as f:
with pytest.raises(AttributeError):
f.foobar
def test_getAttributeNames(sf_stereo_r):
names = sf_stereo_r._getAttributeNames()
assert 'artist' in names
assert 'genre' in names
def test_read_int_data_from_float_file(file_inmemory):
"""This is a very uncommon use case."""
unnormalized_float_to_clipped_int16 = [
(-2.0**15 - 1 , -2**15),
(-2.0**15 , -2**15),
(-2.0**15 + 1 , -2**15 + 1),
(-1.0 , -1),
(-0.51 , -1),
(-0.5 , 0),
( 0.0 , 0),
( 0.5 , 0),
( 0.51 , 1),
( 1.0 , 1),
( 2.0**15 - 2 , 2**15 - 2),
( 2.0**15 - 1 , 2**15 - 1),
( 2.0**15 , 2**15 - 1),
]
file_data, expected = zip(*unnormalized_float_to_clipped_int16)
sf.write(file_inmemory, file_data, 44100, format='WAV', subtype='FLOAT')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory, always_2d=False, dtype='int16')
assert np.all(read == expected)
assert fs == 44100
def test_libsndfile_version():
assert '.' in sf.__libsndfile_version__
# -----------------------------------------------------------------------------
# RAW tests
# -----------------------------------------------------------------------------
def test_read_raw_files_should_read_data():
with sf.SoundFile(filename_raw, 'r', 44100, 1, 'PCM_16') as f:
assert np.all(f.read(dtype='int16') == data_mono)
def test_read_raw_files_with_too_few_arguments_should_fail():
with pytest.raises(TypeError): # missing everything
sf.SoundFile(filename_raw)
with pytest.raises(TypeError): # missing subtype
sf.SoundFile(filename_raw, samplerate=44100, channels=2)
with pytest.raises(TypeError): # missing channels
sf.SoundFile(filename_raw, samplerate=44100, subtype='PCM_16')
with pytest.raises(TypeError): # missing samplerate
sf.SoundFile(filename_raw, channels=2, subtype='PCM_16')
def test_available_formats():
formats = sf.available_formats()
assert 'WAV' in formats
assert 'OGG' in formats
assert 'FLAC' in formats
def test_available_subtypes():
subtypes = sf.available_subtypes()
assert 'PCM_24' in subtypes
assert 'FLOAT' in subtypes
assert 'VORBIS' in subtypes
subtypes = sf.available_subtypes('WAV')
assert 'PCM_24' in subtypes
assert 'FLOAT' in subtypes
assert 'VORBIS' not in subtypes
subtypes = sf.available_subtypes('nonsense')
assert subtypes == {}
def test_default_subtype():
assert sf.default_subtype('FLAC') == 'PCM_16'
assert sf.default_subtype('RAW') is None
with pytest.raises(ValueError) as excinfo:
sf.default_subtype('nonsense')
assert str(excinfo.value) == "Unknown format: 'nonsense'"
with pytest.raises(TypeError) as excinfo:
sf.default_subtype(666)
assert str(excinfo.value) == "Invalid format: 666"
# -----------------------------------------------------------------------------
# Test non-seekable files
# -----------------------------------------------------------------------------
def test_write_non_seekable_file(file_w):
with sf.SoundFile(file_w, 'w', 44100, 1, format='XI') as f:
assert not f.seekable()
assert f.frames == 0
f.write(data_mono)
assert f.frames == len(data_mono)
with pytest.raises(RuntimeError) as excinfo:
f.seek(2)
assert "unseekable" in str(excinfo.value)
with sf.SoundFile(filename_new) as f:
assert not f.seekable()
assert f.frames == len(data_mono)
data = f.read(3, dtype='int16')
assert np.all(data == data_mono[:3])
data = f.read(666, dtype='int16')
assert np.all(data == data_mono[3:])
with pytest.raises(RuntimeError) as excinfo:
f.seek(2)
assert "unseekable" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
f.read()
assert "frames" in str(excinfo.value)
data, fs = sf.read(filename_new, dtype='int16')
assert np.all(data == data_mono)
assert fs == 44100
with pytest.raises(ValueError) as excinfo:
sf.read(filename_new, start=3)
assert "start is only allowed for seekable files" in str(excinfo.value)
|
import soundfile as sf
import numpy as np
import os
import io
import shutil
import pytest
import cffi
import sys
import gc
import weakref
# floating point data is typically limited to the interval [-1.0, 1.0],
# but smaller/larger values are supported as well
data_stereo = np.array([[1.75, -1.75],
[1.0, -1.0],
[0.5, -0.5],
[0.25, -0.25]])
data_mono = np.array([0, 1, 2, -2, -1], dtype='int16')
filename_stereo = 'tests/stereo.wav'
filename_mono = 'tests/mono.wav'
filename_raw = 'tests/mono.raw'
filename_new = 'tests/delme.please'
if sys.version_info >= (3, 6):
import pathlib
open_variants = 'name', 'fd', 'obj', 'pathlib'
else:
open_variants = 'name', 'fd', 'obj'
xfail_from_buffer = pytest.mark.xfail(cffi.__version_info__ < (0, 9),
reason="from_buffer() since CFFI 0.9")
def _file_existing(request, filename, fdarg, objarg=None):
if request.param == 'name':
return filename
if request.param == 'pathlib':
return pathlib.Path(filename)
elif request.param == 'fd':
fd = os.open(filename, fdarg)
def finalizer():
with pytest.raises(OSError):
os.close(fd)
request.addfinalizer(finalizer)
return fd
elif request.param == 'obj':
obj = open(filename, objarg, buffering=False)
request.addfinalizer(obj.close)
return obj
def _file_new(request, fdarg, objarg=None):
filename = filename_new
request.addfinalizer(lambda: os.remove(filename))
return _file_existing(request, filename, fdarg, objarg)
def _file_copy(request, filename, fdarg, objarg=None):
shutil.copy(filename, filename_new)
request.addfinalizer(lambda: os.remove(filename_new))
return _file_existing(request, filename_new, fdarg, objarg)
@pytest.fixture(params=open_variants)
def file_stereo_r(request):
return _file_existing(request, filename_stereo, os.O_RDONLY, 'rb')
@pytest.fixture(params=open_variants)
def file_mono_r(request):
return _file_existing(request, filename_mono, os.O_RDONLY, 'rb')
@pytest.fixture(params=open_variants)
def file_w(request):
return _file_new(request, os.O_CREAT | os.O_WRONLY, 'wb')
@pytest.fixture(params=open_variants)
def file_stereo_rplus(request):
return _file_copy(request, filename_stereo, os.O_RDWR, 'r+b')
@pytest.fixture(params=['obj'])
def file_obj_stereo_rplus(request):
return _file_copy(request, filename_stereo, os.O_RDWR, 'r+b')
@pytest.fixture(params=['obj'])
def file_obj_w(request):
return _file_new(request, os.O_CREAT | os.O_WRONLY, 'wb')
@pytest.fixture(params=open_variants)
def file_wplus(request):
return _file_new(request, os.O_CREAT | os.O_RDWR, 'w+b')
@pytest.yield_fixture
def file_inmemory():
with io.BytesIO() as f:
yield f
@pytest.yield_fixture
def sf_stereo_r(file_stereo_r):
with sf.SoundFile(file_stereo_r) as f:
yield f
@pytest.yield_fixture
def sf_stereo_w(file_w):
with sf.SoundFile(file_w, 'w', 44100, 2, format='WAV') as f:
yield f
@pytest.yield_fixture
def sf_stereo_rplus(file_stereo_rplus):
with sf.SoundFile(file_stereo_rplus, 'r+') as f:
yield f
@pytest.yield_fixture
def sf_stereo_wplus(file_wplus):
with sf.SoundFile(file_wplus, 'w+', 44100, 2,
format='WAV', subtype='FLOAT') as f:
yield f
# -----------------------------------------------------------------------------
# Test read() function
# -----------------------------------------------------------------------------
def test_if_read_returns_float64_data(file_stereo_r):
data, fs = sf.read(file_stereo_r)
assert fs == 44100
assert np.all(data == data_stereo)
assert data.dtype == np.float64
def test_read_float32(file_stereo_r):
data, fs = sf.read(file_stereo_r, dtype='float32')
assert np.all(data == data_stereo)
assert data.dtype == np.float32
def test_read_int16(file_mono_r):
data, fs = sf.read(file_mono_r, dtype='int16')
assert np.all(data == data_mono)
assert data.dtype == np.int16
def test_read_int32(file_mono_r):
data, fs = sf.read(file_mono_r, dtype='int32')
assert np.all(data // 2**16 == data_mono)
assert data.dtype == np.int32
def test_read_into_out(file_stereo_r):
out = np.empty((3, 2), dtype='float64')
data, fs = sf.read(file_stereo_r, out=out)
assert data is out
assert np.all(data == data_stereo[:3])
def test_if_read_into_malformed_out_fails(file_stereo_r):
out = np.empty((2, 3), dtype='float64')
with pytest.raises(ValueError):
sf.read(file_stereo_r, out=out)
def test_if_read_into_out_with_too_many_dimensions_fails(file_stereo_r):
out = np.empty((3, 2, 1), dtype='float64')
with pytest.raises(ValueError):
sf.read(file_stereo_r, out=out)
def test_if_read_into_zero_len_out_works(file_stereo_r):
out = np.empty((0, 2), dtype='float64')
data, fs = sf.read(file_stereo_r, out=out)
assert data is out
assert len(out) == 0
def test_read_into_non_contiguous_out(file_stereo_r):
out = np.empty(data_stereo.shape[::-1], dtype='float64')
if getattr(sys, 'pypy_version_info', (999,)) < (2, 6):
# The test for C-contiguous doesn't work with PyPy 2.5.0
sf.read(file_stereo_r, out=out.T)
else:
with pytest.raises(ValueError) as excinfo:
sf.read(file_stereo_r, out=out.T)
assert "C-contiguous" in str(excinfo.value)
def test_read_into_out_with_invalid_dtype(file_stereo_r):
out = np.empty((3, 2), dtype='int64')
with pytest.raises(ValueError) as excinfo:
sf.read(file_stereo_r, out=out)
assert "dtype must be one of" in str(excinfo.value)
def test_read_mono(file_mono_r):
data, fs = sf.read(file_mono_r, dtype='int16')
assert data.ndim == 1
assert np.all(data == data_mono)
def test_if_read_mono_with_always2d_returns_2d_array(file_mono_r):
data, fs = sf.read(file_mono_r, dtype='int16', always_2d=True)
assert data.ndim == 2
assert np.all(data == data_mono.reshape(-1, 1))
def test_read_mono_into_1d_out(file_mono_r):
out = np.empty(len(data_mono), dtype='int16')
data, fs = sf.read(file_mono_r, out=out)
assert data is out
assert np.all(data == data_mono)
def test_read_mono_into_2d_out(file_mono_r):
out = np.empty((len(data_mono), 1), dtype='int16')
data, fs = sf.read(file_mono_r, out=out)
assert data is out
assert np.all(data == data_mono.reshape(-1, 1))
def test_read_non_existing_file():
with pytest.raises(RuntimeError) as excinfo:
sf.read("i_do_not_exist.wav")
assert "Error opening 'i_do_not_exist.wav'" in str(excinfo.value)
# -----------------------------------------------------------------------------
# Test write() function
# -----------------------------------------------------------------------------
# The read() function is tested above, we assume here that it is working.
def test_write_float_data_to_float_file(file_inmemory):
sf.write(file_inmemory, data_stereo, 44100, format='WAV', subtype='FLOAT')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory)
assert np.all(read == data_stereo)
assert fs == 44100
def test_write_float_data_to_pcm_file(file_inmemory):
float_to_clipped_int16 = [
(-1.0 - 2**-15, -2**15 ),
(-1.0 , -2**15 ),
(-1.0 + 2**-15, -2**15 + 1),
( 0.0 , 0 ),
( 1.0 - 2**-14, 2**15 - 2),
( 1.0 - 2**-15, 2**15 - 1),
( 1.0 , 2**15 - 1),
]
written, expected = zip(*float_to_clipped_int16)
sf.write(file_inmemory, written, 44100, format='WAV', subtype='PCM_16')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory, dtype='int16')
assert np.all(read == expected)
assert fs == 44100
def test_write_int_data_to_pcm_file(file_inmemory):
sf.write(file_inmemory, data_mono, 44100, format='WAV')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory, dtype='int16')
assert fs == 44100
assert np.all(read == data_mono)
def test_write_int_data_to_float_file(file_inmemory):
"""This is a very uncommon use case."""
sf.write(file_inmemory, data_mono, 44100, format='WAV', subtype='FLOAT')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory, always_2d=False, dtype='float32')
assert np.all(read == data_mono)
assert fs == 44100
@pytest.mark.parametrize("filename", ["wav", ".wav", "wav.py"])
def test_write_with_unknown_extension(filename):
with pytest.raises(TypeError) as excinfo:
sf.write(filename, [0.0], 44100)
assert "file extension" in str(excinfo.value)
# -----------------------------------------------------------------------------
# Test blocks() function
# -----------------------------------------------------------------------------
def assert_equal_list_of_arrays(list1, list2):
"""Helper function to assert equality of all list items."""
for item1, item2 in zip(list1, list2):
assert np.all(item1 == item2)
def test_blocks_without_blocksize():
with pytest.raises(TypeError):
list(sf.blocks(filename_stereo))
def test_blocks_full_last_block(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2))
assert_equal_list_of_arrays(blocks, [data_stereo[0:2], data_stereo[2:4]])
def test_blocks_partial_last_block(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=3))
assert_equal_list_of_arrays(blocks, [data_stereo[0:3], data_stereo[3:4]])
def test_blocks_fill_last_block(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=3, fill_value=0))
last_block = np.row_stack((data_stereo[3:4], np.zeros((2, 2))))
assert_equal_list_of_arrays(blocks, [data_stereo[0:3], last_block])
def test_blocks_with_overlap(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=3, overlap=2))
assert_equal_list_of_arrays(blocks, [data_stereo[0:3], data_stereo[1:4]])
def test_blocks_with_start(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, start=2))
assert_equal_list_of_arrays(blocks, [data_stereo[2:4]])
def test_blocks_with_stop(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, stop=2))
assert_equal_list_of_arrays(blocks, [data_stereo[0:2]])
with pytest.raises(TypeError):
list(sf.blocks(filename_stereo, blocksize=2, frames=2, stop=2))
def test_blocks_with_too_large_start(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, start=666))
assert_equal_list_of_arrays(blocks, [[]])
def test_blocks_with_too_large_stop(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=3, stop=666))
assert_equal_list_of_arrays(blocks, [data_stereo[0:3], data_stereo[3:4]])
def test_blocks_with_negative_start_and_stop(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, start=-2, stop=-1))
assert_equal_list_of_arrays(blocks, [data_stereo[-2:-1]])
def test_blocks_with_stop_smaller_than_start(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, start=2, stop=1))
assert blocks == []
def test_blocks_with_frames(file_stereo_r):
blocks = list(sf.blocks(file_stereo_r, blocksize=2, frames=3))
assert_equal_list_of_arrays(blocks, [data_stereo[0:2], data_stereo[2:3]])
def test_blocks_with_frames_and_fill_value(file_stereo_r):
blocks = list(
sf.blocks(file_stereo_r, blocksize=2, frames=3, fill_value=0))
last_block = np.row_stack((data_stereo[2:3], np.zeros((1, 2))))
assert_equal_list_of_arrays(blocks, [data_stereo[0:2], last_block])
def test_blocks_with_out(file_stereo_r):
out = np.empty((3, 2))
blocks = list(sf.blocks(file_stereo_r, out=out))
assert blocks[0] is out
# First frame was overwritten by second block:
assert np.all(blocks[0] == data_stereo[[3, 1, 2]])
assert blocks[1].base is out
assert np.all(blocks[1] == data_stereo[[3]])
with pytest.raises(TypeError):
list(sf.blocks(filename_stereo, blocksize=3, out=out))
def test_blocks_inplace_modification(file_stereo_r):
out = np.empty((3, 2))
blocks = []
for block in sf.blocks(file_stereo_r, out=out, overlap=1):
blocks.append(np.copy(block))
block *= 2
expected_blocks = [data_stereo[0:3], data_stereo[2:5]]
assert_equal_list_of_arrays(blocks, expected_blocks)
def test_blocks_mono():
blocks = list(sf.blocks(filename_mono, blocksize=3, dtype='int16',
fill_value=0))
assert_equal_list_of_arrays(blocks, [[0, 1, 2], [-2, -1, 0]])
def test_blocks_rplus(sf_stereo_rplus):
blocks = list(sf_stereo_rplus.blocks(blocksize=2))
assert_equal_list_of_arrays(blocks, [data_stereo[0:2], data_stereo[2:4]])
def test_blocks_wplus(sf_stereo_wplus):
"""There is nothing to yield in a 'w+' file."""
blocks = list(sf_stereo_wplus.blocks(blocksize=2, frames=666))
assert blocks == []
def test_blocks_write(sf_stereo_w):
with pytest.raises(RuntimeError):
list(sf_stereo_w.blocks(blocksize=2))
# -----------------------------------------------------------------------------
# Test SoundFile.__init__()
# -----------------------------------------------------------------------------
def test_open_bytes_filename():
with sf.SoundFile(filename_stereo.encode()) as f:
assert np.all(f.read() == data_stereo)
def test_open_with_invalid_file():
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(3.1415)
assert "Invalid file" in str(excinfo.value)
def test_open_with_invalid_mode():
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, 42)
assert "Invalid mode: 42" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf.SoundFile(filename_stereo, 'rr')
assert "Invalid mode: 'rr'" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf.SoundFile(filename_stereo, 'rw')
assert "exactly one of 'xrw'" in str(excinfo.value)
def test_open_with_more_invalid_arguments():
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, 'w', 3.1415, 2, format='WAV')
assert "integer" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 3.1415, format='WAV')
assert "integer" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 2, format='WAF')
assert "Unknown format" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 2, 'PCM16', format='WAV')
assert "Unknown subtype" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 2, 666, format='WAV')
assert "Invalid subtype" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 2, endian='BOTH', format='WAV')
assert "Unknown endian-ness" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, 'w', 44100, 2, endian=True, format='WAV')
assert "Invalid endian-ness" in str(excinfo.value)
def test_open_r_and_rplus_with_too_many_arguments():
for mode in 'r', 'r+':
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode, samplerate=44100)
assert "Not allowed" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode, channels=2)
assert "Not allowed" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode, format='WAV')
assert "Not allowed" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode, subtype='FLOAT')
assert "Not allowed" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode, endian='FILE')
assert "Not allowed" in str(excinfo.value)
def test_open_w_and_wplus_with_too_few_arguments():
for mode in 'w', 'w+':
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, mode, samplerate=44100, channels=2)
assert "No format specified" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, mode, samplerate=44100, format='WAV')
assert "channels" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_new, mode, channels=2, format='WAV')
assert "samplerate" in str(excinfo.value)
def test_open_with_mode_is_none():
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(filename_stereo, mode=None)
assert "Invalid mode: None" in str(excinfo.value)
with open(filename_stereo, 'rb') as fobj:
with sf.SoundFile(fobj, mode=None) as f:
assert f.mode == 'rb'
def test_open_with_mode_is_x():
with pytest.raises(OSError) as excinfo:
sf.SoundFile(filename_stereo, 'x', 44100, 2)
assert "exists" in str(excinfo.value)
with pytest.raises(OSError) as excinfo:
sf.SoundFile(filename_stereo, 'x+', 44100, 2)
assert "exists" in str(excinfo.value)
@pytest.mark.parametrize("mode", ['w', 'w+'])
def test_if_open_with_mode_w_truncates(file_stereo_rplus, mode):
with sf.SoundFile(file_stereo_rplus, mode, 48000, 6, format='AIFF') as f:
pass
with sf.SoundFile(filename_new) as f:
if isinstance(file_stereo_rplus, str):
assert f.samplerate == 48000
assert f.channels == 6
assert f.format == 'AIFF'
assert f.frames == 0
else:
# This doesn't really work for file descriptors and file objects
pass
class LimitedFile(object):
def __init__(self, file, attrs):
for attr in attrs:
setattr(self, attr, getattr(file, attr))
@pytest.mark.parametrize("readmethod", ['read', 'readinto'])
def test_virtual_io_readonly(file_obj_stereo_rplus, readmethod):
limitedfile = LimitedFile(file_obj_stereo_rplus,
['seek', 'tell', readmethod])
data, fs = sf.read(limitedfile)
assert fs == 44100
assert np.all(data == data_stereo)
def test_virtual_io_writeonly(file_obj_w):
limitedfile = LimitedFile(file_obj_w, ['seek', 'tell', 'write'])
sf.write(limitedfile, [0.5], 48000, format='WAV')
data, fs = sf.read(filename_new)
assert fs == 48000
assert data == [0.5]
VIRTUAL_IO_ATTRS = 'seek', 'tell', 'read', 'write'
@pytest.mark.parametrize("missing", VIRTUAL_IO_ATTRS)
def test_virtual_io_missing_attr(file_obj_stereo_rplus, missing):
attrs = list(VIRTUAL_IO_ATTRS)
goodfile = LimitedFile(file_obj_stereo_rplus, attrs)
success = sf.SoundFile(goodfile, 'r+')
attrs.remove(missing)
badfile = LimitedFile(file_obj_stereo_rplus, attrs)
with pytest.raises(TypeError) as excinfo:
sf.SoundFile(badfile, 'r+')
assert "Invalid file" in str(excinfo.value)
assert np.all(success.read() == data_stereo)
# -----------------------------------------------------------------------------
# Test file metadata
# -----------------------------------------------------------------------------
def test_file_content(sf_stereo_r):
assert np.all(data_stereo == sf_stereo_r.read())
def test_file_attributes_in_read_mode(sf_stereo_r):
if isinstance(sf_stereo_r.name, str):
assert sf_stereo_r.name == filename_stereo
elif not isinstance(sf_stereo_r.name, int):
assert sf_stereo_r.name.name == filename_stereo
assert sf_stereo_r.mode == 'r'
assert sf_stereo_r.samplerate == 44100
assert sf_stereo_r.channels == 2
assert sf_stereo_r.format == 'WAV'
assert sf_stereo_r.subtype == 'FLOAT'
assert sf_stereo_r.endian == 'FILE'
assert sf_stereo_r.format_info == 'WAV (Microsoft)'
assert sf_stereo_r.subtype_info == '32 bit float'
assert sf_stereo_r.sections == 1
assert sf_stereo_r.closed is False
assert sf_stereo_r.seekable() is True
assert sf_stereo_r.frames == len(data_stereo)
def test__repr__(sf_stereo_r):
assert repr(sf_stereo_r) == ("SoundFile({0.name!r}, mode='r', "
"samplerate=44100, channels=2, "
"format='WAV', subtype='FLOAT', "
"endian='FILE')").format(sf_stereo_r)
def test_extra_info(sf_stereo_r):
assert 'WAVE_FORMAT_IEEE_FLOAT' in sf_stereo_r.extra_info
def test_mode_should_be_in_write_mode(sf_stereo_w):
assert sf_stereo_w.mode == 'w'
assert sf_stereo_w.frames == 0
def test_mode_should_be_in_readwrite_mode(sf_stereo_rplus):
assert sf_stereo_rplus.mode == 'r+'
def test_file_truthiness(file_w):
with sf.SoundFile(file_w, 'w', 44100, 2, format='WAV') as f:
assert f
# -----------------------------------------------------------------------------
# Test seek/tell
# -----------------------------------------------------------------------------
def test_seek_in_read_mode(sf_stereo_r):
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 0
assert sf_stereo_r.tell() == 0
assert sf_stereo_r.seek(2) == 2
assert sf_stereo_r.tell() == 2
assert sf_stereo_r.seek(2, sf.SEEK_CUR) == 4
assert sf_stereo_r.seek(-2, sf.SEEK_END) == len(data_stereo) - 2
with pytest.raises(RuntimeError):
sf_stereo_r.seek(666)
with pytest.raises(RuntimeError):
sf_stereo_r.seek(-666)
def test_seek_in_write_mode(sf_stereo_w):
assert sf_stereo_w.seek(0, sf.SEEK_CUR) == 0
assert sf_stereo_w.tell() == 0
assert sf_stereo_w.seek(2) == 2
assert sf_stereo_w.tell() == 2
def test_seek_in_rplus_mode(sf_stereo_rplus):
assert sf_stereo_rplus.seek(0, sf.SEEK_CUR) == 0
assert sf_stereo_rplus.tell() == 0
assert sf_stereo_rplus.seek(2) == 2
assert sf_stereo_rplus.seek(0, sf.SEEK_CUR) == 2
assert sf_stereo_rplus.tell() == 2
@pytest.mark.parametrize("use_default", [True, False])
def test_truncate(file_stereo_rplus, use_default):
if (isinstance(file_stereo_rplus, (str, int))
or hasattr(file_stereo_rplus, '__fspath__')):
with sf.SoundFile(file_stereo_rplus, 'r+', closefd=False) as f:
if use_default:
f.seek(2)
f.truncate()
else:
f.truncate(2)
assert f.tell() == 2
assert f.frames == 2
if isinstance(file_stereo_rplus, int):
os.lseek(file_stereo_rplus, 0, os.SEEK_SET)
data, fs = sf.read(file_stereo_rplus)
assert np.all(data == data_stereo[:2])
assert fs == 44100
else:
# file objects don't support truncate()
with sf.SoundFile(file_stereo_rplus, 'r+', closefd=False) as f:
with pytest.raises(RuntimeError) as excinfo:
f.truncate()
assert "Error truncating" in str(excinfo.value)
# -----------------------------------------------------------------------------
# Test read
# -----------------------------------------------------------------------------
def test_read_write_only(sf_stereo_w):
with pytest.raises(RuntimeError):
sf_stereo_w.read(2)
def test_read_should_read_data_and_advance_read_pointer(sf_stereo_r):
data = sf_stereo_r.read(2)
assert np.all(data == data_stereo[:2])
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 2
def test_read_n_frames_should_return_n_frames(sf_stereo_r):
assert len(sf_stereo_r.read(2)) == 2
def test_read_all_frames_should_read_all_remaining_frames(sf_stereo_r):
sf_stereo_r.seek(-2, sf.SEEK_END)
assert np.all(sf_stereo_r.read() == data_stereo[-2:])
def test_read_over_end_should_return_only_remaining_frames(sf_stereo_r):
sf_stereo_r.seek(-2, sf.SEEK_END)
assert np.all(sf_stereo_r.read(4) == data_stereo[-2:])
def test_read_over_end_with_fill_should_reaturn_asked_frames(sf_stereo_r):
sf_stereo_r.seek(-2, sf.SEEK_END)
data = sf_stereo_r.read(4, fill_value=0)
assert np.all(data[:2] == data_stereo[-2:])
assert np.all(data[2:] == 0)
assert len(data) == 4
def test_read_into_out_over_end_should_return_shorter_data_and_write_into_out(
sf_stereo_r):
out = np.ones((4, sf_stereo_r.channels), dtype='float64')
sf_stereo_r.seek(-2, sf.SEEK_END)
data = sf_stereo_r.read(out=out)
assert np.all(data[:2] == out[:2])
assert np.all(data[2:] == 1)
assert out.shape == (4, sf_stereo_r.channels)
assert data.shape == (2, sf_stereo_r.channels)
def test_read_into_out_over_end_with_fill_should_return_full_data_and_write_into_out(
sf_stereo_r):
out = np.ones((4, sf_stereo_r.channels), dtype='float64')
sf_stereo_r.seek(-2, sf.SEEK_END)
data = sf_stereo_r.read(out=out, fill_value=0)
assert np.all(data == out)
assert np.all(data[2:] == 0)
assert out.shape == (4, sf_stereo_r.channels)
# -----------------------------------------------------------------------------
# Test buffer read
# -----------------------------------------------------------------------------
def test_buffer_read(sf_stereo_r):
buf = sf_stereo_r.buffer_read(2, dtype='float64')
assert len(buf) == 2 * 2 * 8
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 2
data = np.frombuffer(buf, dtype='float64').reshape(-1, 2)
assert np.all(data == data_stereo[:2])
buf = sf_stereo_r.buffer_read(dtype='float32')
assert len(buf) == 2 * 2 * 4
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 4
data = np.frombuffer(buf, dtype='float32').reshape(-1, 2)
assert np.all(data == data_stereo[2:])
buf = sf_stereo_r.buffer_read(dtype='float32')
assert len(buf) == 0
buf = sf_stereo_r.buffer_read(666, dtype='float32')
assert len(buf) == 0
with pytest.raises(ValueError) as excinfo:
sf_stereo_r.buffer_read(dtype='int8')
assert "dtype must be one of" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
sf_stereo_r.buffer_read()
assert "dtype must be one of" in str(excinfo.value)
@xfail_from_buffer
def test_buffer_read_into(sf_stereo_r):
out = np.ones((3, 2))
frames = sf_stereo_r.buffer_read_into(out, dtype='float64')
assert frames == 3
assert np.all(out == data_stereo[:3])
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 3
frames = sf_stereo_r.buffer_read_into(out, dtype='float64')
assert frames == 1
assert np.all(out[:1] == data_stereo[3:])
assert sf_stereo_r.seek(0, sf.SEEK_CUR) == 4
# -----------------------------------------------------------------------------
# Test write
# -----------------------------------------------------------------------------
def test_write_to_read_only_file_should_fail(sf_stereo_r):
with pytest.raises(RuntimeError):
sf_stereo_r.write(data_stereo)
def test_if_write_advances_write_pointer(sf_stereo_w):
position = sf_stereo_w.seek(0, sf.SEEK_CUR)
sf_stereo_w.write(data_stereo)
assert sf_stereo_w.seek(0, sf.SEEK_CUR) == position + len(data_stereo)
def test_write_flush_should_write_to_disk(sf_stereo_w):
sf_stereo_w.flush()
size = os.path.getsize(filename_new)
sf_stereo_w.write(data_stereo)
sf_stereo_w.flush()
assert os.path.getsize(filename_new) == size + data_stereo.size * 2
def test_wplus_read_written_data(sf_stereo_wplus):
sf_stereo_wplus.write(data_stereo)
assert sf_stereo_wplus.seek(0, sf.SEEK_CUR) == len(data_stereo)
sf_stereo_wplus.seek(0)
assert np.all(sf_stereo_wplus.read() == data_stereo)
assert sf_stereo_wplus.seek(0, sf.SEEK_CUR) == len(data_stereo)
sf_stereo_wplus.close()
data, fs = sf.read(filename_new)
assert np.all(data == data_stereo)
def test_rplus_append_data(sf_stereo_rplus):
sf_stereo_rplus.seek(0, sf.SEEK_END)
sf_stereo_rplus.write(data_stereo / 2)
sf_stereo_rplus.close()
data, fs = sf.read(filename_new)
assert np.all(data[:len(data_stereo)] == data_stereo)
assert np.all(data[len(data_stereo):] == data_stereo / 2)
# -----------------------------------------------------------------------------
# Test buffer write
# -----------------------------------------------------------------------------
@xfail_from_buffer
def test_buffer_write(sf_stereo_w):
buf = np.array([[1, 2], [-1, -2]], dtype='int16')
sf_stereo_w.buffer_write(buf, dtype='int16')
sf_stereo_w.close()
data, fs = sf.read(filename_new, dtype='int16')
assert np.all(data == buf)
assert fs == 44100
def test_buffer_write_with_bytes(sf_stereo_w):
b = b"\x01\x00\xFF\xFF\xFF\x00\x00\xFF"
sf_stereo_w.buffer_write(b, dtype='int16')
sf_stereo_w.close()
data, fs = sf.read(filename_new, dtype='int16')
assert np.all(data == [[1, -1], [255, -256]])
assert fs == 44100
@xfail_from_buffer
def test_buffer_write_with_wrong_size(sf_stereo_w):
buf = np.array([1, 2, 3], dtype='int16')
with pytest.raises(ValueError) as excinfo:
sf_stereo_w.buffer_write(buf, dtype='int16')
assert "multiple of frame size" in str(excinfo.value)
# -----------------------------------------------------------------------------
# Other tests
# -----------------------------------------------------------------------------
def test_context_manager_should_open_and_close_file(file_stereo_r):
with sf.SoundFile(file_stereo_r) as f:
assert not f.closed
assert f.closed
def test_closing_should_close_file(file_stereo_r):
f = sf.SoundFile(file_stereo_r)
assert not f.closed
f.close()
assert f.closed
def test_anything_on_closed_file(file_stereo_r):
with sf.SoundFile(file_stereo_r) as f:
pass
with pytest.raises(RuntimeError) as excinfo:
f.seek(0)
assert "closed" in str(excinfo.value)
def test_garbage(file_stereo_r):
f = sf.SoundFile(file_stereo_r)
ref = weakref.ref(f)
f = None
gc.collect()
assert ref() is None
def test_file_attributes_should_save_to_disk(file_w):
with sf.SoundFile(file_w, 'w', 44100, 2, format='WAV') as f:
f.title = 'testing'
with sf.SoundFile(filename_new) as f:
assert f.title == 'testing'
def test_non_file_attributes_should_not_save_to_disk(file_w):
with sf.SoundFile(file_w, 'w', 44100, 2, format='WAV') as f:
f.foobar = 'testing'
with sf.SoundFile(filename_new) as f:
with pytest.raises(AttributeError):
f.foobar
def test_getAttributeNames(sf_stereo_r):
names = sf_stereo_r._getAttributeNames()
assert 'artist' in names
assert 'genre' in names
def test_read_int_data_from_float_file(file_inmemory):
"""This is a very uncommon use case."""
unnormalized_float_to_clipped_int16 = [
(-2.0**15 - 1 , -2**15),
(-2.0**15 , -2**15),
(-2.0**15 + 1 , -2**15 + 1),
(-1.0 , -1),
(-0.51 , -1),
(-0.5 , 0),
( 0.0 , 0),
( 0.5 , 0),
( 0.51 , 1),
( 1.0 , 1),
( 2.0**15 - 2 , 2**15 - 2),
( 2.0**15 - 1 , 2**15 - 1),
( 2.0**15 , 2**15 - 1),
]
file_data, expected = zip(*unnormalized_float_to_clipped_int16)
sf.write(file_inmemory, file_data, 44100, format='WAV', subtype='FLOAT')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory, always_2d=False, dtype='int16')
assert np.all(read == expected)
assert fs == 44100
def test_libsndfile_version():
assert '.' in sf.__libsndfile_version__
# -----------------------------------------------------------------------------
# RAW tests
# -----------------------------------------------------------------------------
def test_read_raw_files_should_read_data():
with sf.SoundFile(filename_raw, 'r', 44100, 1, 'PCM_16') as f:
assert np.all(f.read(dtype='int16') == data_mono)
def test_read_raw_files_with_too_few_arguments_should_fail():
with pytest.raises(TypeError): # missing everything
sf.SoundFile(filename_raw)
with pytest.raises(TypeError): # missing subtype
sf.SoundFile(filename_raw, samplerate=44100, channels=2)
with pytest.raises(TypeError): # missing channels
sf.SoundFile(filename_raw, samplerate=44100, subtype='PCM_16')
with pytest.raises(TypeError): # missing samplerate
sf.SoundFile(filename_raw, channels=2, subtype='PCM_16')
def test_available_formats():
formats = sf.available_formats()
assert 'WAV' in formats
assert 'OGG' in formats
assert 'FLAC' in formats
def test_available_subtypes():
subtypes = sf.available_subtypes()
assert 'PCM_24' in subtypes
assert 'FLOAT' in subtypes
assert 'VORBIS' in subtypes
subtypes = sf.available_subtypes('WAV')
assert 'PCM_24' in subtypes
assert 'FLOAT' in subtypes
assert 'VORBIS' not in subtypes
subtypes = sf.available_subtypes('nonsense')
assert subtypes == {}
def test_default_subtype():
assert sf.default_subtype('FLAC') == 'PCM_16'
assert sf.default_subtype('RAW') is None
with pytest.raises(ValueError) as excinfo:
sf.default_subtype('nonsense')
assert str(excinfo.value) == "Unknown format: 'nonsense'"
with pytest.raises(TypeError) as excinfo:
sf.default_subtype(666)
assert str(excinfo.value) == "Invalid format: 666"
# -----------------------------------------------------------------------------
# Test non-seekable files
# -----------------------------------------------------------------------------
def test_write_non_seekable_file(file_w):
with sf.SoundFile(file_w, 'w', 44100, 1, format='XI') as f:
assert not f.seekable()
assert f.frames == 0
f.write(data_mono)
assert f.frames == len(data_mono)
with pytest.raises(RuntimeError) as excinfo:
f.seek(2)
assert "unseekable" in str(excinfo.value)
with sf.SoundFile(filename_new) as f:
assert not f.seekable()
assert f.frames == len(data_mono)
data = f.read(3, dtype='int16')
assert np.all(data == data_mono[:3])
data = f.read(666, dtype='int16')
assert np.all(data == data_mono[3:])
with pytest.raises(RuntimeError) as excinfo:
f.seek(2)
assert "unseekable" in str(excinfo.value)
with pytest.raises(ValueError) as excinfo:
f.read()
assert "frames" in str(excinfo.value)
data, fs = sf.read(filename_new, dtype='int16')
assert np.all(data == data_mono)
assert fs == 44100
with pytest.raises(ValueError) as excinfo:
sf.read(filename_new, start=3)
assert "start is only allowed for seekable files" in str(excinfo.value)
|
en
| 0.341951
|
# floating point data is typically limited to the interval [-1.0, 1.0], # but smaller/larger values are supported as well # ----------------------------------------------------------------------------- # Test read() function # ----------------------------------------------------------------------------- # The test for C-contiguous doesn't work with PyPy 2.5.0 # ----------------------------------------------------------------------------- # Test write() function # ----------------------------------------------------------------------------- # The read() function is tested above, we assume here that it is working. This is a very uncommon use case. # ----------------------------------------------------------------------------- # Test blocks() function # ----------------------------------------------------------------------------- Helper function to assert equality of all list items. # First frame was overwritten by second block: There is nothing to yield in a 'w+' file. # ----------------------------------------------------------------------------- # Test SoundFile.__init__() # ----------------------------------------------------------------------------- # This doesn't really work for file descriptors and file objects # ----------------------------------------------------------------------------- # Test file metadata # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # Test seek/tell # ----------------------------------------------------------------------------- # file objects don't support truncate() # ----------------------------------------------------------------------------- # Test read # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # Test buffer read # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # Test write # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # Test buffer write # ----------------------------------------------------------------------------- # ----------------------------------------------------------------------------- # Other tests # ----------------------------------------------------------------------------- This is a very uncommon use case. # ----------------------------------------------------------------------------- # RAW tests # ----------------------------------------------------------------------------- # missing everything # missing subtype # missing channels # missing samplerate # ----------------------------------------------------------------------------- # Test non-seekable files # -----------------------------------------------------------------------------
| 2.099527
| 2
|
python/app/plugins/port/IIS/CVE_2017_7269.py
|
taomujian/linbing
| 351
|
6626262
|
#!/usr/bin/env python3
import socket
from urllib.parse import urlparse
class CVE_2017_7269_BaseVerify:
def __init__(self, url):
self.info = {
'name': 'CVE-2017-7269 远程代码执行漏洞',
'description': 'CVE-2017-7269 远程代码执行漏洞,影响范围为: IIS 6.0',
'date': '2017-03-26',
'exptype': 'check',
'type': 'RCE'
}
self.url = url
self.timeout = 20
url_parse = urlparse(self.url)
self.host = url_parse.hostname
self.port = url_parse.port
if not self.port:
self.port = '80'
def check(self):
"""
检测是否存在漏洞
:param:
:return bool True or False: 是否存在漏洞
"""
try:
socket.setdefaulttimeout(self.timeout)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, int(self.port)))
pay = b"OPTIONS / HTTP/1.0\r\n\r\n"
s.send(pay)
data = s.recv(2048)
s.close()
if b"PROPFIND" in data and b"Microsoft-IIS/6.0" in data :
print('存在CVE-2017-7269 远程代码执行漏洞')
return True
else:
print('不存在CVE-2017-7269 远程代码执行漏洞')
return False
except Exception as e:
print(e)
print('不存在CVE-2017-7269 远程代码执行漏洞')
return False
finally:
pass
if __name__ == "__main__":
CVE_2017_7269 = CVE_2017_7269_BaseVerify('https://baidu.com')
CVE_2017_7269.check()
|
#!/usr/bin/env python3
import socket
from urllib.parse import urlparse
class CVE_2017_7269_BaseVerify:
def __init__(self, url):
self.info = {
'name': 'CVE-2017-7269 远程代码执行漏洞',
'description': 'CVE-2017-7269 远程代码执行漏洞,影响范围为: IIS 6.0',
'date': '2017-03-26',
'exptype': 'check',
'type': 'RCE'
}
self.url = url
self.timeout = 20
url_parse = urlparse(self.url)
self.host = url_parse.hostname
self.port = url_parse.port
if not self.port:
self.port = '80'
def check(self):
"""
检测是否存在漏洞
:param:
:return bool True or False: 是否存在漏洞
"""
try:
socket.setdefaulttimeout(self.timeout)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((self.host, int(self.port)))
pay = b"OPTIONS / HTTP/1.0\r\n\r\n"
s.send(pay)
data = s.recv(2048)
s.close()
if b"PROPFIND" in data and b"Microsoft-IIS/6.0" in data :
print('存在CVE-2017-7269 远程代码执行漏洞')
return True
else:
print('不存在CVE-2017-7269 远程代码执行漏洞')
return False
except Exception as e:
print(e)
print('不存在CVE-2017-7269 远程代码执行漏洞')
return False
finally:
pass
if __name__ == "__main__":
CVE_2017_7269 = CVE_2017_7269_BaseVerify('https://baidu.com')
CVE_2017_7269.check()
|
zh
| 0.454818
|
#!/usr/bin/env python3 检测是否存在漏洞 :param: :return bool True or False: 是否存在漏洞
| 2.783717
| 3
|
networkx/classes/tests/test_graph.py
|
dizcza/networkx
| 0
|
6626263
|
import pickle
import gc
import platform
import pytest
import networkx as nx
from networkx.utils import nodes_equal, edges_equal, graphs_equal
class BaseGraphTester:
"""Tests for data-structure independent graph class features."""
def test_contains(self):
G = self.K3
assert 1 in G
assert 4 not in G
assert "b" not in G
assert [] not in G # no exception for nonhashable
assert {1: 1} not in G # no exception for nonhashable
def test_order(self):
G = self.K3
assert len(G) == 3
assert G.order() == 3
assert G.number_of_nodes() == 3
def test_nodes(self):
G = self.K3
assert sorted(G.nodes()) == self.k3nodes
assert sorted(G.nodes(data=True)) == [(0, {}), (1, {}), (2, {})]
def test_has_node(self):
G = self.K3
assert G.has_node(1)
assert not G.has_node(4)
assert not G.has_node([]) # no exception for nonhashable
assert not G.has_node({1: 1}) # no exception for nonhashable
def test_has_edge(self):
G = self.K3
assert G.has_edge(0, 1)
assert not G.has_edge(0, -1)
def test_neighbors(self):
G = self.K3
assert sorted(G.neighbors(0)) == [1, 2]
with pytest.raises(nx.NetworkXError):
G.neighbors(-1)
@pytest.mark.skipif(
platform.python_implementation() == "PyPy", reason="PyPy gc is different"
)
def test_memory_leak(self):
G = self.Graph()
def count_objects_of_type(_type):
return sum(1 for obj in gc.get_objects() if isinstance(obj, _type))
gc.collect()
before = count_objects_of_type(self.Graph)
G.copy()
gc.collect()
after = count_objects_of_type(self.Graph)
assert before == after
# test a subgraph of the base class
class MyGraph(self.Graph):
pass
gc.collect()
G = MyGraph()
before = count_objects_of_type(MyGraph)
G.copy()
gc.collect()
after = count_objects_of_type(MyGraph)
assert before == after
def test_edges(self):
G = self.K3
assert edges_equal(G.edges(), [(0, 1), (0, 2), (1, 2)])
assert edges_equal(G.edges(0), [(0, 1), (0, 2)])
assert edges_equal(G.edges([0, 1]), [(0, 1), (0, 2), (1, 2)])
with pytest.raises(nx.NetworkXError):
G.edges(-1)
def test_degree(self):
G = self.K3
assert sorted(G.degree()) == [(0, 2), (1, 2), (2, 2)]
assert dict(G.degree()) == {0: 2, 1: 2, 2: 2}
assert G.degree(0) == 2
with pytest.raises(nx.NetworkXError):
G.degree(-1) # node not in graph
def test_size(self):
G = self.K3
assert G.size() == 3
assert G.number_of_edges() == 3
def test_nbunch_iter(self):
G = self.K3
assert nodes_equal(G.nbunch_iter(), self.k3nodes) # all nodes
assert nodes_equal(G.nbunch_iter(0), [0]) # single node
assert nodes_equal(G.nbunch_iter([0, 1]), [0, 1]) # sequence
# sequence with none in graph
assert nodes_equal(G.nbunch_iter([-1]), [])
# string sequence with none in graph
assert nodes_equal(G.nbunch_iter("foo"), [])
# node not in graph doesn't get caught upon creation of iterator
bunch = G.nbunch_iter(-1)
# but gets caught when iterator used
with pytest.raises(nx.NetworkXError, match="is not a node or a sequence"):
list(bunch)
# unhashable doesn't get caught upon creation of iterator
bunch = G.nbunch_iter([0, 1, 2, {}])
# but gets caught when iterator hits the unhashable
with pytest.raises(
nx.NetworkXError, match="in sequence nbunch is not a valid node"
):
list(bunch)
def test_nbunch_iter_node_format_raise(self):
# Tests that a node that would have failed string formatting
# doesn't cause an error when attempting to raise a
# :exc:`nx.NetworkXError`.
# For more information, see pull request #1813.
G = self.Graph()
nbunch = [("x", set())]
with pytest.raises(nx.NetworkXError):
list(G.nbunch_iter(nbunch))
def test_selfloop_degree(self):
G = self.Graph()
G.add_edge(1, 1)
assert sorted(G.degree()) == [(1, 2)]
assert dict(G.degree()) == {1: 2}
assert G.degree(1) == 2
assert sorted(G.degree([1])) == [(1, 2)]
assert G.degree(1, weight="weight") == 2
def test_selfloops(self):
G = self.K3.copy()
G.add_edge(0, 0)
assert nodes_equal(nx.nodes_with_selfloops(G), [0])
assert edges_equal(nx.selfloop_edges(G), [(0, 0)])
assert nx.number_of_selfloops(G) == 1
G.remove_edge(0, 0)
G.add_edge(0, 0)
G.remove_edges_from([(0, 0)])
G.add_edge(1, 1)
G.remove_node(1)
G.add_edge(0, 0)
G.add_edge(1, 1)
G.remove_nodes_from([0, 1])
class BaseAttrGraphTester(BaseGraphTester):
"""Tests of graph class attribute features."""
def test_weighted_degree(self):
G = self.Graph()
G.add_edge(1, 2, weight=2, other=3)
G.add_edge(2, 3, weight=3, other=4)
assert sorted(d for n, d in G.degree(weight="weight")) == [2, 3, 5]
assert dict(G.degree(weight="weight")) == {1: 2, 2: 5, 3: 3}
assert G.degree(1, weight="weight") == 2
assert nodes_equal((G.degree([1], weight="weight")), [(1, 2)])
assert nodes_equal((d for n, d in G.degree(weight="other")), [3, 7, 4])
assert dict(G.degree(weight="other")) == {1: 3, 2: 7, 3: 4}
assert G.degree(1, weight="other") == 3
assert edges_equal((G.degree([1], weight="other")), [(1, 3)])
def add_attributes(self, G):
G.graph["foo"] = []
G.nodes[0]["foo"] = []
G.remove_edge(1, 2)
ll = []
G.add_edge(1, 2, foo=ll)
G.add_edge(2, 1, foo=ll)
def test_name(self):
G = self.Graph(name="")
assert G.name == ""
G = self.Graph(name="test")
assert G.name == "test"
def test_str_unnamed(self):
G = self.Graph()
G.add_edges_from([(1, 2), (2, 3)])
assert str(G) == f"{type(G).__name__} with 3 nodes and 2 edges"
def test_str_named(self):
G = self.Graph(name="foo")
G.add_edges_from([(1, 2), (2, 3)])
assert str(G) == f"{type(G).__name__} named 'foo' with 3 nodes and 2 edges"
def test_graph_chain(self):
G = self.Graph([(0, 1), (1, 2)])
DG = G.to_directed(as_view=True)
SDG = DG.subgraph([0, 1])
RSDG = SDG.reverse(copy=False)
assert G is DG._graph
assert DG is SDG._graph
assert SDG is RSDG._graph
def test_copy(self):
G = self.Graph()
G.add_node(0)
G.add_edge(1, 2)
self.add_attributes(G)
# copy edge datadict but any container attr are same
H = G.copy()
self.graphs_equal(H, G)
self.different_attrdict(H, G)
self.shallow_copy_attrdict(H, G)
def test_class_copy(self):
G = self.Graph()
G.add_node(0)
G.add_edge(1, 2)
self.add_attributes(G)
# copy edge datadict but any container attr are same
H = G.__class__(G)
self.graphs_equal(H, G)
self.different_attrdict(H, G)
self.shallow_copy_attrdict(H, G)
def test_fresh_copy(self):
G = self.Graph()
G.add_node(0)
G.add_edge(1, 2)
self.add_attributes(G)
# copy graph structure but use fresh datadict
H = G.__class__()
H.add_nodes_from(G)
H.add_edges_from(G.edges())
assert len(G.nodes[0]) == 1
ddict = G.adj[1][2][0] if G.is_multigraph() else G.adj[1][2]
assert len(ddict) == 1
assert len(H.nodes[0]) == 0
ddict = H.adj[1][2][0] if H.is_multigraph() else H.adj[1][2]
assert len(ddict) == 0
def is_deepcopy(self, H, G):
self.graphs_equal(H, G)
self.different_attrdict(H, G)
self.deep_copy_attrdict(H, G)
def deep_copy_attrdict(self, H, G):
self.deepcopy_graph_attr(H, G)
self.deepcopy_node_attr(H, G)
self.deepcopy_edge_attr(H, G)
def deepcopy_graph_attr(self, H, G):
assert G.graph["foo"] == H.graph["foo"]
G.graph["foo"].append(1)
assert G.graph["foo"] != H.graph["foo"]
def deepcopy_node_attr(self, H, G):
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
G.nodes[0]["foo"].append(1)
assert G.nodes[0]["foo"] != H.nodes[0]["foo"]
def deepcopy_edge_attr(self, H, G):
assert G[1][2]["foo"] == H[1][2]["foo"]
G[1][2]["foo"].append(1)
assert G[1][2]["foo"] != H[1][2]["foo"]
def is_shallow_copy(self, H, G):
self.graphs_equal(H, G)
self.shallow_copy_attrdict(H, G)
def shallow_copy_attrdict(self, H, G):
self.shallow_copy_graph_attr(H, G)
self.shallow_copy_node_attr(H, G)
self.shallow_copy_edge_attr(H, G)
def shallow_copy_graph_attr(self, H, G):
assert G.graph["foo"] == H.graph["foo"]
G.graph["foo"].append(1)
assert G.graph["foo"] == H.graph["foo"]
def shallow_copy_node_attr(self, H, G):
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
G.nodes[0]["foo"].append(1)
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
def shallow_copy_edge_attr(self, H, G):
assert G[1][2]["foo"] == H[1][2]["foo"]
G[1][2]["foo"].append(1)
assert G[1][2]["foo"] == H[1][2]["foo"]
def same_attrdict(self, H, G):
old_foo = H[1][2]["foo"]
H.adj[1][2]["foo"] = "baz"
assert G.edges == H.edges
H.adj[1][2]["foo"] = old_foo
assert G.edges == H.edges
old_foo = H.nodes[0]["foo"]
H.nodes[0]["foo"] = "baz"
assert G.nodes == H.nodes
H.nodes[0]["foo"] = old_foo
assert G.nodes == H.nodes
def different_attrdict(self, H, G):
old_foo = H[1][2]["foo"]
H.adj[1][2]["foo"] = "baz"
assert G._adj != H._adj
H.adj[1][2]["foo"] = old_foo
assert G._adj == H._adj
old_foo = H.nodes[0]["foo"]
H.nodes[0]["foo"] = "baz"
assert G._node != H._node
H.nodes[0]["foo"] = old_foo
assert G._node == H._node
def graphs_equal(self, H, G):
assert G._adj == H._adj
assert G._node == H._node
assert G.graph == H.graph
assert G.name == H.name
if not G.is_directed() and not H.is_directed():
assert H._adj[1][2] is H._adj[2][1]
assert G._adj[1][2] is G._adj[2][1]
else: # at least one is directed
if not G.is_directed():
G._pred = G._adj
G._succ = G._adj
if not H.is_directed():
H._pred = H._adj
H._succ = H._adj
assert G._pred == H._pred
assert G._succ == H._succ
assert H._succ[1][2] is H._pred[2][1]
assert G._succ[1][2] is G._pred[2][1]
def test_graph_attr(self):
G = self.K3.copy()
G.graph["foo"] = "bar"
assert G.graph["foo"] == "bar"
del G.graph["foo"]
assert G.graph == {}
H = self.Graph(foo="bar")
assert H.graph["foo"] == "bar"
def test_node_attr(self):
G = self.K3.copy()
G.add_node(1, foo="bar")
assert nodes_equal(G.nodes(), [0, 1, 2])
assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "bar"}), (2, {})])
G.nodes[1]["foo"] = "baz"
assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "baz"}), (2, {})])
assert nodes_equal(G.nodes(data="foo"), [(0, None), (1, "baz"), (2, None)])
assert nodes_equal(
G.nodes(data="foo", default="bar"), [(0, "bar"), (1, "baz"), (2, "bar")]
)
def test_node_attr2(self):
G = self.K3.copy()
a = {"foo": "bar"}
G.add_node(3, **a)
assert nodes_equal(G.nodes(), [0, 1, 2, 3])
assert nodes_equal(
G.nodes(data=True), [(0, {}), (1, {}), (2, {}), (3, {"foo": "bar"})]
)
def test_edge_lookup(self):
G = self.Graph()
G.add_edge(1, 2, foo="bar")
assert edges_equal(G.edges[1, 2], {"foo": "bar"})
def test_edge_attr(self):
G = self.Graph()
G.add_edge(1, 2, foo="bar")
assert edges_equal(G.edges(data=True), [(1, 2, {"foo": "bar"})])
assert edges_equal(G.edges(data="foo"), [(1, 2, "bar")])
def test_edge_attr2(self):
G = self.Graph()
G.add_edges_from([(1, 2), (3, 4)], foo="foo")
assert edges_equal(
G.edges(data=True), [(1, 2, {"foo": "foo"}), (3, 4, {"foo": "foo"})]
)
assert edges_equal(G.edges(data="foo"), [(1, 2, "foo"), (3, 4, "foo")])
def test_edge_attr3(self):
G = self.Graph()
G.add_edges_from([(1, 2, {"weight": 32}), (3, 4, {"weight": 64})], foo="foo")
assert edges_equal(
G.edges(data=True),
[
(1, 2, {"foo": "foo", "weight": 32}),
(3, 4, {"foo": "foo", "weight": 64}),
],
)
G.remove_edges_from([(1, 2), (3, 4)])
G.add_edge(1, 2, data=7, spam="bar", bar="foo")
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
)
def test_edge_attr4(self):
G = self.Graph()
G.add_edge(1, 2, data=7, spam="bar", bar="foo")
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
)
G[1][2]["data"] = 10 # OK to set data like this
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 10, "spam": "bar", "bar": "foo"})]
)
G.adj[1][2]["data"] = 20
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 20, "spam": "bar", "bar": "foo"})]
)
G.edges[1, 2]["data"] = 21 # another spelling, "edge"
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 21, "spam": "bar", "bar": "foo"})]
)
G.adj[1][2]["listdata"] = [20, 200]
G.adj[1][2]["weight"] = 20
dd = {
"data": 21,
"spam": "bar",
"bar": "foo",
"listdata": [20, 200],
"weight": 20,
}
assert edges_equal(G.edges(data=True), [(1, 2, dd)])
def test_to_undirected(self):
G = self.K3
self.add_attributes(G)
H = nx.Graph(G)
self.is_shallow_copy(H, G)
self.different_attrdict(H, G)
H = G.to_undirected()
self.is_deepcopy(H, G)
def test_to_directed(self):
G = self.K3
self.add_attributes(G)
H = nx.DiGraph(G)
self.is_shallow_copy(H, G)
self.different_attrdict(H, G)
H = G.to_directed()
self.is_deepcopy(H, G)
def test_subgraph(self):
G = self.K3
self.add_attributes(G)
H = G.subgraph([0, 1, 2, 5])
self.graphs_equal(H, G)
self.same_attrdict(H, G)
self.shallow_copy_attrdict(H, G)
H = G.subgraph(0)
assert H.adj == {0: {}}
H = G.subgraph([])
assert H.adj == {}
assert G.adj != {}
def test_selfloops_attr(self):
G = self.K3.copy()
G.add_edge(0, 0)
G.add_edge(1, 1, weight=2)
assert edges_equal(
nx.selfloop_edges(G, data=True), [(0, 0, {}), (1, 1, {"weight": 2})]
)
assert edges_equal(
nx.selfloop_edges(G, data="weight"), [(0, 0, None), (1, 1, 2)]
)
class TestGraph(BaseAttrGraphTester):
"""Tests specific to dict-of-dict-of-dict graph data structure"""
def setup_method(self):
self.Graph = nx.Graph
# build dict-of-dict-of-dict K3
ed1, ed2, ed3 = ({}, {}, {})
self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
self.k3edges = [(0, 1), (0, 2), (1, 2)]
self.k3nodes = [0, 1, 2]
self.K3 = self.Graph()
self.K3._adj = self.k3adj
self.K3._node = {}
self.K3._node[0] = {}
self.K3._node[1] = {}
self.K3._node[2] = {}
def test_pickle(self):
G = self.K3
pg = pickle.loads(pickle.dumps(G, -1))
self.graphs_equal(pg, G)
pg = pickle.loads(pickle.dumps(G))
self.graphs_equal(pg, G)
def test_data_input(self):
G = self.Graph({1: [2], 2: [1]}, name="test")
assert G.name == "test"
assert sorted(G.adj.items()) == [(1, {2: {}}), (2, {1: {}})]
def test_adjacency(self):
G = self.K3
assert dict(G.adjacency()) == {
0: {1: {}, 2: {}},
1: {0: {}, 2: {}},
2: {0: {}, 1: {}},
}
def test_getitem(self):
G = self.K3
assert G[0] == {1: {}, 2: {}}
with pytest.raises(KeyError):
G.__getitem__("j")
with pytest.raises(TypeError):
G.__getitem__(["A"])
def test_add_node(self):
G = self.Graph()
G.add_node(0)
assert G.adj == {0: {}}
# test add attributes
G.add_node(1, c="red")
G.add_node(2, c="blue")
G.add_node(3, c="red")
assert G.nodes[1]["c"] == "red"
assert G.nodes[2]["c"] == "blue"
assert G.nodes[3]["c"] == "red"
# test updating attributes
G.add_node(1, c="blue")
G.add_node(2, c="red")
G.add_node(3, c="blue")
assert G.nodes[1]["c"] == "blue"
assert G.nodes[2]["c"] == "red"
assert G.nodes[3]["c"] == "blue"
def test_add_nodes_from(self):
G = self.Graph()
G.add_nodes_from([0, 1, 2])
assert G.adj == {0: {}, 1: {}, 2: {}}
# test add attributes
G.add_nodes_from([0, 1, 2], c="red")
assert G.nodes[0]["c"] == "red"
assert G.nodes[2]["c"] == "red"
# test that attribute dicts are not the same
assert G.nodes[0] is not G.nodes[1]
# test updating attributes
G.add_nodes_from([0, 1, 2], c="blue")
assert G.nodes[0]["c"] == "blue"
assert G.nodes[2]["c"] == "blue"
assert G.nodes[0] is not G.nodes[1]
# test tuple input
H = self.Graph()
H.add_nodes_from(G.nodes(data=True))
assert H.nodes[0]["c"] == "blue"
assert H.nodes[2]["c"] == "blue"
assert H.nodes[0] is not H.nodes[1]
# specific overrides general
H.add_nodes_from([0, (1, {"c": "green"}), (3, {"c": "cyan"})], c="red")
assert H.nodes[0]["c"] == "red"
assert H.nodes[1]["c"] == "green"
assert H.nodes[2]["c"] == "blue"
assert H.nodes[3]["c"] == "cyan"
def test_remove_node(self):
G = self.K3.copy()
G.remove_node(0)
assert G.adj == {1: {2: {}}, 2: {1: {}}}
with pytest.raises(nx.NetworkXError):
G.remove_node(-1)
# generator here to implement list,set,string...
def test_remove_nodes_from(self):
G = self.K3.copy()
G.remove_nodes_from([0, 1])
assert G.adj == {2: {}}
G.remove_nodes_from([-1]) # silent fail
def test_add_edge(self):
G = self.Graph()
G.add_edge(0, 1)
assert G.adj == {0: {1: {}}, 1: {0: {}}}
G = self.Graph()
G.add_edge(*(0, 1))
assert G.adj == {0: {1: {}}, 1: {0: {}}}
def test_add_edges_from(self):
G = self.Graph()
G.add_edges_from([(0, 1), (0, 2, {"weight": 3})])
assert G.adj == {
0: {1: {}, 2: {"weight": 3}},
1: {0: {}},
2: {0: {"weight": 3}},
}
G = self.Graph()
G.add_edges_from([(0, 1), (0, 2, {"weight": 3}), (1, 2, {"data": 4})], data=2)
assert G.adj == {
0: {1: {"data": 2}, 2: {"weight": 3, "data": 2}},
1: {0: {"data": 2}, 2: {"data": 4}},
2: {0: {"weight": 3, "data": 2}, 1: {"data": 4}},
}
with pytest.raises(nx.NetworkXError):
G.add_edges_from([(0,)]) # too few in tuple
with pytest.raises(nx.NetworkXError):
G.add_edges_from([(0, 1, 2, 3)]) # too many in tuple
with pytest.raises(TypeError):
G.add_edges_from([0]) # not a tuple
def test_remove_edge(self):
G = self.K3.copy()
G.remove_edge(0, 1)
assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
with pytest.raises(nx.NetworkXError):
G.remove_edge(-1, 0)
def test_remove_edges_from(self):
G = self.K3.copy()
G.remove_edges_from([(0, 1)])
assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
G.remove_edges_from([(0, 0)]) # silent fail
def test_clear(self):
G = self.K3.copy()
G.graph["name"] = "K3"
G.clear()
assert list(G.nodes) == []
assert G.adj == {}
assert G.graph == {}
def test_clear_edges(self):
G = self.K3.copy()
G.graph["name"] = "K3"
nodes = list(G.nodes)
G.clear_edges()
assert list(G.nodes) == nodes
assert G.adj == {0: {}, 1: {}, 2: {}}
assert list(G.edges) == []
assert G.graph["name"] == "K3"
def test_edges_data(self):
G = self.K3
all_edges = [(0, 1, {}), (0, 2, {}), (1, 2, {})]
assert edges_equal(G.edges(data=True), all_edges)
assert edges_equal(G.edges(0, data=True), [(0, 1, {}), (0, 2, {})])
assert edges_equal(G.edges([0, 1], data=True), all_edges)
with pytest.raises(nx.NetworkXError):
G.edges(-1, True)
def test_get_edge_data(self):
G = self.K3.copy()
assert G.get_edge_data(0, 1) == {}
assert G[0][1] == {}
assert G.get_edge_data(10, 20) is None
assert G.get_edge_data(-1, 0) is None
assert G.get_edge_data(-1, 0, default=1) == 1
def test_update(self):
# specify both edgees and nodes
G = self.K3.copy()
G.update(nodes=[3, (4, {"size": 2})], edges=[(4, 5), (6, 7, {"weight": 2})])
nlist = [
(0, {}),
(1, {}),
(2, {}),
(3, {}),
(4, {"size": 2}),
(5, {}),
(6, {}),
(7, {}),
]
assert sorted(G.nodes.data()) == nlist
if G.is_directed():
elist = [
(0, 1, {}),
(0, 2, {}),
(1, 0, {}),
(1, 2, {}),
(2, 0, {}),
(2, 1, {}),
(4, 5, {}),
(6, 7, {"weight": 2}),
]
else:
elist = [
(0, 1, {}),
(0, 2, {}),
(1, 2, {}),
(4, 5, {}),
(6, 7, {"weight": 2}),
]
assert sorted(G.edges.data()) == elist
assert G.graph == {}
# no keywords -- order is edges, nodes
G = self.K3.copy()
G.update([(4, 5), (6, 7, {"weight": 2})], [3, (4, {"size": 2})])
assert sorted(G.nodes.data()) == nlist
assert sorted(G.edges.data()) == elist
assert G.graph == {}
# update using only a graph
G = self.Graph()
G.graph["foo"] = "bar"
G.add_node(2, data=4)
G.add_edge(0, 1, weight=0.5)
GG = G.copy()
H = self.Graph()
GG.update(H)
assert graphs_equal(G, GG)
H.update(G)
assert graphs_equal(H, G)
# update nodes only
H = self.Graph()
H.update(nodes=[3, 4])
assert H.nodes ^ {3, 4} == set()
assert H.size() == 0
# update edges only
H = self.Graph()
H.update(edges=[(3, 4)])
assert sorted(H.edges.data()) == [(3, 4, {})]
assert H.size() == 1
# No inputs -> exception
with pytest.raises(nx.NetworkXError):
nx.Graph().update()
class TestEdgeSubgraph:
"""Unit tests for the :meth:`Graph.edge_subgraph` method."""
def setup_method(self):
# Create a path graph on five nodes.
G = nx.path_graph(5)
# Add some node, edge, and graph attributes.
for i in range(5):
G.nodes[i]["name"] = f"node{i}"
G.edges[0, 1]["name"] = "edge01"
G.edges[3, 4]["name"] = "edge34"
G.graph["name"] = "graph"
# Get the subgraph induced by the first and last edges.
self.G = G
self.H = G.edge_subgraph([(0, 1), (3, 4)])
def test_correct_nodes(self):
"""Tests that the subgraph has the correct nodes."""
assert [0, 1, 3, 4] == sorted(self.H.nodes())
def test_correct_edges(self):
"""Tests that the subgraph has the correct edges."""
assert [(0, 1, "edge01"), (3, 4, "edge34")] == sorted(self.H.edges(data="name"))
def test_add_node(self):
"""Tests that adding a node to the original graph does not
affect the nodes of the subgraph.
"""
self.G.add_node(5)
assert [0, 1, 3, 4] == sorted(self.H.nodes())
def test_remove_node(self):
"""Tests that removing a node in the original graph does
affect the nodes of the subgraph.
"""
self.G.remove_node(0)
assert [1, 3, 4] == sorted(self.H.nodes())
def test_node_attr_dict(self):
"""Tests that the node attribute dictionary of the two graphs is
the same object.
"""
for v in self.H:
assert self.G.nodes[v] == self.H.nodes[v]
# Making a change to G should make a change in H and vice versa.
self.G.nodes[0]["name"] = "foo"
assert self.G.nodes[0] == self.H.nodes[0]
self.H.nodes[1]["name"] = "bar"
assert self.G.nodes[1] == self.H.nodes[1]
def test_edge_attr_dict(self):
"""Tests that the edge attribute dictionary of the two graphs is
the same object.
"""
for u, v in self.H.edges():
assert self.G.edges[u, v] == self.H.edges[u, v]
# Making a change to G should make a change in H and vice versa.
self.G.edges[0, 1]["name"] = "foo"
assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"]
self.H.edges[3, 4]["name"] = "bar"
assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"]
def test_graph_attr_dict(self):
"""Tests that the graph attribute dictionary of the two graphs
is the same object.
"""
assert self.G.graph is self.H.graph
|
import pickle
import gc
import platform
import pytest
import networkx as nx
from networkx.utils import nodes_equal, edges_equal, graphs_equal
class BaseGraphTester:
"""Tests for data-structure independent graph class features."""
def test_contains(self):
G = self.K3
assert 1 in G
assert 4 not in G
assert "b" not in G
assert [] not in G # no exception for nonhashable
assert {1: 1} not in G # no exception for nonhashable
def test_order(self):
G = self.K3
assert len(G) == 3
assert G.order() == 3
assert G.number_of_nodes() == 3
def test_nodes(self):
G = self.K3
assert sorted(G.nodes()) == self.k3nodes
assert sorted(G.nodes(data=True)) == [(0, {}), (1, {}), (2, {})]
def test_has_node(self):
G = self.K3
assert G.has_node(1)
assert not G.has_node(4)
assert not G.has_node([]) # no exception for nonhashable
assert not G.has_node({1: 1}) # no exception for nonhashable
def test_has_edge(self):
G = self.K3
assert G.has_edge(0, 1)
assert not G.has_edge(0, -1)
def test_neighbors(self):
G = self.K3
assert sorted(G.neighbors(0)) == [1, 2]
with pytest.raises(nx.NetworkXError):
G.neighbors(-1)
@pytest.mark.skipif(
platform.python_implementation() == "PyPy", reason="PyPy gc is different"
)
def test_memory_leak(self):
G = self.Graph()
def count_objects_of_type(_type):
return sum(1 for obj in gc.get_objects() if isinstance(obj, _type))
gc.collect()
before = count_objects_of_type(self.Graph)
G.copy()
gc.collect()
after = count_objects_of_type(self.Graph)
assert before == after
# test a subgraph of the base class
class MyGraph(self.Graph):
pass
gc.collect()
G = MyGraph()
before = count_objects_of_type(MyGraph)
G.copy()
gc.collect()
after = count_objects_of_type(MyGraph)
assert before == after
def test_edges(self):
G = self.K3
assert edges_equal(G.edges(), [(0, 1), (0, 2), (1, 2)])
assert edges_equal(G.edges(0), [(0, 1), (0, 2)])
assert edges_equal(G.edges([0, 1]), [(0, 1), (0, 2), (1, 2)])
with pytest.raises(nx.NetworkXError):
G.edges(-1)
def test_degree(self):
G = self.K3
assert sorted(G.degree()) == [(0, 2), (1, 2), (2, 2)]
assert dict(G.degree()) == {0: 2, 1: 2, 2: 2}
assert G.degree(0) == 2
with pytest.raises(nx.NetworkXError):
G.degree(-1) # node not in graph
def test_size(self):
G = self.K3
assert G.size() == 3
assert G.number_of_edges() == 3
def test_nbunch_iter(self):
G = self.K3
assert nodes_equal(G.nbunch_iter(), self.k3nodes) # all nodes
assert nodes_equal(G.nbunch_iter(0), [0]) # single node
assert nodes_equal(G.nbunch_iter([0, 1]), [0, 1]) # sequence
# sequence with none in graph
assert nodes_equal(G.nbunch_iter([-1]), [])
# string sequence with none in graph
assert nodes_equal(G.nbunch_iter("foo"), [])
# node not in graph doesn't get caught upon creation of iterator
bunch = G.nbunch_iter(-1)
# but gets caught when iterator used
with pytest.raises(nx.NetworkXError, match="is not a node or a sequence"):
list(bunch)
# unhashable doesn't get caught upon creation of iterator
bunch = G.nbunch_iter([0, 1, 2, {}])
# but gets caught when iterator hits the unhashable
with pytest.raises(
nx.NetworkXError, match="in sequence nbunch is not a valid node"
):
list(bunch)
def test_nbunch_iter_node_format_raise(self):
# Tests that a node that would have failed string formatting
# doesn't cause an error when attempting to raise a
# :exc:`nx.NetworkXError`.
# For more information, see pull request #1813.
G = self.Graph()
nbunch = [("x", set())]
with pytest.raises(nx.NetworkXError):
list(G.nbunch_iter(nbunch))
def test_selfloop_degree(self):
G = self.Graph()
G.add_edge(1, 1)
assert sorted(G.degree()) == [(1, 2)]
assert dict(G.degree()) == {1: 2}
assert G.degree(1) == 2
assert sorted(G.degree([1])) == [(1, 2)]
assert G.degree(1, weight="weight") == 2
def test_selfloops(self):
G = self.K3.copy()
G.add_edge(0, 0)
assert nodes_equal(nx.nodes_with_selfloops(G), [0])
assert edges_equal(nx.selfloop_edges(G), [(0, 0)])
assert nx.number_of_selfloops(G) == 1
G.remove_edge(0, 0)
G.add_edge(0, 0)
G.remove_edges_from([(0, 0)])
G.add_edge(1, 1)
G.remove_node(1)
G.add_edge(0, 0)
G.add_edge(1, 1)
G.remove_nodes_from([0, 1])
class BaseAttrGraphTester(BaseGraphTester):
"""Tests of graph class attribute features."""
def test_weighted_degree(self):
G = self.Graph()
G.add_edge(1, 2, weight=2, other=3)
G.add_edge(2, 3, weight=3, other=4)
assert sorted(d for n, d in G.degree(weight="weight")) == [2, 3, 5]
assert dict(G.degree(weight="weight")) == {1: 2, 2: 5, 3: 3}
assert G.degree(1, weight="weight") == 2
assert nodes_equal((G.degree([1], weight="weight")), [(1, 2)])
assert nodes_equal((d for n, d in G.degree(weight="other")), [3, 7, 4])
assert dict(G.degree(weight="other")) == {1: 3, 2: 7, 3: 4}
assert G.degree(1, weight="other") == 3
assert edges_equal((G.degree([1], weight="other")), [(1, 3)])
def add_attributes(self, G):
G.graph["foo"] = []
G.nodes[0]["foo"] = []
G.remove_edge(1, 2)
ll = []
G.add_edge(1, 2, foo=ll)
G.add_edge(2, 1, foo=ll)
def test_name(self):
G = self.Graph(name="")
assert G.name == ""
G = self.Graph(name="test")
assert G.name == "test"
def test_str_unnamed(self):
G = self.Graph()
G.add_edges_from([(1, 2), (2, 3)])
assert str(G) == f"{type(G).__name__} with 3 nodes and 2 edges"
def test_str_named(self):
G = self.Graph(name="foo")
G.add_edges_from([(1, 2), (2, 3)])
assert str(G) == f"{type(G).__name__} named 'foo' with 3 nodes and 2 edges"
def test_graph_chain(self):
G = self.Graph([(0, 1), (1, 2)])
DG = G.to_directed(as_view=True)
SDG = DG.subgraph([0, 1])
RSDG = SDG.reverse(copy=False)
assert G is DG._graph
assert DG is SDG._graph
assert SDG is RSDG._graph
def test_copy(self):
G = self.Graph()
G.add_node(0)
G.add_edge(1, 2)
self.add_attributes(G)
# copy edge datadict but any container attr are same
H = G.copy()
self.graphs_equal(H, G)
self.different_attrdict(H, G)
self.shallow_copy_attrdict(H, G)
def test_class_copy(self):
G = self.Graph()
G.add_node(0)
G.add_edge(1, 2)
self.add_attributes(G)
# copy edge datadict but any container attr are same
H = G.__class__(G)
self.graphs_equal(H, G)
self.different_attrdict(H, G)
self.shallow_copy_attrdict(H, G)
def test_fresh_copy(self):
G = self.Graph()
G.add_node(0)
G.add_edge(1, 2)
self.add_attributes(G)
# copy graph structure but use fresh datadict
H = G.__class__()
H.add_nodes_from(G)
H.add_edges_from(G.edges())
assert len(G.nodes[0]) == 1
ddict = G.adj[1][2][0] if G.is_multigraph() else G.adj[1][2]
assert len(ddict) == 1
assert len(H.nodes[0]) == 0
ddict = H.adj[1][2][0] if H.is_multigraph() else H.adj[1][2]
assert len(ddict) == 0
def is_deepcopy(self, H, G):
self.graphs_equal(H, G)
self.different_attrdict(H, G)
self.deep_copy_attrdict(H, G)
def deep_copy_attrdict(self, H, G):
self.deepcopy_graph_attr(H, G)
self.deepcopy_node_attr(H, G)
self.deepcopy_edge_attr(H, G)
def deepcopy_graph_attr(self, H, G):
assert G.graph["foo"] == H.graph["foo"]
G.graph["foo"].append(1)
assert G.graph["foo"] != H.graph["foo"]
def deepcopy_node_attr(self, H, G):
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
G.nodes[0]["foo"].append(1)
assert G.nodes[0]["foo"] != H.nodes[0]["foo"]
def deepcopy_edge_attr(self, H, G):
assert G[1][2]["foo"] == H[1][2]["foo"]
G[1][2]["foo"].append(1)
assert G[1][2]["foo"] != H[1][2]["foo"]
def is_shallow_copy(self, H, G):
self.graphs_equal(H, G)
self.shallow_copy_attrdict(H, G)
def shallow_copy_attrdict(self, H, G):
self.shallow_copy_graph_attr(H, G)
self.shallow_copy_node_attr(H, G)
self.shallow_copy_edge_attr(H, G)
def shallow_copy_graph_attr(self, H, G):
assert G.graph["foo"] == H.graph["foo"]
G.graph["foo"].append(1)
assert G.graph["foo"] == H.graph["foo"]
def shallow_copy_node_attr(self, H, G):
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
G.nodes[0]["foo"].append(1)
assert G.nodes[0]["foo"] == H.nodes[0]["foo"]
def shallow_copy_edge_attr(self, H, G):
assert G[1][2]["foo"] == H[1][2]["foo"]
G[1][2]["foo"].append(1)
assert G[1][2]["foo"] == H[1][2]["foo"]
def same_attrdict(self, H, G):
old_foo = H[1][2]["foo"]
H.adj[1][2]["foo"] = "baz"
assert G.edges == H.edges
H.adj[1][2]["foo"] = old_foo
assert G.edges == H.edges
old_foo = H.nodes[0]["foo"]
H.nodes[0]["foo"] = "baz"
assert G.nodes == H.nodes
H.nodes[0]["foo"] = old_foo
assert G.nodes == H.nodes
def different_attrdict(self, H, G):
old_foo = H[1][2]["foo"]
H.adj[1][2]["foo"] = "baz"
assert G._adj != H._adj
H.adj[1][2]["foo"] = old_foo
assert G._adj == H._adj
old_foo = H.nodes[0]["foo"]
H.nodes[0]["foo"] = "baz"
assert G._node != H._node
H.nodes[0]["foo"] = old_foo
assert G._node == H._node
def graphs_equal(self, H, G):
assert G._adj == H._adj
assert G._node == H._node
assert G.graph == H.graph
assert G.name == H.name
if not G.is_directed() and not H.is_directed():
assert H._adj[1][2] is H._adj[2][1]
assert G._adj[1][2] is G._adj[2][1]
else: # at least one is directed
if not G.is_directed():
G._pred = G._adj
G._succ = G._adj
if not H.is_directed():
H._pred = H._adj
H._succ = H._adj
assert G._pred == H._pred
assert G._succ == H._succ
assert H._succ[1][2] is H._pred[2][1]
assert G._succ[1][2] is G._pred[2][1]
def test_graph_attr(self):
G = self.K3.copy()
G.graph["foo"] = "bar"
assert G.graph["foo"] == "bar"
del G.graph["foo"]
assert G.graph == {}
H = self.Graph(foo="bar")
assert H.graph["foo"] == "bar"
def test_node_attr(self):
G = self.K3.copy()
G.add_node(1, foo="bar")
assert nodes_equal(G.nodes(), [0, 1, 2])
assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "bar"}), (2, {})])
G.nodes[1]["foo"] = "baz"
assert nodes_equal(G.nodes(data=True), [(0, {}), (1, {"foo": "baz"}), (2, {})])
assert nodes_equal(G.nodes(data="foo"), [(0, None), (1, "baz"), (2, None)])
assert nodes_equal(
G.nodes(data="foo", default="bar"), [(0, "bar"), (1, "baz"), (2, "bar")]
)
def test_node_attr2(self):
G = self.K3.copy()
a = {"foo": "bar"}
G.add_node(3, **a)
assert nodes_equal(G.nodes(), [0, 1, 2, 3])
assert nodes_equal(
G.nodes(data=True), [(0, {}), (1, {}), (2, {}), (3, {"foo": "bar"})]
)
def test_edge_lookup(self):
G = self.Graph()
G.add_edge(1, 2, foo="bar")
assert edges_equal(G.edges[1, 2], {"foo": "bar"})
def test_edge_attr(self):
G = self.Graph()
G.add_edge(1, 2, foo="bar")
assert edges_equal(G.edges(data=True), [(1, 2, {"foo": "bar"})])
assert edges_equal(G.edges(data="foo"), [(1, 2, "bar")])
def test_edge_attr2(self):
G = self.Graph()
G.add_edges_from([(1, 2), (3, 4)], foo="foo")
assert edges_equal(
G.edges(data=True), [(1, 2, {"foo": "foo"}), (3, 4, {"foo": "foo"})]
)
assert edges_equal(G.edges(data="foo"), [(1, 2, "foo"), (3, 4, "foo")])
def test_edge_attr3(self):
G = self.Graph()
G.add_edges_from([(1, 2, {"weight": 32}), (3, 4, {"weight": 64})], foo="foo")
assert edges_equal(
G.edges(data=True),
[
(1, 2, {"foo": "foo", "weight": 32}),
(3, 4, {"foo": "foo", "weight": 64}),
],
)
G.remove_edges_from([(1, 2), (3, 4)])
G.add_edge(1, 2, data=7, spam="bar", bar="foo")
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
)
def test_edge_attr4(self):
G = self.Graph()
G.add_edge(1, 2, data=7, spam="bar", bar="foo")
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 7, "spam": "bar", "bar": "foo"})]
)
G[1][2]["data"] = 10 # OK to set data like this
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 10, "spam": "bar", "bar": "foo"})]
)
G.adj[1][2]["data"] = 20
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 20, "spam": "bar", "bar": "foo"})]
)
G.edges[1, 2]["data"] = 21 # another spelling, "edge"
assert edges_equal(
G.edges(data=True), [(1, 2, {"data": 21, "spam": "bar", "bar": "foo"})]
)
G.adj[1][2]["listdata"] = [20, 200]
G.adj[1][2]["weight"] = 20
dd = {
"data": 21,
"spam": "bar",
"bar": "foo",
"listdata": [20, 200],
"weight": 20,
}
assert edges_equal(G.edges(data=True), [(1, 2, dd)])
def test_to_undirected(self):
G = self.K3
self.add_attributes(G)
H = nx.Graph(G)
self.is_shallow_copy(H, G)
self.different_attrdict(H, G)
H = G.to_undirected()
self.is_deepcopy(H, G)
def test_to_directed(self):
G = self.K3
self.add_attributes(G)
H = nx.DiGraph(G)
self.is_shallow_copy(H, G)
self.different_attrdict(H, G)
H = G.to_directed()
self.is_deepcopy(H, G)
def test_subgraph(self):
G = self.K3
self.add_attributes(G)
H = G.subgraph([0, 1, 2, 5])
self.graphs_equal(H, G)
self.same_attrdict(H, G)
self.shallow_copy_attrdict(H, G)
H = G.subgraph(0)
assert H.adj == {0: {}}
H = G.subgraph([])
assert H.adj == {}
assert G.adj != {}
def test_selfloops_attr(self):
G = self.K3.copy()
G.add_edge(0, 0)
G.add_edge(1, 1, weight=2)
assert edges_equal(
nx.selfloop_edges(G, data=True), [(0, 0, {}), (1, 1, {"weight": 2})]
)
assert edges_equal(
nx.selfloop_edges(G, data="weight"), [(0, 0, None), (1, 1, 2)]
)
class TestGraph(BaseAttrGraphTester):
"""Tests specific to dict-of-dict-of-dict graph data structure"""
def setup_method(self):
self.Graph = nx.Graph
# build dict-of-dict-of-dict K3
ed1, ed2, ed3 = ({}, {}, {})
self.k3adj = {0: {1: ed1, 2: ed2}, 1: {0: ed1, 2: ed3}, 2: {0: ed2, 1: ed3}}
self.k3edges = [(0, 1), (0, 2), (1, 2)]
self.k3nodes = [0, 1, 2]
self.K3 = self.Graph()
self.K3._adj = self.k3adj
self.K3._node = {}
self.K3._node[0] = {}
self.K3._node[1] = {}
self.K3._node[2] = {}
def test_pickle(self):
G = self.K3
pg = pickle.loads(pickle.dumps(G, -1))
self.graphs_equal(pg, G)
pg = pickle.loads(pickle.dumps(G))
self.graphs_equal(pg, G)
def test_data_input(self):
G = self.Graph({1: [2], 2: [1]}, name="test")
assert G.name == "test"
assert sorted(G.adj.items()) == [(1, {2: {}}), (2, {1: {}})]
def test_adjacency(self):
G = self.K3
assert dict(G.adjacency()) == {
0: {1: {}, 2: {}},
1: {0: {}, 2: {}},
2: {0: {}, 1: {}},
}
def test_getitem(self):
G = self.K3
assert G[0] == {1: {}, 2: {}}
with pytest.raises(KeyError):
G.__getitem__("j")
with pytest.raises(TypeError):
G.__getitem__(["A"])
def test_add_node(self):
G = self.Graph()
G.add_node(0)
assert G.adj == {0: {}}
# test add attributes
G.add_node(1, c="red")
G.add_node(2, c="blue")
G.add_node(3, c="red")
assert G.nodes[1]["c"] == "red"
assert G.nodes[2]["c"] == "blue"
assert G.nodes[3]["c"] == "red"
# test updating attributes
G.add_node(1, c="blue")
G.add_node(2, c="red")
G.add_node(3, c="blue")
assert G.nodes[1]["c"] == "blue"
assert G.nodes[2]["c"] == "red"
assert G.nodes[3]["c"] == "blue"
def test_add_nodes_from(self):
G = self.Graph()
G.add_nodes_from([0, 1, 2])
assert G.adj == {0: {}, 1: {}, 2: {}}
# test add attributes
G.add_nodes_from([0, 1, 2], c="red")
assert G.nodes[0]["c"] == "red"
assert G.nodes[2]["c"] == "red"
# test that attribute dicts are not the same
assert G.nodes[0] is not G.nodes[1]
# test updating attributes
G.add_nodes_from([0, 1, 2], c="blue")
assert G.nodes[0]["c"] == "blue"
assert G.nodes[2]["c"] == "blue"
assert G.nodes[0] is not G.nodes[1]
# test tuple input
H = self.Graph()
H.add_nodes_from(G.nodes(data=True))
assert H.nodes[0]["c"] == "blue"
assert H.nodes[2]["c"] == "blue"
assert H.nodes[0] is not H.nodes[1]
# specific overrides general
H.add_nodes_from([0, (1, {"c": "green"}), (3, {"c": "cyan"})], c="red")
assert H.nodes[0]["c"] == "red"
assert H.nodes[1]["c"] == "green"
assert H.nodes[2]["c"] == "blue"
assert H.nodes[3]["c"] == "cyan"
def test_remove_node(self):
G = self.K3.copy()
G.remove_node(0)
assert G.adj == {1: {2: {}}, 2: {1: {}}}
with pytest.raises(nx.NetworkXError):
G.remove_node(-1)
# generator here to implement list,set,string...
def test_remove_nodes_from(self):
G = self.K3.copy()
G.remove_nodes_from([0, 1])
assert G.adj == {2: {}}
G.remove_nodes_from([-1]) # silent fail
def test_add_edge(self):
G = self.Graph()
G.add_edge(0, 1)
assert G.adj == {0: {1: {}}, 1: {0: {}}}
G = self.Graph()
G.add_edge(*(0, 1))
assert G.adj == {0: {1: {}}, 1: {0: {}}}
def test_add_edges_from(self):
G = self.Graph()
G.add_edges_from([(0, 1), (0, 2, {"weight": 3})])
assert G.adj == {
0: {1: {}, 2: {"weight": 3}},
1: {0: {}},
2: {0: {"weight": 3}},
}
G = self.Graph()
G.add_edges_from([(0, 1), (0, 2, {"weight": 3}), (1, 2, {"data": 4})], data=2)
assert G.adj == {
0: {1: {"data": 2}, 2: {"weight": 3, "data": 2}},
1: {0: {"data": 2}, 2: {"data": 4}},
2: {0: {"weight": 3, "data": 2}, 1: {"data": 4}},
}
with pytest.raises(nx.NetworkXError):
G.add_edges_from([(0,)]) # too few in tuple
with pytest.raises(nx.NetworkXError):
G.add_edges_from([(0, 1, 2, 3)]) # too many in tuple
with pytest.raises(TypeError):
G.add_edges_from([0]) # not a tuple
def test_remove_edge(self):
G = self.K3.copy()
G.remove_edge(0, 1)
assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
with pytest.raises(nx.NetworkXError):
G.remove_edge(-1, 0)
def test_remove_edges_from(self):
G = self.K3.copy()
G.remove_edges_from([(0, 1)])
assert G.adj == {0: {2: {}}, 1: {2: {}}, 2: {0: {}, 1: {}}}
G.remove_edges_from([(0, 0)]) # silent fail
def test_clear(self):
G = self.K3.copy()
G.graph["name"] = "K3"
G.clear()
assert list(G.nodes) == []
assert G.adj == {}
assert G.graph == {}
def test_clear_edges(self):
G = self.K3.copy()
G.graph["name"] = "K3"
nodes = list(G.nodes)
G.clear_edges()
assert list(G.nodes) == nodes
assert G.adj == {0: {}, 1: {}, 2: {}}
assert list(G.edges) == []
assert G.graph["name"] == "K3"
def test_edges_data(self):
G = self.K3
all_edges = [(0, 1, {}), (0, 2, {}), (1, 2, {})]
assert edges_equal(G.edges(data=True), all_edges)
assert edges_equal(G.edges(0, data=True), [(0, 1, {}), (0, 2, {})])
assert edges_equal(G.edges([0, 1], data=True), all_edges)
with pytest.raises(nx.NetworkXError):
G.edges(-1, True)
def test_get_edge_data(self):
G = self.K3.copy()
assert G.get_edge_data(0, 1) == {}
assert G[0][1] == {}
assert G.get_edge_data(10, 20) is None
assert G.get_edge_data(-1, 0) is None
assert G.get_edge_data(-1, 0, default=1) == 1
def test_update(self):
# specify both edgees and nodes
G = self.K3.copy()
G.update(nodes=[3, (4, {"size": 2})], edges=[(4, 5), (6, 7, {"weight": 2})])
nlist = [
(0, {}),
(1, {}),
(2, {}),
(3, {}),
(4, {"size": 2}),
(5, {}),
(6, {}),
(7, {}),
]
assert sorted(G.nodes.data()) == nlist
if G.is_directed():
elist = [
(0, 1, {}),
(0, 2, {}),
(1, 0, {}),
(1, 2, {}),
(2, 0, {}),
(2, 1, {}),
(4, 5, {}),
(6, 7, {"weight": 2}),
]
else:
elist = [
(0, 1, {}),
(0, 2, {}),
(1, 2, {}),
(4, 5, {}),
(6, 7, {"weight": 2}),
]
assert sorted(G.edges.data()) == elist
assert G.graph == {}
# no keywords -- order is edges, nodes
G = self.K3.copy()
G.update([(4, 5), (6, 7, {"weight": 2})], [3, (4, {"size": 2})])
assert sorted(G.nodes.data()) == nlist
assert sorted(G.edges.data()) == elist
assert G.graph == {}
# update using only a graph
G = self.Graph()
G.graph["foo"] = "bar"
G.add_node(2, data=4)
G.add_edge(0, 1, weight=0.5)
GG = G.copy()
H = self.Graph()
GG.update(H)
assert graphs_equal(G, GG)
H.update(G)
assert graphs_equal(H, G)
# update nodes only
H = self.Graph()
H.update(nodes=[3, 4])
assert H.nodes ^ {3, 4} == set()
assert H.size() == 0
# update edges only
H = self.Graph()
H.update(edges=[(3, 4)])
assert sorted(H.edges.data()) == [(3, 4, {})]
assert H.size() == 1
# No inputs -> exception
with pytest.raises(nx.NetworkXError):
nx.Graph().update()
class TestEdgeSubgraph:
"""Unit tests for the :meth:`Graph.edge_subgraph` method."""
def setup_method(self):
# Create a path graph on five nodes.
G = nx.path_graph(5)
# Add some node, edge, and graph attributes.
for i in range(5):
G.nodes[i]["name"] = f"node{i}"
G.edges[0, 1]["name"] = "edge01"
G.edges[3, 4]["name"] = "edge34"
G.graph["name"] = "graph"
# Get the subgraph induced by the first and last edges.
self.G = G
self.H = G.edge_subgraph([(0, 1), (3, 4)])
def test_correct_nodes(self):
"""Tests that the subgraph has the correct nodes."""
assert [0, 1, 3, 4] == sorted(self.H.nodes())
def test_correct_edges(self):
"""Tests that the subgraph has the correct edges."""
assert [(0, 1, "edge01"), (3, 4, "edge34")] == sorted(self.H.edges(data="name"))
def test_add_node(self):
"""Tests that adding a node to the original graph does not
affect the nodes of the subgraph.
"""
self.G.add_node(5)
assert [0, 1, 3, 4] == sorted(self.H.nodes())
def test_remove_node(self):
"""Tests that removing a node in the original graph does
affect the nodes of the subgraph.
"""
self.G.remove_node(0)
assert [1, 3, 4] == sorted(self.H.nodes())
def test_node_attr_dict(self):
"""Tests that the node attribute dictionary of the two graphs is
the same object.
"""
for v in self.H:
assert self.G.nodes[v] == self.H.nodes[v]
# Making a change to G should make a change in H and vice versa.
self.G.nodes[0]["name"] = "foo"
assert self.G.nodes[0] == self.H.nodes[0]
self.H.nodes[1]["name"] = "bar"
assert self.G.nodes[1] == self.H.nodes[1]
def test_edge_attr_dict(self):
"""Tests that the edge attribute dictionary of the two graphs is
the same object.
"""
for u, v in self.H.edges():
assert self.G.edges[u, v] == self.H.edges[u, v]
# Making a change to G should make a change in H and vice versa.
self.G.edges[0, 1]["name"] = "foo"
assert self.G.edges[0, 1]["name"] == self.H.edges[0, 1]["name"]
self.H.edges[3, 4]["name"] = "bar"
assert self.G.edges[3, 4]["name"] == self.H.edges[3, 4]["name"]
def test_graph_attr_dict(self):
"""Tests that the graph attribute dictionary of the two graphs
is the same object.
"""
assert self.G.graph is self.H.graph
|
en
| 0.845137
|
Tests for data-structure independent graph class features. # no exception for nonhashable # no exception for nonhashable # no exception for nonhashable # no exception for nonhashable # test a subgraph of the base class # node not in graph # all nodes # single node # sequence # sequence with none in graph # string sequence with none in graph # node not in graph doesn't get caught upon creation of iterator # but gets caught when iterator used # unhashable doesn't get caught upon creation of iterator # but gets caught when iterator hits the unhashable # Tests that a node that would have failed string formatting # doesn't cause an error when attempting to raise a # :exc:`nx.NetworkXError`. # For more information, see pull request #1813. Tests of graph class attribute features. # copy edge datadict but any container attr are same # copy edge datadict but any container attr are same # copy graph structure but use fresh datadict # at least one is directed # OK to set data like this # another spelling, "edge" Tests specific to dict-of-dict-of-dict graph data structure # build dict-of-dict-of-dict K3 # test add attributes # test updating attributes # test add attributes # test that attribute dicts are not the same # test updating attributes # test tuple input # specific overrides general # generator here to implement list,set,string... # silent fail # too few in tuple # too many in tuple # not a tuple # silent fail # specify both edgees and nodes # no keywords -- order is edges, nodes # update using only a graph # update nodes only # update edges only # No inputs -> exception Unit tests for the :meth:`Graph.edge_subgraph` method. # Create a path graph on five nodes. # Add some node, edge, and graph attributes. # Get the subgraph induced by the first and last edges. Tests that the subgraph has the correct nodes. Tests that the subgraph has the correct edges. Tests that adding a node to the original graph does not affect the nodes of the subgraph. Tests that removing a node in the original graph does affect the nodes of the subgraph. Tests that the node attribute dictionary of the two graphs is the same object. # Making a change to G should make a change in H and vice versa. Tests that the edge attribute dictionary of the two graphs is the same object. # Making a change to G should make a change in H and vice versa. Tests that the graph attribute dictionary of the two graphs is the same object.
| 2.418984
| 2
|
pysyte/freds/__main__.py
|
git-wwts/pysyte
| 1
|
6626264
|
from pysyte import cli
@cli.args
def fred():
pass
# Below reformatted to allow flaking
def pa(*_, **__):
pass
some_args = [
pa(
"directories",
metavar="items",
type=str,
nargs="*",
help="Only look for fred files in these directories",
),
pa(
"-d",
"--debug",
action="store_true",
help="Debug the first fred.py with pudb",
),
pa("-e", "--edit", action="store_true", help="Edit the freds with vim"),
pa("-l", "--list", action="store_true", help="Use long listing"),
pa("-r", "--remove", action="store_true", help="Remove the freds"),
pa(
"-p",
"--python",
action="store_true",
help="Run the first fred.py script",
),
pa(
"-s",
"--shell",
action="store_true",
help="Run the first fred.sh script",
),
pa("-v", "--version", action="store_true", help="Show version"),
]
|
from pysyte import cli
@cli.args
def fred():
pass
# Below reformatted to allow flaking
def pa(*_, **__):
pass
some_args = [
pa(
"directories",
metavar="items",
type=str,
nargs="*",
help="Only look for fred files in these directories",
),
pa(
"-d",
"--debug",
action="store_true",
help="Debug the first fred.py with pudb",
),
pa("-e", "--edit", action="store_true", help="Edit the freds with vim"),
pa("-l", "--list", action="store_true", help="Use long listing"),
pa("-r", "--remove", action="store_true", help="Remove the freds"),
pa(
"-p",
"--python",
action="store_true",
help="Run the first fred.py script",
),
pa(
"-s",
"--shell",
action="store_true",
help="Run the first fred.sh script",
),
pa("-v", "--version", action="store_true", help="Show version"),
]
|
en
| 0.874661
|
# Below reformatted to allow flaking
| 2.297048
| 2
|
stage4/06-jupyter/blinkt-examples/morse_code.py
|
ADMETE-OHIO/pi-gen
| 0
|
6626265
|
#!/usr/bin/env python
import time
import blinkt
blinkt.set_clear_on_exit()
def show_all(state):
"""Set all LEDs."""
for i in range(blinkt.NUM_PIXELS):
val = state * 255
blinkt.set_pixel(i, val, val, val)
blinkt.show()
def dot():
"""Blink LEDs for 0.05 seconds."""
show_all(1)
time.sleep(0.05)
show_all(0)
time.sleep(0.2)
def dash():
"""Blink LEDs for 0.2 seconds."""
show_all(1)
time.sleep(0.2)
show_all(0)
time.sleep(0.2)
def space():
"""Delay for 0.02 seconds."""
time.sleep(0.2)
# 0 is a space, 1 is a dot and 2 is a dash
MORSE = ' -... .. . -.. - -. . - . - -. -. - '
for m in MORSE:
if m == ' ':
space()
elif m == '.':
dot()
elif m == '-':
dash()
|
#!/usr/bin/env python
import time
import blinkt
blinkt.set_clear_on_exit()
def show_all(state):
"""Set all LEDs."""
for i in range(blinkt.NUM_PIXELS):
val = state * 255
blinkt.set_pixel(i, val, val, val)
blinkt.show()
def dot():
"""Blink LEDs for 0.05 seconds."""
show_all(1)
time.sleep(0.05)
show_all(0)
time.sleep(0.2)
def dash():
"""Blink LEDs for 0.2 seconds."""
show_all(1)
time.sleep(0.2)
show_all(0)
time.sleep(0.2)
def space():
"""Delay for 0.02 seconds."""
time.sleep(0.2)
# 0 is a space, 1 is a dot and 2 is a dash
MORSE = ' -... .. . -.. - -. . - . - -. -. - '
for m in MORSE:
if m == ' ':
space()
elif m == '.':
dot()
elif m == '-':
dash()
|
en
| 0.858385
|
#!/usr/bin/env python Set all LEDs. Blink LEDs for 0.05 seconds. Blink LEDs for 0.2 seconds. Delay for 0.02 seconds. # 0 is a space, 1 is a dot and 2 is a dash
| 3.157348
| 3
|
leehao/learn105.py
|
pilihaotian/pythonlearning
| 1
|
6626266
|
# super
class A:
def work(self):
print("A类的work被调用")
class B(A):
def work(self):
print("B类的work被调用")
b = B()
# 调用子类的work方法
b.work()
# 调用父类的work方法
super(B, b).work()
|
# super
class A:
def work(self):
print("A类的work被调用")
class B(A):
def work(self):
print("B类的work被调用")
b = B()
# 调用子类的work方法
b.work()
# 调用父类的work方法
super(B, b).work()
|
zh
| 0.732572
|
# super # 调用子类的work方法 # 调用父类的work方法
| 3.665437
| 4
|
apartment_scraper/apartments.py
|
golgor/apartment_scraper
| 0
|
6626267
|
<reponame>golgor/apartment_scraper
import logging
import re
from time import perf_counter
import concurrent.futures
import pandas as pd
import requests
from bs4 import BeautifulSoup
# Logging: https://docs.python.org/3/howto/logging-cookbook.html
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Create handlers
c_handler = logging.StreamHandler()
f_handler = logging.FileHandler("apartments.log")
c_handler.setLevel(logging.WARNING)
f_handler.setLevel(logging.INFO)
# Create formatters and add it to handlers
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
f_format = logging.Formatter('%(asctime)-12s - %(name)-12s - %(levelname)-8s %(message)s\n', datefmt='%m-%d %H:%M')
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)
# Add handlers to the logger
logger.addHandler(c_handler)
logger.addHandler(f_handler)
# TODO: Implement class method to validate URL, see:
# https://stackoverflow.com/questions/25200763/how-to-return-none-if-constructor-arguments-invalid
def get_source(apartment) -> BeautifulSoup:
"""Function to getting the source from a url.
Args:
apartment (Apartment): The object to process.
Returns:
BeautifulSoup: Soup of the source.
"""
try:
r = requests.get(apartment.url)
# Todo, check for http-status?
print(f"Fetching source: {apartment.url}")
return r.content
except requests.exceptions.ConnectionError:
logger.error("Connection refused by target server.")
except Exception as e:
logger.error(f"Couldn't not find source {e}"
f"soup for object {apartment.url}.")
return None
def get_div(soup, html_type, class_name: str):
"""Function to scrape the two facts divs from a soup.
Args:
soup (Beautifulsoup): A soup where to find a pattern.
regex (str): A regex string to use.
Returns:
soup: If found, returns a soup for the div with the wanted class.
"""
try:
div = soup.find(html_type, class_name)
if div:
return div
else:
logger.info(f"No tag with type '{html_type}' and "
f"attribute '{class_name}' found!")
return None
except Exception:
logger.error(f"No soup found to parse for a '{html_type}' "
f"with attribute '{class_name}'")
return None
def get_value_with_regex(div: str, regex: str) -> str:
"""Get a value from a str that matches a specific regex.
Args:
div (str): A stringified div to search.
regex (str): A regex expression.
Returns:
str: A value matching the pattern from the regex.
"""
if div is None:
return None
try:
# Try to find the regex as provided and return
# the value, else return N/A
value = re.search(regex, div).group()
# Only return numeric values, i.e. strip any €, m² and similar.
return float(re.sub("[^0-9,]", "", value).replace(",", "."))
except AttributeError as e:
# This error will occur if no expression is found. re.search
# will return None which does not have the attribute 'group'
logger.info(f"{e} - No substring found")
return None
except Exception as e:
logger.error(f"{e} ({regex}) in:\n{div}\n")
return None
def stringify_div(div):
if div is not None:
return re.sub("[\s.]", "", str(div).lower())
else:
return None
def get_location(div):
if div is None:
return 0, None
location_list = div.text.split()
return location_list[0][1:3], location_list[1]
class Apartment:
def __init__(self, url: str):
self.url = url
# If the current url is not available anymore, a message is given
# in a div. I.e. if this div is on the page, the object is no
# longer available on the site. Setting internal values to None
# makes all other values to default to N/A.
# TODO: Remove this instance from the apartmentlist
def fetch_data(self):
"""Function to fetch the data and specific divs
Typically 0.3 - 0.4 seconds (IO Bound)
"""
self.source = get_source(self)
def parse_data(self):
"""Function to parse the data using Beautifulsoups HTML-parser
and finding specific divs.
Typical time consumption: 0.36-0.4 seconds (CPU bound)
"""
try:
self.soup = BeautifulSoup(self.source, features="html.parser")
except Exception:
self.soup = None
self.quickfacts = get_div(self.soup, "div", "quickfacts iw_left")
self.hardfacts = get_div(self.soup, "div", "hardfacts clear")
def process_data(self):
"""Processing the soups and finding specific expressions using regex.
Note: Timing is excluding the parse_data() call at the start
of the function.
Typical time consumption: 200-300µs (CPU Bound)
"""
self.parse_data()
hardfacts = stringify_div(self.hardfacts)
self.rent = get_value_with_regex(div=hardfacts, regex="[0-9,]+€")
self.area = get_value_with_regex(div=hardfacts, regex="([0-9,]+)m")
self.rooms = get_value_with_regex(div=hardfacts, regex=">([0-9])<")
quickfacts = get_div(self.quickfacts, "span", "no_s")
self.bezirk, self.city = get_location(quickfacts)
self.bezirk = int(self.bezirk)
def fetch(apartment):
apartment.fetch_data()
def process(apartment):
apartment.process_data()
return (apartment.rent, apartment.area, apartment.rooms,
apartment.bezirk, apartment.city)
# ~264s with threading with 10 workers without ProcessPool
# ~268s with threading with 15 workers without ProcessPool
# with 2 workers with ProcessPool with 16 workers. ~650 items
# Time for fetching data: 119.40933409999707
# Time for processing: 25.59249959999579
# Time for saving data: 1.2901472999947146
# Time since start: 146.30282830000215
#with 2 workers with ProcessPool with 16 workers. ~6998 items
# Time for fetching data: 1969.1336764000007
# Time for processing: 266.7142402999889
# Time for saving data: 16.85627160000149
# Time since start: 2252.713053300002
def main(file):
start_main = perf_counter()
with open(file) as f:
apartment_list = [
Apartment(apartment)
for apartment
in f.read().split("\n")[:-1]
]
data = pd.DataFrame(
columns=["rent", "area", "rooms", "bezirk_no", "city", "url"]
)
print("Started fetching".center(50, "="))
start_fetching = perf_counter()
# Using threading with IO Bound fetching of data.
# High amount of workers lead to that Connections are refused.
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.map(fetch, apartment_list)
end_fetching = perf_counter()
print("Started processing".center(50, "="))
start_processing = perf_counter()
# Using multiprocessing for CPU Bound Parsing and regex pattern finding.
with concurrent.futures.ProcessPoolExecutor(max_workers=16) as executor:
results = executor.map(process, apartment_list)
end_processing = perf_counter()
start_save = perf_counter()
for result, apartment in zip(results, apartment_list):
apartment.rent = result[0]
apartment.area = result[1]
apartment.rooms = result[2]
apartment.bezirk = result[3]
apartment.city = result[4]
for idx, apartment in enumerate(apartment_list):
data.loc[idx] = (
apartment.rent,
apartment.area,
apartment.rooms,
apartment.bezirk,
apartment.city,
apartment.url
)
data.to_csv("apartments.csv", decimal=".")
end_saving = perf_counter()
print(f"Time for fetching data: {end_fetching - start_fetching}")
print(f"Time for processing: {end_processing - start_processing}")
print(f"Time for saving data: {end_saving - start_save}")
print(f"Time since start: {perf_counter() - start_main}")
FILE = "apartments.txt"
if __name__ == "__main__":
main(FILE)
|
import logging
import re
from time import perf_counter
import concurrent.futures
import pandas as pd
import requests
from bs4 import BeautifulSoup
# Logging: https://docs.python.org/3/howto/logging-cookbook.html
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Create handlers
c_handler = logging.StreamHandler()
f_handler = logging.FileHandler("apartments.log")
c_handler.setLevel(logging.WARNING)
f_handler.setLevel(logging.INFO)
# Create formatters and add it to handlers
c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
f_format = logging.Formatter('%(asctime)-12s - %(name)-12s - %(levelname)-8s %(message)s\n', datefmt='%m-%d %H:%M')
c_handler.setFormatter(c_format)
f_handler.setFormatter(f_format)
# Add handlers to the logger
logger.addHandler(c_handler)
logger.addHandler(f_handler)
# TODO: Implement class method to validate URL, see:
# https://stackoverflow.com/questions/25200763/how-to-return-none-if-constructor-arguments-invalid
def get_source(apartment) -> BeautifulSoup:
"""Function to getting the source from a url.
Args:
apartment (Apartment): The object to process.
Returns:
BeautifulSoup: Soup of the source.
"""
try:
r = requests.get(apartment.url)
# Todo, check for http-status?
print(f"Fetching source: {apartment.url}")
return r.content
except requests.exceptions.ConnectionError:
logger.error("Connection refused by target server.")
except Exception as e:
logger.error(f"Couldn't not find source {e}"
f"soup for object {apartment.url}.")
return None
def get_div(soup, html_type, class_name: str):
"""Function to scrape the two facts divs from a soup.
Args:
soup (Beautifulsoup): A soup where to find a pattern.
regex (str): A regex string to use.
Returns:
soup: If found, returns a soup for the div with the wanted class.
"""
try:
div = soup.find(html_type, class_name)
if div:
return div
else:
logger.info(f"No tag with type '{html_type}' and "
f"attribute '{class_name}' found!")
return None
except Exception:
logger.error(f"No soup found to parse for a '{html_type}' "
f"with attribute '{class_name}'")
return None
def get_value_with_regex(div: str, regex: str) -> str:
"""Get a value from a str that matches a specific regex.
Args:
div (str): A stringified div to search.
regex (str): A regex expression.
Returns:
str: A value matching the pattern from the regex.
"""
if div is None:
return None
try:
# Try to find the regex as provided and return
# the value, else return N/A
value = re.search(regex, div).group()
# Only return numeric values, i.e. strip any €, m² and similar.
return float(re.sub("[^0-9,]", "", value).replace(",", "."))
except AttributeError as e:
# This error will occur if no expression is found. re.search
# will return None which does not have the attribute 'group'
logger.info(f"{e} - No substring found")
return None
except Exception as e:
logger.error(f"{e} ({regex}) in:\n{div}\n")
return None
def stringify_div(div):
if div is not None:
return re.sub("[\s.]", "", str(div).lower())
else:
return None
def get_location(div):
if div is None:
return 0, None
location_list = div.text.split()
return location_list[0][1:3], location_list[1]
class Apartment:
def __init__(self, url: str):
self.url = url
# If the current url is not available anymore, a message is given
# in a div. I.e. if this div is on the page, the object is no
# longer available on the site. Setting internal values to None
# makes all other values to default to N/A.
# TODO: Remove this instance from the apartmentlist
def fetch_data(self):
"""Function to fetch the data and specific divs
Typically 0.3 - 0.4 seconds (IO Bound)
"""
self.source = get_source(self)
def parse_data(self):
"""Function to parse the data using Beautifulsoups HTML-parser
and finding specific divs.
Typical time consumption: 0.36-0.4 seconds (CPU bound)
"""
try:
self.soup = BeautifulSoup(self.source, features="html.parser")
except Exception:
self.soup = None
self.quickfacts = get_div(self.soup, "div", "quickfacts iw_left")
self.hardfacts = get_div(self.soup, "div", "hardfacts clear")
def process_data(self):
"""Processing the soups and finding specific expressions using regex.
Note: Timing is excluding the parse_data() call at the start
of the function.
Typical time consumption: 200-300µs (CPU Bound)
"""
self.parse_data()
hardfacts = stringify_div(self.hardfacts)
self.rent = get_value_with_regex(div=hardfacts, regex="[0-9,]+€")
self.area = get_value_with_regex(div=hardfacts, regex="([0-9,]+)m")
self.rooms = get_value_with_regex(div=hardfacts, regex=">([0-9])<")
quickfacts = get_div(self.quickfacts, "span", "no_s")
self.bezirk, self.city = get_location(quickfacts)
self.bezirk = int(self.bezirk)
def fetch(apartment):
apartment.fetch_data()
def process(apartment):
apartment.process_data()
return (apartment.rent, apartment.area, apartment.rooms,
apartment.bezirk, apartment.city)
# ~264s with threading with 10 workers without ProcessPool
# ~268s with threading with 15 workers without ProcessPool
# with 2 workers with ProcessPool with 16 workers. ~650 items
# Time for fetching data: 119.40933409999707
# Time for processing: 25.59249959999579
# Time for saving data: 1.2901472999947146
# Time since start: 146.30282830000215
#with 2 workers with ProcessPool with 16 workers. ~6998 items
# Time for fetching data: 1969.1336764000007
# Time for processing: 266.7142402999889
# Time for saving data: 16.85627160000149
# Time since start: 2252.713053300002
def main(file):
start_main = perf_counter()
with open(file) as f:
apartment_list = [
Apartment(apartment)
for apartment
in f.read().split("\n")[:-1]
]
data = pd.DataFrame(
columns=["rent", "area", "rooms", "bezirk_no", "city", "url"]
)
print("Started fetching".center(50, "="))
start_fetching = perf_counter()
# Using threading with IO Bound fetching of data.
# High amount of workers lead to that Connections are refused.
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.map(fetch, apartment_list)
end_fetching = perf_counter()
print("Started processing".center(50, "="))
start_processing = perf_counter()
# Using multiprocessing for CPU Bound Parsing and regex pattern finding.
with concurrent.futures.ProcessPoolExecutor(max_workers=16) as executor:
results = executor.map(process, apartment_list)
end_processing = perf_counter()
start_save = perf_counter()
for result, apartment in zip(results, apartment_list):
apartment.rent = result[0]
apartment.area = result[1]
apartment.rooms = result[2]
apartment.bezirk = result[3]
apartment.city = result[4]
for idx, apartment in enumerate(apartment_list):
data.loc[idx] = (
apartment.rent,
apartment.area,
apartment.rooms,
apartment.bezirk,
apartment.city,
apartment.url
)
data.to_csv("apartments.csv", decimal=".")
end_saving = perf_counter()
print(f"Time for fetching data: {end_fetching - start_fetching}")
print(f"Time for processing: {end_processing - start_processing}")
print(f"Time for saving data: {end_saving - start_save}")
print(f"Time since start: {perf_counter() - start_main}")
FILE = "apartments.txt"
if __name__ == "__main__":
main(FILE)
|
en
| 0.76775
|
# Logging: https://docs.python.org/3/howto/logging-cookbook.html # Create handlers # Create formatters and add it to handlers # Add handlers to the logger # TODO: Implement class method to validate URL, see: # https://stackoverflow.com/questions/25200763/how-to-return-none-if-constructor-arguments-invalid Function to getting the source from a url. Args: apartment (Apartment): The object to process. Returns: BeautifulSoup: Soup of the source. # Todo, check for http-status? Function to scrape the two facts divs from a soup. Args: soup (Beautifulsoup): A soup where to find a pattern. regex (str): A regex string to use. Returns: soup: If found, returns a soup for the div with the wanted class. Get a value from a str that matches a specific regex. Args: div (str): A stringified div to search. regex (str): A regex expression. Returns: str: A value matching the pattern from the regex. # Try to find the regex as provided and return # the value, else return N/A # Only return numeric values, i.e. strip any €, m² and similar. # This error will occur if no expression is found. re.search # will return None which does not have the attribute 'group' # If the current url is not available anymore, a message is given # in a div. I.e. if this div is on the page, the object is no # longer available on the site. Setting internal values to None # makes all other values to default to N/A. # TODO: Remove this instance from the apartmentlist Function to fetch the data and specific divs Typically 0.3 - 0.4 seconds (IO Bound) Function to parse the data using Beautifulsoups HTML-parser and finding specific divs. Typical time consumption: 0.36-0.4 seconds (CPU bound) Processing the soups and finding specific expressions using regex. Note: Timing is excluding the parse_data() call at the start of the function. Typical time consumption: 200-300µs (CPU Bound) # ~264s with threading with 10 workers without ProcessPool # ~268s with threading with 15 workers without ProcessPool # with 2 workers with ProcessPool with 16 workers. ~650 items # Time for fetching data: 119.40933409999707 # Time for processing: 25.59249959999579 # Time for saving data: 1.2901472999947146 # Time since start: 146.30282830000215 #with 2 workers with ProcessPool with 16 workers. ~6998 items # Time for fetching data: 1969.1336764000007 # Time for processing: 266.7142402999889 # Time for saving data: 16.85627160000149 # Time since start: 2252.713053300002 # Using threading with IO Bound fetching of data. # High amount of workers lead to that Connections are refused. # Using multiprocessing for CPU Bound Parsing and regex pattern finding.
| 2.703047
| 3
|
config.py
|
foongsy/mickey
| 0
|
6626268
|
<reponame>foongsy/mickey
DATABASE = 'sqlite:///master.db'
DEBUG = True
|
DATABASE = 'sqlite:///master.db'
DEBUG = True
|
none
| 1
| 1.105249
| 1
|
|
Solutions/Python/Is it a vowel on this position(7 kyu).py
|
collenirwin/Codewars-Solutions
| 0
|
6626269
|
<filename>Solutions/Python/Is it a vowel on this position(7 kyu).py
def check_vowel(string, position):
return string.lower()[position] in "aeiou" if position > -1 and position < len(string) else False
|
<filename>Solutions/Python/Is it a vowel on this position(7 kyu).py
def check_vowel(string, position):
return string.lower()[position] in "aeiou" if position > -1 and position < len(string) else False
|
none
| 1
| 3.757381
| 4
|
|
Easy/Birthday Cake Candles.py
|
drkndl/Coding-Practice
| 0
|
6626270
|
<reponame>drkndl/Coding-Practice
import math
import os
import random
import re
import sys
# Complete the birthdayCakeCandles function below.
def birthdayCakeCandles(ar):
maxi=0
count=0
for item in range(len(ar)):
if ar[item]>=maxi:
maxi=ar[item]
for item in range(len(ar)):
if ar[item]==maxi:
count=count+1
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
ar_count = int(input())
ar = list(map(int, input().rstrip().split()))
result = birthdayCakeCandles(ar)
fptr.write(str(result) + '\n')
fptr.close()
|
import math
import os
import random
import re
import sys
# Complete the birthdayCakeCandles function below.
def birthdayCakeCandles(ar):
maxi=0
count=0
for item in range(len(ar)):
if ar[item]>=maxi:
maxi=ar[item]
for item in range(len(ar)):
if ar[item]==maxi:
count=count+1
return count
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
ar_count = int(input())
ar = list(map(int, input().rstrip().split()))
result = birthdayCakeCandles(ar)
fptr.write(str(result) + '\n')
fptr.close()
|
en
| 0.406087
|
# Complete the birthdayCakeCandles function below.
| 3.392748
| 3
|
python/deepercluster/src/clustering.py
|
GG-yuki/bugs
| 0
|
6626271
|
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from logging import getLogger
import os
import pickle
import faiss
import torch
import torch.distributed as dist
from torch.utils.data.sampler import Sampler
import numpy as np
from .utils import PCA, AverageMeter, normalize, get_indices_sparse
from .distributed_kmeans import distributed_kmeans, initialize_cache
logger = getLogger()
def get_cluster_assignments(args, model, dataset, groups):
"""
"""
# pseudo-labels are confusing
dataset.sub_classes = None
# swith to eval mode
model.eval()
# this process deals only with a subset of the dataset
local_nmb_data = len(dataset) // args.world_size
indices = torch.arange(args.rank * local_nmb_data, (args.rank + 1) * local_nmb_data).int()
if os.path.isfile(os.path.join(args.dump_path, 'super_class_assignments.pkl')):
# super-class assignments have already been computed in a previous run
super_class_assignements = pickle.load(open(os.path.join(args.dump_path, 'super_class_assignments.pkl'), 'rb'))
logger.info('loaded super-class assignments')
# dump cache
where_helper = get_indices_sparse(super_class_assignements[indices])
nmb_data_per_super_cluster = torch.zeros(args.nmb_super_clusters).cuda()
for super_class in range(len(where_helper)):
nmb_data_per_super_cluster[super_class] = len(where_helper[super_class][0])
else:
sampler = Subset_Sampler(indices)
# we need a data loader
loader = torch.utils.data.DataLoader(
dataset,
batch_size=args.batch_size,
sampler=sampler,
num_workers=args.workers,
pin_memory=True,
)
# initialize cache, pca and centroids
cache, centroids = initialize_cache(args, loader, model)
# empty cuda cache (useful because we're about to use faiss on gpu)
torch.cuda.empty_cache()
## perform clustering into super_clusters
super_class_assignements, centroids_sc = distributed_kmeans(
args,
args.size_dataset,
args.nmb_super_clusters,
cache,
args.rank,
args.world_size,
centroids,
)
# dump activations in the cache
where_helper = get_indices_sparse(super_class_assignements[indices])
nmb_data_per_super_cluster = torch.zeros(args.nmb_super_clusters).cuda()
for super_class in range(len(where_helper)):
ind_sc = where_helper[super_class][0]
np.save(open(os.path.join(
args.dump_path,
'cache/',
'super_class' + str(super_class) + '-' + str(args.rank),
), 'wb'), cache[ind_sc])
nmb_data_per_super_cluster[super_class] = len(ind_sc)
dist.barrier()
# dump super_class assignment and centroids of super_class
if not args.rank:
pickle.dump(
super_class_assignements,
open(os.path.join(args.dump_path, 'super_class_assignments.pkl'), 'wb'),
)
pickle.dump(
centroids_sc,
open(os.path.join(args.dump_path, 'super_class_centroids.pkl'), 'wb'),
)
# size of the different super clusters
all_counts = [torch.zeros(args.nmb_super_clusters).cuda() for _ in range(args.world_size)]
dist.all_gather(all_counts, nmb_data_per_super_cluster)
all_counts = torch.cat(all_counts).cpu().long()
all_counts = all_counts.reshape(args.world_size, args.nmb_super_clusters)
logger.info(all_counts.sum(dim=0))
# what are the data belonging to this super class
dataset.subset_indexes = np.where(super_class_assignements == args.clustering_local_world_id)[0]
div = args.batch_size * args.clustering_local_world_size
dataset.subset_indexes = dataset.subset_indexes[:len(dataset) // div * div]
dist.barrier()
# which files this process is going to read
local_nmb_data = int(len(dataset) / args.clustering_local_world_size)
low = np.long(args.clustering_local_rank * local_nmb_data)
high = np.long(low + local_nmb_data)
curr_ind = 0
cache = torch.zeros(local_nmb_data, args.dim_pca, dtype=torch.float32)
cumsum = torch.cumsum(all_counts[:, args.clustering_local_world_id].long(), 0).long()
for r in range(args.world_size):
# data in this bucket r: [cumsum[r - 1] : cumsum[r] - 1]
low_bucket = np.long(cumsum[r - 1]) if r else 0
# this bucket is empty
if low_bucket > cumsum[r] - 1:
continue
if cumsum[r] - 1 < low:
continue
if low_bucket >= high:
break
# which are the data we are interested in inside this bucket ?
ind_low = np.long(max(low, low_bucket))
ind_high = np.long(min(high, cumsum[r]))
cache_r = np.load(open(os.path.join(args.dump_path, 'cache/', 'super_class' + str(args.clustering_local_world_id) + '-' + str(r)), 'rb'))
cache[curr_ind: curr_ind + ind_high - ind_low] = torch.FloatTensor(cache_r[ind_low - low_bucket: ind_high - low_bucket])
curr_ind += (ind_high - ind_low)
# randomly pick some centroids and dump them
centroids_path = os.path.join(args.dump_path, 'centroids' + str(args.clustering_local_world_id) + '.pkl')
if not args.clustering_local_rank:
centroids = cache[np.random.choice(
np.arange(cache.shape[0]),
replace=cache.shape[0] < args.k // args.nmb_super_clusters,
size=args.k // args.nmb_super_clusters,
)]
pickle.dump(centroids, open(centroids_path, 'wb'), -1)
dist.barrier()
# read centroids
centroids = pickle.load(open(centroids_path, 'rb')).cuda()
# distributed kmeans into sub-classes
cluster_assignments, centroids = distributed_kmeans(
args,
len(dataset),
args.k // args.nmb_super_clusters,
cache,
args.clustering_local_rank,
args.clustering_local_world_size,
centroids,
world_id=args.clustering_local_world_id,
group=groups[args.clustering_local_world_id],
)
# free RAM
del cache
# write cluster assignments and centroids
if not args.clustering_local_rank:
pickle.dump(
cluster_assignments,
open(os.path.join(args.dump_path, 'cluster_assignments' + str(args.clustering_local_world_id) + '.pkl'), 'wb'),
)
pickle.dump(
centroids,
open(centroids_path, 'wb'),
)
dist.barrier()
return cluster_assignments
class Subset_Sampler(Sampler):
"""
Sample indices.
"""
def __init__(self, indices):
self.indices = indices
def __iter__(self):
return iter(self.indices)
def __len__(self):
return len(self.indices)
def load_cluster_assignments(args, dataset):
"""
Load cluster assignments if they are present in experiment repository.
"""
super_file = os.path.join(args.dump_path, 'super_class_assignments.pkl')
sub_file = os.path.join(
args.dump_path,
'sub_class_assignments' + str(args.clustering_local_world_id) + '.pkl',
)
if os.path.isfile(super_file) and os.path.isfile(sub_file):
super_class_assignments = pickle.load(open(super_file, 'rb'))
dataset.subset_indexes = np.where(super_class_assignments == args.clustering_local_world_id)[0]
div = args.batch_size * args.clustering_local_world_size
clustering_size_dataset = len(dataset) // div * div
dataset.subset_indexes = dataset.subset_indexes[:clustering_size_dataset]
logger.info('Found cluster assignments in experiment repository')
return pickle.load(open(sub_file, "rb"))
return None
|
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from logging import getLogger
import os
import pickle
import faiss
import torch
import torch.distributed as dist
from torch.utils.data.sampler import Sampler
import numpy as np
from .utils import PCA, AverageMeter, normalize, get_indices_sparse
from .distributed_kmeans import distributed_kmeans, initialize_cache
logger = getLogger()
def get_cluster_assignments(args, model, dataset, groups):
"""
"""
# pseudo-labels are confusing
dataset.sub_classes = None
# swith to eval mode
model.eval()
# this process deals only with a subset of the dataset
local_nmb_data = len(dataset) // args.world_size
indices = torch.arange(args.rank * local_nmb_data, (args.rank + 1) * local_nmb_data).int()
if os.path.isfile(os.path.join(args.dump_path, 'super_class_assignments.pkl')):
# super-class assignments have already been computed in a previous run
super_class_assignements = pickle.load(open(os.path.join(args.dump_path, 'super_class_assignments.pkl'), 'rb'))
logger.info('loaded super-class assignments')
# dump cache
where_helper = get_indices_sparse(super_class_assignements[indices])
nmb_data_per_super_cluster = torch.zeros(args.nmb_super_clusters).cuda()
for super_class in range(len(where_helper)):
nmb_data_per_super_cluster[super_class] = len(where_helper[super_class][0])
else:
sampler = Subset_Sampler(indices)
# we need a data loader
loader = torch.utils.data.DataLoader(
dataset,
batch_size=args.batch_size,
sampler=sampler,
num_workers=args.workers,
pin_memory=True,
)
# initialize cache, pca and centroids
cache, centroids = initialize_cache(args, loader, model)
# empty cuda cache (useful because we're about to use faiss on gpu)
torch.cuda.empty_cache()
## perform clustering into super_clusters
super_class_assignements, centroids_sc = distributed_kmeans(
args,
args.size_dataset,
args.nmb_super_clusters,
cache,
args.rank,
args.world_size,
centroids,
)
# dump activations in the cache
where_helper = get_indices_sparse(super_class_assignements[indices])
nmb_data_per_super_cluster = torch.zeros(args.nmb_super_clusters).cuda()
for super_class in range(len(where_helper)):
ind_sc = where_helper[super_class][0]
np.save(open(os.path.join(
args.dump_path,
'cache/',
'super_class' + str(super_class) + '-' + str(args.rank),
), 'wb'), cache[ind_sc])
nmb_data_per_super_cluster[super_class] = len(ind_sc)
dist.barrier()
# dump super_class assignment and centroids of super_class
if not args.rank:
pickle.dump(
super_class_assignements,
open(os.path.join(args.dump_path, 'super_class_assignments.pkl'), 'wb'),
)
pickle.dump(
centroids_sc,
open(os.path.join(args.dump_path, 'super_class_centroids.pkl'), 'wb'),
)
# size of the different super clusters
all_counts = [torch.zeros(args.nmb_super_clusters).cuda() for _ in range(args.world_size)]
dist.all_gather(all_counts, nmb_data_per_super_cluster)
all_counts = torch.cat(all_counts).cpu().long()
all_counts = all_counts.reshape(args.world_size, args.nmb_super_clusters)
logger.info(all_counts.sum(dim=0))
# what are the data belonging to this super class
dataset.subset_indexes = np.where(super_class_assignements == args.clustering_local_world_id)[0]
div = args.batch_size * args.clustering_local_world_size
dataset.subset_indexes = dataset.subset_indexes[:len(dataset) // div * div]
dist.barrier()
# which files this process is going to read
local_nmb_data = int(len(dataset) / args.clustering_local_world_size)
low = np.long(args.clustering_local_rank * local_nmb_data)
high = np.long(low + local_nmb_data)
curr_ind = 0
cache = torch.zeros(local_nmb_data, args.dim_pca, dtype=torch.float32)
cumsum = torch.cumsum(all_counts[:, args.clustering_local_world_id].long(), 0).long()
for r in range(args.world_size):
# data in this bucket r: [cumsum[r - 1] : cumsum[r] - 1]
low_bucket = np.long(cumsum[r - 1]) if r else 0
# this bucket is empty
if low_bucket > cumsum[r] - 1:
continue
if cumsum[r] - 1 < low:
continue
if low_bucket >= high:
break
# which are the data we are interested in inside this bucket ?
ind_low = np.long(max(low, low_bucket))
ind_high = np.long(min(high, cumsum[r]))
cache_r = np.load(open(os.path.join(args.dump_path, 'cache/', 'super_class' + str(args.clustering_local_world_id) + '-' + str(r)), 'rb'))
cache[curr_ind: curr_ind + ind_high - ind_low] = torch.FloatTensor(cache_r[ind_low - low_bucket: ind_high - low_bucket])
curr_ind += (ind_high - ind_low)
# randomly pick some centroids and dump them
centroids_path = os.path.join(args.dump_path, 'centroids' + str(args.clustering_local_world_id) + '.pkl')
if not args.clustering_local_rank:
centroids = cache[np.random.choice(
np.arange(cache.shape[0]),
replace=cache.shape[0] < args.k // args.nmb_super_clusters,
size=args.k // args.nmb_super_clusters,
)]
pickle.dump(centroids, open(centroids_path, 'wb'), -1)
dist.barrier()
# read centroids
centroids = pickle.load(open(centroids_path, 'rb')).cuda()
# distributed kmeans into sub-classes
cluster_assignments, centroids = distributed_kmeans(
args,
len(dataset),
args.k // args.nmb_super_clusters,
cache,
args.clustering_local_rank,
args.clustering_local_world_size,
centroids,
world_id=args.clustering_local_world_id,
group=groups[args.clustering_local_world_id],
)
# free RAM
del cache
# write cluster assignments and centroids
if not args.clustering_local_rank:
pickle.dump(
cluster_assignments,
open(os.path.join(args.dump_path, 'cluster_assignments' + str(args.clustering_local_world_id) + '.pkl'), 'wb'),
)
pickle.dump(
centroids,
open(centroids_path, 'wb'),
)
dist.barrier()
return cluster_assignments
class Subset_Sampler(Sampler):
"""
Sample indices.
"""
def __init__(self, indices):
self.indices = indices
def __iter__(self):
return iter(self.indices)
def __len__(self):
return len(self.indices)
def load_cluster_assignments(args, dataset):
"""
Load cluster assignments if they are present in experiment repository.
"""
super_file = os.path.join(args.dump_path, 'super_class_assignments.pkl')
sub_file = os.path.join(
args.dump_path,
'sub_class_assignments' + str(args.clustering_local_world_id) + '.pkl',
)
if os.path.isfile(super_file) and os.path.isfile(sub_file):
super_class_assignments = pickle.load(open(super_file, 'rb'))
dataset.subset_indexes = np.where(super_class_assignments == args.clustering_local_world_id)[0]
div = args.batch_size * args.clustering_local_world_size
clustering_size_dataset = len(dataset) // div * div
dataset.subset_indexes = dataset.subset_indexes[:clustering_size_dataset]
logger.info('Found cluster assignments in experiment repository')
return pickle.load(open(sub_file, "rb"))
return None
|
en
| 0.894363
|
# Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # # pseudo-labels are confusing # swith to eval mode # this process deals only with a subset of the dataset # super-class assignments have already been computed in a previous run # dump cache # we need a data loader # initialize cache, pca and centroids # empty cuda cache (useful because we're about to use faiss on gpu) ## perform clustering into super_clusters # dump activations in the cache # dump super_class assignment and centroids of super_class # size of the different super clusters # what are the data belonging to this super class # which files this process is going to read # data in this bucket r: [cumsum[r - 1] : cumsum[r] - 1] # this bucket is empty # which are the data we are interested in inside this bucket ? # randomly pick some centroids and dump them # read centroids # distributed kmeans into sub-classes # free RAM # write cluster assignments and centroids Sample indices. Load cluster assignments if they are present in experiment repository.
| 1.821233
| 2
|
tensorflow/python/kernel_tests/conditional_accumulator_test.py
|
yanzhiwei1990/tensorflow
| 1
|
6626272
|
<gh_stars>1-10
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes as dtypes_lib
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
# from functools import reduce
class ConditionalAccumulatorTest(test.TestCase):
def testConstructor(self):
with ops.Graph().as_default():
q = data_flow_ops.ConditionalAccumulator(dtypes_lib.float32, name="Q")
self.assertTrue(isinstance(q.accumulator_ref, ops.Tensor))
self.assertProtoEquals(
"""
name:'Q' op:'ConditionalAccumulator'
attr { key: 'dtype' value { type: DT_FLOAT } }
attr { key: 'shape' value { shape { unknown_rank: true} } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: '' } }
attr { key: 'reduction_type' value {s: 'MEAN'} }
""", q.accumulator_ref.op.node_def)
def testConstructorWithInvalidArg(self):
with ops.Graph().as_default():
with self.assertRaises(ValueError):
data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", reduction_type="Invalid")
def testConstructorWithShape(self):
with ops.Graph().as_default():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1, 5, 2, 8]))
self.assertTrue(isinstance(q.accumulator_ref, ops.Tensor))
self.assertProtoEquals(
"""
name:'Q' op:'ConditionalAccumulator'
attr { key: 'dtype' value { type: DT_FLOAT } }
attr { key: 'shape' value { shape { dim {size: 1 }
dim {size: 5 }
dim {size: 2 }
dim {size: 8 }
} } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: '' } }
attr { key: 'reduction_type' value {s: 'MEAN'} }
""", q.accumulator_ref.op.node_def)
def testAccumulatorSizeEmpty(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(dtypes_lib.float32, name="Q")
self.assertEqual(q.num_accumulated().eval(), 0)
def testAccumulatorSetGlobalStep(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
set_global_step_op = q.set_global_step(1)
set_global_step_op.run()
def testAccumulatorApplyGradFloat32(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
accum_op = q.apply_grad((10.0,))
accum_op.run()
def testDtypes(self):
with self.test_session() as sess:
dtypes = [dtypes_lib.float16, dtypes_lib.float32, dtypes_lib.float64]
for i in range(len(dtypes)):
dtype = dtypes[i]
q = data_flow_ops.ConditionalAccumulator(
dtype, shape=tensor_shape.TensorShape([1]))
elems = np.arange(10).astype(dtype.as_numpy_dtype)
for e in elems:
q.apply_grad((e,)).run()
result = sess.run(q.take_grad(1))
self.assertEqual(sum(elems) / len(elems), result)
def testAccumulatorMultipleAccumulators(self):
with self.test_session():
q_f32_0 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
q_f32_1 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
q_f16_0 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float16, name="Q", shape=tensor_shape.TensorShape([1]))
q_f16_1 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float16, name="Q", shape=tensor_shape.TensorShape([1]))
accums = [q_f16_0, q_f16_1, q_f32_0, q_f32_1]
for i in range(len(accums)):
accums[i].apply_grad((i + 10.0,)).run()
for i in range(len(accums)):
result = accums[i].take_grad(1).eval()
self.assertEqual(result, i + 10.0)
def testAccumulatorApplyAndTakeGradWithShape(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=(3, 2))
elems = [[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
[[10.0, 20.0], [30.0, 40.0], [50.0, 60.0]]]
elems_ave = [[(a + b) / len(elems) for a, b in zip(x, y)]
for x, y in zip(elems[0], elems[1])]
accum_ops = [q.apply_grad(x) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
is_all_equal = True
val = takeg_t.eval()
for i in range(len(val)):
for j in range(len(val[i])):
is_all_equal &= (val[i][j] == elems_ave[i][j])
self.assertTrue(is_all_equal)
def testAccumulatorApplyGradWithWrongShape(self):
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=(3, 2))
with self.assertRaises(ValueError):
q.apply_grad([[1.0, 2.0], [3.0, 4.0]])
with self.assertRaises(ValueError):
q.apply_grad([[1.0], [2.0], [3.0]])
def testAccumulatorDynamicShape(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=None)
x = array_ops.placeholder(dtypes_lib.float32)
accum_op = q.apply_grad(x)
elems = [[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
[[10.0, 20.0], [30.0, 40.0], [50.0, 60.0]]]
elems_ave = [[(a + b) / len(elems) for a, b in zip(c, d)]
for c, d in zip(elems[0], elems[1])]
takeg_t = q.take_grad(1)
for elem in elems:
sess.run(accum_op, feed_dict={x: elem})
is_all_equal = True
val = takeg_t.eval()
for i in range(len(val)):
for j in range(len(val[i])):
is_all_equal &= (val[i][j] == elems_ave[i][j])
self.assertTrue(is_all_equal)
def testAccumulatorWrongDynamicShape(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=None)
x = array_ops.placeholder(dtypes_lib.float32)
accum_op = q.apply_grad(x)
# First successful apply_grad determines shape
sess.run(accum_op, feed_dict={x: [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]})
with self.assertRaises(errors_impl.InvalidArgumentError):
sess.run(accum_op, feed_dict={x: [[1.0, 2.0], [3.0, 4.0]]})
with self.assertRaises(errors_impl.InvalidArgumentError):
sess.run(accum_op, feed_dict={x: [[1.0], [2.0], [3.0]]})
def testAccumulatorSizeAfterApplyGrad(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
accum_op = q.apply_grad((10.0,))
self.assertEqual(q.num_accumulated().eval(), 0)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 1)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 2)
def testAccumulatorSizeAfterApplyGradAndTakeGrad(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
accum_op = q.apply_grad((10.0,))
extract_t = q.take_grad(2)
# Applying gradient multiple times to increase size from 0 to 2.
self.assertEqual(q.num_accumulated().eval(), 0)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 1)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 2)
# Extract will reduce size to 0
extract_t.op.run()
self.assertEqual(q.num_accumulated().eval(), 0)
# Take gradients always sets the size back to 0 if successful.
accum_op = q.apply_grad((10.0,), local_step=1)
accum_op.run()
accum_op.run()
accum_op.run()
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 4)
extract_t.op.run()
self.assertEqual(q.num_accumulated().eval(), 0)
def testAccumulatorTakeGradMean(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0]
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(15.0, val)
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(constant_op.constant(1))
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(15.0, val)
def testAccumulatorTakeGradSum(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1]),
reduction_type="SUM")
elems = [10.0, 20.0]
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(30.0, val)
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(constant_op.constant(1))
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(30.0, val)
def testAccumulatorTakeGradInvalidReductionType(self):
with self.assertRaises(ValueError):
data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1]),
reduction_type="Invalid")
def testAccumulatorInvalidTakeGrad(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0]
accum_ops = [q.apply_grad((x,)) for x in elems]
takeg_t = q.take_grad(-1)
for accum_op in accum_ops:
accum_op.run()
with self.assertRaises(errors_impl.InvalidArgumentError):
takeg_t.eval()
def testAccumulatorRepeatedTakeGradMean(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0]
elems_ave = sum(elems) / len(elems)
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(elems_ave, val)
elems = [20.0, 30.0]
elems_ave = sum(elems) / len(elems)
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(elems_ave + 0.0, val)
def testAccumulatorRepeatedTakeGradSum(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1]),
reduction_type="SUM")
elems = [10.0, 20.0]
elems_sum = 30.0
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(elems_sum, val)
elems = [20.0, 30.0]
elems_sum = 50.0
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(elems_sum, val)
def testAccumulatorIncrementGlobalStep(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
global_step = variables.Variable(0, name="global_step")
new_global_step = math_ops.add(global_step, 1)
inc_global_step = state_ops.assign(global_step, new_global_step)
set_global_step_op = q.set_global_step(new_global_step)
variables.global_variables_initializer().run()
for _ in range(3):
set_global_step_op.run()
inc_global_step.eval()
def testAccumulatorSetGlobalStepPreventsAccumulation(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
local_steps = range(1000, 1005)
accum_ops = [q.apply_grad((0.0 + x,), local_step=x) for x in local_steps]
for ls in local_steps:
set_global_step_op = q.set_global_step(ls)
set_global_step_op.run()
for accum_op in accum_ops:
accum_op.run()
takeg_t = q.take_grad(1)
val = takeg_t.eval()
self.assertEqual(0.0 + sum(x for x in local_steps
if x >= ls) / sum(1 for x in local_steps
if x >= ls), val)
def testParallelApplyGrad(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
def apply_grad(accum_op):
sess.run(accum_op)
threads = [
self.checkedThread(
target=apply_grad, args=(o,)) for o in accum_ops
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
val = takeg_t.eval()
self.assertEqual(val, sum(elems) / len(elems))
def testParallelTakeGrad(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [e for e in range(10)]
accum_ops = [q.apply_grad((np.float32(e),), local_step=e) for e in elems]
takeg_t = q.take_grad(1)
def apply_grad():
for accum_op in accum_ops:
time.sleep(1.0)
sess.run(accum_op)
apply_grad_thread = self.checkedThread(target=apply_grad)
results = []
def take_grad():
results.append(sess.run(takeg_t))
threads = [self.checkedThread(target=take_grad) for _ in range(10)]
for thread in threads:
thread.start()
apply_grad_thread.start()
for thread in threads:
thread.join()
apply_grad_thread.join()
self.assertItemsEqual(elems, results)
def testAccumulatorApplyAndBlockingTake(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0, 30.0]
elems_ave = sum(elems) / len(elems)
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(3)
def apply_grad():
time.sleep(1.0)
for accum_op in accum_ops:
sess.run(accum_op)
return_array = []
def take_grad():
return_array.append(sess.run(takeg_t))
accum_thread = self.checkedThread(target=apply_grad)
takeg_thread = self.checkedThread(target=take_grad)
accum_thread.start()
takeg_thread.start()
accum_thread.join()
takeg_thread.join()
self.assertEqual([elems_ave], return_array)
def _blocking_takeg(self, sess, takeg_op):
with self.assertRaisesOpError("was cancelled"):
sess.run(takeg_op)
def testAccumulatorCancel(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
takeg_t = q.take_grad(1)
takeg_thread = self.checkedThread(
self._blocking_takeg, args=(sess, takeg_t))
takeg_thread.start()
time.sleep(1.0)
sess.close() # Will cancel blocked operation
takeg_thread.join()
if __name__ == "__main__":
test.main()
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes as dtypes_lib
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
# from functools import reduce
class ConditionalAccumulatorTest(test.TestCase):
def testConstructor(self):
with ops.Graph().as_default():
q = data_flow_ops.ConditionalAccumulator(dtypes_lib.float32, name="Q")
self.assertTrue(isinstance(q.accumulator_ref, ops.Tensor))
self.assertProtoEquals(
"""
name:'Q' op:'ConditionalAccumulator'
attr { key: 'dtype' value { type: DT_FLOAT } }
attr { key: 'shape' value { shape { unknown_rank: true} } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: '' } }
attr { key: 'reduction_type' value {s: 'MEAN'} }
""", q.accumulator_ref.op.node_def)
def testConstructorWithInvalidArg(self):
with ops.Graph().as_default():
with self.assertRaises(ValueError):
data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", reduction_type="Invalid")
def testConstructorWithShape(self):
with ops.Graph().as_default():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1, 5, 2, 8]))
self.assertTrue(isinstance(q.accumulator_ref, ops.Tensor))
self.assertProtoEquals(
"""
name:'Q' op:'ConditionalAccumulator'
attr { key: 'dtype' value { type: DT_FLOAT } }
attr { key: 'shape' value { shape { dim {size: 1 }
dim {size: 5 }
dim {size: 2 }
dim {size: 8 }
} } }
attr { key: 'container' value { s: '' } }
attr { key: 'shared_name' value { s: '' } }
attr { key: 'reduction_type' value {s: 'MEAN'} }
""", q.accumulator_ref.op.node_def)
def testAccumulatorSizeEmpty(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(dtypes_lib.float32, name="Q")
self.assertEqual(q.num_accumulated().eval(), 0)
def testAccumulatorSetGlobalStep(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
set_global_step_op = q.set_global_step(1)
set_global_step_op.run()
def testAccumulatorApplyGradFloat32(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
accum_op = q.apply_grad((10.0,))
accum_op.run()
def testDtypes(self):
with self.test_session() as sess:
dtypes = [dtypes_lib.float16, dtypes_lib.float32, dtypes_lib.float64]
for i in range(len(dtypes)):
dtype = dtypes[i]
q = data_flow_ops.ConditionalAccumulator(
dtype, shape=tensor_shape.TensorShape([1]))
elems = np.arange(10).astype(dtype.as_numpy_dtype)
for e in elems:
q.apply_grad((e,)).run()
result = sess.run(q.take_grad(1))
self.assertEqual(sum(elems) / len(elems), result)
def testAccumulatorMultipleAccumulators(self):
with self.test_session():
q_f32_0 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
q_f32_1 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
q_f16_0 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float16, name="Q", shape=tensor_shape.TensorShape([1]))
q_f16_1 = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float16, name="Q", shape=tensor_shape.TensorShape([1]))
accums = [q_f16_0, q_f16_1, q_f32_0, q_f32_1]
for i in range(len(accums)):
accums[i].apply_grad((i + 10.0,)).run()
for i in range(len(accums)):
result = accums[i].take_grad(1).eval()
self.assertEqual(result, i + 10.0)
def testAccumulatorApplyAndTakeGradWithShape(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=(3, 2))
elems = [[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
[[10.0, 20.0], [30.0, 40.0], [50.0, 60.0]]]
elems_ave = [[(a + b) / len(elems) for a, b in zip(x, y)]
for x, y in zip(elems[0], elems[1])]
accum_ops = [q.apply_grad(x) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
is_all_equal = True
val = takeg_t.eval()
for i in range(len(val)):
for j in range(len(val[i])):
is_all_equal &= (val[i][j] == elems_ave[i][j])
self.assertTrue(is_all_equal)
def testAccumulatorApplyGradWithWrongShape(self):
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=(3, 2))
with self.assertRaises(ValueError):
q.apply_grad([[1.0, 2.0], [3.0, 4.0]])
with self.assertRaises(ValueError):
q.apply_grad([[1.0], [2.0], [3.0]])
def testAccumulatorDynamicShape(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=None)
x = array_ops.placeholder(dtypes_lib.float32)
accum_op = q.apply_grad(x)
elems = [[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],
[[10.0, 20.0], [30.0, 40.0], [50.0, 60.0]]]
elems_ave = [[(a + b) / len(elems) for a, b in zip(c, d)]
for c, d in zip(elems[0], elems[1])]
takeg_t = q.take_grad(1)
for elem in elems:
sess.run(accum_op, feed_dict={x: elem})
is_all_equal = True
val = takeg_t.eval()
for i in range(len(val)):
for j in range(len(val[i])):
is_all_equal &= (val[i][j] == elems_ave[i][j])
self.assertTrue(is_all_equal)
def testAccumulatorWrongDynamicShape(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=None)
x = array_ops.placeholder(dtypes_lib.float32)
accum_op = q.apply_grad(x)
# First successful apply_grad determines shape
sess.run(accum_op, feed_dict={x: [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]})
with self.assertRaises(errors_impl.InvalidArgumentError):
sess.run(accum_op, feed_dict={x: [[1.0, 2.0], [3.0, 4.0]]})
with self.assertRaises(errors_impl.InvalidArgumentError):
sess.run(accum_op, feed_dict={x: [[1.0], [2.0], [3.0]]})
def testAccumulatorSizeAfterApplyGrad(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
accum_op = q.apply_grad((10.0,))
self.assertEqual(q.num_accumulated().eval(), 0)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 1)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 2)
def testAccumulatorSizeAfterApplyGradAndTakeGrad(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
accum_op = q.apply_grad((10.0,))
extract_t = q.take_grad(2)
# Applying gradient multiple times to increase size from 0 to 2.
self.assertEqual(q.num_accumulated().eval(), 0)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 1)
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 2)
# Extract will reduce size to 0
extract_t.op.run()
self.assertEqual(q.num_accumulated().eval(), 0)
# Take gradients always sets the size back to 0 if successful.
accum_op = q.apply_grad((10.0,), local_step=1)
accum_op.run()
accum_op.run()
accum_op.run()
accum_op.run()
self.assertEqual(q.num_accumulated().eval(), 4)
extract_t.op.run()
self.assertEqual(q.num_accumulated().eval(), 0)
def testAccumulatorTakeGradMean(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0]
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(15.0, val)
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(constant_op.constant(1))
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(15.0, val)
def testAccumulatorTakeGradSum(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1]),
reduction_type="SUM")
elems = [10.0, 20.0]
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(30.0, val)
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(constant_op.constant(1))
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(30.0, val)
def testAccumulatorTakeGradInvalidReductionType(self):
with self.assertRaises(ValueError):
data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1]),
reduction_type="Invalid")
def testAccumulatorInvalidTakeGrad(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0]
accum_ops = [q.apply_grad((x,)) for x in elems]
takeg_t = q.take_grad(-1)
for accum_op in accum_ops:
accum_op.run()
with self.assertRaises(errors_impl.InvalidArgumentError):
takeg_t.eval()
def testAccumulatorRepeatedTakeGradMean(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0]
elems_ave = sum(elems) / len(elems)
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(elems_ave, val)
elems = [20.0, 30.0]
elems_ave = sum(elems) / len(elems)
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(elems_ave + 0.0, val)
def testAccumulatorRepeatedTakeGradSum(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32,
name="Q",
shape=tensor_shape.TensorShape([1]),
reduction_type="SUM")
elems = [10.0, 20.0]
elems_sum = 30.0
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(elems_sum, val)
elems = [20.0, 30.0]
elems_sum = 50.0
accum_ops = [q.apply_grad((x,), local_step=1) for x in elems]
takeg_t = q.take_grad(1)
for accum_op in accum_ops:
accum_op.run()
val = takeg_t.eval()
self.assertEqual(elems_sum, val)
def testAccumulatorIncrementGlobalStep(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
global_step = variables.Variable(0, name="global_step")
new_global_step = math_ops.add(global_step, 1)
inc_global_step = state_ops.assign(global_step, new_global_step)
set_global_step_op = q.set_global_step(new_global_step)
variables.global_variables_initializer().run()
for _ in range(3):
set_global_step_op.run()
inc_global_step.eval()
def testAccumulatorSetGlobalStepPreventsAccumulation(self):
with self.test_session():
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
local_steps = range(1000, 1005)
accum_ops = [q.apply_grad((0.0 + x,), local_step=x) for x in local_steps]
for ls in local_steps:
set_global_step_op = q.set_global_step(ls)
set_global_step_op.run()
for accum_op in accum_ops:
accum_op.run()
takeg_t = q.take_grad(1)
val = takeg_t.eval()
self.assertEqual(0.0 + sum(x for x in local_steps
if x >= ls) / sum(1 for x in local_steps
if x >= ls), val)
def testParallelApplyGrad(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0]
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(1)
def apply_grad(accum_op):
sess.run(accum_op)
threads = [
self.checkedThread(
target=apply_grad, args=(o,)) for o in accum_ops
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
val = takeg_t.eval()
self.assertEqual(val, sum(elems) / len(elems))
def testParallelTakeGrad(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [e for e in range(10)]
accum_ops = [q.apply_grad((np.float32(e),), local_step=e) for e in elems]
takeg_t = q.take_grad(1)
def apply_grad():
for accum_op in accum_ops:
time.sleep(1.0)
sess.run(accum_op)
apply_grad_thread = self.checkedThread(target=apply_grad)
results = []
def take_grad():
results.append(sess.run(takeg_t))
threads = [self.checkedThread(target=take_grad) for _ in range(10)]
for thread in threads:
thread.start()
apply_grad_thread.start()
for thread in threads:
thread.join()
apply_grad_thread.join()
self.assertItemsEqual(elems, results)
def testAccumulatorApplyAndBlockingTake(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
elems = [10.0, 20.0, 30.0]
elems_ave = sum(elems) / len(elems)
accum_ops = [q.apply_grad((x,), local_step=0) for x in elems]
takeg_t = q.take_grad(3)
def apply_grad():
time.sleep(1.0)
for accum_op in accum_ops:
sess.run(accum_op)
return_array = []
def take_grad():
return_array.append(sess.run(takeg_t))
accum_thread = self.checkedThread(target=apply_grad)
takeg_thread = self.checkedThread(target=take_grad)
accum_thread.start()
takeg_thread.start()
accum_thread.join()
takeg_thread.join()
self.assertEqual([elems_ave], return_array)
def _blocking_takeg(self, sess, takeg_op):
with self.assertRaisesOpError("was cancelled"):
sess.run(takeg_op)
def testAccumulatorCancel(self):
with self.test_session() as sess:
q = data_flow_ops.ConditionalAccumulator(
dtypes_lib.float32, name="Q", shape=tensor_shape.TensorShape([1]))
takeg_t = q.take_grad(1)
takeg_thread = self.checkedThread(
self._blocking_takeg, args=(sess, takeg_t))
takeg_thread.start()
time.sleep(1.0)
sess.close() # Will cancel blocked operation
takeg_thread.join()
if __name__ == "__main__":
test.main()
|
en
| 0.580622
|
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== # from functools import reduce name:'Q' op:'ConditionalAccumulator' attr { key: 'dtype' value { type: DT_FLOAT } } attr { key: 'shape' value { shape { unknown_rank: true} } } attr { key: 'container' value { s: '' } } attr { key: 'shared_name' value { s: '' } } attr { key: 'reduction_type' value {s: 'MEAN'} } name:'Q' op:'ConditionalAccumulator' attr { key: 'dtype' value { type: DT_FLOAT } } attr { key: 'shape' value { shape { dim {size: 1 } dim {size: 5 } dim {size: 2 } dim {size: 8 } } } } attr { key: 'container' value { s: '' } } attr { key: 'shared_name' value { s: '' } } attr { key: 'reduction_type' value {s: 'MEAN'} } # First successful apply_grad determines shape # Applying gradient multiple times to increase size from 0 to 2. # Extract will reduce size to 0 # Take gradients always sets the size back to 0 if successful. # Will cancel blocked operation
| 1.907342
| 2
|
src/train.py
|
jwrickman/UglyDuckling22
| 0
|
6626273
|
<filename>src/train.py<gh_stars>0
import pytorch_lightning as pl
import glob
from pl_bolts.models.autoencoders import VAE
from pipeline import MoleMapDataModule
DATA_DIR = "/media/storage4/molemap/dumped_images/"
if __name__ == "__main__":
image_paths = glob.glob(DATA_DIR + "*.jpg")
print(len(image_paths))
datamodule = MoleMapDataModule(
image_paths=image_paths,
batch_size=32,
image_size=128,
num_workers=6,
persistent_workers=False)
model = VAE(
input_height=128,
enc_type="resnet18",
latent_dim=12
)
### Train ###
trainer = pl.Trainer(
accelerator="gpu",
gpus=1,
max_epochs=5,
auto_scale_batch_size=True,
)
trainer.fit(model, datamodule)
|
<filename>src/train.py<gh_stars>0
import pytorch_lightning as pl
import glob
from pl_bolts.models.autoencoders import VAE
from pipeline import MoleMapDataModule
DATA_DIR = "/media/storage4/molemap/dumped_images/"
if __name__ == "__main__":
image_paths = glob.glob(DATA_DIR + "*.jpg")
print(len(image_paths))
datamodule = MoleMapDataModule(
image_paths=image_paths,
batch_size=32,
image_size=128,
num_workers=6,
persistent_workers=False)
model = VAE(
input_height=128,
enc_type="resnet18",
latent_dim=12
)
### Train ###
trainer = pl.Trainer(
accelerator="gpu",
gpus=1,
max_epochs=5,
auto_scale_batch_size=True,
)
trainer.fit(model, datamodule)
|
de
| 0.408435
|
### Train ###
| 2.098311
| 2
|
apps/Docs/views.py
|
steve-njuguna-k/Kenya-ePolice
| 1
|
6626274
|
<gh_stars>1-10
import imp
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from apps.Docs.models import Docs
# Create your views here.
@login_required(login_url='Login')
def OfficerDocs(request):
all_docs = Docs.objects.all().order_by('title')
return render(request, 'Officer Docs.html', {'all_docs':all_docs})
|
import imp
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from apps.Docs.models import Docs
# Create your views here.
@login_required(login_url='Login')
def OfficerDocs(request):
all_docs = Docs.objects.all().order_by('title')
return render(request, 'Officer Docs.html', {'all_docs':all_docs})
|
en
| 0.968116
|
# Create your views here.
| 1.803205
| 2
|
06.classifying_day_and_night/02.standardizing_run.py
|
eshanmherath/computer_vision_expert_nd
| 0
|
6626275
|
import cv2
import matplotlib.pyplot as plt
import helpers
image_dir_train = 'day_night_images/training'
image_dir_test = 'day_night_images/test'
IMAGE_LIST = helpers.load_dataset(image_dir_train)
print("Training images count", len(IMAGE_LIST))
def standardize_input(image):
# Resize image so that all "standard" images are the same size 600x1100 (hxw)
resized_image = cv2.resize(image, (1100, 600)) # CV2 takes (w, h)
return resized_image
def encode(label):
encoded_value = 0
if label == "day":
encoded_value = 1
return encoded_value
def standardize(image_list):
standard_list = []
for item in image_list:
image = item[0]
label = item[1]
standardized_im = standardize_input(image)
binary_label = encode(label)
standard_list.append((standardized_im, binary_label))
return standard_list
STANDARDIZED_LIST = standardize(IMAGE_LIST)
image_num = 0
selected_image = STANDARDIZED_LIST[image_num][0]
selected_label = STANDARDIZED_LIST[image_num][1]
print(f"Image size {selected_image.shape} with label {selected_label} [Day=1; Night =0]")
plt.imshow(selected_image)
plt.show()
|
import cv2
import matplotlib.pyplot as plt
import helpers
image_dir_train = 'day_night_images/training'
image_dir_test = 'day_night_images/test'
IMAGE_LIST = helpers.load_dataset(image_dir_train)
print("Training images count", len(IMAGE_LIST))
def standardize_input(image):
# Resize image so that all "standard" images are the same size 600x1100 (hxw)
resized_image = cv2.resize(image, (1100, 600)) # CV2 takes (w, h)
return resized_image
def encode(label):
encoded_value = 0
if label == "day":
encoded_value = 1
return encoded_value
def standardize(image_list):
standard_list = []
for item in image_list:
image = item[0]
label = item[1]
standardized_im = standardize_input(image)
binary_label = encode(label)
standard_list.append((standardized_im, binary_label))
return standard_list
STANDARDIZED_LIST = standardize(IMAGE_LIST)
image_num = 0
selected_image = STANDARDIZED_LIST[image_num][0]
selected_label = STANDARDIZED_LIST[image_num][1]
print(f"Image size {selected_image.shape} with label {selected_label} [Day=1; Night =0]")
plt.imshow(selected_image)
plt.show()
|
en
| 0.771812
|
# Resize image so that all "standard" images are the same size 600x1100 (hxw) # CV2 takes (w, h)
| 3.341067
| 3
|
taurex_ultranest/__init__.py
|
ucl-exoplanets/taurex-ultranest
| 0
|
6626276
|
<filename>taurex_ultranest/__init__.py
from .ultranestoptimizer import UltranestSampler
|
<filename>taurex_ultranest/__init__.py
from .ultranestoptimizer import UltranestSampler
|
none
| 1
| 1.089644
| 1
|
|
vsts/vsts/test/v4_0/models/test_run_statistic.py
|
kenkuo/azure-devops-python-api
| 0
|
6626277
|
<reponame>kenkuo/azure-devops-python-api
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class TestRunStatistic(Model):
"""TestRunStatistic.
:param run:
:type run: :class:`ShallowReference <test.v4_0.models.ShallowReference>`
:param run_statistics:
:type run_statistics: list of :class:`RunStatistic <test.v4_0.models.RunStatistic>`
"""
_attribute_map = {
'run': {'key': 'run', 'type': 'ShallowReference'},
'run_statistics': {'key': 'runStatistics', 'type': '[RunStatistic]'}
}
def __init__(self, run=None, run_statistics=None):
super(TestRunStatistic, self).__init__()
self.run = run
self.run_statistics = run_statistics
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class TestRunStatistic(Model):
"""TestRunStatistic.
:param run:
:type run: :class:`ShallowReference <test.v4_0.models.ShallowReference>`
:param run_statistics:
:type run_statistics: list of :class:`RunStatistic <test.v4_0.models.RunStatistic>`
"""
_attribute_map = {
'run': {'key': 'run', 'type': 'ShallowReference'},
'run_statistics': {'key': 'runStatistics', 'type': '[RunStatistic]'}
}
def __init__(self, run=None, run_statistics=None):
super(TestRunStatistic, self).__init__()
self.run = run
self.run_statistics = run_statistics
|
en
| 0.478277
|
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # Generated file, DO NOT EDIT # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------------------------- TestRunStatistic. :param run: :type run: :class:`ShallowReference <test.v4_0.models.ShallowReference>` :param run_statistics: :type run_statistics: list of :class:`RunStatistic <test.v4_0.models.RunStatistic>`
| 2.050384
| 2
|
test/test_rnn_state_encoder.py
|
YasMME/habitat-lab
| 489
|
6626278
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import pytest
try:
import torch
except ImportError:
torch = None
@pytest.mark.skipif(torch is None, reason="Test requires pytorch")
def test_rnn_state_encoder():
from habitat_baselines.rl.models.rnn_state_encoder import (
build_rnn_state_encoder,
)
device = (
torch.device("cuda")
if torch.cuda.is_available()
else torch.device("cpu")
)
rnn_state_encoder = build_rnn_state_encoder(32, 32, num_layers=2).to(
device=device
)
rnn = rnn_state_encoder.rnn
with torch.no_grad():
for T in [1, 2, 4, 8, 16, 32, 64, 3, 13, 31]:
for N in [1, 2, 4, 8, 3, 5]:
masks = torch.randint(
0, 2, size=(T, N, 1), dtype=torch.bool, device=device
)
inputs = torch.randn((T, N, 32), device=device)
hidden_states = torch.randn(
rnn_state_encoder.num_recurrent_layers,
N,
32,
device=device,
)
outputs, out_hiddens = rnn_state_encoder(
inputs.flatten(0, 1),
hidden_states.permute(1, 0, 2),
masks.flatten(0, 1),
)
out_hiddens = out_hiddens.permute(1, 0, 2)
reference_ouputs = []
reference_hiddens = hidden_states.clone()
for t in range(T):
reference_hiddens = torch.where(
masks[t].view(1, -1, 1),
reference_hiddens,
reference_hiddens.new_zeros(()),
)
x, reference_hiddens = rnn(
inputs[t : t + 1], reference_hiddens
)
reference_ouputs.append(x.squeeze(0))
reference_ouputs = torch.stack(reference_ouputs, 0).flatten(
0, 1
)
assert (
torch.norm(reference_ouputs - outputs).item() < 1e-3
), "Failed on (T={}, N={})".format(T, N)
assert (
torch.norm(reference_hiddens - out_hiddens).item() < 1e-3
), "Failed on (T={}, N={})".format(T, N)
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import pytest
try:
import torch
except ImportError:
torch = None
@pytest.mark.skipif(torch is None, reason="Test requires pytorch")
def test_rnn_state_encoder():
from habitat_baselines.rl.models.rnn_state_encoder import (
build_rnn_state_encoder,
)
device = (
torch.device("cuda")
if torch.cuda.is_available()
else torch.device("cpu")
)
rnn_state_encoder = build_rnn_state_encoder(32, 32, num_layers=2).to(
device=device
)
rnn = rnn_state_encoder.rnn
with torch.no_grad():
for T in [1, 2, 4, 8, 16, 32, 64, 3, 13, 31]:
for N in [1, 2, 4, 8, 3, 5]:
masks = torch.randint(
0, 2, size=(T, N, 1), dtype=torch.bool, device=device
)
inputs = torch.randn((T, N, 32), device=device)
hidden_states = torch.randn(
rnn_state_encoder.num_recurrent_layers,
N,
32,
device=device,
)
outputs, out_hiddens = rnn_state_encoder(
inputs.flatten(0, 1),
hidden_states.permute(1, 0, 2),
masks.flatten(0, 1),
)
out_hiddens = out_hiddens.permute(1, 0, 2)
reference_ouputs = []
reference_hiddens = hidden_states.clone()
for t in range(T):
reference_hiddens = torch.where(
masks[t].view(1, -1, 1),
reference_hiddens,
reference_hiddens.new_zeros(()),
)
x, reference_hiddens = rnn(
inputs[t : t + 1], reference_hiddens
)
reference_ouputs.append(x.squeeze(0))
reference_ouputs = torch.stack(reference_ouputs, 0).flatten(
0, 1
)
assert (
torch.norm(reference_ouputs - outputs).item() < 1e-3
), "Failed on (T={}, N={})".format(T, N)
assert (
torch.norm(reference_hiddens - out_hiddens).item() < 1e-3
), "Failed on (T={}, N={})".format(T, N)
|
en
| 0.896436
|
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree.
| 2.127663
| 2
|
util.py
|
corenel/walkman-utils
| 3
|
6626279
|
<reponame>corenel/walkman-utils
import os
import re
import click
import shutil
import unicodedata
from appscript import app, k
from tqdm import tqdm
def confirm(text, fg='green', **kwargs):
"""
Confirm prompt
:param text: prompt text
:type text: str
:param fg: foreground color
:type fg: str
:param kwargs: other arguments
:return: confirmation result
"""
return click.confirm(click.style('> {}'.format(text), fg=fg, bold=True),
**kwargs)
def status(text):
"""
Print running status
:param text: status text
:type text: str
"""
click.secho('{}'.format(text), fg='blue', bold=True)
def info(text):
"""
Print running info
:param text: status text
:type text: str
"""
click.secho('{}'.format(text), fg='green', bold=True)
def warning(text):
"""
Print warning message
:param text: warning message
:type text: str
"""
click.secho('{}'.format(text), fg='yellow', bold=True)
def error(text):
"""
Print error message
:param text: error message
:type text: str
"""
click.secho('{}'.format(text), fg='red', bold=True)
# sys.exit(1)
APPS = {
'iTunes': {
'binary': '/Applications/iTunes.app/Contents/MacOS/iTunes',
},
'Music': {
'binary': '/System/Applications/Music.app/Contents/MacOS/Music',
}
}
def detect_app():
"""
Detect application (iTunes or Music)
"""
for music_app, config in APPS.items():
if os.path.isfile(config['binary']):
return music_app
raise RuntimeError('Error detecting music player application')
def get_itunes_playlists():
"""
Get list of playlist from iTunes
:return: playlists in iTunes
:rtype: list
"""
return app(detect_app()).user_playlists()
def get_tracks_in_playlist(playlists):
"""
Get tracks of desired playlists in iTunes
:param playlists: name of desired playlists
:type playlists: str or list[str]
:return: list of file path
:rtype: list
"""
if isinstance(playlists, str):
playlists = [playlists]
tracks_in_playlist = []
for playlist in get_itunes_playlists():
if playlist.name() in playlists:
for track in playlist.file_tracks():
tracks_in_playlist.append(track)
return tracks_in_playlist
def valid_value(value):
return value != k.missing_value
def get_files_in_playlist(playlists):
"""
Get file path of desired playlists in iTunes
Note that path to track file may contain decomposed japanese
character like `0x3099` and `0x309a`, which won"t recognized by walkman
:param playlists: name of desired playlists
:type playlists: str or list[str]
:return: list of file path
:rtype: list[str]
"""
tracks_in_playlist = get_tracks_in_playlist(playlists)
files_in_playlist = []
for t in tqdm(tracks_in_playlist):
if valid_value(t.location()):
files_in_playlist.append(t.location().path)
return files_in_playlist
def get_lyrics_files_in_playlist(playlists):
"""
Get lyrics file path of desired playlists in iTunes
Note that path to lyrics file may contain decomposed japanese
character like `0x3099` and `0x309a`, which won"t recognized by walkman
:param playlists: name of desired playlists
:type playlists: str or list[str]
:return: list of lyrics file path
:rtype: list[str]
"""
tracks_in_playlist = get_tracks_in_playlist(playlists)
files_in_playlist = [
get_lyrics_path(t.location().path)
for t in tracks_in_playlist
if valid_value(t.location())
]
return files_in_playlist
def split_filepath(files, prefix=None):
"""
get common prefix and relative filepath
:param files: list of filepath
:type files: list[str]
:param prefix: common prefix of music files
:type prefix: str
:return: common prefix and relative filepath
:rtype: tuple(str, list[str])
"""
common_prefix = os.path.commonprefix(files)
if prefix is not None:
print('\n'.join([f for f in files if not f.startswith(prefix)]))
assert common_prefix == prefix
relative_paths = [os.path.relpath(f, common_prefix) for f in files]
return common_prefix, relative_paths
def scan_directory(target, extension):
"""
Scan given directory and get file lists
Note that `os.walk()` will return a path with decomposed japanese
character like `0x3099` and `0x309a` despite the real path is composed
:param target: target directory
:type target: str
:param extension: valid extension
:type extension: str or list[str]
:return: relative file lists
:rtype: list[str]
"""
if not target.endswith('/'):
target += '/'
relative_path = []
for root, dirs, files in os.walk(target):
curr = root.replace(target, '')
for f in files:
if is_extension(f, extension):
relative_path.append(os.path.join(curr, f))
return relative_path
def compare_filelists(files_src, files_dst, root_src, root_dst):
"""
Compare two file lists
Note that `files_src`, `files_dst` and files in `root_src` may contain
decomposed japanese character like `0x3099` and `0x309a`.
While files in `root_dst` won't.
:param files_src: list of files in source directory
:type files_src: list[str]
:param files_dst: list of files in source directory
:type files_dst: list[str]
:param root_src: path to source directory
:type root_src: str
:param root_dst: path to source directory
:type root_dst: str
:return: list of files to be updated, removed and ignored
:rtype: tuple(list, list, list)
"""
to_be_updated = [x for x in files_src if x not in files_dst]
to_be_removed = [x for x in files_dst if x not in files_src]
to_be_ignored = []
files_on_both_sides = [x for x in files_src if x in files_dst]
eps = 0.01
for f in files_on_both_sides:
if os.path.getmtime(os.path.join(root_src, f)) - eps > \
os.path.getmtime(os.path.join(root_dst, compose_str(f))):
print(f)
print(os.path.getmtime(os.path.join(root_src, f)))
print(os.path.getmtime(os.path.join(root_dst, compose_str(f))))
to_be_updated.append(f)
else:
to_be_ignored.append(f)
return to_be_updated, to_be_removed, to_be_ignored
def sync_filelists(to_be_updated,
to_be_removed,
src_dir,
dst_dir,
remove_unmatched=False):
"""
Sync list of files from source directory to target
:param to_be_updated: files to update
:type to_be_updated: list[str]
:param to_be_removed: files to remove
:type to_be_removed: list[str]
:param src_dir: path to source directory
:type src_dir: str
:param dst_dir: path to target directory
:type dst_dir: str
:param remove_unmatched: whether to remove unmatched files or not
:type remove_unmatched: bool
"""
if len(to_be_updated) > 0:
progress = tqdm(sorted(to_be_updated))
for file in progress:
if os.path.exists(os.path.join(src_dir, file)):
progress.set_description('Updating {}'.format(
os.path.basename(file)))
target_file = os.path.join(dst_dir, compose_str(file))
target_dir = os.path.dirname(target_file)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
shutil.copy2(os.path.join(src_dir, file),
os.path.join(dst_dir, compose_str(file)))
else:
print('Nothing to update')
if len(to_be_removed) > 0 and remove_unmatched:
progress = tqdm(sorted(to_be_removed))
for file in progress:
if os.path.exists(os.path.join(src_dir, file)):
progress.set_description('Removing {}'.format(
os.path.basename(file)))
target_file = os.path.join(dst_dir, compose_str(file))
os.remove(target_file)
else:
print('Nothing to remove')
def is_extension(filepath, ext):
"""
Check whether file extension is desired
:param filepath: path to file
:type filepath: str
:param ext: valid extension
:type ext: str or list
:return: whether file extension is desired
:rtype: bool
"""
if isinstance(ext, str):
ext = [ext]
filename, file_ext = os.path.splitext(filepath)
return file_ext in ext
def get_lyricsx_file(track, lyrics_dir):
"""
Get lyrics file of given track in LyricsX directory
:param track: given track
:param lyrics_dir: root directory of lyrics files
:type lyrics_dir: str
:return: lyrics filename
:rtype: str
"""
title = track.name().replace('/', '&')
artist = track.artist().replace('/', '&')
lrc_file = os.path.join(lyrics_dir, "{} - {}.lrcx".format(title, artist))
if os.path.exists(lrc_file):
return lrc_file
else:
return None
def get_lyrics_path(song):
"""
Convert song file path to corresponding lyrics file path
:param song: path to song file
:type song: str
:return: path to corresponding lyrics file
:rtype: str
"""
return os.path.splitext(song)[0] + '.lrc'
def format_timestamp(timestamp):
"""
Format timestamp xx:xx.xxx as xx:xx.xx
:param timestamp: timestamp
:type timestamp: str
:return: formatted timestamp
:rtype: str
"""
if len(re.findall('\d+:\d+\.\d\d\d', timestamp)) != 0:
timestamp = re.findall('\d+:\d+\.\d\d\d', timestamp)[0]
tsp = timestamp.split(':')
return '%s:%05.2f' % (tsp[0], float(tsp[1]))
elif len(re.findall('\d+:\d+\.\d\d', timestamp)) == 0:
# print(timestamp)
pass
return timestamp
def format_lyrics(lrc_file):
"""
Parse lyrics file and convert it to walkman-compatible format
:param lrc_file: path to lyrics file
:type lrc_file: str
:return: lyrics in walkman-compatible format
:rtype: str
"""
formatted = []
with open(lrc_file) as f:
lines = f.readlines()
lrc_lines = [
l.strip()
for l in lines
if re.findall('\[\d+:\d+\.\d+\]', l) != [] and '[tr]' not in l and
'[tt]' not in l
]
for idx, lrc_line in enumerate(lrc_lines):
if idx + 1 == len(lrc_lines):
continue
curr_timestamp = re.findall('\d+:\d+\.\d+', lrc_line)[0]
next_timestamp = re.findall('\d+:\d+\.\d+', lrc_lines[idx + 1])[0]
curr_timestamp_formatted = format_timestamp(curr_timestamp)
next_timestamp_formatted = format_timestamp(next_timestamp)
curr_line_split = lrc_line.split('[{}]'.format(curr_timestamp))
curr_lyrics = curr_line_split[1] if len(
curr_line_split) == 2 else ''
formatted.append('[{}][{}]{}'.format(curr_timestamp_formatted,
next_timestamp_formatted,
curr_lyrics))
with open(lrc_file, 'w') as f:
f.write('\n'.join(formatted))
def struct_lyrics_dir(tracks, src_dir, dst_dir):
"""
Copy lyrics file to given directory with the same structure as tracks
:param tracks: list of tracks
:type tracks: list
:param src_dir: path to soruce directory
:type src_dir: str
:param dst_dir: path to target directory
:type dst_dir: str
"""
# get files
files = [t.location().path for t in tracks if valid_value(t.location())]
common_prefix = os.path.commonprefix(files)
relative_paths = [
get_lyrics_path(f.replace(common_prefix, '')) for f in files
]
progress = tqdm(tracks)
for idx, track in enumerate(progress):
lrc_src = get_lyricsx_file(track, src_dir)
if lrc_src is not None:
lrc_dst = os.path.join(dst_dir, relative_paths[idx])
if not os.path.exists(os.path.dirname(lrc_dst)):
os.makedirs(os.path.dirname(lrc_dst))
progress.set_description('Copying {}'.format(
os.path.basename(lrc_dst)))
shutil.copy2(lrc_src, lrc_dst)
format_lyrics(lrc_dst)
def format_playlist_with_prefix(songs, prefix):
"""
Format track list in relative paths with given prefix
:param songs: list of songs
:type songs: list[str]
:param prefix: path prefix
:type prefix: str
:return: track list in relative paths with given prefix
:rtype: list[str]
"""
_, songs_rel = split_filepath(songs)
songs_with_prefix = [
os.path.join(prefix, compose_str(song)).replace('/', '\\')
for song in songs_rel
]
return songs_with_prefix
def str_to_ord(s):
"""
Convert string to list of character orders
:param s: given string
:type s: str
:return: list of character orders
:rtype: list[int]
"""
return [ord(c) for c in s]
def ord_to_str(ord_list):
"""
Convert list of character orders to string
:param ord_list: list of character orders
:type ord_list: int or list[int]
:return: corresponding string
:rtype: str
"""
if isinstance(ord_list, int):
ord_list = [ord_list]
s = ''
for o in ord_list:
s += chr(o)
return s
def locate_all_occurrence(l, e):
"""
Return indices of all element occurrences in given list
:param l: given list
:type l: list
:param e: element to locate
:return: indices of all occurrences
:rtype: list
"""
return [i for i, x in enumerate(l) if x == e]
def compose_str(s):
"""
Replace decomposed character (like 0x3099 or 0x309a) in given string
with composed one
:param s: given string
:type s: str
:return: composed string
:rtype: str
"""
# char_list = str_to_ord(s)
# corrected_list = []
# voice_mark = locate_all_occurrence(char_list, 0x3099)
# semivoice_mark = locate_all_occurrence(char_list, 0x309a)
#
# curr_idx = 0
# while curr_idx < len(char_list):
# if curr_idx + 1 in voice_mark:
# corrected_ord = char_list[curr_idx] + 1
# corrected_list.append(corrected_ord)
# curr_idx += 2
# elif curr_idx + 1 in semivoice_mark:
# corrected_ord = char_list[curr_idx] + 2
# corrected_list.append(corrected_ord)
# curr_idx += 2
# else:
# corrected_list.append(char_list[curr_idx])
# curr_idx += 1
#
# return ord_to_str(corrected_list)
return unicodedata.normalize('NFC', s)
def decompose_str(s):
"""
Replace composed character in given string with decomposed one
(like 0x3099 or 0x309a)
:param s: given string
:type s: str
:return: decomposed string
:rtype: str
"""
return unicodedata.normalize('NFD', s)
|
import os
import re
import click
import shutil
import unicodedata
from appscript import app, k
from tqdm import tqdm
def confirm(text, fg='green', **kwargs):
"""
Confirm prompt
:param text: prompt text
:type text: str
:param fg: foreground color
:type fg: str
:param kwargs: other arguments
:return: confirmation result
"""
return click.confirm(click.style('> {}'.format(text), fg=fg, bold=True),
**kwargs)
def status(text):
"""
Print running status
:param text: status text
:type text: str
"""
click.secho('{}'.format(text), fg='blue', bold=True)
def info(text):
"""
Print running info
:param text: status text
:type text: str
"""
click.secho('{}'.format(text), fg='green', bold=True)
def warning(text):
"""
Print warning message
:param text: warning message
:type text: str
"""
click.secho('{}'.format(text), fg='yellow', bold=True)
def error(text):
"""
Print error message
:param text: error message
:type text: str
"""
click.secho('{}'.format(text), fg='red', bold=True)
# sys.exit(1)
APPS = {
'iTunes': {
'binary': '/Applications/iTunes.app/Contents/MacOS/iTunes',
},
'Music': {
'binary': '/System/Applications/Music.app/Contents/MacOS/Music',
}
}
def detect_app():
"""
Detect application (iTunes or Music)
"""
for music_app, config in APPS.items():
if os.path.isfile(config['binary']):
return music_app
raise RuntimeError('Error detecting music player application')
def get_itunes_playlists():
"""
Get list of playlist from iTunes
:return: playlists in iTunes
:rtype: list
"""
return app(detect_app()).user_playlists()
def get_tracks_in_playlist(playlists):
"""
Get tracks of desired playlists in iTunes
:param playlists: name of desired playlists
:type playlists: str or list[str]
:return: list of file path
:rtype: list
"""
if isinstance(playlists, str):
playlists = [playlists]
tracks_in_playlist = []
for playlist in get_itunes_playlists():
if playlist.name() in playlists:
for track in playlist.file_tracks():
tracks_in_playlist.append(track)
return tracks_in_playlist
def valid_value(value):
return value != k.missing_value
def get_files_in_playlist(playlists):
"""
Get file path of desired playlists in iTunes
Note that path to track file may contain decomposed japanese
character like `0x3099` and `0x309a`, which won"t recognized by walkman
:param playlists: name of desired playlists
:type playlists: str or list[str]
:return: list of file path
:rtype: list[str]
"""
tracks_in_playlist = get_tracks_in_playlist(playlists)
files_in_playlist = []
for t in tqdm(tracks_in_playlist):
if valid_value(t.location()):
files_in_playlist.append(t.location().path)
return files_in_playlist
def get_lyrics_files_in_playlist(playlists):
"""
Get lyrics file path of desired playlists in iTunes
Note that path to lyrics file may contain decomposed japanese
character like `0x3099` and `0x309a`, which won"t recognized by walkman
:param playlists: name of desired playlists
:type playlists: str or list[str]
:return: list of lyrics file path
:rtype: list[str]
"""
tracks_in_playlist = get_tracks_in_playlist(playlists)
files_in_playlist = [
get_lyrics_path(t.location().path)
for t in tracks_in_playlist
if valid_value(t.location())
]
return files_in_playlist
def split_filepath(files, prefix=None):
"""
get common prefix and relative filepath
:param files: list of filepath
:type files: list[str]
:param prefix: common prefix of music files
:type prefix: str
:return: common prefix and relative filepath
:rtype: tuple(str, list[str])
"""
common_prefix = os.path.commonprefix(files)
if prefix is not None:
print('\n'.join([f for f in files if not f.startswith(prefix)]))
assert common_prefix == prefix
relative_paths = [os.path.relpath(f, common_prefix) for f in files]
return common_prefix, relative_paths
def scan_directory(target, extension):
"""
Scan given directory and get file lists
Note that `os.walk()` will return a path with decomposed japanese
character like `0x3099` and `0x309a` despite the real path is composed
:param target: target directory
:type target: str
:param extension: valid extension
:type extension: str or list[str]
:return: relative file lists
:rtype: list[str]
"""
if not target.endswith('/'):
target += '/'
relative_path = []
for root, dirs, files in os.walk(target):
curr = root.replace(target, '')
for f in files:
if is_extension(f, extension):
relative_path.append(os.path.join(curr, f))
return relative_path
def compare_filelists(files_src, files_dst, root_src, root_dst):
"""
Compare two file lists
Note that `files_src`, `files_dst` and files in `root_src` may contain
decomposed japanese character like `0x3099` and `0x309a`.
While files in `root_dst` won't.
:param files_src: list of files in source directory
:type files_src: list[str]
:param files_dst: list of files in source directory
:type files_dst: list[str]
:param root_src: path to source directory
:type root_src: str
:param root_dst: path to source directory
:type root_dst: str
:return: list of files to be updated, removed and ignored
:rtype: tuple(list, list, list)
"""
to_be_updated = [x for x in files_src if x not in files_dst]
to_be_removed = [x for x in files_dst if x not in files_src]
to_be_ignored = []
files_on_both_sides = [x for x in files_src if x in files_dst]
eps = 0.01
for f in files_on_both_sides:
if os.path.getmtime(os.path.join(root_src, f)) - eps > \
os.path.getmtime(os.path.join(root_dst, compose_str(f))):
print(f)
print(os.path.getmtime(os.path.join(root_src, f)))
print(os.path.getmtime(os.path.join(root_dst, compose_str(f))))
to_be_updated.append(f)
else:
to_be_ignored.append(f)
return to_be_updated, to_be_removed, to_be_ignored
def sync_filelists(to_be_updated,
to_be_removed,
src_dir,
dst_dir,
remove_unmatched=False):
"""
Sync list of files from source directory to target
:param to_be_updated: files to update
:type to_be_updated: list[str]
:param to_be_removed: files to remove
:type to_be_removed: list[str]
:param src_dir: path to source directory
:type src_dir: str
:param dst_dir: path to target directory
:type dst_dir: str
:param remove_unmatched: whether to remove unmatched files or not
:type remove_unmatched: bool
"""
if len(to_be_updated) > 0:
progress = tqdm(sorted(to_be_updated))
for file in progress:
if os.path.exists(os.path.join(src_dir, file)):
progress.set_description('Updating {}'.format(
os.path.basename(file)))
target_file = os.path.join(dst_dir, compose_str(file))
target_dir = os.path.dirname(target_file)
if not os.path.exists(target_dir):
os.makedirs(target_dir)
shutil.copy2(os.path.join(src_dir, file),
os.path.join(dst_dir, compose_str(file)))
else:
print('Nothing to update')
if len(to_be_removed) > 0 and remove_unmatched:
progress = tqdm(sorted(to_be_removed))
for file in progress:
if os.path.exists(os.path.join(src_dir, file)):
progress.set_description('Removing {}'.format(
os.path.basename(file)))
target_file = os.path.join(dst_dir, compose_str(file))
os.remove(target_file)
else:
print('Nothing to remove')
def is_extension(filepath, ext):
"""
Check whether file extension is desired
:param filepath: path to file
:type filepath: str
:param ext: valid extension
:type ext: str or list
:return: whether file extension is desired
:rtype: bool
"""
if isinstance(ext, str):
ext = [ext]
filename, file_ext = os.path.splitext(filepath)
return file_ext in ext
def get_lyricsx_file(track, lyrics_dir):
"""
Get lyrics file of given track in LyricsX directory
:param track: given track
:param lyrics_dir: root directory of lyrics files
:type lyrics_dir: str
:return: lyrics filename
:rtype: str
"""
title = track.name().replace('/', '&')
artist = track.artist().replace('/', '&')
lrc_file = os.path.join(lyrics_dir, "{} - {}.lrcx".format(title, artist))
if os.path.exists(lrc_file):
return lrc_file
else:
return None
def get_lyrics_path(song):
"""
Convert song file path to corresponding lyrics file path
:param song: path to song file
:type song: str
:return: path to corresponding lyrics file
:rtype: str
"""
return os.path.splitext(song)[0] + '.lrc'
def format_timestamp(timestamp):
"""
Format timestamp xx:xx.xxx as xx:xx.xx
:param timestamp: timestamp
:type timestamp: str
:return: formatted timestamp
:rtype: str
"""
if len(re.findall('\d+:\d+\.\d\d\d', timestamp)) != 0:
timestamp = re.findall('\d+:\d+\.\d\d\d', timestamp)[0]
tsp = timestamp.split(':')
return '%s:%05.2f' % (tsp[0], float(tsp[1]))
elif len(re.findall('\d+:\d+\.\d\d', timestamp)) == 0:
# print(timestamp)
pass
return timestamp
def format_lyrics(lrc_file):
"""
Parse lyrics file and convert it to walkman-compatible format
:param lrc_file: path to lyrics file
:type lrc_file: str
:return: lyrics in walkman-compatible format
:rtype: str
"""
formatted = []
with open(lrc_file) as f:
lines = f.readlines()
lrc_lines = [
l.strip()
for l in lines
if re.findall('\[\d+:\d+\.\d+\]', l) != [] and '[tr]' not in l and
'[tt]' not in l
]
for idx, lrc_line in enumerate(lrc_lines):
if idx + 1 == len(lrc_lines):
continue
curr_timestamp = re.findall('\d+:\d+\.\d+', lrc_line)[0]
next_timestamp = re.findall('\d+:\d+\.\d+', lrc_lines[idx + 1])[0]
curr_timestamp_formatted = format_timestamp(curr_timestamp)
next_timestamp_formatted = format_timestamp(next_timestamp)
curr_line_split = lrc_line.split('[{}]'.format(curr_timestamp))
curr_lyrics = curr_line_split[1] if len(
curr_line_split) == 2 else ''
formatted.append('[{}][{}]{}'.format(curr_timestamp_formatted,
next_timestamp_formatted,
curr_lyrics))
with open(lrc_file, 'w') as f:
f.write('\n'.join(formatted))
def struct_lyrics_dir(tracks, src_dir, dst_dir):
"""
Copy lyrics file to given directory with the same structure as tracks
:param tracks: list of tracks
:type tracks: list
:param src_dir: path to soruce directory
:type src_dir: str
:param dst_dir: path to target directory
:type dst_dir: str
"""
# get files
files = [t.location().path for t in tracks if valid_value(t.location())]
common_prefix = os.path.commonprefix(files)
relative_paths = [
get_lyrics_path(f.replace(common_prefix, '')) for f in files
]
progress = tqdm(tracks)
for idx, track in enumerate(progress):
lrc_src = get_lyricsx_file(track, src_dir)
if lrc_src is not None:
lrc_dst = os.path.join(dst_dir, relative_paths[idx])
if not os.path.exists(os.path.dirname(lrc_dst)):
os.makedirs(os.path.dirname(lrc_dst))
progress.set_description('Copying {}'.format(
os.path.basename(lrc_dst)))
shutil.copy2(lrc_src, lrc_dst)
format_lyrics(lrc_dst)
def format_playlist_with_prefix(songs, prefix):
"""
Format track list in relative paths with given prefix
:param songs: list of songs
:type songs: list[str]
:param prefix: path prefix
:type prefix: str
:return: track list in relative paths with given prefix
:rtype: list[str]
"""
_, songs_rel = split_filepath(songs)
songs_with_prefix = [
os.path.join(prefix, compose_str(song)).replace('/', '\\')
for song in songs_rel
]
return songs_with_prefix
def str_to_ord(s):
"""
Convert string to list of character orders
:param s: given string
:type s: str
:return: list of character orders
:rtype: list[int]
"""
return [ord(c) for c in s]
def ord_to_str(ord_list):
"""
Convert list of character orders to string
:param ord_list: list of character orders
:type ord_list: int or list[int]
:return: corresponding string
:rtype: str
"""
if isinstance(ord_list, int):
ord_list = [ord_list]
s = ''
for o in ord_list:
s += chr(o)
return s
def locate_all_occurrence(l, e):
"""
Return indices of all element occurrences in given list
:param l: given list
:type l: list
:param e: element to locate
:return: indices of all occurrences
:rtype: list
"""
return [i for i, x in enumerate(l) if x == e]
def compose_str(s):
"""
Replace decomposed character (like 0x3099 or 0x309a) in given string
with composed one
:param s: given string
:type s: str
:return: composed string
:rtype: str
"""
# char_list = str_to_ord(s)
# corrected_list = []
# voice_mark = locate_all_occurrence(char_list, 0x3099)
# semivoice_mark = locate_all_occurrence(char_list, 0x309a)
#
# curr_idx = 0
# while curr_idx < len(char_list):
# if curr_idx + 1 in voice_mark:
# corrected_ord = char_list[curr_idx] + 1
# corrected_list.append(corrected_ord)
# curr_idx += 2
# elif curr_idx + 1 in semivoice_mark:
# corrected_ord = char_list[curr_idx] + 2
# corrected_list.append(corrected_ord)
# curr_idx += 2
# else:
# corrected_list.append(char_list[curr_idx])
# curr_idx += 1
#
# return ord_to_str(corrected_list)
return unicodedata.normalize('NFC', s)
def decompose_str(s):
"""
Replace composed character in given string with decomposed one
(like 0x3099 or 0x309a)
:param s: given string
:type s: str
:return: decomposed string
:rtype: str
"""
return unicodedata.normalize('NFD', s)
|
en
| 0.657439
|
Confirm prompt :param text: prompt text :type text: str :param fg: foreground color :type fg: str :param kwargs: other arguments :return: confirmation result Print running status :param text: status text :type text: str Print running info :param text: status text :type text: str Print warning message :param text: warning message :type text: str Print error message :param text: error message :type text: str # sys.exit(1) Detect application (iTunes or Music) Get list of playlist from iTunes :return: playlists in iTunes :rtype: list Get tracks of desired playlists in iTunes :param playlists: name of desired playlists :type playlists: str or list[str] :return: list of file path :rtype: list Get file path of desired playlists in iTunes Note that path to track file may contain decomposed japanese character like `0x3099` and `0x309a`, which won"t recognized by walkman :param playlists: name of desired playlists :type playlists: str or list[str] :return: list of file path :rtype: list[str] Get lyrics file path of desired playlists in iTunes Note that path to lyrics file may contain decomposed japanese character like `0x3099` and `0x309a`, which won"t recognized by walkman :param playlists: name of desired playlists :type playlists: str or list[str] :return: list of lyrics file path :rtype: list[str] get common prefix and relative filepath :param files: list of filepath :type files: list[str] :param prefix: common prefix of music files :type prefix: str :return: common prefix and relative filepath :rtype: tuple(str, list[str]) Scan given directory and get file lists Note that `os.walk()` will return a path with decomposed japanese character like `0x3099` and `0x309a` despite the real path is composed :param target: target directory :type target: str :param extension: valid extension :type extension: str or list[str] :return: relative file lists :rtype: list[str] Compare two file lists Note that `files_src`, `files_dst` and files in `root_src` may contain decomposed japanese character like `0x3099` and `0x309a`. While files in `root_dst` won't. :param files_src: list of files in source directory :type files_src: list[str] :param files_dst: list of files in source directory :type files_dst: list[str] :param root_src: path to source directory :type root_src: str :param root_dst: path to source directory :type root_dst: str :return: list of files to be updated, removed and ignored :rtype: tuple(list, list, list) Sync list of files from source directory to target :param to_be_updated: files to update :type to_be_updated: list[str] :param to_be_removed: files to remove :type to_be_removed: list[str] :param src_dir: path to source directory :type src_dir: str :param dst_dir: path to target directory :type dst_dir: str :param remove_unmatched: whether to remove unmatched files or not :type remove_unmatched: bool Check whether file extension is desired :param filepath: path to file :type filepath: str :param ext: valid extension :type ext: str or list :return: whether file extension is desired :rtype: bool Get lyrics file of given track in LyricsX directory :param track: given track :param lyrics_dir: root directory of lyrics files :type lyrics_dir: str :return: lyrics filename :rtype: str Convert song file path to corresponding lyrics file path :param song: path to song file :type song: str :return: path to corresponding lyrics file :rtype: str Format timestamp xx:xx.xxx as xx:xx.xx :param timestamp: timestamp :type timestamp: str :return: formatted timestamp :rtype: str # print(timestamp) Parse lyrics file and convert it to walkman-compatible format :param lrc_file: path to lyrics file :type lrc_file: str :return: lyrics in walkman-compatible format :rtype: str Copy lyrics file to given directory with the same structure as tracks :param tracks: list of tracks :type tracks: list :param src_dir: path to soruce directory :type src_dir: str :param dst_dir: path to target directory :type dst_dir: str # get files Format track list in relative paths with given prefix :param songs: list of songs :type songs: list[str] :param prefix: path prefix :type prefix: str :return: track list in relative paths with given prefix :rtype: list[str] Convert string to list of character orders :param s: given string :type s: str :return: list of character orders :rtype: list[int] Convert list of character orders to string :param ord_list: list of character orders :type ord_list: int or list[int] :return: corresponding string :rtype: str Return indices of all element occurrences in given list :param l: given list :type l: list :param e: element to locate :return: indices of all occurrences :rtype: list Replace decomposed character (like 0x3099 or 0x309a) in given string with composed one :param s: given string :type s: str :return: composed string :rtype: str # char_list = str_to_ord(s) # corrected_list = [] # voice_mark = locate_all_occurrence(char_list, 0x3099) # semivoice_mark = locate_all_occurrence(char_list, 0x309a) # # curr_idx = 0 # while curr_idx < len(char_list): # if curr_idx + 1 in voice_mark: # corrected_ord = char_list[curr_idx] + 1 # corrected_list.append(corrected_ord) # curr_idx += 2 # elif curr_idx + 1 in semivoice_mark: # corrected_ord = char_list[curr_idx] + 2 # corrected_list.append(corrected_ord) # curr_idx += 2 # else: # corrected_list.append(char_list[curr_idx]) # curr_idx += 1 # # return ord_to_str(corrected_list) Replace composed character in given string with decomposed one (like 0x3099 or 0x309a) :param s: given string :type s: str :return: decomposed string :rtype: str
| 2.433472
| 2
|
aiocoap/cli/common.py
|
mguc/aiocoap
| 0
|
6626280
|
#!/usr/bin/env python3
# This file is part of the Python aiocoap library project.
#
# Copyright (c) 2012-2014 <NAME> <http://sixpinetrees.blogspot.com/>,
# 2013-2014 <NAME> <<EMAIL>>
#
# aiocoap is free software, this file is published under the MIT license as
# described in the accompanying LICENSE file.
"""Common options of aiocoap command line utilities
Unlike those in :mod:`aiocoap.util.cli`, these are particular to aiocoap
functionality.
Typical use is like this::
>>> p = argparse.ArgumentParser()
>>> p.add_argument('--foo') # doctest: +ELLIPSIS
_...
>>> add_server_arguments(p)
>>> opts = p.parse_args(['--bind', '[::1]:56830', '--foo=bar'])
You can then either pass opts directly to
:func:`server_context_from_arguments`, or split up the arguments::
>>> server_opts = extract_server_arguments(opts)
>>> opts
Namespace(foo='bar')
Then, server_opts can be passed to `server_context_from_arguments`.
"""
import sys
import argparse
import json
from pathlib import Path
from ..util import hostportsplit
from ..util.asyncio.coro_or_contextmanager import AwaitOrAenter
from ..protocol import Context
from ..credentials import CredentialsMap
class _HelpBind(argparse.Action):
def __init__(self, *args, **kwargs):
kwargs['nargs'] = 0
super().__init__(*args, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
print("The --bind option can take either of the following formats:"
"\n :port -- bind to a given port on all available interfaces"
"\n host -- bind to default ports on a given host name (can also be an IP address; IPv6 addresses need to be in square brackets)"
"\n host:port -- bind only to a specific port on a given host"
"\n\nBy default, the server will bind to all available addressess and protocols on the respective default ports."
"\nIf a port is specified, and (D)TLS support is available, those protocols will be bound to one port higher (as are the default ports, 5683 for CoAP and 5684 for CoAP over (D)TLS)."
"\n", file=sys.stderr)
parser.exit()
def add_server_arguments(parser):
"""Add the --bind option to an argparse parser"""
def hostportsplit_helper(arg):
"""Wrapper around hostportsplit that gives better error messages than
'invalid hostportsplit value'"""
try:
return hostportsplit(arg)
except ValueError:
raise parser.error("Invalid argument to --bind." +
" Did you mean --bind '[%s]'?" % arg
if arg.count(':') >= 2 and '[' not in arg
else " See --help-bind for details.")
parser.add_argument('--bind', help="Host and/or port to bind to (see --help-bind for details)", type=hostportsplit_helper, default=None)
parser.add_argument('--credentials', help="JSON file pointing to credentials for the server's identity/ies.", type=Path)
# These are to be eventually migrated into credentials
parser.add_argument('--tls-server-certificate', help="TLS certificate (chain) to present to connecting clients (in PEM format)", metavar="CRT")
parser.add_argument('--tls-server-key', help="TLS key to load that supports the server certificate", metavar="KEY")
parser.add_argument('--help-bind', help=argparse.SUPPRESS, action=_HelpBind)
def extract_server_arguments(namespace):
"""Given the output of .parse() on a ArgumentParser that had
add_server_arguments called with it, remove the resulting option in-place
from namespace and return them in a separate namespace."""
server_arguments = type(namespace)()
server_arguments.bind = namespace.bind
server_arguments.tls_server_certificate = namespace.tls_server_certificate
server_arguments.tls_server_key = namespace.tls_server_key
server_arguments.credentials = namespace.credentials
del namespace.bind
del namespace.tls_server_certificate
del namespace.tls_server_key
del namespace.credentials
del namespace.help_bind
return server_arguments
@AwaitOrAenter.decorate
async def server_context_from_arguments(site, namespace, **kwargs):
"""Create a bound context like
:meth:`.aiocoap.Context.create_server_context`, but take the bind and TLS
settings from a namespace returned from an argparse parser that has had
:func:`add_server_arguments` run on it.
"""
if namespace.tls_server_certificate:
import ssl
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(certfile=namespace.tls_server_certificate, keyfile=namespace.tls_server_key)
ssl_context.set_alpn_protocols(["coap"])
if hasattr(ssl_context, 'sni_callback'): # starting python 3.7
ssl_context.sni_callback = lambda obj, name, context: setattr(obj, "indicated_server_name", name)
else:
ssl_context = None
if namespace.credentials:
server_credentials = CredentialsMap()
server_credentials.load_from_dict(json.load(namespace.credentials.open('rb')))
# FIXME: could be non-OSCORE as well -- can we build oscore_sitewrapper
# in such a way it only depends on the OSCORE dependencies if there are
# actual identities present?
from aiocoap.oscore_sitewrapper import OscoreSiteWrapper
site = OscoreSiteWrapper(site, server_credentials)
else:
server_credentials = None
return await Context.create_server_context(site, namespace.bind, _ssl_context=ssl_context, server_credentials=server_credentials, **kwargs)
|
#!/usr/bin/env python3
# This file is part of the Python aiocoap library project.
#
# Copyright (c) 2012-2014 <NAME> <http://sixpinetrees.blogspot.com/>,
# 2013-2014 <NAME> <<EMAIL>>
#
# aiocoap is free software, this file is published under the MIT license as
# described in the accompanying LICENSE file.
"""Common options of aiocoap command line utilities
Unlike those in :mod:`aiocoap.util.cli`, these are particular to aiocoap
functionality.
Typical use is like this::
>>> p = argparse.ArgumentParser()
>>> p.add_argument('--foo') # doctest: +ELLIPSIS
_...
>>> add_server_arguments(p)
>>> opts = p.parse_args(['--bind', '[::1]:56830', '--foo=bar'])
You can then either pass opts directly to
:func:`server_context_from_arguments`, or split up the arguments::
>>> server_opts = extract_server_arguments(opts)
>>> opts
Namespace(foo='bar')
Then, server_opts can be passed to `server_context_from_arguments`.
"""
import sys
import argparse
import json
from pathlib import Path
from ..util import hostportsplit
from ..util.asyncio.coro_or_contextmanager import AwaitOrAenter
from ..protocol import Context
from ..credentials import CredentialsMap
class _HelpBind(argparse.Action):
def __init__(self, *args, **kwargs):
kwargs['nargs'] = 0
super().__init__(*args, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
print("The --bind option can take either of the following formats:"
"\n :port -- bind to a given port on all available interfaces"
"\n host -- bind to default ports on a given host name (can also be an IP address; IPv6 addresses need to be in square brackets)"
"\n host:port -- bind only to a specific port on a given host"
"\n\nBy default, the server will bind to all available addressess and protocols on the respective default ports."
"\nIf a port is specified, and (D)TLS support is available, those protocols will be bound to one port higher (as are the default ports, 5683 for CoAP and 5684 for CoAP over (D)TLS)."
"\n", file=sys.stderr)
parser.exit()
def add_server_arguments(parser):
"""Add the --bind option to an argparse parser"""
def hostportsplit_helper(arg):
"""Wrapper around hostportsplit that gives better error messages than
'invalid hostportsplit value'"""
try:
return hostportsplit(arg)
except ValueError:
raise parser.error("Invalid argument to --bind." +
" Did you mean --bind '[%s]'?" % arg
if arg.count(':') >= 2 and '[' not in arg
else " See --help-bind for details.")
parser.add_argument('--bind', help="Host and/or port to bind to (see --help-bind for details)", type=hostportsplit_helper, default=None)
parser.add_argument('--credentials', help="JSON file pointing to credentials for the server's identity/ies.", type=Path)
# These are to be eventually migrated into credentials
parser.add_argument('--tls-server-certificate', help="TLS certificate (chain) to present to connecting clients (in PEM format)", metavar="CRT")
parser.add_argument('--tls-server-key', help="TLS key to load that supports the server certificate", metavar="KEY")
parser.add_argument('--help-bind', help=argparse.SUPPRESS, action=_HelpBind)
def extract_server_arguments(namespace):
"""Given the output of .parse() on a ArgumentParser that had
add_server_arguments called with it, remove the resulting option in-place
from namespace and return them in a separate namespace."""
server_arguments = type(namespace)()
server_arguments.bind = namespace.bind
server_arguments.tls_server_certificate = namespace.tls_server_certificate
server_arguments.tls_server_key = namespace.tls_server_key
server_arguments.credentials = namespace.credentials
del namespace.bind
del namespace.tls_server_certificate
del namespace.tls_server_key
del namespace.credentials
del namespace.help_bind
return server_arguments
@AwaitOrAenter.decorate
async def server_context_from_arguments(site, namespace, **kwargs):
"""Create a bound context like
:meth:`.aiocoap.Context.create_server_context`, but take the bind and TLS
settings from a namespace returned from an argparse parser that has had
:func:`add_server_arguments` run on it.
"""
if namespace.tls_server_certificate:
import ssl
ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_context.load_cert_chain(certfile=namespace.tls_server_certificate, keyfile=namespace.tls_server_key)
ssl_context.set_alpn_protocols(["coap"])
if hasattr(ssl_context, 'sni_callback'): # starting python 3.7
ssl_context.sni_callback = lambda obj, name, context: setattr(obj, "indicated_server_name", name)
else:
ssl_context = None
if namespace.credentials:
server_credentials = CredentialsMap()
server_credentials.load_from_dict(json.load(namespace.credentials.open('rb')))
# FIXME: could be non-OSCORE as well -- can we build oscore_sitewrapper
# in such a way it only depends on the OSCORE dependencies if there are
# actual identities present?
from aiocoap.oscore_sitewrapper import OscoreSiteWrapper
site = OscoreSiteWrapper(site, server_credentials)
else:
server_credentials = None
return await Context.create_server_context(site, namespace.bind, _ssl_context=ssl_context, server_credentials=server_credentials, **kwargs)
|
en
| 0.641763
|
#!/usr/bin/env python3 # This file is part of the Python aiocoap library project. # # Copyright (c) 2012-2014 <NAME> <http://sixpinetrees.blogspot.com/>, # 2013-2014 <NAME> <<EMAIL>> # # aiocoap is free software, this file is published under the MIT license as # described in the accompanying LICENSE file. Common options of aiocoap command line utilities Unlike those in :mod:`aiocoap.util.cli`, these are particular to aiocoap functionality. Typical use is like this:: >>> p = argparse.ArgumentParser() >>> p.add_argument('--foo') # doctest: +ELLIPSIS _... >>> add_server_arguments(p) >>> opts = p.parse_args(['--bind', '[::1]:56830', '--foo=bar']) You can then either pass opts directly to :func:`server_context_from_arguments`, or split up the arguments:: >>> server_opts = extract_server_arguments(opts) >>> opts Namespace(foo='bar') Then, server_opts can be passed to `server_context_from_arguments`. Add the --bind option to an argparse parser Wrapper around hostportsplit that gives better error messages than 'invalid hostportsplit value' # These are to be eventually migrated into credentials Given the output of .parse() on a ArgumentParser that had add_server_arguments called with it, remove the resulting option in-place from namespace and return them in a separate namespace. Create a bound context like :meth:`.aiocoap.Context.create_server_context`, but take the bind and TLS settings from a namespace returned from an argparse parser that has had :func:`add_server_arguments` run on it. # starting python 3.7 # FIXME: could be non-OSCORE as well -- can we build oscore_sitewrapper # in such a way it only depends on the OSCORE dependencies if there are # actual identities present?
| 2.408286
| 2
|
Deployment/ConsumerServices/GeneralService.py
|
Caius-Lu/Savior
| 0
|
6626281
|
<reponame>Caius-Lu/Savior
from Deployment.ConsumerWorker import celery_worker_app
from Deployment.server_config import IS_TEST
from Operators.ExampleDownloadOperator import ImageDownloadOperator
from Utils.ServiceUtils import ServiceTask
from Utils.Storage import get_oss_handler
image_download_op = ImageDownloadOperator(IS_TEST)
@celery_worker_app.task(name="ConsumerServices.GeneralService.download_image_from_url")
def download_image_from_url(_image_url):
oss_helper = get_oss_handler()
download_result = image_download_op.execute(_image_url, oss_helper, _image_size_threshold=None)
return {
'image_info': {
'bucket_name': download_result['bucket_name'],
'path': download_result['saved_path'],
'height': download_result['image_height'],
'width': download_result['image_width'],
'channel': download_result['image_channel'],
},
}
class DownloadImageFromURLServiceTask(ServiceTask):
service_version = 'v1.0.20210317'
service_name = 'download_image_from_url'
mock_result = {
'image_info': {
'bucket_name': '',
'path': '',
},
}
require_field = {
"_image_url",
}
binding_service = download_image_from_url
|
from Deployment.ConsumerWorker import celery_worker_app
from Deployment.server_config import IS_TEST
from Operators.ExampleDownloadOperator import ImageDownloadOperator
from Utils.ServiceUtils import ServiceTask
from Utils.Storage import get_oss_handler
image_download_op = ImageDownloadOperator(IS_TEST)
@celery_worker_app.task(name="ConsumerServices.GeneralService.download_image_from_url")
def download_image_from_url(_image_url):
oss_helper = get_oss_handler()
download_result = image_download_op.execute(_image_url, oss_helper, _image_size_threshold=None)
return {
'image_info': {
'bucket_name': download_result['bucket_name'],
'path': download_result['saved_path'],
'height': download_result['image_height'],
'width': download_result['image_width'],
'channel': download_result['image_channel'],
},
}
class DownloadImageFromURLServiceTask(ServiceTask):
service_version = 'v1.0.20210317'
service_name = 'download_image_from_url'
mock_result = {
'image_info': {
'bucket_name': '',
'path': '',
},
}
require_field = {
"_image_url",
}
binding_service = download_image_from_url
|
none
| 1
| 2.073953
| 2
|
|
Python3/1040.py
|
rakhi2001/ecom7
| 854
|
6626282
|
<reponame>rakhi2001/ecom7
__________________________________________________________________________________________________
sample 116 ms submission
class Solution:
def numMovesStonesII(self, stones):
# window width
st, ww = sorted(stones), len(stones)
# core width
i, coreb, coree, maxc = 0, 0, 0, 0
for j in range(ww):
while st[j] - st[i] >= ww:
i += 1
if j - i + 1 > maxc:
coreb, coree, maxc = st[i], st[j], j - i + 1
# min
mini = ww - maxc + (1 if coree - coreb + 1 == maxc and maxc == ww - 1 and (coreb - 2 not in stones and coree + 2 not in stones) else 0)
# max
maxi = max(st[-2] - st[0] + 2 - ww, st[-1] - st[1] + 2 - ww)
return [mini, maxi]
__________________________________________________________________________________________________
sample 120 ms submission
class Solution:
def numMovesStonesII(self, stones: List[int]) -> List[int]:
stones.sort()
n, low, leng = 0, len(stones), len(stones)
high = max(stones[-1]-stones[1]-leng+2, stones[-2]-stones[0]-leng+2)
for i in range(leng):
while stones[i]-stones[n]+1 > leng:
n += 1
if i-n+1==leng-1 and stones[i]-stones[n]+1==leng-1:
low = min(low, 2)
else:
low = min(low,leng-i+n-1)
return [low, high]
__________________________________________________________________________________________________
|
__________________________________________________________________________________________________
sample 116 ms submission
class Solution:
def numMovesStonesII(self, stones):
# window width
st, ww = sorted(stones), len(stones)
# core width
i, coreb, coree, maxc = 0, 0, 0, 0
for j in range(ww):
while st[j] - st[i] >= ww:
i += 1
if j - i + 1 > maxc:
coreb, coree, maxc = st[i], st[j], j - i + 1
# min
mini = ww - maxc + (1 if coree - coreb + 1 == maxc and maxc == ww - 1 and (coreb - 2 not in stones and coree + 2 not in stones) else 0)
# max
maxi = max(st[-2] - st[0] + 2 - ww, st[-1] - st[1] + 2 - ww)
return [mini, maxi]
__________________________________________________________________________________________________
sample 120 ms submission
class Solution:
def numMovesStonesII(self, stones: List[int]) -> List[int]:
stones.sort()
n, low, leng = 0, len(stones), len(stones)
high = max(stones[-1]-stones[1]-leng+2, stones[-2]-stones[0]-leng+2)
for i in range(leng):
while stones[i]-stones[n]+1 > leng:
n += 1
if i-n+1==leng-1 and stones[i]-stones[n]+1==leng-1:
low = min(low, 2)
else:
low = min(low,leng-i+n-1)
return [low, high]
__________________________________________________________________________________________________
|
en
| 0.324922
|
# window width # core width # min # max
| 2.814479
| 3
|
fhirclient/models/schedule.py
|
JamesSkane/smart_resources
| 0
|
6626283
|
<gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 0.5.0.5149 (http://hl7.org/fhir/StructureDefinition/Schedule) on 2015-07-06.
# 2015, SMART Health IT.
from . import codeableconcept
from . import domainresource
from . import fhirreference
from . import identifier
from . import period
class Schedule(domainresource.DomainResource):
""" A container for slot(s) of time that may be available for booking
appointments.
"""
resource_name = "Schedule"
def __init__(self, jsondict=None):
""" Initialize all valid properties.
"""
self.actor = None
""" The resource this Schedule resource is providing availability
information for. These are expected to usually be one of
HealthcareService, Location, Practitioner, Device, Patient or
RelatedPerson.
Type `FHIRReference` referencing `Resource` (represented as `dict` in JSON). """
self.comment = None
""" Comments on the availability to describe any extended information.
Such as custom constraints on the slot(s) that may be associated.
Type `str`. """
self.identifier = None
""" External Ids for this item.
List of `Identifier` items (represented as `dict` in JSON). """
self.planningHorizon = None
""" The period of time that the slots that are attached to this
Schedule resource cover (even if none exist). These cover the
amount of time that an organization's planning horizon; the
interval for which they are currently accepting appointments. This
does not define a "template" for planning outside these dates.
Type `Period` (represented as `dict` in JSON). """
self.type = None
""" The schedule type can be used for the categorization of healthcare
services or other appointment types.
List of `CodeableConcept` items (represented as `dict` in JSON). """
super(Schedule, self).__init__(jsondict)
def elementProperties(self):
js = super(Schedule, self).elementProperties()
js.extend([
("actor", "actor", fhirreference.FHIRReference, False),
("comment", "comment", str, False),
("identifier", "identifier", identifier.Identifier, True),
("planningHorizon", "planningHorizon", period.Period, False),
("type", "type", codeableconcept.CodeableConcept, True),
])
return js
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 0.5.0.5149 (http://hl7.org/fhir/StructureDefinition/Schedule) on 2015-07-06.
# 2015, SMART Health IT.
from . import codeableconcept
from . import domainresource
from . import fhirreference
from . import identifier
from . import period
class Schedule(domainresource.DomainResource):
""" A container for slot(s) of time that may be available for booking
appointments.
"""
resource_name = "Schedule"
def __init__(self, jsondict=None):
""" Initialize all valid properties.
"""
self.actor = None
""" The resource this Schedule resource is providing availability
information for. These are expected to usually be one of
HealthcareService, Location, Practitioner, Device, Patient or
RelatedPerson.
Type `FHIRReference` referencing `Resource` (represented as `dict` in JSON). """
self.comment = None
""" Comments on the availability to describe any extended information.
Such as custom constraints on the slot(s) that may be associated.
Type `str`. """
self.identifier = None
""" External Ids for this item.
List of `Identifier` items (represented as `dict` in JSON). """
self.planningHorizon = None
""" The period of time that the slots that are attached to this
Schedule resource cover (even if none exist). These cover the
amount of time that an organization's planning horizon; the
interval for which they are currently accepting appointments. This
does not define a "template" for planning outside these dates.
Type `Period` (represented as `dict` in JSON). """
self.type = None
""" The schedule type can be used for the categorization of healthcare
services or other appointment types.
List of `CodeableConcept` items (represented as `dict` in JSON). """
super(Schedule, self).__init__(jsondict)
def elementProperties(self):
js = super(Schedule, self).elementProperties()
js.extend([
("actor", "actor", fhirreference.FHIRReference, False),
("comment", "comment", str, False),
("identifier", "identifier", identifier.Identifier, True),
("planningHorizon", "planningHorizon", period.Period, False),
("type", "type", codeableconcept.CodeableConcept, True),
])
return js
|
en
| 0.863339
|
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 0.5.0.5149 (http://hl7.org/fhir/StructureDefinition/Schedule) on 2015-07-06. # 2015, SMART Health IT. A container for slot(s) of time that may be available for booking appointments. Initialize all valid properties. The resource this Schedule resource is providing availability information for. These are expected to usually be one of HealthcareService, Location, Practitioner, Device, Patient or RelatedPerson. Type `FHIRReference` referencing `Resource` (represented as `dict` in JSON). Comments on the availability to describe any extended information. Such as custom constraints on the slot(s) that may be associated. Type `str`. External Ids for this item. List of `Identifier` items (represented as `dict` in JSON). The period of time that the slots that are attached to this Schedule resource cover (even if none exist). These cover the amount of time that an organization's planning horizon; the interval for which they are currently accepting appointments. This does not define a "template" for planning outside these dates. Type `Period` (represented as `dict` in JSON). The schedule type can be used for the categorization of healthcare services or other appointment types. List of `CodeableConcept` items (represented as `dict` in JSON).
| 2.332278
| 2
|
src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_archive_utils.py
|
mattgillard/azure-cli
| 0
|
6626284
|
<reponame>mattgillard/azure-cli<filename>src/command_modules/azure-cli-acr/azure/cli/command_modules/acr/_archive_utils.py<gh_stars>0
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import tarfile
import os
import re
import codecs
from io import open
import requests
from knack.log import get_logger
from knack.util import CLIError
from msrestazure.azure_exceptions import CloudError
from azure.storage.blob import BlockBlobService
from ._azure_utils import get_blob_info
from ._constants import TASK_VALID_VSTS_URLS
logger = get_logger(__name__)
def upload_source_code(client,
registry_name,
resource_group_name,
source_location,
tar_file_path,
docker_file_path,
docker_file_in_tar):
_pack_source_code(source_location,
tar_file_path,
docker_file_path,
docker_file_in_tar)
size = os.path.getsize(tar_file_path)
unit = 'GiB'
for S in ['Bytes', 'KiB', 'MiB', 'GiB']:
if size < 1024:
unit = S
break
size = size / 1024.0
logger.warning("Uploading archived source code from '%s'...", tar_file_path)
upload_url = None
relative_path = None
error_message = "Could not get SAS URL to upload."
try:
source_upload_location = client.get_build_source_upload_url(
resource_group_name, registry_name)
upload_url = source_upload_location.upload_url
relative_path = source_upload_location.relative_path
except (AttributeError, CloudError) as e:
logger.debug("%s Exception: %s", error_message, e)
raise CLIError(error_message)
if not upload_url:
logger.debug("%s Empty source upload URL.", error_message)
raise CLIError(error_message)
account_name, endpoint_suffix, container_name, blob_name, sas_token = get_blob_info(upload_url)
BlockBlobService(account_name=account_name,
sas_token=sas_token,
endpoint_suffix=endpoint_suffix).create_blob_from_path(
container_name=container_name,
blob_name=blob_name,
file_path=tar_file_path)
logger.warning("Sending context ({0:.3f} {1}) to registry: {2}...".format(
size, unit, registry_name))
return relative_path
def _pack_source_code(source_location, tar_file_path, docker_file_path, docker_file_in_tar):
logger.warning("Packing source code into tar to upload...")
ignore_list, ignore_list_size = _load_dockerignore_file(source_location)
common_vcs_ignore_list = {'.git', '.gitignore', '.bzr', 'bzrignore', '.hg', '.hgignore', '.svn'}
def _ignore_check(tarinfo, parent_ignored, parent_matching_rule_index):
# ignore common vcs dir or file
if tarinfo.name in common_vcs_ignore_list:
logger.warning("Excluding '%s' based on default ignore rules", tarinfo.name)
return True, parent_matching_rule_index
if ignore_list is None:
# if .dockerignore doesn't exists, inherit from parent
# eg, it will ignore the files under .git folder.
return parent_ignored, parent_matching_rule_index
for index, item in enumerate(ignore_list):
# stop checking the remaining rules whose priorities are lower than the parent matching rule
# at this point, current item should just inherit from parent
if index >= parent_matching_rule_index:
break
if re.match(item.pattern, tarinfo.name):
logger.debug(".dockerignore: rule '%s' matches '%s'.",
item.rule, tarinfo.name)
return item.ignore, index
logger.debug(".dockerignore: no rule for '%s'. parent ignore '%s'",
tarinfo.name, parent_ignored)
# inherit from parent
return parent_ignored, parent_matching_rule_index
with tarfile.open(tar_file_path, "w:gz") as tar:
# need to set arcname to empty string as the archive root path
_archive_file_recursively(tar,
source_location,
arcname="",
parent_ignored=False,
parent_matching_rule_index=ignore_list_size,
ignore_check=_ignore_check)
# Add the Dockerfile if it's specified.
# In the case of run, there will be no Dockerfile.
if docker_file_path:
docker_file_tarinfo = tar.gettarinfo(
docker_file_path, docker_file_in_tar)
with open(docker_file_path, "rb") as f:
tar.addfile(docker_file_tarinfo, f)
class IgnoreRule(object): # pylint: disable=too-few-public-methods
def __init__(self, rule):
self.rule = rule
self.ignore = True
# ! makes exceptions to exclusions
if rule.startswith('!'):
self.ignore = False
rule = rule[1:] # remove !
self.pattern = "^"
tokens = rule.split('/')
token_length = len(tokens)
for index, token in enumerate(tokens, 1):
# ** matches any number of directories
if token == "**":
self.pattern += ".*" # treat **/ as **
else:
# * matches any sequence of non-seperator characters
# ? matches any single non-seperator character
# . matches dot character
self.pattern += token.replace(
"*", "[^/]*").replace("?", "[^/]").replace(".", "\\.")
if index < token_length:
self.pattern += "/" # add back / if it's not the last
self.pattern += "$"
def _load_dockerignore_file(source_location):
# reference: https://docs.docker.com/engine/reference/builder/#dockerignore-file
docker_ignore_file = os.path.join(source_location, ".dockerignore")
if not os.path.exists(docker_ignore_file):
return None, 0
encoding = "utf-8"
header = open(docker_ignore_file, "rb").read(len(codecs.BOM_UTF8))
if header.startswith(codecs.BOM_UTF8):
encoding = "utf-8-sig"
ignore_list = []
for line in open(docker_ignore_file, 'r', encoding=encoding).readlines():
rule = line.rstrip()
# skip empty line and comment
if not rule or rule.startswith('#'):
continue
# the ignore rule at the end has higher priority
ignore_list = [IgnoreRule(rule)] + ignore_list
return ignore_list, len(ignore_list)
def _archive_file_recursively(tar, name, arcname, parent_ignored, parent_matching_rule_index, ignore_check):
# create a TarInfo object from the file
tarinfo = tar.gettarinfo(name, arcname)
if tarinfo is None:
raise CLIError("tarfile: unsupported type {}".format(name))
# check if the file/dir is ignored
ignored, matching_rule_index = ignore_check(
tarinfo, parent_ignored, parent_matching_rule_index)
if not ignored:
# append the tar header and data to the archive
if tarinfo.isreg():
with open(name, "rb") as f:
tar.addfile(tarinfo, f)
else:
tar.addfile(tarinfo)
# even the dir is ignored, its child items can still be included, so continue to scan
if tarinfo.isdir():
for f in os.listdir(name):
_archive_file_recursively(tar, os.path.join(name, f), os.path.join(arcname, f),
parent_ignored=ignored, parent_matching_rule_index=matching_rule_index,
ignore_check=ignore_check)
def check_remote_source_code(source_location):
lower_source_location = source_location.lower()
# git
if lower_source_location.startswith("git@") or lower_source_location.startswith("git://"):
return source_location
# http
if lower_source_location.startswith("https://") or lower_source_location.startswith("http://") \
or lower_source_location.startswith("github.com/"):
isVSTS = any(url in lower_source_location for url in TASK_VALID_VSTS_URLS)
if isVSTS or re.search(r"\.git(?:#.+)?$", lower_source_location):
# git url must contain ".git" or be from VSTS/Azure DevOps.
# This is because Azure DevOps doesn't follow the standard git server convention of putting
# .git at the end of their URLs, so we have to special case them.
return source_location
elif not lower_source_location.startswith("github.com/"):
# Others are tarball
if requests.head(source_location).status_code < 400:
return source_location
else:
raise CLIError("'{}' doesn't exist.".format(source_location))
raise CLIError(
"'{}' is not a valid remote URL for git or tarball.".format(source_location))
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
import tarfile
import os
import re
import codecs
from io import open
import requests
from knack.log import get_logger
from knack.util import CLIError
from msrestazure.azure_exceptions import CloudError
from azure.storage.blob import BlockBlobService
from ._azure_utils import get_blob_info
from ._constants import TASK_VALID_VSTS_URLS
logger = get_logger(__name__)
def upload_source_code(client,
registry_name,
resource_group_name,
source_location,
tar_file_path,
docker_file_path,
docker_file_in_tar):
_pack_source_code(source_location,
tar_file_path,
docker_file_path,
docker_file_in_tar)
size = os.path.getsize(tar_file_path)
unit = 'GiB'
for S in ['Bytes', 'KiB', 'MiB', 'GiB']:
if size < 1024:
unit = S
break
size = size / 1024.0
logger.warning("Uploading archived source code from '%s'...", tar_file_path)
upload_url = None
relative_path = None
error_message = "Could not get SAS URL to upload."
try:
source_upload_location = client.get_build_source_upload_url(
resource_group_name, registry_name)
upload_url = source_upload_location.upload_url
relative_path = source_upload_location.relative_path
except (AttributeError, CloudError) as e:
logger.debug("%s Exception: %s", error_message, e)
raise CLIError(error_message)
if not upload_url:
logger.debug("%s Empty source upload URL.", error_message)
raise CLIError(error_message)
account_name, endpoint_suffix, container_name, blob_name, sas_token = get_blob_info(upload_url)
BlockBlobService(account_name=account_name,
sas_token=sas_token,
endpoint_suffix=endpoint_suffix).create_blob_from_path(
container_name=container_name,
blob_name=blob_name,
file_path=tar_file_path)
logger.warning("Sending context ({0:.3f} {1}) to registry: {2}...".format(
size, unit, registry_name))
return relative_path
def _pack_source_code(source_location, tar_file_path, docker_file_path, docker_file_in_tar):
logger.warning("Packing source code into tar to upload...")
ignore_list, ignore_list_size = _load_dockerignore_file(source_location)
common_vcs_ignore_list = {'.git', '.gitignore', '.bzr', 'bzrignore', '.hg', '.hgignore', '.svn'}
def _ignore_check(tarinfo, parent_ignored, parent_matching_rule_index):
# ignore common vcs dir or file
if tarinfo.name in common_vcs_ignore_list:
logger.warning("Excluding '%s' based on default ignore rules", tarinfo.name)
return True, parent_matching_rule_index
if ignore_list is None:
# if .dockerignore doesn't exists, inherit from parent
# eg, it will ignore the files under .git folder.
return parent_ignored, parent_matching_rule_index
for index, item in enumerate(ignore_list):
# stop checking the remaining rules whose priorities are lower than the parent matching rule
# at this point, current item should just inherit from parent
if index >= parent_matching_rule_index:
break
if re.match(item.pattern, tarinfo.name):
logger.debug(".dockerignore: rule '%s' matches '%s'.",
item.rule, tarinfo.name)
return item.ignore, index
logger.debug(".dockerignore: no rule for '%s'. parent ignore '%s'",
tarinfo.name, parent_ignored)
# inherit from parent
return parent_ignored, parent_matching_rule_index
with tarfile.open(tar_file_path, "w:gz") as tar:
# need to set arcname to empty string as the archive root path
_archive_file_recursively(tar,
source_location,
arcname="",
parent_ignored=False,
parent_matching_rule_index=ignore_list_size,
ignore_check=_ignore_check)
# Add the Dockerfile if it's specified.
# In the case of run, there will be no Dockerfile.
if docker_file_path:
docker_file_tarinfo = tar.gettarinfo(
docker_file_path, docker_file_in_tar)
with open(docker_file_path, "rb") as f:
tar.addfile(docker_file_tarinfo, f)
class IgnoreRule(object): # pylint: disable=too-few-public-methods
def __init__(self, rule):
self.rule = rule
self.ignore = True
# ! makes exceptions to exclusions
if rule.startswith('!'):
self.ignore = False
rule = rule[1:] # remove !
self.pattern = "^"
tokens = rule.split('/')
token_length = len(tokens)
for index, token in enumerate(tokens, 1):
# ** matches any number of directories
if token == "**":
self.pattern += ".*" # treat **/ as **
else:
# * matches any sequence of non-seperator characters
# ? matches any single non-seperator character
# . matches dot character
self.pattern += token.replace(
"*", "[^/]*").replace("?", "[^/]").replace(".", "\\.")
if index < token_length:
self.pattern += "/" # add back / if it's not the last
self.pattern += "$"
def _load_dockerignore_file(source_location):
# reference: https://docs.docker.com/engine/reference/builder/#dockerignore-file
docker_ignore_file = os.path.join(source_location, ".dockerignore")
if not os.path.exists(docker_ignore_file):
return None, 0
encoding = "utf-8"
header = open(docker_ignore_file, "rb").read(len(codecs.BOM_UTF8))
if header.startswith(codecs.BOM_UTF8):
encoding = "utf-8-sig"
ignore_list = []
for line in open(docker_ignore_file, 'r', encoding=encoding).readlines():
rule = line.rstrip()
# skip empty line and comment
if not rule or rule.startswith('#'):
continue
# the ignore rule at the end has higher priority
ignore_list = [IgnoreRule(rule)] + ignore_list
return ignore_list, len(ignore_list)
def _archive_file_recursively(tar, name, arcname, parent_ignored, parent_matching_rule_index, ignore_check):
# create a TarInfo object from the file
tarinfo = tar.gettarinfo(name, arcname)
if tarinfo is None:
raise CLIError("tarfile: unsupported type {}".format(name))
# check if the file/dir is ignored
ignored, matching_rule_index = ignore_check(
tarinfo, parent_ignored, parent_matching_rule_index)
if not ignored:
# append the tar header and data to the archive
if tarinfo.isreg():
with open(name, "rb") as f:
tar.addfile(tarinfo, f)
else:
tar.addfile(tarinfo)
# even the dir is ignored, its child items can still be included, so continue to scan
if tarinfo.isdir():
for f in os.listdir(name):
_archive_file_recursively(tar, os.path.join(name, f), os.path.join(arcname, f),
parent_ignored=ignored, parent_matching_rule_index=matching_rule_index,
ignore_check=ignore_check)
def check_remote_source_code(source_location):
lower_source_location = source_location.lower()
# git
if lower_source_location.startswith("git@") or lower_source_location.startswith("git://"):
return source_location
# http
if lower_source_location.startswith("https://") or lower_source_location.startswith("http://") \
or lower_source_location.startswith("github.com/"):
isVSTS = any(url in lower_source_location for url in TASK_VALID_VSTS_URLS)
if isVSTS or re.search(r"\.git(?:#.+)?$", lower_source_location):
# git url must contain ".git" or be from VSTS/Azure DevOps.
# This is because Azure DevOps doesn't follow the standard git server convention of putting
# .git at the end of their URLs, so we have to special case them.
return source_location
elif not lower_source_location.startswith("github.com/"):
# Others are tarball
if requests.head(source_location).status_code < 400:
return source_location
else:
raise CLIError("'{}' doesn't exist.".format(source_location))
raise CLIError(
"'{}' is not a valid remote URL for git or tarball.".format(source_location))
|
en
| 0.778475
|
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- # ignore common vcs dir or file # if .dockerignore doesn't exists, inherit from parent # eg, it will ignore the files under .git folder. # stop checking the remaining rules whose priorities are lower than the parent matching rule # at this point, current item should just inherit from parent # inherit from parent # need to set arcname to empty string as the archive root path # Add the Dockerfile if it's specified. # In the case of run, there will be no Dockerfile. # pylint: disable=too-few-public-methods # ! makes exceptions to exclusions # remove ! # ** matches any number of directories # treat **/ as ** # * matches any sequence of non-seperator characters # ? matches any single non-seperator character # . matches dot character # add back / if it's not the last # reference: https://docs.docker.com/engine/reference/builder/#dockerignore-file # skip empty line and comment # the ignore rule at the end has higher priority # create a TarInfo object from the file # check if the file/dir is ignored # append the tar header and data to the archive # even the dir is ignored, its child items can still be included, so continue to scan # git # http #.+)?$", lower_source_location): # git url must contain ".git" or be from VSTS/Azure DevOps. # This is because Azure DevOps doesn't follow the standard git server convention of putting # .git at the end of their URLs, so we have to special case them. # Others are tarball
| 1.941963
| 2
|
src/phoebe_shelves_clt/configure.py
|
anthony-agbay/owl_shelves_clt
| 1
|
6626285
|
""" Methods to read/write a configuration file.
This module provides methods for reading in a configuration file and saving
and updated configuration file to a given path using the configparser package.
"""
import os
import configparser
def create_configs(config_path: str) -> configparser.ConfigParser:
""" Initialize configuration file
Initializes the configuration file with default values for each
configurable property.
Args:
config_path: Path to configuration file
Returns:
configs: Script configurations
Todo:
* Implement additional SQL configurations
* Implement more generalized default data directory
"""
configs = configparser.ConfigParser()
# TODO: Have more generalized default data directory
configs["GENERAL"] = {"backend": "csv",
"data_directory": "data"}
configs["SQL"] = {"database": "phoebeshelves",
"user": "postgres",
"host": "localhost"}
with open(config_path, 'w') as config_file:
configs.write(config_file)
return(configs)
def read_configs(config_path: str) -> configparser.ConfigParser:
""" Read in a configuration file from a location.
Read in the configurations from the config.cfg file from the given
location.
Args:
config_path: Path to configuration file location
Outputs:
configs: Script configurations
"""
if not os.path.isfile(config_path):
configs = create_configs(config_path)
else:
configs = configparser.ConfigParser()
configs.read(config_path)
return(configs)
def print_configs(configs: configparser.ConfigParser):
""" Print out all config properties
Print out each section and its configuration properties for inspection on
the command-line.
Args:
configs: Script configurations
"""
for section in configs.sections():
print(section)
for prop, val in configs.items(section):
print(f"{prop}: {val}")
print("")
def update_config(config_path: str, configs: configparser.ConfigParser,
config_name: str, new_val: str):
""" Updates a configurable property to a new value
Update a configurable property to the user-provided value. This function
will also save the updated configurations to the file as well as return
the updated configurations for additional use, if needed.
Args:
config_path: Path to the config.cfg file
configs: Old script configurations
config_name: Configuration property to update
new_val: New value of the configuration property
Returns:
configs: Updated script configurations
"""
if config_name in {"backend", "data_directory"}:
section = "GENERAL"
else:
section = "SQL"
configs[section][config_name] = new_val
with open(config_path, "w") as config_file:
configs.write(config_file)
return(configs)
|
""" Methods to read/write a configuration file.
This module provides methods for reading in a configuration file and saving
and updated configuration file to a given path using the configparser package.
"""
import os
import configparser
def create_configs(config_path: str) -> configparser.ConfigParser:
""" Initialize configuration file
Initializes the configuration file with default values for each
configurable property.
Args:
config_path: Path to configuration file
Returns:
configs: Script configurations
Todo:
* Implement additional SQL configurations
* Implement more generalized default data directory
"""
configs = configparser.ConfigParser()
# TODO: Have more generalized default data directory
configs["GENERAL"] = {"backend": "csv",
"data_directory": "data"}
configs["SQL"] = {"database": "phoebeshelves",
"user": "postgres",
"host": "localhost"}
with open(config_path, 'w') as config_file:
configs.write(config_file)
return(configs)
def read_configs(config_path: str) -> configparser.ConfigParser:
""" Read in a configuration file from a location.
Read in the configurations from the config.cfg file from the given
location.
Args:
config_path: Path to configuration file location
Outputs:
configs: Script configurations
"""
if not os.path.isfile(config_path):
configs = create_configs(config_path)
else:
configs = configparser.ConfigParser()
configs.read(config_path)
return(configs)
def print_configs(configs: configparser.ConfigParser):
""" Print out all config properties
Print out each section and its configuration properties for inspection on
the command-line.
Args:
configs: Script configurations
"""
for section in configs.sections():
print(section)
for prop, val in configs.items(section):
print(f"{prop}: {val}")
print("")
def update_config(config_path: str, configs: configparser.ConfigParser,
config_name: str, new_val: str):
""" Updates a configurable property to a new value
Update a configurable property to the user-provided value. This function
will also save the updated configurations to the file as well as return
the updated configurations for additional use, if needed.
Args:
config_path: Path to the config.cfg file
configs: Old script configurations
config_name: Configuration property to update
new_val: New value of the configuration property
Returns:
configs: Updated script configurations
"""
if config_name in {"backend", "data_directory"}:
section = "GENERAL"
else:
section = "SQL"
configs[section][config_name] = new_val
with open(config_path, "w") as config_file:
configs.write(config_file)
return(configs)
|
en
| 0.711073
|
Methods to read/write a configuration file. This module provides methods for reading in a configuration file and saving and updated configuration file to a given path using the configparser package. Initialize configuration file Initializes the configuration file with default values for each configurable property. Args: config_path: Path to configuration file Returns: configs: Script configurations Todo: * Implement additional SQL configurations * Implement more generalized default data directory # TODO: Have more generalized default data directory Read in a configuration file from a location. Read in the configurations from the config.cfg file from the given location. Args: config_path: Path to configuration file location Outputs: configs: Script configurations Print out all config properties Print out each section and its configuration properties for inspection on the command-line. Args: configs: Script configurations Updates a configurable property to a new value Update a configurable property to the user-provided value. This function will also save the updated configurations to the file as well as return the updated configurations for additional use, if needed. Args: config_path: Path to the config.cfg file configs: Old script configurations config_name: Configuration property to update new_val: New value of the configuration property Returns: configs: Updated script configurations
| 3.970023
| 4
|
gulpy/inputs/__init__.py
|
learningmatter-mit/gulpy
| 1
|
6626286
|
from .library import Library, LibraryLabels
from .writer import FileWriter, InputWriter
|
from .library import Library, LibraryLabels
from .writer import FileWriter, InputWriter
|
none
| 1
| 1.041881
| 1
|
|
Notice/apps/lottery/models.py
|
Winspain/EasyNotice
| 1
|
6626287
|
from django.db import models
# Create your models here.
class LotteryInfo(models.Model):
drawNum = models.CharField(unique=True, max_length=50, verbose_name='开奖期号')
drawResult = models.CharField(max_length=100, verbose_name='开奖结果')
drawTime = models.DateField(verbose_name='开奖日期')
state = models.CharField(max_length=100)
isDeleted = models.BooleanField()
createdBy = models.CharField(max_length=100)
updateBy = models.CharField(max_length=100)
createdTime = models.DateTimeField(auto_now_add=True)
updateTime = models.DateTimeField(null=True)
class Meta:
db_table = 'lottery_info'
class MyLotteryInfo(models.Model):
selectNum = models.CharField(max_length=100, verbose_name='开奖结果')
state = models.CharField(max_length=100)
isDeleted = models.BooleanField()
createdBy = models.CharField(max_length=100)
updateBy = models.CharField(max_length=100)
createdTime = models.DateTimeField(auto_now_add=True)
updateTime = models.DateTimeField(null=True)
class Meta:
db_table = 'lottery_select'
|
from django.db import models
# Create your models here.
class LotteryInfo(models.Model):
drawNum = models.CharField(unique=True, max_length=50, verbose_name='开奖期号')
drawResult = models.CharField(max_length=100, verbose_name='开奖结果')
drawTime = models.DateField(verbose_name='开奖日期')
state = models.CharField(max_length=100)
isDeleted = models.BooleanField()
createdBy = models.CharField(max_length=100)
updateBy = models.CharField(max_length=100)
createdTime = models.DateTimeField(auto_now_add=True)
updateTime = models.DateTimeField(null=True)
class Meta:
db_table = 'lottery_info'
class MyLotteryInfo(models.Model):
selectNum = models.CharField(max_length=100, verbose_name='开奖结果')
state = models.CharField(max_length=100)
isDeleted = models.BooleanField()
createdBy = models.CharField(max_length=100)
updateBy = models.CharField(max_length=100)
createdTime = models.DateTimeField(auto_now_add=True)
updateTime = models.DateTimeField(null=True)
class Meta:
db_table = 'lottery_select'
|
en
| 0.963489
|
# Create your models here.
| 2.315398
| 2
|
tests/test_parser.py
|
vasechko-sergey/jsonpath-ng
| 0
|
6626288
|
import pytest
from jsonpath_ng import Child, Descendants, Fields, Index, Slice, Where
from jsonpath_ng.lexer import JsonPathLexer
from jsonpath_ng.parser import JsonPathParser
def check_parse_case(string, parsed):
parser = JsonPathParser(
debug=True, lexer_class=lambda: JsonPathLexer(debug=False)
) # Note that just manually passing token streams avoids this dep, but that sucks
assert parser.parse(string) == parsed
@pytest.mark.parametrize('string, parsed', [
('foo', Fields('foo')),
('*', Fields('*')),
('baz,bizzle', Fields('baz', 'bizzle')),
('[1]', Index(1)),
('[1:]', Slice(start=1)),
('[:]', Slice()),
('[*]', Slice()),
('[:2]', Slice(end=2)),
('[1:2]', Slice(start=1, end=2)),
('[5:-2]', Slice(start=5, end=-2))
])
def test_atomic(string, parsed):
check_parse_case(string, parsed)
@pytest.mark.parametrize('string, parsed', [
('foo.baz', Child(Fields('foo'), Fields('baz'))),
('foo.baz,bizzle', Child(Fields('foo'), Fields('baz', 'bizzle'))),
('foo where baz', Where(Fields('foo'), Fields('baz'))),
('foo..baz', Descendants(Fields('foo'), Fields('baz'))),
('foo..baz.bing', Descendants(Fields('foo'), Child(Fields('baz'), Fields('bing'))))
])
def test_nested(string, parsed):
check_parse_case(string, parsed)
|
import pytest
from jsonpath_ng import Child, Descendants, Fields, Index, Slice, Where
from jsonpath_ng.lexer import JsonPathLexer
from jsonpath_ng.parser import JsonPathParser
def check_parse_case(string, parsed):
parser = JsonPathParser(
debug=True, lexer_class=lambda: JsonPathLexer(debug=False)
) # Note that just manually passing token streams avoids this dep, but that sucks
assert parser.parse(string) == parsed
@pytest.mark.parametrize('string, parsed', [
('foo', Fields('foo')),
('*', Fields('*')),
('baz,bizzle', Fields('baz', 'bizzle')),
('[1]', Index(1)),
('[1:]', Slice(start=1)),
('[:]', Slice()),
('[*]', Slice()),
('[:2]', Slice(end=2)),
('[1:2]', Slice(start=1, end=2)),
('[5:-2]', Slice(start=5, end=-2))
])
def test_atomic(string, parsed):
check_parse_case(string, parsed)
@pytest.mark.parametrize('string, parsed', [
('foo.baz', Child(Fields('foo'), Fields('baz'))),
('foo.baz,bizzle', Child(Fields('foo'), Fields('baz', 'bizzle'))),
('foo where baz', Where(Fields('foo'), Fields('baz'))),
('foo..baz', Descendants(Fields('foo'), Fields('baz'))),
('foo..baz.bing', Descendants(Fields('foo'), Child(Fields('baz'), Fields('bing'))))
])
def test_nested(string, parsed):
check_parse_case(string, parsed)
|
en
| 0.865058
|
# Note that just manually passing token streams avoids this dep, but that sucks
| 2.415242
| 2
|
tests/cmdline/commands/test_process.py
|
mkrack/aiida-core
| 0
|
6626289
|
<filename>tests/cmdline/commands/test_process.py
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
"""Tests for `verdi process`."""
import asyncio
from concurrent.futures import Future
import time
import kiwipy
import plumpy
import pytest
from aiida import get_profile
from aiida.cmdline.commands import cmd_process
from aiida.common.links import LinkType
from aiida.common.log import LOG_LEVEL_REPORT
from aiida.orm import CalcJobNode, WorkChainNode, WorkflowNode, WorkFunctionNode
from tests.utils import processes as test_processes
def get_result_lines(result):
return [e for e in result.output.split('\n') if e]
class TestVerdiProcess:
"""Tests for `verdi process`."""
TEST_TIMEOUT = 5.
@pytest.fixture(autouse=True)
def init_profile(self, aiida_profile_clean, run_cli_command): # pylint: disable=unused-argument
"""Initialize the profile."""
# pylint: disable=attribute-defined-outside-init
from aiida.engine import ProcessState
from aiida.orm.groups import Group
self.calcs = []
self.process_label = 'SomeDummyWorkFunctionNode'
# Create 6 WorkFunctionNodes and WorkChainNodes (one for each ProcessState)
for state in ProcessState:
calc = WorkFunctionNode()
calc.set_process_state(state)
# Set the WorkFunctionNode as successful
if state == ProcessState.FINISHED:
calc.set_exit_status(0)
# Give a `process_label` to the `WorkFunctionNodes` so the `--process-label` option can be tested
calc.set_attribute('process_label', self.process_label)
calc.store()
self.calcs.append(calc)
calc = WorkChainNode()
calc.set_process_state(state)
# Set the WorkChainNode as failed
if state == ProcessState.FINISHED:
calc.set_exit_status(1)
# Set the waiting work chain as paused as well
if state == ProcessState.WAITING:
calc.pause()
calc.store()
self.calcs.append(calc)
self.group = Group('some_group').store()
self.group.add_nodes(self.calcs[0])
self.cli_runner = run_cli_command
def test_list_non_raw(self):
"""Test the list command as the user would run it (e.g. without -r)."""
result = self.cli_runner(cmd_process.process_list)
assert 'Total results:' in result.output
assert 'last time an entry changed state' in result.output
def test_list(self):
"""Test the list command."""
# pylint: disable=too-many-branches
# Default behavior should yield all active states (CREATED, RUNNING and WAITING) so six in total
result = self.cli_runner(cmd_process.process_list, ['-r'])
assert len(get_result_lines(result)) == 6
# Ordering shouldn't change the number of results,
for flag in ['-O', '--order-by']:
for flag_value in ['id', 'ctime']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, flag_value])
assert len(get_result_lines(result)) == 6
# but the orders should be inverse
for flag in ['-D', '--order-direction']:
flag_value = 'asc'
result = self.cli_runner(cmd_process.process_list, ['-r', '-O', 'id', flag, flag_value])
result_num_asc = [line.split()[0] for line in get_result_lines(result)]
assert len(result_num_asc) == 6
flag_value = 'desc'
result = self.cli_runner(cmd_process.process_list, ['-r', '-O', 'id', flag, flag_value])
result_num_desc = [line.split()[0] for line in get_result_lines(result)]
assert len(result_num_desc) == 6
assert result_num_asc == list(reversed(result_num_desc))
# Adding the all option should return all entries regardless of process state
for flag in ['-a', '--all']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag])
assert len(get_result_lines(result)) == 12
# Passing the limit option should limit the results
for flag in ['-l', '--limit']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, '6'])
assert len(get_result_lines(result)) == 6
# Filtering for a specific process state
for flag in ['-S', '--process-state']:
for flag_value in ['created', 'running', 'waiting', 'killed', 'excepted', 'finished']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, flag_value])
assert len(get_result_lines(result)) == 2
# Filtering for exit status should only get us one
for flag in ['-E', '--exit-status']:
for exit_status in ['0', '1']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, exit_status])
assert len(get_result_lines(result)) == 1
# Passing the failed flag as a shortcut for FINISHED + non-zero exit status
for flag in ['-X', '--failed']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag])
assert len(get_result_lines(result)) == 1
# Projecting on pk should allow us to verify all the pks
for flag in ['-P', '--project']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, 'pk'])
assert len(get_result_lines(result)) == 6
for line in get_result_lines(result):
assert line.strip() in [str(calc.pk) for calc in self.calcs]
# The group option should limit the query set to nodes in the group
for flag in ['-G', '--group']:
result = self.cli_runner(cmd_process.process_list, ['-r', '-P', 'pk', flag, str(self.group.pk)])
assert len(get_result_lines(result)) == 1
assert get_result_lines(result)[0] == str(self.calcs[0].pk)
# The process label should limit the query set to nodes with the given `process_label` attribute
for flag in ['-L', '--process-label']:
for process_label in [self.process_label, self.process_label.replace('Dummy', '%')]:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, process_label])
assert len(get_result_lines(result)) == 3 # Should only match the active `WorkFunctionNodes`
for line in get_result_lines(result):
assert self.process_label in line.strip()
# There should be exactly one paused
for flag in ['--paused']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag])
assert len(get_result_lines(result)) == 1
def test_process_show(self):
"""Test verdi process show"""
workchain_one = WorkChainNode()
workchain_two = WorkChainNode()
workchains = [workchain_one, workchain_two]
workchain_two.set_attribute('process_label', 'workchain_one_caller')
workchain_two.store()
workchain_one.add_incoming(workchain_two, link_type=LinkType.CALL_WORK, link_label='called')
workchain_one.store()
calcjob_one = CalcJobNode()
calcjob_two = CalcJobNode()
calcjob_one.set_attribute('process_label', 'process_label_one')
calcjob_two.set_attribute('process_label', 'process_label_two')
calcjob_one.add_incoming(workchain_one, link_type=LinkType.CALL_CALC, link_label='one')
calcjob_two.add_incoming(workchain_one, link_type=LinkType.CALL_CALC, link_label='two')
calcjob_one.store()
calcjob_two.store()
# Running without identifiers should not except and not print anything
options = []
result = self.cli_runner(cmd_process.process_show, options)
assert len(get_result_lines(result)) == 0
# Giving a single identifier should print a non empty string message
options = [str(workchain_one.pk)]
result = self.cli_runner(cmd_process.process_show, options)
lines = get_result_lines(result)
assert len(lines) > 0
assert 'workchain_one_caller' in result.output
assert 'process_label_one' in lines[-2]
assert 'process_label_two' in lines[-1]
# Giving multiple identifiers should print a non empty string message
options = [str(node.pk) for node in workchains]
result = self.cli_runner(cmd_process.process_show, options)
assert len(get_result_lines(result)) > 0
def test_process_report(self):
"""Test verdi process report"""
node = WorkflowNode().store()
# Running without identifiers should not except and not print anything
options = []
result = self.cli_runner(cmd_process.process_report, options)
assert len(get_result_lines(result)) == 0
# Giving a single identifier should print a non empty string message
options = [str(node.pk)]
result = self.cli_runner(cmd_process.process_report, options)
assert len(get_result_lines(result)) > 0
# Giving multiple identifiers should print a non empty string message
options = [str(calc.pk) for calc in [node]]
result = self.cli_runner(cmd_process.process_report, options)
assert len(get_result_lines(result)) > 0
def test_report(self):
"""Test the report command."""
grandparent = WorkChainNode().store()
parent = WorkChainNode()
child = WorkChainNode()
parent.add_incoming(grandparent, link_type=LinkType.CALL_WORK, link_label='link')
parent.store()
child.add_incoming(parent, link_type=LinkType.CALL_WORK, link_label='link')
child.store()
grandparent.logger.log(LOG_LEVEL_REPORT, 'grandparent_message')
parent.logger.log(LOG_LEVEL_REPORT, 'parent_message')
child.logger.log(LOG_LEVEL_REPORT, 'child_message')
result = self.cli_runner(cmd_process.process_report, [str(grandparent.pk)])
assert len(get_result_lines(result)) == 3
result = self.cli_runner(cmd_process.process_report, [str(parent.pk)])
assert len(get_result_lines(result)) == 2
result = self.cli_runner(cmd_process.process_report, [str(child.pk)])
assert len(get_result_lines(result)) == 1
# Max depth should limit nesting level
for flag in ['-m', '--max-depth']:
for flag_value in [1, 2]:
result = self.cli_runner(cmd_process.process_report, [str(grandparent.pk), flag, str(flag_value)])
assert len(get_result_lines(result)) == flag_value
# Filtering for other level name such as WARNING should not have any hits and only print the no log message
for flag in ['-l', '--levelname']:
result = self.cli_runner(cmd_process.process_report, [str(grandparent.pk), flag, 'WARNING'])
assert len(get_result_lines(result)) == 1, get_result_lines(result)
assert get_result_lines(result)[0] == 'No log messages recorded for this entry'
@pytest.mark.usefixtures('aiida_profile_clean')
def test_list_worker_slot_warning(run_cli_command, monkeypatch):
"""
Test that the if the number of used worker process slots exceeds a threshold,
that the warning message is displayed to the user when running `verdi process list`
"""
from aiida.cmdline.utils import common
from aiida.engine import DaemonClient, ProcessState
from aiida.manage.configuration import get_config
monkeypatch.setattr(common, 'get_num_workers', lambda: 1)
monkeypatch.setattr(DaemonClient, 'is_daemon_running', lambda: True)
# Get the number of allowed processes per worker:
config = get_config()
worker_process_slots = config.get_option('daemon.worker_process_slots', get_profile().name)
limit = int(worker_process_slots * 0.9)
# Create additional active nodes such that we have 90% of the active slot limit
for _ in range(limit):
calc = WorkFunctionNode()
calc.set_process_state(ProcessState.RUNNING)
calc.store()
# Default cmd should not throw the warning as we are below the limit
result = run_cli_command(cmd_process.process_list)
warning_phrase = 'of the available daemon worker slots have been used!'
assert all(warning_phrase not in line for line in result.output_lines)
# Add one more running node to put us over the limit
calc = WorkFunctionNode()
calc.set_process_state(ProcessState.RUNNING)
calc.store()
# Now the warning should fire
result = run_cli_command(cmd_process.process_list)
warning_phrase = '% of the available daemon worker slots have been used!'
assert any(warning_phrase in line for line in result.output_lines)
class TestVerdiProcessCallRoot:
"""Tests for `verdi process call-root`."""
@pytest.fixture(autouse=True)
def init_profile(self, aiida_profile_clean, run_cli_command): # pylint: disable=unused-argument
"""Initialize the profile."""
# pylint: disable=attribute-defined-outside-init
self.node_root = WorkflowNode()
self.node_middle = WorkflowNode()
self.node_terminal = WorkflowNode()
self.node_root.store()
self.node_middle.add_incoming(self.node_root, link_type=LinkType.CALL_WORK, link_label='call_middle')
self.node_middle.store()
self.node_terminal.add_incoming(self.node_middle, link_type=LinkType.CALL_WORK, link_label='call_terminal')
self.node_terminal.store()
self.cli_runner = run_cli_command
def test_no_caller(self):
"""Test `verdi process call-root` when passing single process without caller."""
options = [str(self.node_root.pk)]
result = self.cli_runner(cmd_process.process_call_root, options)
assert len(get_result_lines(result)) == 1
assert 'No callers found' in get_result_lines(result)[0]
def test_single_caller(self):
"""Test `verdi process call-root` when passing single process with call root."""
# Both the middle and terminal node should have the `root` node as call root.
for node in [self.node_middle, self.node_terminal]:
options = [str(node.pk)]
result = self.cli_runner(cmd_process.process_call_root, options)
assert len(get_result_lines(result)) == 1
assert str(self.node_root.pk) in get_result_lines(result)[0]
def test_multiple_processes(self):
"""Test `verdi process call-root` when passing multiple processes."""
options = [str(self.node_root.pk), str(self.node_middle.pk), str(self.node_terminal.pk)]
result = self.cli_runner(cmd_process.process_call_root, options)
assert len(get_result_lines(result)) == 3
assert 'No callers found' in get_result_lines(result)[0]
assert str(self.node_root.pk) in get_result_lines(result)[1]
assert str(self.node_root.pk) in get_result_lines(result)[2]
@pytest.mark.skip(reason='fails to complete randomly (see issue #4731)')
@pytest.mark.requires_rmq
@pytest.mark.usefixtures('with_daemon', 'aiida_profile_clean')
@pytest.mark.parametrize('cmd_try_all', (True, False))
def test_pause_play_kill(cmd_try_all, run_cli_command):
"""
Test the pause/play/kill commands
"""
# pylint: disable=no-member, too-many-locals
from aiida.cmdline.commands.cmd_process import process_kill, process_pause, process_play
from aiida.engine import ProcessState
from aiida.manage import get_manager
from aiida.orm import load_node
runner = get_manager().create_runner(rmq_submit=True)
calc = runner.submit(test_processes.WaitProcess)
test_daemon_timeout = 5.
start_time = time.time()
while calc.process_state is not plumpy.ProcessState.WAITING:
if time.time() - start_time >= test_daemon_timeout:
raise RuntimeError('Timed out waiting for process to enter waiting state')
# Make sure that calling any command on a non-existing process id will not except but print an error
# To simulate a process without a corresponding task, we simply create a node and store it. This node will not
# have an associated task at RabbitMQ, but it will be a valid `ProcessNode` with and active state, so it will
# pass the initial filtering of the `verdi process` commands
orphaned_node = WorkFunctionNode()
orphaned_node.set_process_state(ProcessState.RUNNING)
orphaned_node.store()
non_existing_process_id = str(orphaned_node.pk)
for command in [process_pause, process_play, process_kill]:
result = run_cli_command(command, [non_existing_process_id])
assert 'Error:' in result.output
assert not calc.paused
result = run_cli_command(process_pause, [str(calc.pk)])
# We need to make sure that the process is picked up by the daemon and put in the Waiting state before we start
# running the CLI commands, so we add a broadcast subscriber for the state change, which when hit will set the
# future to True. This will be our signal that we can start testing
waiting_future = Future()
filters = kiwipy.BroadcastFilter(
lambda *args, **kwargs: waiting_future.set_result(True), sender=calc.pk, subject='state_changed.*.waiting'
)
runner.communicator.add_broadcast_subscriber(filters)
# The process may already have been picked up by the daemon and put in the waiting state, before the subscriber
# got the chance to attach itself, making it have missed the broadcast. That's why check if the state is already
# waiting, and if not, we run the loop of the runner to start waiting for the broadcast message. To make sure
# that we have the latest state of the node as it is in the database, we force refresh it by reloading it.
calc = load_node(calc.pk)
if calc.process_state != plumpy.ProcessState.WAITING:
runner.loop.run_until_complete(asyncio.wait_for(waiting_future, timeout=5.0))
# Here we now that the process is with the daemon runner and in the waiting state so we can starting running
# the `verdi process` commands that we want to test
result = run_cli_command(process_pause, ['--wait', str(calc.pk)])
assert calc.paused
if cmd_try_all:
cmd_option = '--all'
else:
cmd_option = str(calc.pk)
result = run_cli_command(process_play, ['--wait', cmd_option])
assert not calc.paused
result = run_cli_command(process_kill, ['--wait', str(calc.pk)])
assert calc.is_terminated
assert calc.is_killed
|
<filename>tests/cmdline/commands/test_process.py
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida-core #
# For further information on the license, see the LICENSE.txt file #
# For further information please visit http://www.aiida.net #
###########################################################################
"""Tests for `verdi process`."""
import asyncio
from concurrent.futures import Future
import time
import kiwipy
import plumpy
import pytest
from aiida import get_profile
from aiida.cmdline.commands import cmd_process
from aiida.common.links import LinkType
from aiida.common.log import LOG_LEVEL_REPORT
from aiida.orm import CalcJobNode, WorkChainNode, WorkflowNode, WorkFunctionNode
from tests.utils import processes as test_processes
def get_result_lines(result):
return [e for e in result.output.split('\n') if e]
class TestVerdiProcess:
"""Tests for `verdi process`."""
TEST_TIMEOUT = 5.
@pytest.fixture(autouse=True)
def init_profile(self, aiida_profile_clean, run_cli_command): # pylint: disable=unused-argument
"""Initialize the profile."""
# pylint: disable=attribute-defined-outside-init
from aiida.engine import ProcessState
from aiida.orm.groups import Group
self.calcs = []
self.process_label = 'SomeDummyWorkFunctionNode'
# Create 6 WorkFunctionNodes and WorkChainNodes (one for each ProcessState)
for state in ProcessState:
calc = WorkFunctionNode()
calc.set_process_state(state)
# Set the WorkFunctionNode as successful
if state == ProcessState.FINISHED:
calc.set_exit_status(0)
# Give a `process_label` to the `WorkFunctionNodes` so the `--process-label` option can be tested
calc.set_attribute('process_label', self.process_label)
calc.store()
self.calcs.append(calc)
calc = WorkChainNode()
calc.set_process_state(state)
# Set the WorkChainNode as failed
if state == ProcessState.FINISHED:
calc.set_exit_status(1)
# Set the waiting work chain as paused as well
if state == ProcessState.WAITING:
calc.pause()
calc.store()
self.calcs.append(calc)
self.group = Group('some_group').store()
self.group.add_nodes(self.calcs[0])
self.cli_runner = run_cli_command
def test_list_non_raw(self):
"""Test the list command as the user would run it (e.g. without -r)."""
result = self.cli_runner(cmd_process.process_list)
assert 'Total results:' in result.output
assert 'last time an entry changed state' in result.output
def test_list(self):
"""Test the list command."""
# pylint: disable=too-many-branches
# Default behavior should yield all active states (CREATED, RUNNING and WAITING) so six in total
result = self.cli_runner(cmd_process.process_list, ['-r'])
assert len(get_result_lines(result)) == 6
# Ordering shouldn't change the number of results,
for flag in ['-O', '--order-by']:
for flag_value in ['id', 'ctime']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, flag_value])
assert len(get_result_lines(result)) == 6
# but the orders should be inverse
for flag in ['-D', '--order-direction']:
flag_value = 'asc'
result = self.cli_runner(cmd_process.process_list, ['-r', '-O', 'id', flag, flag_value])
result_num_asc = [line.split()[0] for line in get_result_lines(result)]
assert len(result_num_asc) == 6
flag_value = 'desc'
result = self.cli_runner(cmd_process.process_list, ['-r', '-O', 'id', flag, flag_value])
result_num_desc = [line.split()[0] for line in get_result_lines(result)]
assert len(result_num_desc) == 6
assert result_num_asc == list(reversed(result_num_desc))
# Adding the all option should return all entries regardless of process state
for flag in ['-a', '--all']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag])
assert len(get_result_lines(result)) == 12
# Passing the limit option should limit the results
for flag in ['-l', '--limit']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, '6'])
assert len(get_result_lines(result)) == 6
# Filtering for a specific process state
for flag in ['-S', '--process-state']:
for flag_value in ['created', 'running', 'waiting', 'killed', 'excepted', 'finished']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, flag_value])
assert len(get_result_lines(result)) == 2
# Filtering for exit status should only get us one
for flag in ['-E', '--exit-status']:
for exit_status in ['0', '1']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, exit_status])
assert len(get_result_lines(result)) == 1
# Passing the failed flag as a shortcut for FINISHED + non-zero exit status
for flag in ['-X', '--failed']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag])
assert len(get_result_lines(result)) == 1
# Projecting on pk should allow us to verify all the pks
for flag in ['-P', '--project']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, 'pk'])
assert len(get_result_lines(result)) == 6
for line in get_result_lines(result):
assert line.strip() in [str(calc.pk) for calc in self.calcs]
# The group option should limit the query set to nodes in the group
for flag in ['-G', '--group']:
result = self.cli_runner(cmd_process.process_list, ['-r', '-P', 'pk', flag, str(self.group.pk)])
assert len(get_result_lines(result)) == 1
assert get_result_lines(result)[0] == str(self.calcs[0].pk)
# The process label should limit the query set to nodes with the given `process_label` attribute
for flag in ['-L', '--process-label']:
for process_label in [self.process_label, self.process_label.replace('Dummy', '%')]:
result = self.cli_runner(cmd_process.process_list, ['-r', flag, process_label])
assert len(get_result_lines(result)) == 3 # Should only match the active `WorkFunctionNodes`
for line in get_result_lines(result):
assert self.process_label in line.strip()
# There should be exactly one paused
for flag in ['--paused']:
result = self.cli_runner(cmd_process.process_list, ['-r', flag])
assert len(get_result_lines(result)) == 1
def test_process_show(self):
"""Test verdi process show"""
workchain_one = WorkChainNode()
workchain_two = WorkChainNode()
workchains = [workchain_one, workchain_two]
workchain_two.set_attribute('process_label', 'workchain_one_caller')
workchain_two.store()
workchain_one.add_incoming(workchain_two, link_type=LinkType.CALL_WORK, link_label='called')
workchain_one.store()
calcjob_one = CalcJobNode()
calcjob_two = CalcJobNode()
calcjob_one.set_attribute('process_label', 'process_label_one')
calcjob_two.set_attribute('process_label', 'process_label_two')
calcjob_one.add_incoming(workchain_one, link_type=LinkType.CALL_CALC, link_label='one')
calcjob_two.add_incoming(workchain_one, link_type=LinkType.CALL_CALC, link_label='two')
calcjob_one.store()
calcjob_two.store()
# Running without identifiers should not except and not print anything
options = []
result = self.cli_runner(cmd_process.process_show, options)
assert len(get_result_lines(result)) == 0
# Giving a single identifier should print a non empty string message
options = [str(workchain_one.pk)]
result = self.cli_runner(cmd_process.process_show, options)
lines = get_result_lines(result)
assert len(lines) > 0
assert 'workchain_one_caller' in result.output
assert 'process_label_one' in lines[-2]
assert 'process_label_two' in lines[-1]
# Giving multiple identifiers should print a non empty string message
options = [str(node.pk) for node in workchains]
result = self.cli_runner(cmd_process.process_show, options)
assert len(get_result_lines(result)) > 0
def test_process_report(self):
"""Test verdi process report"""
node = WorkflowNode().store()
# Running without identifiers should not except and not print anything
options = []
result = self.cli_runner(cmd_process.process_report, options)
assert len(get_result_lines(result)) == 0
# Giving a single identifier should print a non empty string message
options = [str(node.pk)]
result = self.cli_runner(cmd_process.process_report, options)
assert len(get_result_lines(result)) > 0
# Giving multiple identifiers should print a non empty string message
options = [str(calc.pk) for calc in [node]]
result = self.cli_runner(cmd_process.process_report, options)
assert len(get_result_lines(result)) > 0
def test_report(self):
"""Test the report command."""
grandparent = WorkChainNode().store()
parent = WorkChainNode()
child = WorkChainNode()
parent.add_incoming(grandparent, link_type=LinkType.CALL_WORK, link_label='link')
parent.store()
child.add_incoming(parent, link_type=LinkType.CALL_WORK, link_label='link')
child.store()
grandparent.logger.log(LOG_LEVEL_REPORT, 'grandparent_message')
parent.logger.log(LOG_LEVEL_REPORT, 'parent_message')
child.logger.log(LOG_LEVEL_REPORT, 'child_message')
result = self.cli_runner(cmd_process.process_report, [str(grandparent.pk)])
assert len(get_result_lines(result)) == 3
result = self.cli_runner(cmd_process.process_report, [str(parent.pk)])
assert len(get_result_lines(result)) == 2
result = self.cli_runner(cmd_process.process_report, [str(child.pk)])
assert len(get_result_lines(result)) == 1
# Max depth should limit nesting level
for flag in ['-m', '--max-depth']:
for flag_value in [1, 2]:
result = self.cli_runner(cmd_process.process_report, [str(grandparent.pk), flag, str(flag_value)])
assert len(get_result_lines(result)) == flag_value
# Filtering for other level name such as WARNING should not have any hits and only print the no log message
for flag in ['-l', '--levelname']:
result = self.cli_runner(cmd_process.process_report, [str(grandparent.pk), flag, 'WARNING'])
assert len(get_result_lines(result)) == 1, get_result_lines(result)
assert get_result_lines(result)[0] == 'No log messages recorded for this entry'
@pytest.mark.usefixtures('aiida_profile_clean')
def test_list_worker_slot_warning(run_cli_command, monkeypatch):
"""
Test that the if the number of used worker process slots exceeds a threshold,
that the warning message is displayed to the user when running `verdi process list`
"""
from aiida.cmdline.utils import common
from aiida.engine import DaemonClient, ProcessState
from aiida.manage.configuration import get_config
monkeypatch.setattr(common, 'get_num_workers', lambda: 1)
monkeypatch.setattr(DaemonClient, 'is_daemon_running', lambda: True)
# Get the number of allowed processes per worker:
config = get_config()
worker_process_slots = config.get_option('daemon.worker_process_slots', get_profile().name)
limit = int(worker_process_slots * 0.9)
# Create additional active nodes such that we have 90% of the active slot limit
for _ in range(limit):
calc = WorkFunctionNode()
calc.set_process_state(ProcessState.RUNNING)
calc.store()
# Default cmd should not throw the warning as we are below the limit
result = run_cli_command(cmd_process.process_list)
warning_phrase = 'of the available daemon worker slots have been used!'
assert all(warning_phrase not in line for line in result.output_lines)
# Add one more running node to put us over the limit
calc = WorkFunctionNode()
calc.set_process_state(ProcessState.RUNNING)
calc.store()
# Now the warning should fire
result = run_cli_command(cmd_process.process_list)
warning_phrase = '% of the available daemon worker slots have been used!'
assert any(warning_phrase in line for line in result.output_lines)
class TestVerdiProcessCallRoot:
"""Tests for `verdi process call-root`."""
@pytest.fixture(autouse=True)
def init_profile(self, aiida_profile_clean, run_cli_command): # pylint: disable=unused-argument
"""Initialize the profile."""
# pylint: disable=attribute-defined-outside-init
self.node_root = WorkflowNode()
self.node_middle = WorkflowNode()
self.node_terminal = WorkflowNode()
self.node_root.store()
self.node_middle.add_incoming(self.node_root, link_type=LinkType.CALL_WORK, link_label='call_middle')
self.node_middle.store()
self.node_terminal.add_incoming(self.node_middle, link_type=LinkType.CALL_WORK, link_label='call_terminal')
self.node_terminal.store()
self.cli_runner = run_cli_command
def test_no_caller(self):
"""Test `verdi process call-root` when passing single process without caller."""
options = [str(self.node_root.pk)]
result = self.cli_runner(cmd_process.process_call_root, options)
assert len(get_result_lines(result)) == 1
assert 'No callers found' in get_result_lines(result)[0]
def test_single_caller(self):
"""Test `verdi process call-root` when passing single process with call root."""
# Both the middle and terminal node should have the `root` node as call root.
for node in [self.node_middle, self.node_terminal]:
options = [str(node.pk)]
result = self.cli_runner(cmd_process.process_call_root, options)
assert len(get_result_lines(result)) == 1
assert str(self.node_root.pk) in get_result_lines(result)[0]
def test_multiple_processes(self):
"""Test `verdi process call-root` when passing multiple processes."""
options = [str(self.node_root.pk), str(self.node_middle.pk), str(self.node_terminal.pk)]
result = self.cli_runner(cmd_process.process_call_root, options)
assert len(get_result_lines(result)) == 3
assert 'No callers found' in get_result_lines(result)[0]
assert str(self.node_root.pk) in get_result_lines(result)[1]
assert str(self.node_root.pk) in get_result_lines(result)[2]
@pytest.mark.skip(reason='fails to complete randomly (see issue #4731)')
@pytest.mark.requires_rmq
@pytest.mark.usefixtures('with_daemon', 'aiida_profile_clean')
@pytest.mark.parametrize('cmd_try_all', (True, False))
def test_pause_play_kill(cmd_try_all, run_cli_command):
"""
Test the pause/play/kill commands
"""
# pylint: disable=no-member, too-many-locals
from aiida.cmdline.commands.cmd_process import process_kill, process_pause, process_play
from aiida.engine import ProcessState
from aiida.manage import get_manager
from aiida.orm import load_node
runner = get_manager().create_runner(rmq_submit=True)
calc = runner.submit(test_processes.WaitProcess)
test_daemon_timeout = 5.
start_time = time.time()
while calc.process_state is not plumpy.ProcessState.WAITING:
if time.time() - start_time >= test_daemon_timeout:
raise RuntimeError('Timed out waiting for process to enter waiting state')
# Make sure that calling any command on a non-existing process id will not except but print an error
# To simulate a process without a corresponding task, we simply create a node and store it. This node will not
# have an associated task at RabbitMQ, but it will be a valid `ProcessNode` with and active state, so it will
# pass the initial filtering of the `verdi process` commands
orphaned_node = WorkFunctionNode()
orphaned_node.set_process_state(ProcessState.RUNNING)
orphaned_node.store()
non_existing_process_id = str(orphaned_node.pk)
for command in [process_pause, process_play, process_kill]:
result = run_cli_command(command, [non_existing_process_id])
assert 'Error:' in result.output
assert not calc.paused
result = run_cli_command(process_pause, [str(calc.pk)])
# We need to make sure that the process is picked up by the daemon and put in the Waiting state before we start
# running the CLI commands, so we add a broadcast subscriber for the state change, which when hit will set the
# future to True. This will be our signal that we can start testing
waiting_future = Future()
filters = kiwipy.BroadcastFilter(
lambda *args, **kwargs: waiting_future.set_result(True), sender=calc.pk, subject='state_changed.*.waiting'
)
runner.communicator.add_broadcast_subscriber(filters)
# The process may already have been picked up by the daemon and put in the waiting state, before the subscriber
# got the chance to attach itself, making it have missed the broadcast. That's why check if the state is already
# waiting, and if not, we run the loop of the runner to start waiting for the broadcast message. To make sure
# that we have the latest state of the node as it is in the database, we force refresh it by reloading it.
calc = load_node(calc.pk)
if calc.process_state != plumpy.ProcessState.WAITING:
runner.loop.run_until_complete(asyncio.wait_for(waiting_future, timeout=5.0))
# Here we now that the process is with the daemon runner and in the waiting state so we can starting running
# the `verdi process` commands that we want to test
result = run_cli_command(process_pause, ['--wait', str(calc.pk)])
assert calc.paused
if cmd_try_all:
cmd_option = '--all'
else:
cmd_option = str(calc.pk)
result = run_cli_command(process_play, ['--wait', cmd_option])
assert not calc.paused
result = run_cli_command(process_kill, ['--wait', str(calc.pk)])
assert calc.is_terminated
assert calc.is_killed
|
en
| 0.832604
|
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### Tests for `verdi process`. Tests for `verdi process`. # pylint: disable=unused-argument Initialize the profile. # pylint: disable=attribute-defined-outside-init # Create 6 WorkFunctionNodes and WorkChainNodes (one for each ProcessState) # Set the WorkFunctionNode as successful # Give a `process_label` to the `WorkFunctionNodes` so the `--process-label` option can be tested # Set the WorkChainNode as failed # Set the waiting work chain as paused as well Test the list command as the user would run it (e.g. without -r). Test the list command. # pylint: disable=too-many-branches # Default behavior should yield all active states (CREATED, RUNNING and WAITING) so six in total # Ordering shouldn't change the number of results, # but the orders should be inverse # Adding the all option should return all entries regardless of process state # Passing the limit option should limit the results # Filtering for a specific process state # Filtering for exit status should only get us one # Passing the failed flag as a shortcut for FINISHED + non-zero exit status # Projecting on pk should allow us to verify all the pks # The group option should limit the query set to nodes in the group # The process label should limit the query set to nodes with the given `process_label` attribute # Should only match the active `WorkFunctionNodes` # There should be exactly one paused Test verdi process show # Running without identifiers should not except and not print anything # Giving a single identifier should print a non empty string message # Giving multiple identifiers should print a non empty string message Test verdi process report # Running without identifiers should not except and not print anything # Giving a single identifier should print a non empty string message # Giving multiple identifiers should print a non empty string message Test the report command. # Max depth should limit nesting level # Filtering for other level name such as WARNING should not have any hits and only print the no log message Test that the if the number of used worker process slots exceeds a threshold, that the warning message is displayed to the user when running `verdi process list` # Get the number of allowed processes per worker: # Create additional active nodes such that we have 90% of the active slot limit # Default cmd should not throw the warning as we are below the limit # Add one more running node to put us over the limit # Now the warning should fire Tests for `verdi process call-root`. # pylint: disable=unused-argument Initialize the profile. # pylint: disable=attribute-defined-outside-init Test `verdi process call-root` when passing single process without caller. Test `verdi process call-root` when passing single process with call root. # Both the middle and terminal node should have the `root` node as call root. Test `verdi process call-root` when passing multiple processes. #4731)') Test the pause/play/kill commands # pylint: disable=no-member, too-many-locals # Make sure that calling any command on a non-existing process id will not except but print an error # To simulate a process without a corresponding task, we simply create a node and store it. This node will not # have an associated task at RabbitMQ, but it will be a valid `ProcessNode` with and active state, so it will # pass the initial filtering of the `verdi process` commands # We need to make sure that the process is picked up by the daemon and put in the Waiting state before we start # running the CLI commands, so we add a broadcast subscriber for the state change, which when hit will set the # future to True. This will be our signal that we can start testing # The process may already have been picked up by the daemon and put in the waiting state, before the subscriber # got the chance to attach itself, making it have missed the broadcast. That's why check if the state is already # waiting, and if not, we run the loop of the runner to start waiting for the broadcast message. To make sure # that we have the latest state of the node as it is in the database, we force refresh it by reloading it. # Here we now that the process is with the daemon runner and in the waiting state so we can starting running # the `verdi process` commands that we want to test
| 1.836703
| 2
|
env/lib/python3.6/site-packages/scipy/signal/tests/test_savitzky_golay.py
|
anthowen/duplify
| 6,989
|
6626290
|
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import (assert_allclose, assert_equal,
assert_almost_equal, assert_array_equal,
assert_array_almost_equal)
from scipy.ndimage import convolve1d
from scipy.signal import savgol_coeffs, savgol_filter
from scipy.signal._savitzky_golay import _polyder
def check_polyder(p, m, expected):
dp = _polyder(p, m)
assert_array_equal(dp, expected)
def test_polyder():
cases = [
([5], 0, [5]),
([5], 1, [0]),
([3, 2, 1], 0, [3, 2, 1]),
([3, 2, 1], 1, [6, 2]),
([3, 2, 1], 2, [6]),
([3, 2, 1], 3, [0]),
([[3, 2, 1], [5, 6, 7]], 0, [[3, 2, 1], [5, 6, 7]]),
([[3, 2, 1], [5, 6, 7]], 1, [[6, 2], [10, 6]]),
([[3, 2, 1], [5, 6, 7]], 2, [[6], [10]]),
([[3, 2, 1], [5, 6, 7]], 3, [[0], [0]]),
]
for p, m, expected in cases:
check_polyder(np.array(p).T, m, np.array(expected).T)
#--------------------------------------------------------------------
# savgol_coeffs tests
#--------------------------------------------------------------------
def alt_sg_coeffs(window_length, polyorder, pos):
"""This is an alternative implementation of the SG coefficients.
It uses numpy.polyfit and numpy.polyval. The results should be
equivalent to those of savgol_coeffs(), but this implementation
is slower.
window_length should be odd.
"""
if pos is None:
pos = window_length // 2
t = np.arange(window_length)
unit = (t == pos).astype(int)
h = np.polyval(np.polyfit(t, unit, polyorder), t)
return h
def test_sg_coeffs_trivial():
# Test a trivial case of savgol_coeffs: polyorder = window_length - 1
h = savgol_coeffs(1, 0)
assert_allclose(h, [1])
h = savgol_coeffs(3, 2)
assert_allclose(h, [0, 1, 0], atol=1e-10)
h = savgol_coeffs(5, 4)
assert_allclose(h, [0, 0, 1, 0, 0], atol=1e-10)
h = savgol_coeffs(5, 4, pos=1)
assert_allclose(h, [0, 0, 0, 1, 0], atol=1e-10)
h = savgol_coeffs(5, 4, pos=1, use='dot')
assert_allclose(h, [0, 1, 0, 0, 0], atol=1e-10)
def compare_coeffs_to_alt(window_length, order):
# For the given window_length and order, compare the results
# of savgol_coeffs and alt_sg_coeffs for pos from 0 to window_length - 1.
# Also include pos=None.
for pos in [None] + list(range(window_length)):
h1 = savgol_coeffs(window_length, order, pos=pos, use='dot')
h2 = alt_sg_coeffs(window_length, order, pos=pos)
assert_allclose(h1, h2, atol=1e-10,
err_msg=("window_length = %d, order = %d, pos = %s" %
(window_length, order, pos)))
def test_sg_coeffs_compare():
# Compare savgol_coeffs() to alt_sg_coeffs().
for window_length in range(1, 8, 2):
for order in range(window_length):
compare_coeffs_to_alt(window_length, order)
def test_sg_coeffs_exact():
polyorder = 4
window_length = 9
halflen = window_length // 2
x = np.linspace(0, 21, 43)
delta = x[1] - x[0]
# The data is a cubic polynomial. We'll use an order 4
# SG filter, so the filtered values should equal the input data
# (except within half window_length of the edges).
y = 0.5 * x ** 3 - x
h = savgol_coeffs(window_length, polyorder)
y0 = convolve1d(y, h)
assert_allclose(y0[halflen:-halflen], y[halflen:-halflen])
# Check the same input, but use deriv=1. dy is the exact result.
dy = 1.5 * x ** 2 - 1
h = savgol_coeffs(window_length, polyorder, deriv=1, delta=delta)
y1 = convolve1d(y, h)
assert_allclose(y1[halflen:-halflen], dy[halflen:-halflen])
# Check the same input, but use deriv=2. d2y is the exact result.
d2y = 3.0 * x
h = savgol_coeffs(window_length, polyorder, deriv=2, delta=delta)
y2 = convolve1d(y, h)
assert_allclose(y2[halflen:-halflen], d2y[halflen:-halflen])
def test_sg_coeffs_deriv():
# The data in `x` is a sampled parabola, so using savgol_coeffs with an
# order 2 or higher polynomial should give exact results.
i = np.array([-2.0, 0.0, 2.0, 4.0, 6.0])
x = i ** 2 / 4
dx = i / 2
d2x = 0.5 * np.ones_like(i)
for pos in range(x.size):
coeffs0 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot')
assert_allclose(coeffs0.dot(x), x[pos], atol=1e-10)
coeffs1 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=1)
assert_allclose(coeffs1.dot(x), dx[pos], atol=1e-10)
coeffs2 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=2)
assert_allclose(coeffs2.dot(x), d2x[pos], atol=1e-10)
def test_sg_coeffs_large():
# Test that for large values of window_length and polyorder the array of
# coefficients returned is symmetric. The aim is to ensure that
# no potential numeric overflow occurs.
coeffs0 = savgol_coeffs(31, 9)
assert_array_almost_equal(coeffs0, coeffs0[::-1])
coeffs1 = savgol_coeffs(31, 9, deriv=1)
assert_array_almost_equal(coeffs1, -coeffs1[::-1])
#--------------------------------------------------------------------
# savgol_filter tests
#--------------------------------------------------------------------
def test_sg_filter_trivial():
""" Test some trivial edge cases for savgol_filter()."""
x = np.array([1.0])
y = savgol_filter(x, 1, 0)
assert_equal(y, [1.0])
# Input is a single value. With a window length of 3 and polyorder 1,
# the value in y is from the straight-line fit of (-1,0), (0,3) and
# (1, 0) at 0. This is just the average of the three values, hence 1.0.
x = np.array([3.0])
y = savgol_filter(x, 3, 1, mode='constant')
assert_almost_equal(y, [1.0], decimal=15)
x = np.array([3.0])
y = savgol_filter(x, 3, 1, mode='nearest')
assert_almost_equal(y, [3.0], decimal=15)
x = np.array([1.0] * 3)
y = savgol_filter(x, 3, 1, mode='wrap')
assert_almost_equal(y, [1.0, 1.0, 1.0], decimal=15)
def test_sg_filter_basic():
# Some basic test cases for savgol_filter().
x = np.array([1.0, 2.0, 1.0])
y = savgol_filter(x, 3, 1, mode='constant')
assert_allclose(y, [1.0, 4.0 / 3, 1.0])
y = savgol_filter(x, 3, 1, mode='mirror')
assert_allclose(y, [5.0 / 3, 4.0 / 3, 5.0 / 3])
y = savgol_filter(x, 3, 1, mode='wrap')
assert_allclose(y, [4.0 / 3, 4.0 / 3, 4.0 / 3])
def test_sg_filter_2d():
x = np.array([[1.0, 2.0, 1.0],
[2.0, 4.0, 2.0]])
expected = np.array([[1.0, 4.0 / 3, 1.0],
[2.0, 8.0 / 3, 2.0]])
y = savgol_filter(x, 3, 1, mode='constant')
assert_allclose(y, expected)
y = savgol_filter(x.T, 3, 1, mode='constant', axis=0)
assert_allclose(y, expected.T)
def test_sg_filter_interp_edges():
# Another test with low degree polynomial data, for which we can easily
# give the exact results. In this test, we use mode='interp', so
# savgol_filter should match the exact solution for the entire data set,
# including the edges.
t = np.linspace(-5, 5, 21)
delta = t[1] - t[0]
# Polynomial test data.
x = np.array([t,
3 * t ** 2,
t ** 3 - t])
dx = np.array([np.ones_like(t),
6 * t,
3 * t ** 2 - 1.0])
d2x = np.array([np.zeros_like(t),
6 * np.ones_like(t),
6 * t])
window_length = 7
y = savgol_filter(x, window_length, 3, axis=-1, mode='interp')
assert_allclose(y, x, atol=1e-12)
y1 = savgol_filter(x, window_length, 3, axis=-1, mode='interp',
deriv=1, delta=delta)
assert_allclose(y1, dx, atol=1e-12)
y2 = savgol_filter(x, window_length, 3, axis=-1, mode='interp',
deriv=2, delta=delta)
assert_allclose(y2, d2x, atol=1e-12)
# Transpose everything, and test again with axis=0.
x = x.T
dx = dx.T
d2x = d2x.T
y = savgol_filter(x, window_length, 3, axis=0, mode='interp')
assert_allclose(y, x, atol=1e-12)
y1 = savgol_filter(x, window_length, 3, axis=0, mode='interp',
deriv=1, delta=delta)
assert_allclose(y1, dx, atol=1e-12)
y2 = savgol_filter(x, window_length, 3, axis=0, mode='interp',
deriv=2, delta=delta)
assert_allclose(y2, d2x, atol=1e-12)
def test_sg_filter_interp_edges_3d():
# Test mode='interp' with a 3-D array.
t = np.linspace(-5, 5, 21)
delta = t[1] - t[0]
x1 = np.array([t, -t])
x2 = np.array([t ** 2, 3 * t ** 2 + 5])
x3 = np.array([t ** 3, 2 * t ** 3 + t ** 2 - 0.5 * t])
dx1 = np.array([np.ones_like(t), -np.ones_like(t)])
dx2 = np.array([2 * t, 6 * t])
dx3 = np.array([3 * t ** 2, 6 * t ** 2 + 2 * t - 0.5])
# z has shape (3, 2, 21)
z = np.array([x1, x2, x3])
dz = np.array([dx1, dx2, dx3])
y = savgol_filter(z, 7, 3, axis=-1, mode='interp', delta=delta)
assert_allclose(y, z, atol=1e-10)
dy = savgol_filter(z, 7, 3, axis=-1, mode='interp', deriv=1, delta=delta)
assert_allclose(dy, dz, atol=1e-10)
# z has shape (3, 21, 2)
z = np.array([x1.T, x2.T, x3.T])
dz = np.array([dx1.T, dx2.T, dx3.T])
y = savgol_filter(z, 7, 3, axis=1, mode='interp', delta=delta)
assert_allclose(y, z, atol=1e-10)
dy = savgol_filter(z, 7, 3, axis=1, mode='interp', deriv=1, delta=delta)
assert_allclose(dy, dz, atol=1e-10)
# z has shape (21, 3, 2)
z = z.swapaxes(0, 1).copy()
dz = dz.swapaxes(0, 1).copy()
y = savgol_filter(z, 7, 3, axis=0, mode='interp', delta=delta)
assert_allclose(y, z, atol=1e-10)
dy = savgol_filter(z, 7, 3, axis=0, mode='interp', deriv=1, delta=delta)
assert_allclose(dy, dz, atol=1e-10)
|
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import (assert_allclose, assert_equal,
assert_almost_equal, assert_array_equal,
assert_array_almost_equal)
from scipy.ndimage import convolve1d
from scipy.signal import savgol_coeffs, savgol_filter
from scipy.signal._savitzky_golay import _polyder
def check_polyder(p, m, expected):
dp = _polyder(p, m)
assert_array_equal(dp, expected)
def test_polyder():
cases = [
([5], 0, [5]),
([5], 1, [0]),
([3, 2, 1], 0, [3, 2, 1]),
([3, 2, 1], 1, [6, 2]),
([3, 2, 1], 2, [6]),
([3, 2, 1], 3, [0]),
([[3, 2, 1], [5, 6, 7]], 0, [[3, 2, 1], [5, 6, 7]]),
([[3, 2, 1], [5, 6, 7]], 1, [[6, 2], [10, 6]]),
([[3, 2, 1], [5, 6, 7]], 2, [[6], [10]]),
([[3, 2, 1], [5, 6, 7]], 3, [[0], [0]]),
]
for p, m, expected in cases:
check_polyder(np.array(p).T, m, np.array(expected).T)
#--------------------------------------------------------------------
# savgol_coeffs tests
#--------------------------------------------------------------------
def alt_sg_coeffs(window_length, polyorder, pos):
"""This is an alternative implementation of the SG coefficients.
It uses numpy.polyfit and numpy.polyval. The results should be
equivalent to those of savgol_coeffs(), but this implementation
is slower.
window_length should be odd.
"""
if pos is None:
pos = window_length // 2
t = np.arange(window_length)
unit = (t == pos).astype(int)
h = np.polyval(np.polyfit(t, unit, polyorder), t)
return h
def test_sg_coeffs_trivial():
# Test a trivial case of savgol_coeffs: polyorder = window_length - 1
h = savgol_coeffs(1, 0)
assert_allclose(h, [1])
h = savgol_coeffs(3, 2)
assert_allclose(h, [0, 1, 0], atol=1e-10)
h = savgol_coeffs(5, 4)
assert_allclose(h, [0, 0, 1, 0, 0], atol=1e-10)
h = savgol_coeffs(5, 4, pos=1)
assert_allclose(h, [0, 0, 0, 1, 0], atol=1e-10)
h = savgol_coeffs(5, 4, pos=1, use='dot')
assert_allclose(h, [0, 1, 0, 0, 0], atol=1e-10)
def compare_coeffs_to_alt(window_length, order):
# For the given window_length and order, compare the results
# of savgol_coeffs and alt_sg_coeffs for pos from 0 to window_length - 1.
# Also include pos=None.
for pos in [None] + list(range(window_length)):
h1 = savgol_coeffs(window_length, order, pos=pos, use='dot')
h2 = alt_sg_coeffs(window_length, order, pos=pos)
assert_allclose(h1, h2, atol=1e-10,
err_msg=("window_length = %d, order = %d, pos = %s" %
(window_length, order, pos)))
def test_sg_coeffs_compare():
# Compare savgol_coeffs() to alt_sg_coeffs().
for window_length in range(1, 8, 2):
for order in range(window_length):
compare_coeffs_to_alt(window_length, order)
def test_sg_coeffs_exact():
polyorder = 4
window_length = 9
halflen = window_length // 2
x = np.linspace(0, 21, 43)
delta = x[1] - x[0]
# The data is a cubic polynomial. We'll use an order 4
# SG filter, so the filtered values should equal the input data
# (except within half window_length of the edges).
y = 0.5 * x ** 3 - x
h = savgol_coeffs(window_length, polyorder)
y0 = convolve1d(y, h)
assert_allclose(y0[halflen:-halflen], y[halflen:-halflen])
# Check the same input, but use deriv=1. dy is the exact result.
dy = 1.5 * x ** 2 - 1
h = savgol_coeffs(window_length, polyorder, deriv=1, delta=delta)
y1 = convolve1d(y, h)
assert_allclose(y1[halflen:-halflen], dy[halflen:-halflen])
# Check the same input, but use deriv=2. d2y is the exact result.
d2y = 3.0 * x
h = savgol_coeffs(window_length, polyorder, deriv=2, delta=delta)
y2 = convolve1d(y, h)
assert_allclose(y2[halflen:-halflen], d2y[halflen:-halflen])
def test_sg_coeffs_deriv():
# The data in `x` is a sampled parabola, so using savgol_coeffs with an
# order 2 or higher polynomial should give exact results.
i = np.array([-2.0, 0.0, 2.0, 4.0, 6.0])
x = i ** 2 / 4
dx = i / 2
d2x = 0.5 * np.ones_like(i)
for pos in range(x.size):
coeffs0 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot')
assert_allclose(coeffs0.dot(x), x[pos], atol=1e-10)
coeffs1 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=1)
assert_allclose(coeffs1.dot(x), dx[pos], atol=1e-10)
coeffs2 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=2)
assert_allclose(coeffs2.dot(x), d2x[pos], atol=1e-10)
def test_sg_coeffs_large():
# Test that for large values of window_length and polyorder the array of
# coefficients returned is symmetric. The aim is to ensure that
# no potential numeric overflow occurs.
coeffs0 = savgol_coeffs(31, 9)
assert_array_almost_equal(coeffs0, coeffs0[::-1])
coeffs1 = savgol_coeffs(31, 9, deriv=1)
assert_array_almost_equal(coeffs1, -coeffs1[::-1])
#--------------------------------------------------------------------
# savgol_filter tests
#--------------------------------------------------------------------
def test_sg_filter_trivial():
""" Test some trivial edge cases for savgol_filter()."""
x = np.array([1.0])
y = savgol_filter(x, 1, 0)
assert_equal(y, [1.0])
# Input is a single value. With a window length of 3 and polyorder 1,
# the value in y is from the straight-line fit of (-1,0), (0,3) and
# (1, 0) at 0. This is just the average of the three values, hence 1.0.
x = np.array([3.0])
y = savgol_filter(x, 3, 1, mode='constant')
assert_almost_equal(y, [1.0], decimal=15)
x = np.array([3.0])
y = savgol_filter(x, 3, 1, mode='nearest')
assert_almost_equal(y, [3.0], decimal=15)
x = np.array([1.0] * 3)
y = savgol_filter(x, 3, 1, mode='wrap')
assert_almost_equal(y, [1.0, 1.0, 1.0], decimal=15)
def test_sg_filter_basic():
# Some basic test cases for savgol_filter().
x = np.array([1.0, 2.0, 1.0])
y = savgol_filter(x, 3, 1, mode='constant')
assert_allclose(y, [1.0, 4.0 / 3, 1.0])
y = savgol_filter(x, 3, 1, mode='mirror')
assert_allclose(y, [5.0 / 3, 4.0 / 3, 5.0 / 3])
y = savgol_filter(x, 3, 1, mode='wrap')
assert_allclose(y, [4.0 / 3, 4.0 / 3, 4.0 / 3])
def test_sg_filter_2d():
x = np.array([[1.0, 2.0, 1.0],
[2.0, 4.0, 2.0]])
expected = np.array([[1.0, 4.0 / 3, 1.0],
[2.0, 8.0 / 3, 2.0]])
y = savgol_filter(x, 3, 1, mode='constant')
assert_allclose(y, expected)
y = savgol_filter(x.T, 3, 1, mode='constant', axis=0)
assert_allclose(y, expected.T)
def test_sg_filter_interp_edges():
# Another test with low degree polynomial data, for which we can easily
# give the exact results. In this test, we use mode='interp', so
# savgol_filter should match the exact solution for the entire data set,
# including the edges.
t = np.linspace(-5, 5, 21)
delta = t[1] - t[0]
# Polynomial test data.
x = np.array([t,
3 * t ** 2,
t ** 3 - t])
dx = np.array([np.ones_like(t),
6 * t,
3 * t ** 2 - 1.0])
d2x = np.array([np.zeros_like(t),
6 * np.ones_like(t),
6 * t])
window_length = 7
y = savgol_filter(x, window_length, 3, axis=-1, mode='interp')
assert_allclose(y, x, atol=1e-12)
y1 = savgol_filter(x, window_length, 3, axis=-1, mode='interp',
deriv=1, delta=delta)
assert_allclose(y1, dx, atol=1e-12)
y2 = savgol_filter(x, window_length, 3, axis=-1, mode='interp',
deriv=2, delta=delta)
assert_allclose(y2, d2x, atol=1e-12)
# Transpose everything, and test again with axis=0.
x = x.T
dx = dx.T
d2x = d2x.T
y = savgol_filter(x, window_length, 3, axis=0, mode='interp')
assert_allclose(y, x, atol=1e-12)
y1 = savgol_filter(x, window_length, 3, axis=0, mode='interp',
deriv=1, delta=delta)
assert_allclose(y1, dx, atol=1e-12)
y2 = savgol_filter(x, window_length, 3, axis=0, mode='interp',
deriv=2, delta=delta)
assert_allclose(y2, d2x, atol=1e-12)
def test_sg_filter_interp_edges_3d():
# Test mode='interp' with a 3-D array.
t = np.linspace(-5, 5, 21)
delta = t[1] - t[0]
x1 = np.array([t, -t])
x2 = np.array([t ** 2, 3 * t ** 2 + 5])
x3 = np.array([t ** 3, 2 * t ** 3 + t ** 2 - 0.5 * t])
dx1 = np.array([np.ones_like(t), -np.ones_like(t)])
dx2 = np.array([2 * t, 6 * t])
dx3 = np.array([3 * t ** 2, 6 * t ** 2 + 2 * t - 0.5])
# z has shape (3, 2, 21)
z = np.array([x1, x2, x3])
dz = np.array([dx1, dx2, dx3])
y = savgol_filter(z, 7, 3, axis=-1, mode='interp', delta=delta)
assert_allclose(y, z, atol=1e-10)
dy = savgol_filter(z, 7, 3, axis=-1, mode='interp', deriv=1, delta=delta)
assert_allclose(dy, dz, atol=1e-10)
# z has shape (3, 21, 2)
z = np.array([x1.T, x2.T, x3.T])
dz = np.array([dx1.T, dx2.T, dx3.T])
y = savgol_filter(z, 7, 3, axis=1, mode='interp', delta=delta)
assert_allclose(y, z, atol=1e-10)
dy = savgol_filter(z, 7, 3, axis=1, mode='interp', deriv=1, delta=delta)
assert_allclose(dy, dz, atol=1e-10)
# z has shape (21, 3, 2)
z = z.swapaxes(0, 1).copy()
dz = dz.swapaxes(0, 1).copy()
y = savgol_filter(z, 7, 3, axis=0, mode='interp', delta=delta)
assert_allclose(y, z, atol=1e-10)
dy = savgol_filter(z, 7, 3, axis=0, mode='interp', deriv=1, delta=delta)
assert_allclose(dy, dz, atol=1e-10)
|
en
| 0.797405
|
#-------------------------------------------------------------------- # savgol_coeffs tests #-------------------------------------------------------------------- This is an alternative implementation of the SG coefficients. It uses numpy.polyfit and numpy.polyval. The results should be equivalent to those of savgol_coeffs(), but this implementation is slower. window_length should be odd. # Test a trivial case of savgol_coeffs: polyorder = window_length - 1 # For the given window_length and order, compare the results # of savgol_coeffs and alt_sg_coeffs for pos from 0 to window_length - 1. # Also include pos=None. # Compare savgol_coeffs() to alt_sg_coeffs(). # The data is a cubic polynomial. We'll use an order 4 # SG filter, so the filtered values should equal the input data # (except within half window_length of the edges). # Check the same input, but use deriv=1. dy is the exact result. # Check the same input, but use deriv=2. d2y is the exact result. # The data in `x` is a sampled parabola, so using savgol_coeffs with an # order 2 or higher polynomial should give exact results. # Test that for large values of window_length and polyorder the array of # coefficients returned is symmetric. The aim is to ensure that # no potential numeric overflow occurs. #-------------------------------------------------------------------- # savgol_filter tests #-------------------------------------------------------------------- Test some trivial edge cases for savgol_filter(). # Input is a single value. With a window length of 3 and polyorder 1, # the value in y is from the straight-line fit of (-1,0), (0,3) and # (1, 0) at 0. This is just the average of the three values, hence 1.0. # Some basic test cases for savgol_filter(). # Another test with low degree polynomial data, for which we can easily # give the exact results. In this test, we use mode='interp', so # savgol_filter should match the exact solution for the entire data set, # including the edges. # Polynomial test data. # Transpose everything, and test again with axis=0. # Test mode='interp' with a 3-D array. # z has shape (3, 2, 21) # z has shape (3, 21, 2) # z has shape (21, 3, 2)
| 2.100877
| 2
|
.gitlab-ci/bare-metal/cros_servo_run.py
|
pundiramit/external-mesa3d
| 0
|
6626291
|
#!/usr/bin/env python3
#
# Copyright © 2020 Google LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import argparse
import queue
import re
from serial_buffer import SerialBuffer
import sys
import threading
class CrosServoRun:
def __init__(self, cpu, ec):
# Merged FIFO for the two serial buffers, fed by threads.
self.serial_queue = queue.Queue()
self.sentinel = object()
self.threads_done = 0
self.ec_ser = SerialBuffer(
ec, "results/serial-ec.txt", "R SERIAL-EC> ")
self.cpu_ser = SerialBuffer(
cpu, "results/serial.txt", "R SERIAL-CPU> ")
self.iter_feed_ec = threading.Thread(
target=self.iter_feed_queue, daemon=True, args=(self.ec_ser.lines(),))
self.iter_feed_ec.start()
self.iter_feed_cpu = threading.Thread(
target=self.iter_feed_queue, daemon=True, args=(self.cpu_ser.lines(),))
self.iter_feed_cpu.start()
# Feed lines from our serial queues into the merged queue, marking when our
# input is done.
def iter_feed_queue(self, it):
for i in it:
self.serial_queue.put(i)
self.serial_queue.put(sentinel)
# Return the next line from the queue, counting how many threads have
# terminated and joining when done
def get_serial_queue_line(self):
line = self.serial_queue.get()
if line == self.sentinel:
self.threads_done = self.threads_done + 1
if self.threads_done == 2:
self.iter_feed_cpu.join()
self.iter_feed_ec.join()
return line
# Returns an iterator for getting the next line.
def serial_queue_lines(self):
return iter(self.get_serial_queue_line, self.sentinel)
def ec_write(self, s):
print("W SERIAL-EC> %s" % s)
self.ec_ser.serial.write(s.encode())
def cpu_write(self, s):
print("W SERIAL-CPU> %s" % s)
self.cpu_ser.serial.write(s.encode())
def run(self):
# Flush any partial commands in the EC's prompt, then ask for a reboot.
self.ec_write("\n")
self.ec_write("reboot\n")
# This is emitted right when the bootloader pauses to check for input.
# Emit a ^N character to request network boot, because we don't have a
# direct-to-netboot firmware on cheza.
for line in self.serial_queue_lines():
if re.search("load_archive: loading locale_en.bin", line):
self.cpu_write("\016")
break
# The Cheza boards have issues with failing to bring up power to
# the system sometimes, possibly dependent on ambient temperature
# in the farm.
if re.search("POWER_GOOD not seen in time", line):
print("Detected intermittent poweron failure, restarting run...")
return 2
tftp_failures = 0
for line in self.serial_queue_lines():
if re.search("---. end Kernel panic", line):
return 1
# The Cheza firmware seems to occasionally get stuck looping in
# this error state during TFTP booting, possibly based on amount of
# network traffic around it, but it'll usually recover after a
# reboot.
if re.search("R8152: Bulk read error 0xffffffbf", line):
tftp_failures += 1
if tftp_failures >= 100:
print("Detected intermittent tftp failure, restarting run...")
return 2
# There are very infrequent bus errors during power management transitions
# on cheza, which we don't expect to be the case on future boards.
if re.search("Kernel panic - not syncing: Asynchronous SError Interrupt", line):
print("Detected cheza power management bus error, restarting run...")
return 2
# These HFI response errors started appearing with the introduction
# of piglit runs. CosmicPenguin says:
#
# "message ID 106 isn't a thing, so likely what happened is that we
# got confused when parsing the HFI queue. If it happened on only
# one run, then memory corruption could be a possible clue"
#
# Given that it seems to trigger randomly near a GPU fault and then
# break many tests after that, just restart the whole run.
if re.search("a6xx_hfi_send_msg.*Unexpected message id .* on the response queue", line):
print("Detected cheza power management bus error, restarting run...")
return 2
result = re.search("bare-metal result: (\S*)", line)
if result:
if result.group(1) == "pass":
return 0
else:
return 1
print("Reached the end of the CPU serial log without finding a result")
return 1
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--cpu', type=str,
help='CPU Serial device', required=True)
parser.add_argument(
'--ec', type=str, help='EC Serial device', required=True)
args = parser.parse_args()
servo = CrosServoRun(args.cpu, args.ec)
while True:
retval = servo.run()
if retval != 2:
break
# power down the CPU on the device
servo.ec_write("power off\n")
sys.exit(retval)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
#
# Copyright © 2020 Google LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice (including the next
# paragraph) shall be included in all copies or substantial portions of the
# Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import argparse
import queue
import re
from serial_buffer import SerialBuffer
import sys
import threading
class CrosServoRun:
def __init__(self, cpu, ec):
# Merged FIFO for the two serial buffers, fed by threads.
self.serial_queue = queue.Queue()
self.sentinel = object()
self.threads_done = 0
self.ec_ser = SerialBuffer(
ec, "results/serial-ec.txt", "R SERIAL-EC> ")
self.cpu_ser = SerialBuffer(
cpu, "results/serial.txt", "R SERIAL-CPU> ")
self.iter_feed_ec = threading.Thread(
target=self.iter_feed_queue, daemon=True, args=(self.ec_ser.lines(),))
self.iter_feed_ec.start()
self.iter_feed_cpu = threading.Thread(
target=self.iter_feed_queue, daemon=True, args=(self.cpu_ser.lines(),))
self.iter_feed_cpu.start()
# Feed lines from our serial queues into the merged queue, marking when our
# input is done.
def iter_feed_queue(self, it):
for i in it:
self.serial_queue.put(i)
self.serial_queue.put(sentinel)
# Return the next line from the queue, counting how many threads have
# terminated and joining when done
def get_serial_queue_line(self):
line = self.serial_queue.get()
if line == self.sentinel:
self.threads_done = self.threads_done + 1
if self.threads_done == 2:
self.iter_feed_cpu.join()
self.iter_feed_ec.join()
return line
# Returns an iterator for getting the next line.
def serial_queue_lines(self):
return iter(self.get_serial_queue_line, self.sentinel)
def ec_write(self, s):
print("W SERIAL-EC> %s" % s)
self.ec_ser.serial.write(s.encode())
def cpu_write(self, s):
print("W SERIAL-CPU> %s" % s)
self.cpu_ser.serial.write(s.encode())
def run(self):
# Flush any partial commands in the EC's prompt, then ask for a reboot.
self.ec_write("\n")
self.ec_write("reboot\n")
# This is emitted right when the bootloader pauses to check for input.
# Emit a ^N character to request network boot, because we don't have a
# direct-to-netboot firmware on cheza.
for line in self.serial_queue_lines():
if re.search("load_archive: loading locale_en.bin", line):
self.cpu_write("\016")
break
# The Cheza boards have issues with failing to bring up power to
# the system sometimes, possibly dependent on ambient temperature
# in the farm.
if re.search("POWER_GOOD not seen in time", line):
print("Detected intermittent poweron failure, restarting run...")
return 2
tftp_failures = 0
for line in self.serial_queue_lines():
if re.search("---. end Kernel panic", line):
return 1
# The Cheza firmware seems to occasionally get stuck looping in
# this error state during TFTP booting, possibly based on amount of
# network traffic around it, but it'll usually recover after a
# reboot.
if re.search("R8152: Bulk read error 0xffffffbf", line):
tftp_failures += 1
if tftp_failures >= 100:
print("Detected intermittent tftp failure, restarting run...")
return 2
# There are very infrequent bus errors during power management transitions
# on cheza, which we don't expect to be the case on future boards.
if re.search("Kernel panic - not syncing: Asynchronous SError Interrupt", line):
print("Detected cheza power management bus error, restarting run...")
return 2
# These HFI response errors started appearing with the introduction
# of piglit runs. CosmicPenguin says:
#
# "message ID 106 isn't a thing, so likely what happened is that we
# got confused when parsing the HFI queue. If it happened on only
# one run, then memory corruption could be a possible clue"
#
# Given that it seems to trigger randomly near a GPU fault and then
# break many tests after that, just restart the whole run.
if re.search("a6xx_hfi_send_msg.*Unexpected message id .* on the response queue", line):
print("Detected cheza power management bus error, restarting run...")
return 2
result = re.search("bare-metal result: (\S*)", line)
if result:
if result.group(1) == "pass":
return 0
else:
return 1
print("Reached the end of the CPU serial log without finding a result")
return 1
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--cpu', type=str,
help='CPU Serial device', required=True)
parser.add_argument(
'--ec', type=str, help='EC Serial device', required=True)
args = parser.parse_args()
servo = CrosServoRun(args.cpu, args.ec)
while True:
retval = servo.run()
if retval != 2:
break
# power down the CPU on the device
servo.ec_write("power off\n")
sys.exit(retval)
if __name__ == '__main__':
main()
|
en
| 0.90138
|
#!/usr/bin/env python3 # # Copyright © 2020 Google LLC # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice (including the next # paragraph) shall be included in all copies or substantial portions of the # Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # Merged FIFO for the two serial buffers, fed by threads. # Feed lines from our serial queues into the merged queue, marking when our # input is done. # Return the next line from the queue, counting how many threads have # terminated and joining when done # Returns an iterator for getting the next line. # Flush any partial commands in the EC's prompt, then ask for a reboot. # This is emitted right when the bootloader pauses to check for input. # Emit a ^N character to request network boot, because we don't have a # direct-to-netboot firmware on cheza. # The Cheza boards have issues with failing to bring up power to # the system sometimes, possibly dependent on ambient temperature # in the farm. # The Cheza firmware seems to occasionally get stuck looping in # this error state during TFTP booting, possibly based on amount of # network traffic around it, but it'll usually recover after a # reboot. # There are very infrequent bus errors during power management transitions # on cheza, which we don't expect to be the case on future boards. # These HFI response errors started appearing with the introduction # of piglit runs. CosmicPenguin says: # # "message ID 106 isn't a thing, so likely what happened is that we # got confused when parsing the HFI queue. If it happened on only # one run, then memory corruption could be a possible clue" # # Given that it seems to trigger randomly near a GPU fault and then # break many tests after that, just restart the whole run. # power down the CPU on the device
| 2.091293
| 2
|
server.py
|
Rudiakru/Chatbot
| 0
|
6626292
|
from flask import Flask
app = Flask(__name__)
from flask import render_template
from flask import request
from collections import deque
messages = deque()
import sys
sys.path.append("./..")
#LADE AIML BOT
from aiml import Kernel
import sys
kern = Kernel()
brainLoaded = False
forceReload = True
while not brainLoaded:
if forceReload or (len(sys.argv) >= 2 and sys.argv[1] == "reload"):
kern.bootstrap(learnFiles="std-startup.xml", commands="load aiml b")
brainLoaded = True
kern.saveBrain("standard.brn")
else:
try:
kern.bootstrap(brainFile="standard.brn")
brainLoaded = True
except:
forceReload = True
messages.append(kern.respond("start"))
#BOT FERTIG
@app.route("/")
def hello():
return app.send_static_file('chat-index.html')
@app.route("/sendMessage", methods = ["POST"])
def sendMessage():
print("rein")
print(request.form["msg"])
messages.append(kern.respond(request.form["msg"]))
return "nachricht"
@app.route("/getMessages", methods = ["GET"])
def getMessages():
print("raus")
if len(messages) > 0:
return messages.popleft()
else:
return ""
if __name__ == "__main__":
app.run()
|
from flask import Flask
app = Flask(__name__)
from flask import render_template
from flask import request
from collections import deque
messages = deque()
import sys
sys.path.append("./..")
#LADE AIML BOT
from aiml import Kernel
import sys
kern = Kernel()
brainLoaded = False
forceReload = True
while not brainLoaded:
if forceReload or (len(sys.argv) >= 2 and sys.argv[1] == "reload"):
kern.bootstrap(learnFiles="std-startup.xml", commands="load aiml b")
brainLoaded = True
kern.saveBrain("standard.brn")
else:
try:
kern.bootstrap(brainFile="standard.brn")
brainLoaded = True
except:
forceReload = True
messages.append(kern.respond("start"))
#BOT FERTIG
@app.route("/")
def hello():
return app.send_static_file('chat-index.html')
@app.route("/sendMessage", methods = ["POST"])
def sendMessage():
print("rein")
print(request.form["msg"])
messages.append(kern.respond(request.form["msg"]))
return "nachricht"
@app.route("/getMessages", methods = ["GET"])
def getMessages():
print("raus")
if len(messages) > 0:
return messages.popleft()
else:
return ""
if __name__ == "__main__":
app.run()
|
en
| 0.214458
|
#LADE AIML BOT #BOT FERTIG
| 2.410307
| 2
|
src/ssosp/request_response.py
|
barsgroup/m3-ssosp
| 0
|
6626293
|
<gh_stars>0
# coding:utf-8
u"""
Классы SAML-запросов и ответов
"""
from __future__ import absolute_import
from six.moves.urllib.parse import quote
from importlib import import_module
from django.conf import settings
from django.contrib.auth import login, logout
from django.shortcuts import redirect
from m3_django_compat import get_user_model
from ssosp.assertion_parser import (assertion_to_xml, build_assertion,
get_attributes_from_assertion,
get_session_from_request_assertion,
get_session_from_response_assertion,
get_userid_from_assertion,
is_logout_request, is_logout_response,
sign_request, verify_assertion,
xml_to_assertion)
from ssosp.exceptions import SSOLoginException
from ssosp.settings import get_sso_setting
from ssosp.utils import (decode_base64, decode_base64_and_inflate,
deflate_and_base64_encode, get_random_id,
get_time_string)
class SSOException(Exception):
u"""
Класс исключений работы с SSO
"""
pass
def get_session_map():
u"""
Получение бэкенда хранения соответствия сессий, указанного в
настройке SSO_CONFIG['session_map']
:return: Экземпляр бэкенда, наследника BaseSSOSessionMap
:rtype: ssosp.backends.base.BaseSSOSessionMap
"""
session_map_engine = get_sso_setting('session_map')
engine = import_module(session_map_engine)
return engine.SSOSessionMap()
def get_method(method_str):
u"""
Получение функции, представленной строкой с полным путем
:param basesting method_str: полный путь к функции
:return: указатель на функцию или None, если строка пустая
"""
if method_str:
module = '.'.join(method_str.split('.')[:-1])
method = method_str.split('.')[-1]
mod = import_module(module)
return getattr(mod, method)
else:
return None
class SAMLObject(object):
u"""
Базовый класс SAML-объекта
"""
def __init__(self, request):
u"""
Инициализация
:param request: запрос, в рамках которого создан объект
:type request: django.http.HttpRequest
"""
self.idp_url = get_sso_setting('idp')
self.issuer = get_sso_setting('issuer')
self.service_index = get_sso_setting('index')
self.acs_url = request.build_absolute_uri(get_sso_setting('acs'))
self.signing = get_sso_setting('signing')
self.validate = get_sso_setting('validate')
self.public_key_str = get_sso_setting('public_key')
self.private_key_str = get_sso_setting('private_key')
self.logout_method = get_method(get_sso_setting('logout'))
self.login_method = get_method(get_sso_setting('login'))
self.get_user_method = get_method(get_sso_setting('get_user'))
class AuthResponse(SAMLObject):
u"""
SAML-ответ на запрос аутентификации
"""
def __init__(self, request):
super(AuthResponse, self).__init__(request)
def from_assertion(self, assertion):
u"""
Заполнить из утверждения. Загрузить.
Определяется сессия, пользователь, атрибуты пользователя.
:param assertion: Утверждение, из которого надо получить данные
:type assertion: etree.ElementTree
"""
if self.validate and (not self.public_key_str
or not verify_assertion(assertion,
self.public_key_str)):
raise SSOException("Response not valid")
self.session_id = get_session_from_response_assertion(assertion)
self.attributes = get_attributes_from_assertion(assertion)
userid = get_userid_from_assertion(assertion)
if self.get_user_method:
self.user = self.get_user_method(userid, self.attributes)
else:
User = get_user_model()
try:
self.user = User.objects.get(username=userid)
# возьмем первый попавшийся бэкенд
self.user.backend = settings.AUTHENTICATION_BACKENDS[0]
except User.DoesNotExist:
self.user = None
def do_login(self, request, next_url):
u"""
Выполнить вход в систему.
Атрибуты пользователя сохраняются в сессию.
Сохраняется соответствие SSO-сессии и django-сессии.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
:param basestring next_url: адрес, на который вернуться после входа
:return: ответ на запрос - редирект на адрес возврата
:rtype: django.http.HttpResponseRedirect
"""
if self.login_method:
try:
self.login_method(request, self.user)
except SSOLoginException as ex:
return redirect(u'{}?msg={}'.format(ex.next_url, ex.message))
else:
login(request, self.user)
request.session['attributes'] = self.attributes
# сохраним соответствие SSO-сессии и django-сессии
if self.session_id:
session_map = get_session_map()
session_map.set_session_map(self.session_id,
request.session.session_key)
return redirect(next_url)
class LogoutResponse(SAMLObject):
u"""
SAML-ответ на запрос выхода из системы
"""
def __init__(self, request):
super(LogoutResponse, self).__init__(request)
def from_assertion(self, assertion):
u"""
Заполнить из утверждения. Загрузить.
Просто проверим цифровую подпись, если надо.
:param assertion: Утверждение, из которого надо получить данные
:type assertion: etree.ElementTree
"""
if self.validate and (not self.public_key_str
or not verify_assertion(assertion,
self.public_key_str)):
raise SSOException("Response not valid")
def do_logout(self, request, next_url):
u"""
Выполнить выход из системы.
Удаляется соответствие SSO-сессии и django-сессии.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
:param basestring next_url: адрес, на который вернуться после выхода
:return: ответ на запрос - редирект на адрес возврата
:rtype: django.http.HttpResponseRedirect
"""
session_map = get_session_map()
session_key = request.session.session_key
if self.logout_method:
self.logout_method(request)
else:
logout(request)
session_map.delete_by_django_session(session_key)
return redirect(next_url)
class AuthRequest(SAMLObject):
u"""
SAML-запрос на вход в систему
"""
def __init__(self, request):
super(AuthRequest, self).__init__(request)
def get_request(self):
u"""
Получить SAML-запрос.
Формируется утверждение AuthnRequest и преобразовывается в строку.
:return: Утверждение для входа в систему, представленное в виде строки
:rtype: basestring
"""
assertion_struct = {
'tag': '{samlp}AuthnRequest',
'attrs': {
'AssertionConsumerServiceURL': self.acs_url,
'Destination': self.idp_url,
'ID': get_random_id(),
'IssueInstant': get_time_string(),
'ProtocolBinding':
"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
'Version': "2.0",
},
'nsmap': {'samlp': 'urn:oasis:names:tc:SAML:2.0:protocol',
'saml': 'urn:oasis:names:tc:SAML:2.0:assertion'},
'value': [
{
'tag': '{saml}Issuer',
'value': self.issuer,
},
{
'tag': '{saml}AttributeQuery',
'value': [
{
'tag': '{saml}Attribute',
'attrs': {'Name': 'role'}
}
]
}
],
}
if self.service_index:
assertion_struct['attrs']['AttributeConsumingServiceIndex'] = \
self.service_index
assertion = build_assertion(assertion_struct)
req = get_str_from_assertion(assertion)
return req
def get_login(self, next_url):
u"""
Получить GET-запрос на вход в систему.
:param basestring next_url: адрес, на который вернуться после входа
:return: редирект на адрес SSO с SAML-запросом на вход в качестве
параметра
:rtype: django.http.HttpResponseRedirect
"""
request_str = self.get_request()
if self.signing and self.private_key_str:
req = 'SAMLRequest=%s&RelayState=%s&SigAlg=%s' % (
quote(request_str),
quote(next_url),
quote('http://www.w3.org/2000/09/xmldsig#rsa-sha1'),
)
signature = sign_request(req, self.private_key_str)
login_url = '%s?%s&Signature=%s' % (
self.idp_url, req,
quote(signature),
)
else:
login_url = '%s?SAMLRequest=%s&RelayState=%s' % (
self.idp_url, quote(request_str), quote(next_url)
)
return redirect(login_url)
class LogoutRequest(SAMLObject):
u"""
SAML-запрос на выход из системы
"""
def __init__(self, request):
super(LogoutRequest, self).__init__(request)
session_map = get_session_map()
self.session_id = session_map.get_sso_session_key(
request.session.session_key)
def from_assertion(self, assertion):
u"""
Заполнить из утверждения. Загрузить.
Просто проверим цифровую подпись, если надо.
И вытащим сессию, если ее передали в утверждении.
:param assertion: Утверждение, из которого надо получить данные
:type assertion: etree.ElementTree
"""
if self.validate and (not self.public_key_str
or not verify_assertion(assertion,
self.public_key_str)):
raise SSOException("Response not valid")
self.session_id = get_session_from_request_assertion(assertion)
def do_logout_by_session(self, request):
u"""
Осуществить выход из систему по сессии SSO.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
"""
session_map = get_session_map()
# найдем django-сессию, соответствующую SSO-сессии
if session_map.exists_sso_session(self.session_id):
engine = import_module(settings.SESSION_ENGINE)
session_key = session_map.get_django_session_key(self.session_id)
request.session = engine.SessionStore(session_key)
if self.logout_method:
self.logout_method(request)
else:
logout(request)
session_map.delete_by_sso_session(self.session_id)
else:
# на нашли соответствующую сессию
pass
def get_request(self, username):
u"""
Получить SAML-запрос на выход.
Формируется утверждение LogoutRequest и преобразовывается в строку.
Используется текущая сессия: либо загруженная, либо определенная из
request.
:param basestring username: пользователь, который должен выйти из
системы. (Похоже, что уже не надо использовать)
:return: Утверждение для выхода из системы, представленное в виде строки
:rtype: basestring
"""
assertion_struct = {
'tag': '{samlp}LogoutRequest',
'attrs': {
'AssertionConsumerServiceURL': self.acs_url,
'ID': get_random_id(),
'Destination': self.idp_url,
'IssueInstant': get_time_string(),
'ProtocolBinding':
"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
'Version': "2.0",
'AttributeConsumingServiceIndex': self.service_index,
},
'nsmap': {'samlp': 'urn:oasis:names:tc:SAML:2.0:protocol',
'saml': 'urn:oasis:names:tc:SAML:2.0:assertion'},
'value': [
{
'tag': '{saml}Issuer',
'value': self.issuer,
},
{
'tag': '{saml}NameID',
'value': username,
},
],
}
if self.session_id:
assertion_struct['value'].append({
'tag': '{samlp}SessionIndex',
'value': self.session_id,
})
assertion = build_assertion(assertion_struct)
req = get_str_from_assertion(assertion)
return req
def get_logout(self, username, next_url):
u"""
Получить GET-запрос на выход из системы.
:param basestring username: пользователь, который должен выйти из
системы. (Похоже, что уже не надо использовать)
:param basestring next_url: адрес, на который вернуться после входа
:return: редирект на адрес SSO с SAML-запросом на выход в качестве
параметра
:rtype: django.http.HttpResponseRedirect
"""
request_str = self.get_request(username)
if self.signing and self.private_key_str:
req = 'SAMLRequest=%s&RelayState=%s&SigAlg=%s' % (
quote(request_str),
quote(next_url),
quote('http://www.w3.org/2000/09/xmldsig#rsa-sha1'),
)
signature = sign_request(req, self.private_key_str)
logout_url = '%s?%s&Signature=%s' % (
self.idp_url, req,
quote(signature),
)
else:
logout_url = '%s?SAMLRequest=%s&RelayState=%s' % (
self.idp_url, quote(request_str),
quote(next_url)
)
return redirect(logout_url)
def do_logout(self, request):
u"""
Осуществить выход из систему по текущей сессии django.
Сессия получается из текущего запроса.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
"""
session_map = get_session_map()
session_key = request.session.session_key
if self.logout_method:
self.logout_method(request)
else:
logout(request)
session_map.delete_by_django_session(session_key)
def get_response_from_data(request, xml_string):
u"""
Получить утверждение-ответ из xml-строки.
Используется для определения объекта в сервисе ACS.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
:param basestring xml_string: xml-строка, содержащая утверждение
:return: объект Response, преобразованный из xml-строки
:rtype: либо LogoutResponse, либо AuthResponse
"""
if get_sso_setting('zipped'):
assertion_str = decode_base64_and_inflate(xml_string)
else:
assertion_str = decode_base64(xml_string)
assertion = xml_to_assertion(assertion_str)
if is_logout_response(assertion):
response = LogoutResponse(request)
response.from_assertion(assertion)
return response
else:
response = AuthResponse(request)
response.from_assertion(assertion)
return response
def get_request_from_data(request, xml_string):
u"""
Получить утверждение-запрос из xml-строки.
Используется для определения объекта в сервисе ACS.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
:param xml_string: xml-строка, содержащая утверждение
:type xml_string: basestring
:return: объект Request, преобразованный из xml-строки
:rtype: LogoutRequest | None
"""
if get_sso_setting('zipped'):
assertion_str = decode_base64_and_inflate(xml_string)
else:
assertion_str = decode_base64(xml_string)
assertion = xml_to_assertion(assertion_str)
if is_logout_request(assertion):
request = LogoutRequest(request)
request.from_assertion(assertion)
return request
else:
return None
def get_str_from_assertion(assertion):
u"""
Преобразовать утверждение в строку перекодированную и упакованную.
:param assertion: Утверждение (Assertion, xml)
:type assertion: etree.ElementTree
:return: xml-строка, содержащая утверждение
:rtype: basestring
"""
xml_string = assertion_to_xml(assertion)
assertion_str = deflate_and_base64_encode(xml_string)
return assertion_str
|
# coding:utf-8
u"""
Классы SAML-запросов и ответов
"""
from __future__ import absolute_import
from six.moves.urllib.parse import quote
from importlib import import_module
from django.conf import settings
from django.contrib.auth import login, logout
from django.shortcuts import redirect
from m3_django_compat import get_user_model
from ssosp.assertion_parser import (assertion_to_xml, build_assertion,
get_attributes_from_assertion,
get_session_from_request_assertion,
get_session_from_response_assertion,
get_userid_from_assertion,
is_logout_request, is_logout_response,
sign_request, verify_assertion,
xml_to_assertion)
from ssosp.exceptions import SSOLoginException
from ssosp.settings import get_sso_setting
from ssosp.utils import (decode_base64, decode_base64_and_inflate,
deflate_and_base64_encode, get_random_id,
get_time_string)
class SSOException(Exception):
u"""
Класс исключений работы с SSO
"""
pass
def get_session_map():
u"""
Получение бэкенда хранения соответствия сессий, указанного в
настройке SSO_CONFIG['session_map']
:return: Экземпляр бэкенда, наследника BaseSSOSessionMap
:rtype: ssosp.backends.base.BaseSSOSessionMap
"""
session_map_engine = get_sso_setting('session_map')
engine = import_module(session_map_engine)
return engine.SSOSessionMap()
def get_method(method_str):
u"""
Получение функции, представленной строкой с полным путем
:param basesting method_str: полный путь к функции
:return: указатель на функцию или None, если строка пустая
"""
if method_str:
module = '.'.join(method_str.split('.')[:-1])
method = method_str.split('.')[-1]
mod = import_module(module)
return getattr(mod, method)
else:
return None
class SAMLObject(object):
u"""
Базовый класс SAML-объекта
"""
def __init__(self, request):
u"""
Инициализация
:param request: запрос, в рамках которого создан объект
:type request: django.http.HttpRequest
"""
self.idp_url = get_sso_setting('idp')
self.issuer = get_sso_setting('issuer')
self.service_index = get_sso_setting('index')
self.acs_url = request.build_absolute_uri(get_sso_setting('acs'))
self.signing = get_sso_setting('signing')
self.validate = get_sso_setting('validate')
self.public_key_str = get_sso_setting('public_key')
self.private_key_str = get_sso_setting('private_key')
self.logout_method = get_method(get_sso_setting('logout'))
self.login_method = get_method(get_sso_setting('login'))
self.get_user_method = get_method(get_sso_setting('get_user'))
class AuthResponse(SAMLObject):
u"""
SAML-ответ на запрос аутентификации
"""
def __init__(self, request):
super(AuthResponse, self).__init__(request)
def from_assertion(self, assertion):
u"""
Заполнить из утверждения. Загрузить.
Определяется сессия, пользователь, атрибуты пользователя.
:param assertion: Утверждение, из которого надо получить данные
:type assertion: etree.ElementTree
"""
if self.validate and (not self.public_key_str
or not verify_assertion(assertion,
self.public_key_str)):
raise SSOException("Response not valid")
self.session_id = get_session_from_response_assertion(assertion)
self.attributes = get_attributes_from_assertion(assertion)
userid = get_userid_from_assertion(assertion)
if self.get_user_method:
self.user = self.get_user_method(userid, self.attributes)
else:
User = get_user_model()
try:
self.user = User.objects.get(username=userid)
# возьмем первый попавшийся бэкенд
self.user.backend = settings.AUTHENTICATION_BACKENDS[0]
except User.DoesNotExist:
self.user = None
def do_login(self, request, next_url):
u"""
Выполнить вход в систему.
Атрибуты пользователя сохраняются в сессию.
Сохраняется соответствие SSO-сессии и django-сессии.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
:param basestring next_url: адрес, на который вернуться после входа
:return: ответ на запрос - редирект на адрес возврата
:rtype: django.http.HttpResponseRedirect
"""
if self.login_method:
try:
self.login_method(request, self.user)
except SSOLoginException as ex:
return redirect(u'{}?msg={}'.format(ex.next_url, ex.message))
else:
login(request, self.user)
request.session['attributes'] = self.attributes
# сохраним соответствие SSO-сессии и django-сессии
if self.session_id:
session_map = get_session_map()
session_map.set_session_map(self.session_id,
request.session.session_key)
return redirect(next_url)
class LogoutResponse(SAMLObject):
u"""
SAML-ответ на запрос выхода из системы
"""
def __init__(self, request):
super(LogoutResponse, self).__init__(request)
def from_assertion(self, assertion):
u"""
Заполнить из утверждения. Загрузить.
Просто проверим цифровую подпись, если надо.
:param assertion: Утверждение, из которого надо получить данные
:type assertion: etree.ElementTree
"""
if self.validate and (not self.public_key_str
or not verify_assertion(assertion,
self.public_key_str)):
raise SSOException("Response not valid")
def do_logout(self, request, next_url):
u"""
Выполнить выход из системы.
Удаляется соответствие SSO-сессии и django-сессии.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
:param basestring next_url: адрес, на который вернуться после выхода
:return: ответ на запрос - редирект на адрес возврата
:rtype: django.http.HttpResponseRedirect
"""
session_map = get_session_map()
session_key = request.session.session_key
if self.logout_method:
self.logout_method(request)
else:
logout(request)
session_map.delete_by_django_session(session_key)
return redirect(next_url)
class AuthRequest(SAMLObject):
u"""
SAML-запрос на вход в систему
"""
def __init__(self, request):
super(AuthRequest, self).__init__(request)
def get_request(self):
u"""
Получить SAML-запрос.
Формируется утверждение AuthnRequest и преобразовывается в строку.
:return: Утверждение для входа в систему, представленное в виде строки
:rtype: basestring
"""
assertion_struct = {
'tag': '{samlp}AuthnRequest',
'attrs': {
'AssertionConsumerServiceURL': self.acs_url,
'Destination': self.idp_url,
'ID': get_random_id(),
'IssueInstant': get_time_string(),
'ProtocolBinding':
"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
'Version': "2.0",
},
'nsmap': {'samlp': 'urn:oasis:names:tc:SAML:2.0:protocol',
'saml': 'urn:oasis:names:tc:SAML:2.0:assertion'},
'value': [
{
'tag': '{saml}Issuer',
'value': self.issuer,
},
{
'tag': '{saml}AttributeQuery',
'value': [
{
'tag': '{saml}Attribute',
'attrs': {'Name': 'role'}
}
]
}
],
}
if self.service_index:
assertion_struct['attrs']['AttributeConsumingServiceIndex'] = \
self.service_index
assertion = build_assertion(assertion_struct)
req = get_str_from_assertion(assertion)
return req
def get_login(self, next_url):
u"""
Получить GET-запрос на вход в систему.
:param basestring next_url: адрес, на который вернуться после входа
:return: редирект на адрес SSO с SAML-запросом на вход в качестве
параметра
:rtype: django.http.HttpResponseRedirect
"""
request_str = self.get_request()
if self.signing and self.private_key_str:
req = 'SAMLRequest=%s&RelayState=%s&SigAlg=%s' % (
quote(request_str),
quote(next_url),
quote('http://www.w3.org/2000/09/xmldsig#rsa-sha1'),
)
signature = sign_request(req, self.private_key_str)
login_url = '%s?%s&Signature=%s' % (
self.idp_url, req,
quote(signature),
)
else:
login_url = '%s?SAMLRequest=%s&RelayState=%s' % (
self.idp_url, quote(request_str), quote(next_url)
)
return redirect(login_url)
class LogoutRequest(SAMLObject):
u"""
SAML-запрос на выход из системы
"""
def __init__(self, request):
super(LogoutRequest, self).__init__(request)
session_map = get_session_map()
self.session_id = session_map.get_sso_session_key(
request.session.session_key)
def from_assertion(self, assertion):
u"""
Заполнить из утверждения. Загрузить.
Просто проверим цифровую подпись, если надо.
И вытащим сессию, если ее передали в утверждении.
:param assertion: Утверждение, из которого надо получить данные
:type assertion: etree.ElementTree
"""
if self.validate and (not self.public_key_str
or not verify_assertion(assertion,
self.public_key_str)):
raise SSOException("Response not valid")
self.session_id = get_session_from_request_assertion(assertion)
def do_logout_by_session(self, request):
u"""
Осуществить выход из систему по сессии SSO.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
"""
session_map = get_session_map()
# найдем django-сессию, соответствующую SSO-сессии
if session_map.exists_sso_session(self.session_id):
engine = import_module(settings.SESSION_ENGINE)
session_key = session_map.get_django_session_key(self.session_id)
request.session = engine.SessionStore(session_key)
if self.logout_method:
self.logout_method(request)
else:
logout(request)
session_map.delete_by_sso_session(self.session_id)
else:
# на нашли соответствующую сессию
pass
def get_request(self, username):
u"""
Получить SAML-запрос на выход.
Формируется утверждение LogoutRequest и преобразовывается в строку.
Используется текущая сессия: либо загруженная, либо определенная из
request.
:param basestring username: пользователь, который должен выйти из
системы. (Похоже, что уже не надо использовать)
:return: Утверждение для выхода из системы, представленное в виде строки
:rtype: basestring
"""
assertion_struct = {
'tag': '{samlp}LogoutRequest',
'attrs': {
'AssertionConsumerServiceURL': self.acs_url,
'ID': get_random_id(),
'Destination': self.idp_url,
'IssueInstant': get_time_string(),
'ProtocolBinding':
"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect",
'Version': "2.0",
'AttributeConsumingServiceIndex': self.service_index,
},
'nsmap': {'samlp': 'urn:oasis:names:tc:SAML:2.0:protocol',
'saml': 'urn:oasis:names:tc:SAML:2.0:assertion'},
'value': [
{
'tag': '{saml}Issuer',
'value': self.issuer,
},
{
'tag': '{saml}NameID',
'value': username,
},
],
}
if self.session_id:
assertion_struct['value'].append({
'tag': '{samlp}SessionIndex',
'value': self.session_id,
})
assertion = build_assertion(assertion_struct)
req = get_str_from_assertion(assertion)
return req
def get_logout(self, username, next_url):
u"""
Получить GET-запрос на выход из системы.
:param basestring username: пользователь, который должен выйти из
системы. (Похоже, что уже не надо использовать)
:param basestring next_url: адрес, на который вернуться после входа
:return: редирект на адрес SSO с SAML-запросом на выход в качестве
параметра
:rtype: django.http.HttpResponseRedirect
"""
request_str = self.get_request(username)
if self.signing and self.private_key_str:
req = 'SAMLRequest=%s&RelayState=%s&SigAlg=%s' % (
quote(request_str),
quote(next_url),
quote('http://www.w3.org/2000/09/xmldsig#rsa-sha1'),
)
signature = sign_request(req, self.private_key_str)
logout_url = '%s?%s&Signature=%s' % (
self.idp_url, req,
quote(signature),
)
else:
logout_url = '%s?SAMLRequest=%s&RelayState=%s' % (
self.idp_url, quote(request_str),
quote(next_url)
)
return redirect(logout_url)
def do_logout(self, request):
u"""
Осуществить выход из систему по текущей сессии django.
Сессия получается из текущего запроса.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
"""
session_map = get_session_map()
session_key = request.session.session_key
if self.logout_method:
self.logout_method(request)
else:
logout(request)
session_map.delete_by_django_session(session_key)
def get_response_from_data(request, xml_string):
u"""
Получить утверждение-ответ из xml-строки.
Используется для определения объекта в сервисе ACS.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
:param basestring xml_string: xml-строка, содержащая утверждение
:return: объект Response, преобразованный из xml-строки
:rtype: либо LogoutResponse, либо AuthResponse
"""
if get_sso_setting('zipped'):
assertion_str = decode_base64_and_inflate(xml_string)
else:
assertion_str = decode_base64(xml_string)
assertion = xml_to_assertion(assertion_str)
if is_logout_response(assertion):
response = LogoutResponse(request)
response.from_assertion(assertion)
return response
else:
response = AuthResponse(request)
response.from_assertion(assertion)
return response
def get_request_from_data(request, xml_string):
u"""
Получить утверждение-запрос из xml-строки.
Используется для определения объекта в сервисе ACS.
:param request: запрос, в рамках которого выполняется действие
:type request: django.http.HttpRequest
:param xml_string: xml-строка, содержащая утверждение
:type xml_string: basestring
:return: объект Request, преобразованный из xml-строки
:rtype: LogoutRequest | None
"""
if get_sso_setting('zipped'):
assertion_str = decode_base64_and_inflate(xml_string)
else:
assertion_str = decode_base64(xml_string)
assertion = xml_to_assertion(assertion_str)
if is_logout_request(assertion):
request = LogoutRequest(request)
request.from_assertion(assertion)
return request
else:
return None
def get_str_from_assertion(assertion):
u"""
Преобразовать утверждение в строку перекодированную и упакованную.
:param assertion: Утверждение (Assertion, xml)
:type assertion: etree.ElementTree
:return: xml-строка, содержащая утверждение
:rtype: basestring
"""
xml_string = assertion_to_xml(assertion)
assertion_str = deflate_and_base64_encode(xml_string)
return assertion_str
|
ru
| 0.97902
|
# coding:utf-8 Классы SAML-запросов и ответов Класс исключений работы с SSO Получение бэкенда хранения соответствия сессий, указанного в настройке SSO_CONFIG['session_map'] :return: Экземпляр бэкенда, наследника BaseSSOSessionMap :rtype: ssosp.backends.base.BaseSSOSessionMap Получение функции, представленной строкой с полным путем :param basesting method_str: полный путь к функции :return: указатель на функцию или None, если строка пустая Базовый класс SAML-объекта Инициализация :param request: запрос, в рамках которого создан объект :type request: django.http.HttpRequest SAML-ответ на запрос аутентификации Заполнить из утверждения. Загрузить. Определяется сессия, пользователь, атрибуты пользователя. :param assertion: Утверждение, из которого надо получить данные :type assertion: etree.ElementTree # возьмем первый попавшийся бэкенд Выполнить вход в систему. Атрибуты пользователя сохраняются в сессию. Сохраняется соответствие SSO-сессии и django-сессии. :param request: запрос, в рамках которого выполняется действие :type request: django.http.HttpRequest :param basestring next_url: адрес, на который вернуться после входа :return: ответ на запрос - редирект на адрес возврата :rtype: django.http.HttpResponseRedirect # сохраним соответствие SSO-сессии и django-сессии SAML-ответ на запрос выхода из системы Заполнить из утверждения. Загрузить. Просто проверим цифровую подпись, если надо. :param assertion: Утверждение, из которого надо получить данные :type assertion: etree.ElementTree Выполнить выход из системы. Удаляется соответствие SSO-сессии и django-сессии. :param request: запрос, в рамках которого выполняется действие :type request: django.http.HttpRequest :param basestring next_url: адрес, на который вернуться после выхода :return: ответ на запрос - редирект на адрес возврата :rtype: django.http.HttpResponseRedirect SAML-запрос на вход в систему Получить SAML-запрос. Формируется утверждение AuthnRequest и преобразовывается в строку. :return: Утверждение для входа в систему, представленное в виде строки :rtype: basestring Получить GET-запрос на вход в систему. :param basestring next_url: адрес, на который вернуться после входа :return: редирект на адрес SSO с SAML-запросом на вход в качестве параметра :rtype: django.http.HttpResponseRedirect #rsa-sha1'), SAML-запрос на выход из системы Заполнить из утверждения. Загрузить. Просто проверим цифровую подпись, если надо. И вытащим сессию, если ее передали в утверждении. :param assertion: Утверждение, из которого надо получить данные :type assertion: etree.ElementTree Осуществить выход из систему по сессии SSO. :param request: запрос, в рамках которого выполняется действие :type request: django.http.HttpRequest # найдем django-сессию, соответствующую SSO-сессии # на нашли соответствующую сессию Получить SAML-запрос на выход. Формируется утверждение LogoutRequest и преобразовывается в строку. Используется текущая сессия: либо загруженная, либо определенная из request. :param basestring username: пользователь, который должен выйти из системы. (Похоже, что уже не надо использовать) :return: Утверждение для выхода из системы, представленное в виде строки :rtype: basestring Получить GET-запрос на выход из системы. :param basestring username: пользователь, который должен выйти из системы. (Похоже, что уже не надо использовать) :param basestring next_url: адрес, на который вернуться после входа :return: редирект на адрес SSO с SAML-запросом на выход в качестве параметра :rtype: django.http.HttpResponseRedirect #rsa-sha1'), Осуществить выход из систему по текущей сессии django. Сессия получается из текущего запроса. :param request: запрос, в рамках которого выполняется действие :type request: django.http.HttpRequest Получить утверждение-ответ из xml-строки. Используется для определения объекта в сервисе ACS. :param request: запрос, в рамках которого выполняется действие :type request: django.http.HttpRequest :param basestring xml_string: xml-строка, содержащая утверждение :return: объект Response, преобразованный из xml-строки :rtype: либо LogoutResponse, либо AuthResponse Получить утверждение-запрос из xml-строки. Используется для определения объекта в сервисе ACS. :param request: запрос, в рамках которого выполняется действие :type request: django.http.HttpRequest :param xml_string: xml-строка, содержащая утверждение :type xml_string: basestring :return: объект Request, преобразованный из xml-строки :rtype: LogoutRequest | None Преобразовать утверждение в строку перекодированную и упакованную. :param assertion: Утверждение (Assertion, xml) :type assertion: etree.ElementTree :return: xml-строка, содержащая утверждение :rtype: basestring
| 1.618974
| 2
|
tests/test_synchronize.py
|
pombredanne/loky
| 0
|
6626294
|
<filename>tests/test_synchronize.py
import os
import sys
import time
import pytest
import signal
import threading
from loky.backend import get_context
from .utils import TimingWrapper
loky_context = get_context("loky")
DELTA = 0.1
TIMEOUT1 = .1
TIMEOUT2 = .3
@pytest.mark.skipif(sys.platform == "win32", reason="UNIX test")
def test_semlock_failure():
from loky.backend.synchronize import SemLock, sem_unlink
name = "loky-test-semlock"
try:
sem_unlink(name)
except FileNotFoundError:
pass
try:
sl = SemLock(0, 1, 1, name=name)
assert sl.name == name
with pytest.raises(FileExistsError):
SemLock(0, 1, 1, name=name)
finally:
# Always clean-up the test semaphore to make this test independent of
# previous runs (successful or not).
sem_unlink(name)
with pytest.raises(FileNotFoundError):
sl._semlock._rebuild(0, 0, 0, name)
def assert_sem_value_equal(sem, value):
try:
assert sem.get_value() == value
except NotImplementedError:
pass
def assert_timing_almost_equal(t1, t2=0):
assert abs(t1 - t2) < 1e-1
class TestLock:
def test_lock(self):
lock = loky_context.Lock()
assert lock.acquire()
assert not lock.acquire(False)
assert lock.release() is None
with pytest.raises(ValueError) as excinfo:
lock.release()
assert "released too many times" in str(excinfo.value)
def test_rlock(self):
lock = loky_context.RLock()
assert lock.acquire()
assert lock.acquire()
assert lock.acquire()
assert lock.release() is None
assert lock.release() is None
assert lock.release() is None
with pytest.raises(AssertionError) as excinfo:
lock.release()
assert "not owned by thread" in str(excinfo.value)
def test_lock_context(self):
with loky_context.Lock():
pass
class TestSemaphore:
def _test_semaphore(self, sem):
assert_sem_value_equal(sem, 2)
assert sem.acquire()
assert_sem_value_equal(sem, 1)
assert sem.acquire()
assert_sem_value_equal(sem, 0)
assert not sem.acquire(False)
assert_sem_value_equal(sem, 0)
assert sem.release() is None
assert_sem_value_equal(sem, 1)
assert sem.release() is None
assert_sem_value_equal(sem, 2)
def test_semaphore(self):
sem = loky_context.Semaphore(2)
self._test_semaphore(sem)
assert sem.release() is None
assert_sem_value_equal(sem, 3)
assert sem.release() is None
assert_sem_value_equal(sem, 4)
@pytest.mark.skipif(sys.platform == "darwin",
reason="OSX have borken `get_value`")
def test_bounded_semaphore(self):
sem = loky_context.BoundedSemaphore(2)
self._test_semaphore(sem)
with pytest.raises(ValueError):
sem.release()
assert_sem_value_equal(sem, 2)
def test_timeout(self):
sem = loky_context.Semaphore(0)
acquire = TimingWrapper(sem.acquire)
assert not acquire(False)
assert_timing_almost_equal(acquire.elapsed)
assert not acquire(False, None)
assert_timing_almost_equal(acquire.elapsed)
assert not acquire(False, TIMEOUT1)
assert_timing_almost_equal(acquire.elapsed)
assert not acquire(True, TIMEOUT1)
assert_timing_almost_equal(acquire.elapsed, TIMEOUT1)
assert not acquire(True, TIMEOUT2)
assert_timing_almost_equal(acquire.elapsed, TIMEOUT2)
class TestCondition:
@classmethod
def _test_notify(cls, cond, sleeping, woken, timeout=None):
cond.acquire()
sleeping.release()
cond.wait(timeout)
woken.release()
cond.release()
def check_invariant(self, cond):
# this is only supposed to succeed when there are no sleepers
try:
sleepers = (cond._sleeping_count.get_value() -
cond._woken_count.get_value())
sleepers == 0
cond._wait_semaphore.get_value() == 0
except NotImplementedError:
pass
def test_notify(self):
cond = loky_context.Condition()
sleeping = loky_context.Semaphore(0)
woken = loky_context.Semaphore(0)
p = loky_context.Process(target=self._test_notify,
args=(cond, sleeping, woken))
p.daemon = True
p.start()
p = threading.Thread(target=self._test_notify,
args=(cond, sleeping, woken))
p.daemon = True
p.start()
# wait for both children to start sleeping
sleeping.acquire()
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
assert_sem_value_equal(woken, 0)
# wake up one process/thread
cond.acquire()
cond.notify()
cond.release()
# check one process/thread has woken up
time.sleep(DELTA)
assert_sem_value_equal(woken, 1)
# wake up another
cond.acquire()
cond.notify()
cond.release()
# check other has woken up
time.sleep(DELTA)
assert_sem_value_equal(woken, 2)
# check state is not mucked up
self.check_invariant(cond)
p.join()
def test_notify_all(self):
cond = loky_context.Condition()
sleeping = loky_context.Semaphore(0)
woken = loky_context.Semaphore(0)
# start some threads/processes which will timeout
for _ in range(3):
p = loky_context.Process(target=self._test_notify,
args=(cond, sleeping, woken, TIMEOUT1))
p.daemon = True
p.start()
t = threading.Thread(target=self._test_notify,
args=(cond, sleeping, woken, TIMEOUT1))
t.daemon = True
t.start()
# wait for them all to sleep
for _ in range(6):
sleeping.acquire()
# check they have all timed out
for _ in range(6):
woken.acquire()
assert_sem_value_equal(woken, 0)
# check state is not mucked up
self.check_invariant(cond)
# start some more threads/processes
for _ in range(3):
p = loky_context.Process(target=self._test_notify,
args=(cond, sleeping, woken))
p.daemon = True
p.start()
t = threading.Thread(target=self._test_notify,
args=(cond, sleeping, woken))
t.daemon = True
t.start()
# wait for them to all sleep
for _ in range(6):
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
assert_sem_value_equal(woken, 0)
# wake them all up
cond.acquire()
cond.notify_all()
cond.release()
# check they have all woken
for _ in range(50):
try:
if woken.get_value() == 6:
break
except NotImplementedError:
break
time.sleep(DELTA)
assert_sem_value_equal(woken, 6)
# check state is not mucked up
self.check_invariant(cond)
def test_timeout(self):
cond = loky_context.Condition()
wait = TimingWrapper(cond.wait)
cond.acquire()
res = wait(TIMEOUT1)
cond.release()
assert not res
assert abs(wait.elapsed - TIMEOUT1) < 1e-1
@classmethod
def _test_waitfor_f(cls, cond, state):
with cond:
state.release()
cond.notify()
result = cond.wait_for(lambda: state.get_value() == 5)
if not result or state.get_value() != 5:
sys.exit(1)
def test_waitfor(self):
# based on test in test/lock_tests.py
cond = loky_context.Condition()
state = loky_context.Semaphore(0)
try:
state.get_value()
except NotImplementedError:
pytest.skip(msg="`sem_get_value not implemented")
p = loky_context.Process(target=self._test_waitfor_f,
args=(cond, state))
p.daemon = True
p.start()
with cond:
result = cond.wait_for(lambda: state.get_value() == 1)
assert result
assert state.get_value() == 1
for _ in range(4):
time.sleep(0.01)
with cond:
state.release()
cond.notify()
p.join(5)
assert not p.is_alive()
assert p.exitcode == 0
@classmethod
def _test_wait_result(cls, c, pid):
with c:
c.notify()
time.sleep(1)
if pid is not None:
os.kill(pid, signal.SIGINT)
def test_wait_result(self):
if sys.platform != 'win32':
pid = os.getpid()
else:
pid = None
c = loky_context.Condition()
with c:
assert not c.wait(0)
assert not c.wait(0.1)
p = loky_context.Process(target=self._test_wait_result,
args=(c, pid))
p.start()
assert c.wait(10)
if pid is not None:
with pytest.raises(KeyboardInterrupt):
c.wait(10)
p.join()
class TestEvent:
@classmethod
def _test_event(cls, event):
time.sleep(TIMEOUT1)
event.set()
def test_event(self):
event = loky_context.Event()
wait = TimingWrapper(event.wait)
assert not event.is_set()
assert not wait(0.0)
assert_timing_almost_equal(wait.elapsed)
assert not wait(TIMEOUT1)
assert_timing_almost_equal(wait.elapsed, TIMEOUT1)
event.set()
assert event.is_set()
assert wait()
assert_timing_almost_equal(wait.elapsed)
assert wait(TIMEOUT1)
assert_timing_almost_equal(wait.elapsed)
event.clear()
assert not event.is_set()
p = loky_context.Process(target=self._test_event, args=(event,))
p.daemon = True
p.start()
assert wait()
p.join()
|
<filename>tests/test_synchronize.py
import os
import sys
import time
import pytest
import signal
import threading
from loky.backend import get_context
from .utils import TimingWrapper
loky_context = get_context("loky")
DELTA = 0.1
TIMEOUT1 = .1
TIMEOUT2 = .3
@pytest.mark.skipif(sys.platform == "win32", reason="UNIX test")
def test_semlock_failure():
from loky.backend.synchronize import SemLock, sem_unlink
name = "loky-test-semlock"
try:
sem_unlink(name)
except FileNotFoundError:
pass
try:
sl = SemLock(0, 1, 1, name=name)
assert sl.name == name
with pytest.raises(FileExistsError):
SemLock(0, 1, 1, name=name)
finally:
# Always clean-up the test semaphore to make this test independent of
# previous runs (successful or not).
sem_unlink(name)
with pytest.raises(FileNotFoundError):
sl._semlock._rebuild(0, 0, 0, name)
def assert_sem_value_equal(sem, value):
try:
assert sem.get_value() == value
except NotImplementedError:
pass
def assert_timing_almost_equal(t1, t2=0):
assert abs(t1 - t2) < 1e-1
class TestLock:
def test_lock(self):
lock = loky_context.Lock()
assert lock.acquire()
assert not lock.acquire(False)
assert lock.release() is None
with pytest.raises(ValueError) as excinfo:
lock.release()
assert "released too many times" in str(excinfo.value)
def test_rlock(self):
lock = loky_context.RLock()
assert lock.acquire()
assert lock.acquire()
assert lock.acquire()
assert lock.release() is None
assert lock.release() is None
assert lock.release() is None
with pytest.raises(AssertionError) as excinfo:
lock.release()
assert "not owned by thread" in str(excinfo.value)
def test_lock_context(self):
with loky_context.Lock():
pass
class TestSemaphore:
def _test_semaphore(self, sem):
assert_sem_value_equal(sem, 2)
assert sem.acquire()
assert_sem_value_equal(sem, 1)
assert sem.acquire()
assert_sem_value_equal(sem, 0)
assert not sem.acquire(False)
assert_sem_value_equal(sem, 0)
assert sem.release() is None
assert_sem_value_equal(sem, 1)
assert sem.release() is None
assert_sem_value_equal(sem, 2)
def test_semaphore(self):
sem = loky_context.Semaphore(2)
self._test_semaphore(sem)
assert sem.release() is None
assert_sem_value_equal(sem, 3)
assert sem.release() is None
assert_sem_value_equal(sem, 4)
@pytest.mark.skipif(sys.platform == "darwin",
reason="OSX have borken `get_value`")
def test_bounded_semaphore(self):
sem = loky_context.BoundedSemaphore(2)
self._test_semaphore(sem)
with pytest.raises(ValueError):
sem.release()
assert_sem_value_equal(sem, 2)
def test_timeout(self):
sem = loky_context.Semaphore(0)
acquire = TimingWrapper(sem.acquire)
assert not acquire(False)
assert_timing_almost_equal(acquire.elapsed)
assert not acquire(False, None)
assert_timing_almost_equal(acquire.elapsed)
assert not acquire(False, TIMEOUT1)
assert_timing_almost_equal(acquire.elapsed)
assert not acquire(True, TIMEOUT1)
assert_timing_almost_equal(acquire.elapsed, TIMEOUT1)
assert not acquire(True, TIMEOUT2)
assert_timing_almost_equal(acquire.elapsed, TIMEOUT2)
class TestCondition:
@classmethod
def _test_notify(cls, cond, sleeping, woken, timeout=None):
cond.acquire()
sleeping.release()
cond.wait(timeout)
woken.release()
cond.release()
def check_invariant(self, cond):
# this is only supposed to succeed when there are no sleepers
try:
sleepers = (cond._sleeping_count.get_value() -
cond._woken_count.get_value())
sleepers == 0
cond._wait_semaphore.get_value() == 0
except NotImplementedError:
pass
def test_notify(self):
cond = loky_context.Condition()
sleeping = loky_context.Semaphore(0)
woken = loky_context.Semaphore(0)
p = loky_context.Process(target=self._test_notify,
args=(cond, sleeping, woken))
p.daemon = True
p.start()
p = threading.Thread(target=self._test_notify,
args=(cond, sleeping, woken))
p.daemon = True
p.start()
# wait for both children to start sleeping
sleeping.acquire()
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
assert_sem_value_equal(woken, 0)
# wake up one process/thread
cond.acquire()
cond.notify()
cond.release()
# check one process/thread has woken up
time.sleep(DELTA)
assert_sem_value_equal(woken, 1)
# wake up another
cond.acquire()
cond.notify()
cond.release()
# check other has woken up
time.sleep(DELTA)
assert_sem_value_equal(woken, 2)
# check state is not mucked up
self.check_invariant(cond)
p.join()
def test_notify_all(self):
cond = loky_context.Condition()
sleeping = loky_context.Semaphore(0)
woken = loky_context.Semaphore(0)
# start some threads/processes which will timeout
for _ in range(3):
p = loky_context.Process(target=self._test_notify,
args=(cond, sleeping, woken, TIMEOUT1))
p.daemon = True
p.start()
t = threading.Thread(target=self._test_notify,
args=(cond, sleeping, woken, TIMEOUT1))
t.daemon = True
t.start()
# wait for them all to sleep
for _ in range(6):
sleeping.acquire()
# check they have all timed out
for _ in range(6):
woken.acquire()
assert_sem_value_equal(woken, 0)
# check state is not mucked up
self.check_invariant(cond)
# start some more threads/processes
for _ in range(3):
p = loky_context.Process(target=self._test_notify,
args=(cond, sleeping, woken))
p.daemon = True
p.start()
t = threading.Thread(target=self._test_notify,
args=(cond, sleeping, woken))
t.daemon = True
t.start()
# wait for them to all sleep
for _ in range(6):
sleeping.acquire()
# check no process/thread has woken up
time.sleep(DELTA)
assert_sem_value_equal(woken, 0)
# wake them all up
cond.acquire()
cond.notify_all()
cond.release()
# check they have all woken
for _ in range(50):
try:
if woken.get_value() == 6:
break
except NotImplementedError:
break
time.sleep(DELTA)
assert_sem_value_equal(woken, 6)
# check state is not mucked up
self.check_invariant(cond)
def test_timeout(self):
cond = loky_context.Condition()
wait = TimingWrapper(cond.wait)
cond.acquire()
res = wait(TIMEOUT1)
cond.release()
assert not res
assert abs(wait.elapsed - TIMEOUT1) < 1e-1
@classmethod
def _test_waitfor_f(cls, cond, state):
with cond:
state.release()
cond.notify()
result = cond.wait_for(lambda: state.get_value() == 5)
if not result or state.get_value() != 5:
sys.exit(1)
def test_waitfor(self):
# based on test in test/lock_tests.py
cond = loky_context.Condition()
state = loky_context.Semaphore(0)
try:
state.get_value()
except NotImplementedError:
pytest.skip(msg="`sem_get_value not implemented")
p = loky_context.Process(target=self._test_waitfor_f,
args=(cond, state))
p.daemon = True
p.start()
with cond:
result = cond.wait_for(lambda: state.get_value() == 1)
assert result
assert state.get_value() == 1
for _ in range(4):
time.sleep(0.01)
with cond:
state.release()
cond.notify()
p.join(5)
assert not p.is_alive()
assert p.exitcode == 0
@classmethod
def _test_wait_result(cls, c, pid):
with c:
c.notify()
time.sleep(1)
if pid is not None:
os.kill(pid, signal.SIGINT)
def test_wait_result(self):
if sys.platform != 'win32':
pid = os.getpid()
else:
pid = None
c = loky_context.Condition()
with c:
assert not c.wait(0)
assert not c.wait(0.1)
p = loky_context.Process(target=self._test_wait_result,
args=(c, pid))
p.start()
assert c.wait(10)
if pid is not None:
with pytest.raises(KeyboardInterrupt):
c.wait(10)
p.join()
class TestEvent:
@classmethod
def _test_event(cls, event):
time.sleep(TIMEOUT1)
event.set()
def test_event(self):
event = loky_context.Event()
wait = TimingWrapper(event.wait)
assert not event.is_set()
assert not wait(0.0)
assert_timing_almost_equal(wait.elapsed)
assert not wait(TIMEOUT1)
assert_timing_almost_equal(wait.elapsed, TIMEOUT1)
event.set()
assert event.is_set()
assert wait()
assert_timing_almost_equal(wait.elapsed)
assert wait(TIMEOUT1)
assert_timing_almost_equal(wait.elapsed)
event.clear()
assert not event.is_set()
p = loky_context.Process(target=self._test_event, args=(event,))
p.daemon = True
p.start()
assert wait()
p.join()
|
en
| 0.941853
|
# Always clean-up the test semaphore to make this test independent of # previous runs (successful or not). # this is only supposed to succeed when there are no sleepers # wait for both children to start sleeping # check no process/thread has woken up # wake up one process/thread # check one process/thread has woken up # wake up another # check other has woken up # check state is not mucked up # start some threads/processes which will timeout # wait for them all to sleep # check they have all timed out # check state is not mucked up # start some more threads/processes # wait for them to all sleep # check no process/thread has woken up # wake them all up # check they have all woken # check state is not mucked up # based on test in test/lock_tests.py
| 2.258512
| 2
|
tests/emotion_metrics_test.py
|
apmoore1/nlp-uncertainty-ssl
| 0
|
6626295
|
<filename>tests/emotion_metrics_test.py
import pytest
import numpy as np
from typing import List
from nlp_uncertainty_ssl.emotion_metrics import jaccard_index, f1_metric
@pytest.mark.parametrize("incl_neutral", (True, False))
def test_jaccard_index(incl_neutral: bool):
# Simple case where there is not neutral
predictions = np.array([[0,1,1,0,0], [0,0,0,1,0]])
gold = np.array([[0,1,0,1,1], [0,0,0,1,0]])
answer = (1/4 + 1) / 2
assert answer == jaccard_index(predictions, gold, incl_neutral)
# Case where the neutral class is wrong for predictions
predictions = np.array([[0,1,1,0,0], [0,0,0,1,0], [0,1,1,0,0]])
gold = np.array([[0,1,0,1,1], [0,0,0,1,0], [0,0,0,0,0]])
if incl_neutral:
answer = (1/4 + 1 + 0/3) / 3
assert answer == jaccard_index(predictions, gold, incl_neutral)
else:
answer = (1/4 + 1 + 0/2) / 3
assert answer == jaccard_index(predictions, gold, incl_neutral)
# Case where the neutral case is True for predictions and gold
predictions = np.array([[0,1,1,0,0], [0,0,0,1,0], [0,0,0,0,0]])
gold = np.array([[0,1,0,1,1], [0,0,0,1,0], [0,0,0,0,0]])
if incl_neutral:
answer = (1/4 + 1 + 1) / 3
assert answer == jaccard_index(predictions, gold, incl_neutral)
else:
answer = (1/4 + 1 + 0) / 3
assert answer == jaccard_index(predictions, gold, incl_neutral)
# Check that it raises assertions based on the size of the arrays
predictions = np.array([0,1,1,0,0])
gold = np.array([[0,1,0,1,1], [0,0,0,1,0]])
with pytest.raises(AssertionError):
jaccard_index(predictions, gold, incl_neutral)
predictions = np.array([[0,1,0,1,1], [0,0,0,1,0]])
gold = np.array([0,1,1,0,0])
with pytest.raises(AssertionError):
jaccard_index(predictions, gold, incl_neutral)
from typing import List
def f1_list(precisions: List[float], recalls: List[float]) -> List[float]:
f1_values = []
for precision, recall in zip(precisions, recalls):
if precision == 0 and recall == 0:
f1_values.append(0)
else:
f1 = (2 * precision * recall) / (precision + recall)
f1_values.append(f1)
return f1_values
@pytest.mark.parametrize("incl_neutral", (True, False))
@pytest.mark.parametrize("macro", (True, False))
def test_f1_metric(incl_neutral: bool, macro: bool):
def f1_list(precisions: List[float], recalls: List[float]) -> List[float]:
f1_values = []
for precision, recall in zip(precisions, recalls):
if precision == 0 and recall == 0:
f1_values.append(0.0)
else:
f1 = (2 * precision * recall) / (precision + recall)
f1_values.append(f1)
return f1_values
# Simple case where there is not neutral
predictions = np.array([[1,0,0], [0,1,1]])
gold = np.array([[1,1,0], [1,0,1]])
precision_per_class = [1.0, 0.0, 1.0]
recall_per_class = [0.5, 0.0, 1.0]
num_classes = 3
if incl_neutral:
precision_per_class = [1.0, 0.0, 1.0, 0.0]
recall_per_class = [0.5, 0.0, 1.0, 0.0]
num_classes = 4
if macro:
f1_per_class = f1_list(precision_per_class, recall_per_class)
gold_macro_f1 = sum(f1_per_class) / num_classes
assert gold_macro_f1 == f1_metric(predictions, gold, macro, incl_neutral)
else:
overall_precision = sum(precision_per_class) / 3
overall_recall = sum(recall_per_class) / 3
gold_micro = (2 * overall_precision * overall_recall) / (overall_precision + overall_recall)
assert gold_micro == f1_metric(predictions, gold, macro, incl_neutral)
# Check that it raises assertions based on the size of the arrays
predictions = np.array([0,1,1,0,0])
gold = np.array([[0,1,0,1,1], [0,0,0,1,0]])
with pytest.raises(AssertionError):
f1_metric(predictions, gold, macro, incl_neutral)
predictions = np.array([[0,1,0,1,1], [0,0,0,1,0]])
gold = np.array([0,1,1,0,0])
with pytest.raises(AssertionError):
f1_metric(predictions, gold, macro, incl_neutral)
|
<filename>tests/emotion_metrics_test.py
import pytest
import numpy as np
from typing import List
from nlp_uncertainty_ssl.emotion_metrics import jaccard_index, f1_metric
@pytest.mark.parametrize("incl_neutral", (True, False))
def test_jaccard_index(incl_neutral: bool):
# Simple case where there is not neutral
predictions = np.array([[0,1,1,0,0], [0,0,0,1,0]])
gold = np.array([[0,1,0,1,1], [0,0,0,1,0]])
answer = (1/4 + 1) / 2
assert answer == jaccard_index(predictions, gold, incl_neutral)
# Case where the neutral class is wrong for predictions
predictions = np.array([[0,1,1,0,0], [0,0,0,1,0], [0,1,1,0,0]])
gold = np.array([[0,1,0,1,1], [0,0,0,1,0], [0,0,0,0,0]])
if incl_neutral:
answer = (1/4 + 1 + 0/3) / 3
assert answer == jaccard_index(predictions, gold, incl_neutral)
else:
answer = (1/4 + 1 + 0/2) / 3
assert answer == jaccard_index(predictions, gold, incl_neutral)
# Case where the neutral case is True for predictions and gold
predictions = np.array([[0,1,1,0,0], [0,0,0,1,0], [0,0,0,0,0]])
gold = np.array([[0,1,0,1,1], [0,0,0,1,0], [0,0,0,0,0]])
if incl_neutral:
answer = (1/4 + 1 + 1) / 3
assert answer == jaccard_index(predictions, gold, incl_neutral)
else:
answer = (1/4 + 1 + 0) / 3
assert answer == jaccard_index(predictions, gold, incl_neutral)
# Check that it raises assertions based on the size of the arrays
predictions = np.array([0,1,1,0,0])
gold = np.array([[0,1,0,1,1], [0,0,0,1,0]])
with pytest.raises(AssertionError):
jaccard_index(predictions, gold, incl_neutral)
predictions = np.array([[0,1,0,1,1], [0,0,0,1,0]])
gold = np.array([0,1,1,0,0])
with pytest.raises(AssertionError):
jaccard_index(predictions, gold, incl_neutral)
from typing import List
def f1_list(precisions: List[float], recalls: List[float]) -> List[float]:
f1_values = []
for precision, recall in zip(precisions, recalls):
if precision == 0 and recall == 0:
f1_values.append(0)
else:
f1 = (2 * precision * recall) / (precision + recall)
f1_values.append(f1)
return f1_values
@pytest.mark.parametrize("incl_neutral", (True, False))
@pytest.mark.parametrize("macro", (True, False))
def test_f1_metric(incl_neutral: bool, macro: bool):
def f1_list(precisions: List[float], recalls: List[float]) -> List[float]:
f1_values = []
for precision, recall in zip(precisions, recalls):
if precision == 0 and recall == 0:
f1_values.append(0.0)
else:
f1 = (2 * precision * recall) / (precision + recall)
f1_values.append(f1)
return f1_values
# Simple case where there is not neutral
predictions = np.array([[1,0,0], [0,1,1]])
gold = np.array([[1,1,0], [1,0,1]])
precision_per_class = [1.0, 0.0, 1.0]
recall_per_class = [0.5, 0.0, 1.0]
num_classes = 3
if incl_neutral:
precision_per_class = [1.0, 0.0, 1.0, 0.0]
recall_per_class = [0.5, 0.0, 1.0, 0.0]
num_classes = 4
if macro:
f1_per_class = f1_list(precision_per_class, recall_per_class)
gold_macro_f1 = sum(f1_per_class) / num_classes
assert gold_macro_f1 == f1_metric(predictions, gold, macro, incl_neutral)
else:
overall_precision = sum(precision_per_class) / 3
overall_recall = sum(recall_per_class) / 3
gold_micro = (2 * overall_precision * overall_recall) / (overall_precision + overall_recall)
assert gold_micro == f1_metric(predictions, gold, macro, incl_neutral)
# Check that it raises assertions based on the size of the arrays
predictions = np.array([0,1,1,0,0])
gold = np.array([[0,1,0,1,1], [0,0,0,1,0]])
with pytest.raises(AssertionError):
f1_metric(predictions, gold, macro, incl_neutral)
predictions = np.array([[0,1,0,1,1], [0,0,0,1,0]])
gold = np.array([0,1,1,0,0])
with pytest.raises(AssertionError):
f1_metric(predictions, gold, macro, incl_neutral)
|
en
| 0.917032
|
# Simple case where there is not neutral # Case where the neutral class is wrong for predictions # Case where the neutral case is True for predictions and gold # Check that it raises assertions based on the size of the arrays # Simple case where there is not neutral # Check that it raises assertions based on the size of the arrays
| 2.524282
| 3
|
feline/jobposts/migrations/0004_auto_20211016_2218.py
|
LordFitoi/feline
| 6
|
6626296
|
# Generated by Django 3.1.13 on 2021-10-17 02:18
import ckeditor.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('jobposts', '0003_auto_20211016_2208'),
]
operations = [
migrations.AlterField(
model_name='jobpost',
name='how_to_apply',
field=ckeditor.fields.RichTextField(),
),
]
|
# Generated by Django 3.1.13 on 2021-10-17 02:18
import ckeditor.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('jobposts', '0003_auto_20211016_2208'),
]
operations = [
migrations.AlterField(
model_name='jobpost',
name='how_to_apply',
field=ckeditor.fields.RichTextField(),
),
]
|
en
| 0.846117
|
# Generated by Django 3.1.13 on 2021-10-17 02:18
| 1.597146
| 2
|
stage2/lib/imgTool.py
|
YU-Zhiyang/WEVI
| 14
|
6626297
|
<gh_stars>10-100
from __future__ import division
import torch
import math
import random
import cv2
import numpy as np
import numbers
import collections
import imageio
INTER_MODE = {'NEAREST': cv2.INTER_NEAREST, 'BILINEAR': cv2.INTER_LINEAR, 'BICUBIC': cv2.INTER_CUBIC}
PAD_MOD = {'constant': cv2.BORDER_CONSTANT,
'edge': cv2.BORDER_REPLICATE,
'reflect': cv2.BORDER_DEFAULT,
'symmetric': cv2.BORDER_REFLECT
}
def imglist2GIF(imglist: list, gifPath: str):
imageio.mimsave(gifPath, imglist, 'GIF', duration=0.5)
def makeGrid(imgList: list, shape=(3, 3)):
assert len(imgList) == shape[0] * shape[1], \
'number of img is {}, grid shape is {}'.format(len(imgList), shape[0] * shape[1])
img = np.stack(imgList, axis=0)
N, H, W, C = img.shape
nh = shape[0]
nw = shape[1]
img = img.reshape((nh, nw, H, W, C)).swapaxes(1, 2).reshape(nh * H, nw * W, C)
return img
def flowToImg(flow: torch.Tensor, normalize=True, info=None, flow_mag_max=None, idx=0):
flow = flow[0, ...].permute(1, 2, 0).cpu().detach().numpy()
hsv = np.zeros((flow.shape[0], flow.shape[1], 3), dtype=np.uint8)
flow_magnitude, flow_angle = cv2.cartToPolar(
flow[..., 0].astype(np.float32), flow[..., 1].astype(np.float32))
# A couple times, we've gotten NaNs out of the above...
nans = np.isnan(flow_magnitude)
if np.any(nans):
nans = np.where(nans)
flow_magnitude[nans] = 0.
# Normalize
hsv[..., 0] = flow_angle * 180 / np.pi / 2
if normalize is True:
if flow_mag_max is None:
hsv[..., 1] = cv2.normalize(flow_magnitude, None, 0, 255, cv2.NORM_MINMAX)
# hsv[..., 2] = cv2.normalize(flow_magnitude, None, 0, 255, cv2.NORM_MINMAX)
else:
hsv[..., 1] = flow_magnitude * 255 / flow_mag_max
# hsv[..., 2] = flow_magnitude * 255 / flow_mag_max
else:
hsv[..., 1] = flow_magnitude
# hsv[..., 2] = flow_magnitude
hsv[..., 2] = 255
img = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
# Add text to the image, if requested
if info is not None:
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, info, (20, 20), font, 0.8, (0, 0, 0), 2, cv2.LINE_AA)
cv2.namedWindow('flow{}'.format(idx), 0)
cv2.imshow('flow{}'.format(idx), img)
cv2.waitKey(0)
def _is_tensor_image(img):
# return torch.is_tensor(img) and img.ndimension() == 3
return torch.is_tensor(img)
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, img):
for t in self.transforms:
img = t(img)
return img
def __repr__(self):
format_string = self.__class__.__name__ + '('
for t in self.transforms:
format_string += '\n'
format_string += ' {0}'.format(t)
format_string += '\n)'
return format_string
class ToTensor(object):
def __call__(self, pic: np.ndarray):
img: torch.Tensor = torch.from_numpy(pic.copy()).permute(0, 3, 1, 2).contiguous()
return img.float().div(255.0)
def __repr__(self):
return self.__class__.__name__ + '()'
def toCVImage(tensor: torch.Tensor):
if tensor.shape[1] == 1:
tensor = tensor.repeat(1, 3, 1, 1)
tensor = (tensor - tensor.min()) / (tensor.max() - tensor.min()) * 255
tensor = tensor[0, ...].detach().cpu().numpy().transpose(1, 2, 0).astype(np.uint8)
tensor = np.ascontiguousarray(tensor)
return tensor
class Normalize(object):
def __init__(self, mean, std):
self.mean = torch.tensor(mean).float().view(1, -1, 1, 1)
self.std = torch.tensor(std).float().view(1, -1, 1, 1)
def __call__(self, tensor):
tensor = (tensor.float() - self.mean) / self.std
return tensor
def __repr__(self):
return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
class inNormalize(object):
def __init__(self, mean: list, std: list):
# self.mean = mean
# self.std = std
self.meanTensor = torch.tensor(mean).float().view(1, -1, 1, 1)
self.stdTensor = torch.tensor(std).float().view(1, -1, 1, 1)
def __call__(self, tensor: torch.Tensor):
device0 = tensor.device
meanTensor = self.meanTensor.to(device0).detach()
stdTensor = self.stdTensor.to(device0).detach()
output = tensor * stdTensor + meanTensor
return output
class Resize(object):
"""Resize the input PIL Image to the given size.
Args:
size (sequence or int): Desired output size. If size is a sequence like
(h, w), output size will be matched to this. If size is an int,
smaller edge of the image will be matched to this number.
i.e, if height > width, then image will be rescaled to
(size * height / width, size)
interpolation (int, optional): Desired interpolation. Default is
``BILINEAR``
"""
def __init__(self, factor, interpolation='BILINEAR'):
assert isinstance(factor, int)
self.factor = factor
self.interpolation = interpolation
def method(self, img):
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
if not (isinstance(self.factor, int) or (
isinstance(self.factor, collections.Iterable) and len(self.factor) == 2)):
raise TypeError('Got inappropriate factor arg: {}'.format(self.factor))
h, w, c = img.shape
if ((h // self.factor * self.factor) != h) or ((w // self.factor * self.factor) != w):
oh = math.ceil(h / 32.0) * 32
ow = math.ceil(w / 32.0) * 32
return cv2.resize(img, dsize=(int(ow), int(oh)), interpolation=INTER_MODE[self.interpolation])
else:
return img
def __call__(self, img):
if not isinstance(img, list):
return self.method(img)
else:
return [self.method(i) for i in img]
def __repr__(self):
interpolate_str = self.interpolation
return self.__class__.__name__ + '(size={0}, interpolation={1})'.format(self.size, interpolate_str)
class Pad(object):
"""Pad the given CV Image on all sides with the given "pad" value.
Args:
padding (int or tuple): Padding on each border. If a single int is provided this
is used to pad all borders. If tuple of length 2 is provided this is the padding
on left/right and top/bottom respectively. If a tuple of length 4 is provided
this is the padding for the left, top, right and bottom borders
respectively.
fill: Pixel fill value for constant fill. Default is 0. If a tuple of
length 3, it is used to fill R, G, B channels respectively.
This value is only used when the padding_mode is constant
padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
constant: pads with a constant value, this value is specified with fill
edge: pads with the last value at the edge of the image
reflect: pads with reflection of image (without repeating the last value on the edge)
padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
will result in [3, 2, 1, 2, 3, 4, 3, 2]
symmetric: pads with reflection of image (repeating the last value on the edge)
padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
will result in [2, 1, 1, 2, 3, 4, 4, 3]
"""
def __init__(self, padding, fill=0, padding_mode='constant'):
assert isinstance(padding, (numbers.Number, tuple))
assert isinstance(fill, (numbers.Number, str, tuple))
assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric']
if isinstance(padding, collections.Sequence) and len(padding) not in [2, 4]:
raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " +
"{} element tuple".format(len(padding)))
self.padding = padding
self.fill = fill
self.padding_mode = padding_mode
def method(self, img):
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
if not isinstance(self.padding, (numbers.Number, tuple)):
raise TypeError('Got inappropriate padding arg')
if not isinstance(self.fill, (numbers.Number, str, tuple)):
raise TypeError('Got inappropriate fill arg')
if not isinstance(self.padding_mode, str):
raise TypeError('Got inappropriate padding_mode arg')
if isinstance(self.padding, collections.Sequence) and len(self.padding) not in [2, 4]:
raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " +
"{} element tuple".format(len(self.padding)))
assert self.padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \
'Padding mode should be either constant, edge, reflect or symmetric'
if isinstance(self.padding, int):
pad_left = pad_right = pad_top = pad_bottom = self.padding
if isinstance(self.padding, collections.Sequence) and len(self.padding) == 2:
pad_left = pad_right = self.padding[0]
pad_top = pad_bottom = self.padding[1]
if isinstance(self.padding, collections.Sequence) and len(self.padding) == 4:
pad_left, pad_top, pad_right, pad_bottom = self.padding
if isinstance(self.fill, numbers.Number):
self.fill = (self.fill,) * (2 * len(img.shape) - 3)
if self.padding_mode == 'constant':
assert (len(self.fill) == 3 and len(img.shape) == 3) or (len(self.fill) == 1 and len(img.shape) == 2), \
'channel of image is {} but length of fill is {}'.format(img.shape[-1], len(self.fill))
img = cv2.copyMakeBorder(src=img, top=pad_top, bottom=pad_bottom, left=pad_left, right=pad_right,
borderType=PAD_MOD[self.padding_mode], value=self.fill)
return img
def __call__(self, img):
"""
Args:
img (CV Image): Image to be padded.
Returns:
CV Image: Padded image.
"""
if not isinstance(img, list):
return self.method(img)
else:
return [self.method(i) for i in img]
def __repr__(self):
return self.__class__.__name__ + '(padding={0}, fill={1}, padding_mode={2})'. \
format(self.padding, self.fill, self.padding_mode)
class RandomTransforms(object):
"""Base class for a list of transformations with randomness
Args:
transforms (list or tuple): list of transformations
"""
def __init__(self, transforms):
assert isinstance(transforms, (list, tuple))
self.transforms = transforms
def __call__(self, *args, **kwargs):
raise NotImplementedError()
def __repr__(self):
format_string = self.__class__.__name__ + '('
for t in self.transforms:
format_string += '\n'
format_string += ' {0}'.format(t)
format_string += '\n)'
return format_string
class RandomApply(RandomTransforms):
"""Apply randomly a list of transformations with a given probability
Args:
transforms (list or tuple): list of transformations
p (float): probability
"""
def __init__(self, transforms, p=0.2):
super(RandomApply, self).__init__(transforms)
self.p = p
def __call__(self, img):
if self.p < random.random():
return img
for t in self.transforms:
img = t(img)
return img
def __repr__(self):
format_string = self.__class__.__name__ + '('
format_string += '\n p={}'.format(self.p)
for t in self.transforms:
format_string += '\n'
format_string += ' {0}'.format(t)
format_string += '\n)'
return format_string
class RandomCrop(object):
__slots__ = ['size']
def __init__(self, size: tuple):
self.size = size
def __call__(self, img):
n, h, w, _ = img.shape
th, tw = self.size
if w == tw and h == th:
return 0, 0, h, w
i = random.randint(0, h - th)
j = random.randint(0, w - tw)
return img[:, i:i + th, j:j + tw, :]
class RandomHorizontalFlip(object):
"""Horizontally flip the given CV Image randomly with a given probability.
Args:
p (float): probability of the image being flipped. Default value is 0.5
"""
__slots__ = ['p']
def __init__(self, p=0.5):
self.p = p
def __call__(self, img: np.ndarray):
# N, H, W, C = img.shape
if random.random() < self.p:
img = np.flip(img, axis=2)
return img
def __repr__(self):
return self.__class__.__name__ + '(p={})'.format(self.p)
class AdjustBrightness(object):
__slots__ = ['brightness_factor']
def __init__(self, brightness_factor):
self.brightness_factor = brightness_factor
def method(self, img):
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
im = img.astype(np.float32) * self.brightness_factor
im = im.clip(min=0, max=255)
return im.astype(img.dtype)
def __call__(self, img):
return [self.method(i) for i in img]
class AdjustContrast(object):
__slots__ = ['contrast_factor']
def __init__(self, contrast_factor):
self.contrast_factor = contrast_factor
def method(self, img):
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
im = img.astype(np.float32)
mean = round(cv2.cvtColor(im, cv2.COLOR_RGB2GRAY).mean())
im = (1 - self.contrast_factor) * mean + self.contrast_factor * im
im = im.clip(min=0, max=255)
return im.astype(img.dtype)
def __call__(self, img):
return [self.method(i) for i in img]
class AdjustSaturation(object):
__slots__ = ['saturation_factor']
def __init__(self, saturation_factor):
self.saturation_factor = saturation_factor
def method(self, img):
if not _is_numpy_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
im = img.astype(np.float32)
degenerate = cv2.cvtColor(cv2.cvtColor(im, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB)
im = (1 - self.saturation_factor) * degenerate + self.saturation_factor * im
im = im.clip(min=0, max=255)
return im.astype(img.dtype)
def __call__(self, img):
return [self.method(i) for i in img]
class AdjustHue(object):
__slots__ = ['hue_factor']
def __init__(self, hue_factor):
self.hue_factor = hue_factor
def method(self, img):
if not (-0.5 <= self.hue_factor <= 0.5):
raise ValueError('hue_factor is not in [-0.5, 0.5].'.format(self.hue_factor))
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
im = img.astype(np.uint8)
hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV_FULL)
hsv[..., 0] += np.uint8(self.hue_factor * 255)
im = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB_FULL)
return im.astype(img.dtype)
def __call__(self, img):
return [self.method(i) for i in img]
class RandomColorJitter(object):
"""Randomly change the brightness, contrast and saturation of an image.
Args:
brightness (float): How much to jitter brightness. brightness_factor
is chosen uniformly from [max(0, 1 - brightness), 1 + brightness].
contrast (float): How much to jitter contrast. contrast_factor
is chosen uniformly from [max(0, 1 - contrast), 1 + contrast].
saturation (float): How much to jitter saturation. saturation_factor
is chosen uniformly from [max(0, 1 - saturation), 1 + saturation].
hue(float): How much to jitter hue. hue_factor is chosen uniformly from
[-hue, hue]. Should be >=0 and <= 0.5.
"""
__slots__ = ['brightness', 'contrast', 'saturation', 'hue']
def __init__(self, brightness=0.2, contrast=0.2, saturation=0.1, hue=0.02):
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.hue = hue
@staticmethod
def get_params(brightness, contrast, saturation, hue):
"""Get a randomized transform to be applied on image.
Arguments are same as that of __init__.
Returns:
Transform which randomly adjusts brightness, contrast and
saturation in a random order.
"""
transforms = []
if brightness > 0:
brightness_factor = random.uniform(max(0, 1 - brightness), 1 + brightness)
transforms.append(RandomApply([AdjustBrightness(brightness_factor)]))
if contrast > 0:
contrast_factor = random.uniform(max(0, 1 - contrast), 1 + contrast)
transforms.append(RandomApply([AdjustContrast(contrast_factor)]))
if saturation > 0:
saturation_factor = random.uniform(max(0, 1 - saturation), 1 + saturation)
transforms.append(RandomApply([AdjustSaturation(saturation_factor)]))
if hue > 0:
hue_factor = random.uniform(-hue, hue)
transforms.append(RandomApply([AdjustHue(hue_factor)]))
random.shuffle(transforms)
transform = Compose(transforms)
return transform
def __call__(self, img):
"""
Args:
img (np.ndarray): Input image.
Returns:
np.ndarray: Color jittered image.
"""
transform = self.get_params(self.brightness, self.contrast,
self.saturation, self.hue)
return transform(img)
class GaussianNoise(object):
__slots__ = ['means', 'stds', 'gauss']
def __init__(self, mean=0, std=0.05):
assert isinstance(mean, numbers.Number) and mean >= 0, 'mean should be a positive value'
assert isinstance(std, numbers.Number) and std >= 0, 'std should be a positive value'
self.means = mean
self.stds = std
def get_params(self, img_shape):
mean = random.uniform(-self.means, self.means)
std = random.uniform(0, self.stds)
self.gauss = np.random.normal(mean, std, img_shape).astype(np.float32)
def method(self, img):
if len(img.shape) == 3:
imgtype = img.dtype
noisy = np.clip((1 + self.gauss) * img.astype(np.float32), 0, 255)
return noisy.astype(imgtype)
else:
return img
def __call__(self, img):
img_shape = img[0].shape
self.get_params(img_shape)
return [self.method(i) for i in img]
def __repr__(self):
return self.__class__.__name__
|
from __future__ import division
import torch
import math
import random
import cv2
import numpy as np
import numbers
import collections
import imageio
INTER_MODE = {'NEAREST': cv2.INTER_NEAREST, 'BILINEAR': cv2.INTER_LINEAR, 'BICUBIC': cv2.INTER_CUBIC}
PAD_MOD = {'constant': cv2.BORDER_CONSTANT,
'edge': cv2.BORDER_REPLICATE,
'reflect': cv2.BORDER_DEFAULT,
'symmetric': cv2.BORDER_REFLECT
}
def imglist2GIF(imglist: list, gifPath: str):
imageio.mimsave(gifPath, imglist, 'GIF', duration=0.5)
def makeGrid(imgList: list, shape=(3, 3)):
assert len(imgList) == shape[0] * shape[1], \
'number of img is {}, grid shape is {}'.format(len(imgList), shape[0] * shape[1])
img = np.stack(imgList, axis=0)
N, H, W, C = img.shape
nh = shape[0]
nw = shape[1]
img = img.reshape((nh, nw, H, W, C)).swapaxes(1, 2).reshape(nh * H, nw * W, C)
return img
def flowToImg(flow: torch.Tensor, normalize=True, info=None, flow_mag_max=None, idx=0):
flow = flow[0, ...].permute(1, 2, 0).cpu().detach().numpy()
hsv = np.zeros((flow.shape[0], flow.shape[1], 3), dtype=np.uint8)
flow_magnitude, flow_angle = cv2.cartToPolar(
flow[..., 0].astype(np.float32), flow[..., 1].astype(np.float32))
# A couple times, we've gotten NaNs out of the above...
nans = np.isnan(flow_magnitude)
if np.any(nans):
nans = np.where(nans)
flow_magnitude[nans] = 0.
# Normalize
hsv[..., 0] = flow_angle * 180 / np.pi / 2
if normalize is True:
if flow_mag_max is None:
hsv[..., 1] = cv2.normalize(flow_magnitude, None, 0, 255, cv2.NORM_MINMAX)
# hsv[..., 2] = cv2.normalize(flow_magnitude, None, 0, 255, cv2.NORM_MINMAX)
else:
hsv[..., 1] = flow_magnitude * 255 / flow_mag_max
# hsv[..., 2] = flow_magnitude * 255 / flow_mag_max
else:
hsv[..., 1] = flow_magnitude
# hsv[..., 2] = flow_magnitude
hsv[..., 2] = 255
img = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
# Add text to the image, if requested
if info is not None:
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, info, (20, 20), font, 0.8, (0, 0, 0), 2, cv2.LINE_AA)
cv2.namedWindow('flow{}'.format(idx), 0)
cv2.imshow('flow{}'.format(idx), img)
cv2.waitKey(0)
def _is_tensor_image(img):
# return torch.is_tensor(img) and img.ndimension() == 3
return torch.is_tensor(img)
def _is_numpy_image(img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
class Compose(object):
def __init__(self, transforms):
self.transforms = transforms
def __call__(self, img):
for t in self.transforms:
img = t(img)
return img
def __repr__(self):
format_string = self.__class__.__name__ + '('
for t in self.transforms:
format_string += '\n'
format_string += ' {0}'.format(t)
format_string += '\n)'
return format_string
class ToTensor(object):
def __call__(self, pic: np.ndarray):
img: torch.Tensor = torch.from_numpy(pic.copy()).permute(0, 3, 1, 2).contiguous()
return img.float().div(255.0)
def __repr__(self):
return self.__class__.__name__ + '()'
def toCVImage(tensor: torch.Tensor):
if tensor.shape[1] == 1:
tensor = tensor.repeat(1, 3, 1, 1)
tensor = (tensor - tensor.min()) / (tensor.max() - tensor.min()) * 255
tensor = tensor[0, ...].detach().cpu().numpy().transpose(1, 2, 0).astype(np.uint8)
tensor = np.ascontiguousarray(tensor)
return tensor
class Normalize(object):
def __init__(self, mean, std):
self.mean = torch.tensor(mean).float().view(1, -1, 1, 1)
self.std = torch.tensor(std).float().view(1, -1, 1, 1)
def __call__(self, tensor):
tensor = (tensor.float() - self.mean) / self.std
return tensor
def __repr__(self):
return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
class inNormalize(object):
def __init__(self, mean: list, std: list):
# self.mean = mean
# self.std = std
self.meanTensor = torch.tensor(mean).float().view(1, -1, 1, 1)
self.stdTensor = torch.tensor(std).float().view(1, -1, 1, 1)
def __call__(self, tensor: torch.Tensor):
device0 = tensor.device
meanTensor = self.meanTensor.to(device0).detach()
stdTensor = self.stdTensor.to(device0).detach()
output = tensor * stdTensor + meanTensor
return output
class Resize(object):
"""Resize the input PIL Image to the given size.
Args:
size (sequence or int): Desired output size. If size is a sequence like
(h, w), output size will be matched to this. If size is an int,
smaller edge of the image will be matched to this number.
i.e, if height > width, then image will be rescaled to
(size * height / width, size)
interpolation (int, optional): Desired interpolation. Default is
``BILINEAR``
"""
def __init__(self, factor, interpolation='BILINEAR'):
assert isinstance(factor, int)
self.factor = factor
self.interpolation = interpolation
def method(self, img):
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
if not (isinstance(self.factor, int) or (
isinstance(self.factor, collections.Iterable) and len(self.factor) == 2)):
raise TypeError('Got inappropriate factor arg: {}'.format(self.factor))
h, w, c = img.shape
if ((h // self.factor * self.factor) != h) or ((w // self.factor * self.factor) != w):
oh = math.ceil(h / 32.0) * 32
ow = math.ceil(w / 32.0) * 32
return cv2.resize(img, dsize=(int(ow), int(oh)), interpolation=INTER_MODE[self.interpolation])
else:
return img
def __call__(self, img):
if not isinstance(img, list):
return self.method(img)
else:
return [self.method(i) for i in img]
def __repr__(self):
interpolate_str = self.interpolation
return self.__class__.__name__ + '(size={0}, interpolation={1})'.format(self.size, interpolate_str)
class Pad(object):
"""Pad the given CV Image on all sides with the given "pad" value.
Args:
padding (int or tuple): Padding on each border. If a single int is provided this
is used to pad all borders. If tuple of length 2 is provided this is the padding
on left/right and top/bottom respectively. If a tuple of length 4 is provided
this is the padding for the left, top, right and bottom borders
respectively.
fill: Pixel fill value for constant fill. Default is 0. If a tuple of
length 3, it is used to fill R, G, B channels respectively.
This value is only used when the padding_mode is constant
padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
constant: pads with a constant value, this value is specified with fill
edge: pads with the last value at the edge of the image
reflect: pads with reflection of image (without repeating the last value on the edge)
padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
will result in [3, 2, 1, 2, 3, 4, 3, 2]
symmetric: pads with reflection of image (repeating the last value on the edge)
padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
will result in [2, 1, 1, 2, 3, 4, 4, 3]
"""
def __init__(self, padding, fill=0, padding_mode='constant'):
assert isinstance(padding, (numbers.Number, tuple))
assert isinstance(fill, (numbers.Number, str, tuple))
assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric']
if isinstance(padding, collections.Sequence) and len(padding) not in [2, 4]:
raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " +
"{} element tuple".format(len(padding)))
self.padding = padding
self.fill = fill
self.padding_mode = padding_mode
def method(self, img):
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
if not isinstance(self.padding, (numbers.Number, tuple)):
raise TypeError('Got inappropriate padding arg')
if not isinstance(self.fill, (numbers.Number, str, tuple)):
raise TypeError('Got inappropriate fill arg')
if not isinstance(self.padding_mode, str):
raise TypeError('Got inappropriate padding_mode arg')
if isinstance(self.padding, collections.Sequence) and len(self.padding) not in [2, 4]:
raise ValueError("Padding must be an int or a 2, or 4 element tuple, not a " +
"{} element tuple".format(len(self.padding)))
assert self.padding_mode in ['constant', 'edge', 'reflect', 'symmetric'], \
'Padding mode should be either constant, edge, reflect or symmetric'
if isinstance(self.padding, int):
pad_left = pad_right = pad_top = pad_bottom = self.padding
if isinstance(self.padding, collections.Sequence) and len(self.padding) == 2:
pad_left = pad_right = self.padding[0]
pad_top = pad_bottom = self.padding[1]
if isinstance(self.padding, collections.Sequence) and len(self.padding) == 4:
pad_left, pad_top, pad_right, pad_bottom = self.padding
if isinstance(self.fill, numbers.Number):
self.fill = (self.fill,) * (2 * len(img.shape) - 3)
if self.padding_mode == 'constant':
assert (len(self.fill) == 3 and len(img.shape) == 3) or (len(self.fill) == 1 and len(img.shape) == 2), \
'channel of image is {} but length of fill is {}'.format(img.shape[-1], len(self.fill))
img = cv2.copyMakeBorder(src=img, top=pad_top, bottom=pad_bottom, left=pad_left, right=pad_right,
borderType=PAD_MOD[self.padding_mode], value=self.fill)
return img
def __call__(self, img):
"""
Args:
img (CV Image): Image to be padded.
Returns:
CV Image: Padded image.
"""
if not isinstance(img, list):
return self.method(img)
else:
return [self.method(i) for i in img]
def __repr__(self):
return self.__class__.__name__ + '(padding={0}, fill={1}, padding_mode={2})'. \
format(self.padding, self.fill, self.padding_mode)
class RandomTransforms(object):
"""Base class for a list of transformations with randomness
Args:
transforms (list or tuple): list of transformations
"""
def __init__(self, transforms):
assert isinstance(transforms, (list, tuple))
self.transforms = transforms
def __call__(self, *args, **kwargs):
raise NotImplementedError()
def __repr__(self):
format_string = self.__class__.__name__ + '('
for t in self.transforms:
format_string += '\n'
format_string += ' {0}'.format(t)
format_string += '\n)'
return format_string
class RandomApply(RandomTransforms):
"""Apply randomly a list of transformations with a given probability
Args:
transforms (list or tuple): list of transformations
p (float): probability
"""
def __init__(self, transforms, p=0.2):
super(RandomApply, self).__init__(transforms)
self.p = p
def __call__(self, img):
if self.p < random.random():
return img
for t in self.transforms:
img = t(img)
return img
def __repr__(self):
format_string = self.__class__.__name__ + '('
format_string += '\n p={}'.format(self.p)
for t in self.transforms:
format_string += '\n'
format_string += ' {0}'.format(t)
format_string += '\n)'
return format_string
class RandomCrop(object):
__slots__ = ['size']
def __init__(self, size: tuple):
self.size = size
def __call__(self, img):
n, h, w, _ = img.shape
th, tw = self.size
if w == tw and h == th:
return 0, 0, h, w
i = random.randint(0, h - th)
j = random.randint(0, w - tw)
return img[:, i:i + th, j:j + tw, :]
class RandomHorizontalFlip(object):
"""Horizontally flip the given CV Image randomly with a given probability.
Args:
p (float): probability of the image being flipped. Default value is 0.5
"""
__slots__ = ['p']
def __init__(self, p=0.5):
self.p = p
def __call__(self, img: np.ndarray):
# N, H, W, C = img.shape
if random.random() < self.p:
img = np.flip(img, axis=2)
return img
def __repr__(self):
return self.__class__.__name__ + '(p={})'.format(self.p)
class AdjustBrightness(object):
__slots__ = ['brightness_factor']
def __init__(self, brightness_factor):
self.brightness_factor = brightness_factor
def method(self, img):
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
im = img.astype(np.float32) * self.brightness_factor
im = im.clip(min=0, max=255)
return im.astype(img.dtype)
def __call__(self, img):
return [self.method(i) for i in img]
class AdjustContrast(object):
__slots__ = ['contrast_factor']
def __init__(self, contrast_factor):
self.contrast_factor = contrast_factor
def method(self, img):
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
im = img.astype(np.float32)
mean = round(cv2.cvtColor(im, cv2.COLOR_RGB2GRAY).mean())
im = (1 - self.contrast_factor) * mean + self.contrast_factor * im
im = im.clip(min=0, max=255)
return im.astype(img.dtype)
def __call__(self, img):
return [self.method(i) for i in img]
class AdjustSaturation(object):
__slots__ = ['saturation_factor']
def __init__(self, saturation_factor):
self.saturation_factor = saturation_factor
def method(self, img):
if not _is_numpy_image(img):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
im = img.astype(np.float32)
degenerate = cv2.cvtColor(cv2.cvtColor(im, cv2.COLOR_RGB2GRAY), cv2.COLOR_GRAY2RGB)
im = (1 - self.saturation_factor) * degenerate + self.saturation_factor * im
im = im.clip(min=0, max=255)
return im.astype(img.dtype)
def __call__(self, img):
return [self.method(i) for i in img]
class AdjustHue(object):
__slots__ = ['hue_factor']
def __init__(self, hue_factor):
self.hue_factor = hue_factor
def method(self, img):
if not (-0.5 <= self.hue_factor <= 0.5):
raise ValueError('hue_factor is not in [-0.5, 0.5].'.format(self.hue_factor))
if not _is_numpy_image(img):
raise TypeError('img should be CV Image. Got {}'.format(type(img)))
im = img.astype(np.uint8)
hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV_FULL)
hsv[..., 0] += np.uint8(self.hue_factor * 255)
im = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB_FULL)
return im.astype(img.dtype)
def __call__(self, img):
return [self.method(i) for i in img]
class RandomColorJitter(object):
"""Randomly change the brightness, contrast and saturation of an image.
Args:
brightness (float): How much to jitter brightness. brightness_factor
is chosen uniformly from [max(0, 1 - brightness), 1 + brightness].
contrast (float): How much to jitter contrast. contrast_factor
is chosen uniformly from [max(0, 1 - contrast), 1 + contrast].
saturation (float): How much to jitter saturation. saturation_factor
is chosen uniformly from [max(0, 1 - saturation), 1 + saturation].
hue(float): How much to jitter hue. hue_factor is chosen uniformly from
[-hue, hue]. Should be >=0 and <= 0.5.
"""
__slots__ = ['brightness', 'contrast', 'saturation', 'hue']
def __init__(self, brightness=0.2, contrast=0.2, saturation=0.1, hue=0.02):
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.hue = hue
@staticmethod
def get_params(brightness, contrast, saturation, hue):
"""Get a randomized transform to be applied on image.
Arguments are same as that of __init__.
Returns:
Transform which randomly adjusts brightness, contrast and
saturation in a random order.
"""
transforms = []
if brightness > 0:
brightness_factor = random.uniform(max(0, 1 - brightness), 1 + brightness)
transforms.append(RandomApply([AdjustBrightness(brightness_factor)]))
if contrast > 0:
contrast_factor = random.uniform(max(0, 1 - contrast), 1 + contrast)
transforms.append(RandomApply([AdjustContrast(contrast_factor)]))
if saturation > 0:
saturation_factor = random.uniform(max(0, 1 - saturation), 1 + saturation)
transforms.append(RandomApply([AdjustSaturation(saturation_factor)]))
if hue > 0:
hue_factor = random.uniform(-hue, hue)
transforms.append(RandomApply([AdjustHue(hue_factor)]))
random.shuffle(transforms)
transform = Compose(transforms)
return transform
def __call__(self, img):
"""
Args:
img (np.ndarray): Input image.
Returns:
np.ndarray: Color jittered image.
"""
transform = self.get_params(self.brightness, self.contrast,
self.saturation, self.hue)
return transform(img)
class GaussianNoise(object):
__slots__ = ['means', 'stds', 'gauss']
def __init__(self, mean=0, std=0.05):
assert isinstance(mean, numbers.Number) and mean >= 0, 'mean should be a positive value'
assert isinstance(std, numbers.Number) and std >= 0, 'std should be a positive value'
self.means = mean
self.stds = std
def get_params(self, img_shape):
mean = random.uniform(-self.means, self.means)
std = random.uniform(0, self.stds)
self.gauss = np.random.normal(mean, std, img_shape).astype(np.float32)
def method(self, img):
if len(img.shape) == 3:
imgtype = img.dtype
noisy = np.clip((1 + self.gauss) * img.astype(np.float32), 0, 255)
return noisy.astype(imgtype)
else:
return img
def __call__(self, img):
img_shape = img[0].shape
self.get_params(img_shape)
return [self.method(i) for i in img]
def __repr__(self):
return self.__class__.__name__
|
en
| 0.749256
|
# A couple times, we've gotten NaNs out of the above... # Normalize # hsv[..., 2] = cv2.normalize(flow_magnitude, None, 0, 255, cv2.NORM_MINMAX) # hsv[..., 2] = flow_magnitude * 255 / flow_mag_max # hsv[..., 2] = flow_magnitude # Add text to the image, if requested # return torch.is_tensor(img) and img.ndimension() == 3 # self.mean = mean # self.std = std Resize the input PIL Image to the given size. Args: size (sequence or int): Desired output size. If size is a sequence like (h, w), output size will be matched to this. If size is an int, smaller edge of the image will be matched to this number. i.e, if height > width, then image will be rescaled to (size * height / width, size) interpolation (int, optional): Desired interpolation. Default is ``BILINEAR`` Pad the given CV Image on all sides with the given "pad" value. Args: padding (int or tuple): Padding on each border. If a single int is provided this is used to pad all borders. If tuple of length 2 is provided this is the padding on left/right and top/bottom respectively. If a tuple of length 4 is provided this is the padding for the left, top, right and bottom borders respectively. fill: Pixel fill value for constant fill. Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively. This value is only used when the padding_mode is constant padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant. constant: pads with a constant value, this value is specified with fill edge: pads with the last value at the edge of the image reflect: pads with reflection of image (without repeating the last value on the edge) padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode will result in [3, 2, 1, 2, 3, 4, 3, 2] symmetric: pads with reflection of image (repeating the last value on the edge) padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode will result in [2, 1, 1, 2, 3, 4, 4, 3] Args: img (CV Image): Image to be padded. Returns: CV Image: Padded image. Base class for a list of transformations with randomness Args: transforms (list or tuple): list of transformations Apply randomly a list of transformations with a given probability Args: transforms (list or tuple): list of transformations p (float): probability Horizontally flip the given CV Image randomly with a given probability. Args: p (float): probability of the image being flipped. Default value is 0.5 # N, H, W, C = img.shape Randomly change the brightness, contrast and saturation of an image. Args: brightness (float): How much to jitter brightness. brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]. contrast (float): How much to jitter contrast. contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]. saturation (float): How much to jitter saturation. saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]. hue(float): How much to jitter hue. hue_factor is chosen uniformly from [-hue, hue]. Should be >=0 and <= 0.5. Get a randomized transform to be applied on image. Arguments are same as that of __init__. Returns: Transform which randomly adjusts brightness, contrast and saturation in a random order. Args: img (np.ndarray): Input image. Returns: np.ndarray: Color jittered image.
| 1.97757
| 2
|
zorro/agreement_subject_verb/across_relative_clause.py
|
codebyzeb/Zorro
| 2
|
6626298
|
import random
import inflect
from zorro.filter import collect_unique_pairs
from zorro.words import get_legal_words
template1a = 'the {} that {} like {} {} .'
template1b = 'the {} that {} likes {} {} .'
template2a = 'the {} that was there {} {} .'
template2b = 'the {} that were there {} {} .'
plural = inflect.engine()
def main():
"""
example:
"the dog that i like is green" vs. "the dogs that i like is green"
"""
nouns_s_and_p = get_legal_words(tag='NN', second_tag='NNP')
adjectives = get_legal_words(tag='JJ')
copulas_singular = ["is", "was"]
copulas_plural = ["are", "were"]
pronouns_1p_2p = ['i', 'you', 'we']
pronouns_3p = ['he', 'she', 'it']
assert len(pronouns_3p) == len(pronouns_1p_2p)
while True:
# random choices
noun_s, noun_p = random.choice(nouns_s_and_p)
adj = random.choice(adjectives)
for copula_s in copulas_singular:
# object-relative
for pronoun_1p_2p in pronouns_1p_2p:
yield template1a.format(noun_p, pronoun_1p_2p, copula_s, adj) # bad
yield template1a.format(noun_s, pronoun_1p_2p, copula_s, adj) # good
for pronoun_3p in pronouns_3p:
yield template1b.format(noun_p, pronoun_3p, copula_s, adj)
yield template1b.format(noun_s, pronoun_3p, copula_s, adj)
# subject-relative
yield template2a.format(noun_p, copula_s, adj)
yield template2a.format(noun_s, copula_s, adj)
for copula_p in copulas_plural:
# object-relative
for pronoun_1p_2p in pronouns_1p_2p:
yield template1a.format(noun_s, pronoun_1p_2p, copula_p, adj)
yield template1a.format(noun_p, pronoun_1p_2p, copula_p, adj)
for pronoun_3p in pronouns_3p:
yield template1b.format(noun_s, pronoun_3p, copula_p, adj)
yield template1b.format(noun_p, pronoun_3p, copula_p, adj)
# subject-relative
yield template2b.format(noun_s, copula_p, adj)
yield template2b.format(noun_p, copula_p, adj)
if __name__ == '__main__':
for n, s in enumerate(collect_unique_pairs(main)):
print(f'{n//2+1:>12,}', s)
|
import random
import inflect
from zorro.filter import collect_unique_pairs
from zorro.words import get_legal_words
template1a = 'the {} that {} like {} {} .'
template1b = 'the {} that {} likes {} {} .'
template2a = 'the {} that was there {} {} .'
template2b = 'the {} that were there {} {} .'
plural = inflect.engine()
def main():
"""
example:
"the dog that i like is green" vs. "the dogs that i like is green"
"""
nouns_s_and_p = get_legal_words(tag='NN', second_tag='NNP')
adjectives = get_legal_words(tag='JJ')
copulas_singular = ["is", "was"]
copulas_plural = ["are", "were"]
pronouns_1p_2p = ['i', 'you', 'we']
pronouns_3p = ['he', 'she', 'it']
assert len(pronouns_3p) == len(pronouns_1p_2p)
while True:
# random choices
noun_s, noun_p = random.choice(nouns_s_and_p)
adj = random.choice(adjectives)
for copula_s in copulas_singular:
# object-relative
for pronoun_1p_2p in pronouns_1p_2p:
yield template1a.format(noun_p, pronoun_1p_2p, copula_s, adj) # bad
yield template1a.format(noun_s, pronoun_1p_2p, copula_s, adj) # good
for pronoun_3p in pronouns_3p:
yield template1b.format(noun_p, pronoun_3p, copula_s, adj)
yield template1b.format(noun_s, pronoun_3p, copula_s, adj)
# subject-relative
yield template2a.format(noun_p, copula_s, adj)
yield template2a.format(noun_s, copula_s, adj)
for copula_p in copulas_plural:
# object-relative
for pronoun_1p_2p in pronouns_1p_2p:
yield template1a.format(noun_s, pronoun_1p_2p, copula_p, adj)
yield template1a.format(noun_p, pronoun_1p_2p, copula_p, adj)
for pronoun_3p in pronouns_3p:
yield template1b.format(noun_s, pronoun_3p, copula_p, adj)
yield template1b.format(noun_p, pronoun_3p, copula_p, adj)
# subject-relative
yield template2b.format(noun_s, copula_p, adj)
yield template2b.format(noun_p, copula_p, adj)
if __name__ == '__main__':
for n, s in enumerate(collect_unique_pairs(main)):
print(f'{n//2+1:>12,}', s)
|
en
| 0.940194
|
example: "the dog that i like is green" vs. "the dogs that i like is green" # random choices # object-relative # bad # good # subject-relative # object-relative # subject-relative
| 2.906491
| 3
|
software/openvisualizer/openvisualizer/BspEmulator/BspLeds.py
|
pedrohenriquegomes/openwsn-sw
| 26
|
6626299
|
<filename>software/openvisualizer/openvisualizer/BspEmulator/BspLeds.py
#!/usr/bin/python
# Copyright (c) 2010-2013, Regents of the University of California.
# All rights reserved.
#
# Released under the BSD 3-Clause license as published at the link below.
# https://openwsn.atlassian.net/wiki/display/OW/License
import logging
from openvisualizer.SimEngine import SimEngine
import BspModule
class BspLeds(BspModule.BspModule):
'''
Emulates the 'leds' BSP module
'''
def __init__(self,motehandler):
# store params
self.engine = SimEngine.SimEngine()
self.motehandler = motehandler
# local variables
self.errorLedOn = False
self.radioLedOn = False
self.syncLedOn = False
self.debugLedOn = False
# initialize the parent
BspModule.BspModule.__init__(self,'BspLeds')
#======================== public ==========================================
#=== commands
def cmd_init(self):
'''emulates
void leds_init()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_init')
# remember that module has been intialized
self.isInitialized = True
# error LED
def cmd_error_on(self):
'''emulates
void leds_error_on()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_error_on')
# change the internal state
self.errorLedOn = True
def cmd_error_off(self):
'''emulates
void leds_error_off()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_error_off')
# change the internal state
self.errorLedOn = False
def cmd_error_toggle(self):
'''emulates
void leds_error_toggle()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_error_toggle')
# change the internal state
self.errorLedOn = not self.errorLedOn
def cmd_error_isOn(self):
'''emulates
uint8_t leds_error_isOn()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_error_isOn')
if self.errorLedOn:
returnVal = 1
else:
returnVal = 0
return returnVal
# radio LED
def cmd_radio_on(self):
'''emulates
void leds_radio_on()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_radio_on')
# change the internal state
self.radioLedOn = True
def cmd_radio_off(self):
'''emulates
void leds_radio_off()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_radio_off')
# change the internal state
self.radioLedOn = False
def cmd_radio_toggle(self):
'''emulates
void leds_radio_toggle()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_radio_toggle')
# change the internal state
self.radioLedOn = not self.radioLedOn
def cmd_radio_isOn(self):
'''emulates
uint8_t leds_radio_isOn()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_radio_isOn')
if self.radioLedOn:
returnVal = 1
else:
returnVal = 0
return returnVal
# sync LED
def cmd_sync_on(self):
'''emulates
void leds_sync_on()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_sync_on')
# change the internal state
self.syncLedOn = True
def cmd_sync_off(self):
'''emulates
void leds_sync_off()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_sync_off')
# change the internal state
self.syncLedOn = False
def cmd_sync_toggle(self):
'''emulates
void leds_sync_toggle()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_sync_toggle')
# change the internal state
self.syncLedOn = not self.syncLedOn
def cmd_sync_isOn(self):
'''emulates
uint8_t leds_sync_isOn()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_sync_isOn')
if self.syncLedOn:
returnVal = 1
else:
returnVal = 0
return returnVal
# debug LED
def cmd_debug_on(self):
'''emulates
void leds_debug_on()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_debug_on')
# change the internal state
self.debugLedOn = True
def cmd_debug_off(self):
'''emulates
void leds_debug_off()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_debug_off')
# change the internal state
self.debugLedOn = False
def cmd_debug_toggle(self):
'''emulates
void leds_debug_toggle()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_debug_toggle')
# change the internal state
self.debugLedOn = not self.debugLedOn
def cmd_debug_isOn(self):
'''emulates
uint8_t leds_debug_isOn()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_debug_isOn')
if self.debugLedOn:
returnVal = 1
else:
returnVal = 0
return returnVal
# all LEDs
def cmd_all_on(self):
'''emulates'
void leds_all_on()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_all_on')
# change the internal state
self.errorLedOn = True
self.radioLedOn = True
self.syncLedOn = True
self.debugLedOn = True
def cmd_all_off(self):
'''emulates
void leds_all_off()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_all_off')
# change the internal state
self.errorLedOn = False
self.radioLedOn = False
self.syncLedOn = False
self.debugLedOn = False
def cmd_all_toggle(self):
'''emulates
void leds_all_toggle()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_all_toggle')
# change the internal state
self.errorLedOn = not self.errorLedOn
self.radioLedOn = not self.radioLedOn
self.syncLedOn = not self.syncLedOn
self.debugLedOn = not self.debugLedOn
def cmd_circular_shift(self):
'''emulates
void leds_circular_shift()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_circular_shift')
(self.errorLedOn,
self.radioLedOn,
self.syncLedOn,
self.debugLedOn) = (self.radioLedOn,
self.syncLedOn,
self.debugLedOn,
self.errorLedOn)
def cmd_increment(self):
'''emulates
void leds_increment()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_increment')
# get the current value
val = 0
if self.errorLedOn:
val += 0x08
if self.radioLedOn:
val += 0x04
if self.syncLedOn:
val += 0x02
if self.debugLedOn:
val += 0x01
# increment
val = (val+1)%0xf
# apply back
self.errorLedOn = ((val & 0x08)!=0)
self.radioLedOn = ((val & 0x04)!=0)
self.syncLedOn = ((val & 0x02)!=0)
self.debugLedOn = ((val & 0x01)!=0)
#=== getters
def get_errorLedOn(self):
return self.errorLedOn
def get_radioLedOn(self):
return self.radioLedOn
def get_syncLedOn(self):
return self.syncLedOn
def get_debugLedOn(self):
return self.debugLedOn
#======================== private =========================================
|
<filename>software/openvisualizer/openvisualizer/BspEmulator/BspLeds.py
#!/usr/bin/python
# Copyright (c) 2010-2013, Regents of the University of California.
# All rights reserved.
#
# Released under the BSD 3-Clause license as published at the link below.
# https://openwsn.atlassian.net/wiki/display/OW/License
import logging
from openvisualizer.SimEngine import SimEngine
import BspModule
class BspLeds(BspModule.BspModule):
'''
Emulates the 'leds' BSP module
'''
def __init__(self,motehandler):
# store params
self.engine = SimEngine.SimEngine()
self.motehandler = motehandler
# local variables
self.errorLedOn = False
self.radioLedOn = False
self.syncLedOn = False
self.debugLedOn = False
# initialize the parent
BspModule.BspModule.__init__(self,'BspLeds')
#======================== public ==========================================
#=== commands
def cmd_init(self):
'''emulates
void leds_init()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_init')
# remember that module has been intialized
self.isInitialized = True
# error LED
def cmd_error_on(self):
'''emulates
void leds_error_on()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_error_on')
# change the internal state
self.errorLedOn = True
def cmd_error_off(self):
'''emulates
void leds_error_off()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_error_off')
# change the internal state
self.errorLedOn = False
def cmd_error_toggle(self):
'''emulates
void leds_error_toggle()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_error_toggle')
# change the internal state
self.errorLedOn = not self.errorLedOn
def cmd_error_isOn(self):
'''emulates
uint8_t leds_error_isOn()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_error_isOn')
if self.errorLedOn:
returnVal = 1
else:
returnVal = 0
return returnVal
# radio LED
def cmd_radio_on(self):
'''emulates
void leds_radio_on()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_radio_on')
# change the internal state
self.radioLedOn = True
def cmd_radio_off(self):
'''emulates
void leds_radio_off()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_radio_off')
# change the internal state
self.radioLedOn = False
def cmd_radio_toggle(self):
'''emulates
void leds_radio_toggle()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_radio_toggle')
# change the internal state
self.radioLedOn = not self.radioLedOn
def cmd_radio_isOn(self):
'''emulates
uint8_t leds_radio_isOn()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_radio_isOn')
if self.radioLedOn:
returnVal = 1
else:
returnVal = 0
return returnVal
# sync LED
def cmd_sync_on(self):
'''emulates
void leds_sync_on()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_sync_on')
# change the internal state
self.syncLedOn = True
def cmd_sync_off(self):
'''emulates
void leds_sync_off()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_sync_off')
# change the internal state
self.syncLedOn = False
def cmd_sync_toggle(self):
'''emulates
void leds_sync_toggle()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_sync_toggle')
# change the internal state
self.syncLedOn = not self.syncLedOn
def cmd_sync_isOn(self):
'''emulates
uint8_t leds_sync_isOn()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_sync_isOn')
if self.syncLedOn:
returnVal = 1
else:
returnVal = 0
return returnVal
# debug LED
def cmd_debug_on(self):
'''emulates
void leds_debug_on()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_debug_on')
# change the internal state
self.debugLedOn = True
def cmd_debug_off(self):
'''emulates
void leds_debug_off()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_debug_off')
# change the internal state
self.debugLedOn = False
def cmd_debug_toggle(self):
'''emulates
void leds_debug_toggle()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_debug_toggle')
# change the internal state
self.debugLedOn = not self.debugLedOn
def cmd_debug_isOn(self):
'''emulates
uint8_t leds_debug_isOn()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_debug_isOn')
if self.debugLedOn:
returnVal = 1
else:
returnVal = 0
return returnVal
# all LEDs
def cmd_all_on(self):
'''emulates'
void leds_all_on()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_all_on')
# change the internal state
self.errorLedOn = True
self.radioLedOn = True
self.syncLedOn = True
self.debugLedOn = True
def cmd_all_off(self):
'''emulates
void leds_all_off()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_all_off')
# change the internal state
self.errorLedOn = False
self.radioLedOn = False
self.syncLedOn = False
self.debugLedOn = False
def cmd_all_toggle(self):
'''emulates
void leds_all_toggle()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_all_toggle')
# change the internal state
self.errorLedOn = not self.errorLedOn
self.radioLedOn = not self.radioLedOn
self.syncLedOn = not self.syncLedOn
self.debugLedOn = not self.debugLedOn
def cmd_circular_shift(self):
'''emulates
void leds_circular_shift()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_circular_shift')
(self.errorLedOn,
self.radioLedOn,
self.syncLedOn,
self.debugLedOn) = (self.radioLedOn,
self.syncLedOn,
self.debugLedOn,
self.errorLedOn)
def cmd_increment(self):
'''emulates
void leds_increment()'''
# log the activity
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug('cmd_increment')
# get the current value
val = 0
if self.errorLedOn:
val += 0x08
if self.radioLedOn:
val += 0x04
if self.syncLedOn:
val += 0x02
if self.debugLedOn:
val += 0x01
# increment
val = (val+1)%0xf
# apply back
self.errorLedOn = ((val & 0x08)!=0)
self.radioLedOn = ((val & 0x04)!=0)
self.syncLedOn = ((val & 0x02)!=0)
self.debugLedOn = ((val & 0x01)!=0)
#=== getters
def get_errorLedOn(self):
return self.errorLedOn
def get_radioLedOn(self):
return self.radioLedOn
def get_syncLedOn(self):
return self.syncLedOn
def get_debugLedOn(self):
return self.debugLedOn
#======================== private =========================================
|
en
| 0.583531
|
#!/usr/bin/python # Copyright (c) 2010-2013, Regents of the University of California. # All rights reserved. # # Released under the BSD 3-Clause license as published at the link below. # https://openwsn.atlassian.net/wiki/display/OW/License Emulates the 'leds' BSP module # store params # local variables # initialize the parent #======================== public ========================================== #=== commands emulates void leds_init() # log the activity # remember that module has been intialized # error LED emulates void leds_error_on() # log the activity # change the internal state emulates void leds_error_off() # log the activity # change the internal state emulates void leds_error_toggle() # log the activity # change the internal state emulates uint8_t leds_error_isOn() # log the activity # radio LED emulates void leds_radio_on() # log the activity # change the internal state emulates void leds_radio_off() # log the activity # change the internal state emulates void leds_radio_toggle() # log the activity # change the internal state emulates uint8_t leds_radio_isOn() # log the activity # sync LED emulates void leds_sync_on() # log the activity # change the internal state emulates void leds_sync_off() # log the activity # change the internal state emulates void leds_sync_toggle() # log the activity # change the internal state emulates uint8_t leds_sync_isOn() # log the activity # debug LED emulates void leds_debug_on() # log the activity # change the internal state emulates void leds_debug_off() # log the activity # change the internal state emulates void leds_debug_toggle() # log the activity # change the internal state emulates uint8_t leds_debug_isOn() # log the activity # all LEDs emulates' void leds_all_on() # log the activity # change the internal state emulates void leds_all_off() # log the activity # change the internal state emulates void leds_all_toggle() # log the activity # change the internal state emulates void leds_circular_shift() # log the activity emulates void leds_increment() # log the activity # get the current value # increment # apply back #=== getters #======================== private =========================================
| 2.34639
| 2
|
libs/sqlobject/tests/test_basic.py
|
scambra/HTPC-Manager
| 422
|
6626300
|
<reponame>scambra/HTPC-Manager
from sqlobject import *
from sqlobject.tests.dbtest import *
class TestSO1(SQLObject):
name = StringCol(length=50, dbName='name_col')
name.title = 'Your Name'
name.foobar = 1
passwd = StringCol(length=10)
class sqlmeta:
cacheValues = False
def _set_passwd(self, passwd):
self._SO_set_passwd(passwd.encode('<PASSWORD>'))
def setupGetters(cls):
setupClass(cls)
inserts(cls, [('bob', 'god'), ('sally', 'sordid'),
('dave', 'dremel'), ('fred', 'forgo')],
'name passwd')
def test_case1():
setupGetters(TestSO1)
bob = TestSO1.selectBy(name='bob')[0]
assert bob.name == 'bob'
assert bob.passwd == '<PASSWORD>'.encode('<PASSWORD>')
bobs = TestSO1.selectBy(name='bob')[:10]
assert len(list(bobs)) == 1
def test_newline():
setupGetters(TestSO1)
bob = TestSO1.selectBy(name='bob')[0]
testString = 'hey\nyou\\can\'t you see me?\t'
bob.name = testString
bob.expire()
assert bob.name == testString
def test_count():
setupGetters(TestSO1)
assert TestSO1.selectBy(name=None).count() == 0
assert TestSO1.selectBy(name='bob').count() == 1
assert TestSO1.select(TestSO1.q.name == 'bob').count() == 1
assert TestSO1.select().count() == len(list(TestSO1.select()))
def test_getset():
setupGetters(TestSO1)
bob = TestSO1.selectBy(name='bob')[0]
assert bob.name == 'bob'
bob.name = 'joe'
assert bob.name == 'joe'
bob.set(name='joebob', passwd='<PASSWORD>')
assert bob.name == 'joebob'
def test_extra_vars():
setupGetters(TestSO1)
col = TestSO1.sqlmeta.columns['name']
assert col.title == 'Your Name'
assert col.foobar == 1
assert getattr(TestSO1.sqlmeta.columns['passwd'], 'title', None) is None
class TestSO2(SQLObject):
name = StringCol(length=50, dbName='name_col')
passwd = StringCol(length=10)
def _set_passwd(self, passwd):
self._SO_set_passwd(passwd.encode('rot13'))
def test_case2():
setupGetters(TestSO2)
bob = TestSO2.selectBy(name='bob')[0]
assert bob.name == 'bob'
assert bob.passwd == '<PASSWORD>'.encode('<PASSWORD>')
class Student(SQLObject):
is_smart = BoolCol()
def test_boolCol():
setupClass(Student)
student = Student(is_smart=False)
assert student.is_smart == False
student2 = Student(is_smart=1)
assert student2.is_smart == True
class TestSO3(SQLObject):
name = StringCol(length=10, dbName='name_col')
other = ForeignKey('TestSO4', default=None)
other2 = KeyCol(foreignKey='TestSO4', default=None)
class TestSO4(SQLObject):
me = StringCol(length=10)
def test_foreignKey():
setupClass([TestSO4, TestSO3])
test3_order = [col.name for col in TestSO3.sqlmeta.columnList]
assert test3_order == ['name', 'otherID', 'other2ID']
tc3 = TestSO3(name='a')
assert tc3.other is None
assert tc3.other2 is None
assert tc3.otherID is None
assert tc3.other2ID is None
tc4a = TestSO4(me='1')
tc3.other = tc4a
assert tc3.other == tc4a
assert tc3.otherID == tc4a.id
tc4b = TestSO4(me='2')
tc3.other = tc4b.id
assert tc3.other == tc4b
assert tc3.otherID == tc4b.id
tc4c = TestSO4(me='3')
tc3.other2 = tc4c
assert tc3.other2 == tc4c
assert tc3.other2ID == tc4c.id
tc4d = TestSO4(me='4')
tc3.other2 = tc4d.id
assert tc3.other2 == tc4d
assert tc3.other2ID == tc4d.id
tcc = TestSO3(name='b', other=tc4a)
assert tcc.other == tc4a
tcc2 = TestSO3(name='c', other=tc4a.id)
assert tcc2.other == tc4a
def test_selectBy():
setupClass([TestSO4, TestSO3])
tc4 = TestSO4(me='another')
tc3 = TestSO3(name='sel', other=tc4)
anothertc3 = TestSO3(name='not joined')
assert tc3.other == tc4
assert list(TestSO3.selectBy(other=tc4)) == [tc3]
assert list(TestSO3.selectBy(otherID=tc4.id)) == [tc3]
assert TestSO3.selectBy(otherID=tc4.id)[0] == tc3
assert list(TestSO3.selectBy(otherID=tc4.id)[:10]) == [tc3]
assert list(TestSO3.selectBy(other=tc4)[:10]) == [tc3]
class TestSO5(SQLObject):
name = StringCol(length=10, dbName='name_col')
other = ForeignKey('TestSO6', default=None, cascade=True)
another = ForeignKey('TestSO7', default=None, cascade=True)
class TestSO6(SQLObject):
name = StringCol(length=10, dbName='name_col')
other = ForeignKey('TestSO7', default=None, cascade=True)
class TestSO7(SQLObject):
name = StringCol(length=10, dbName='name_col')
def test_foreignKeyDestroySelfCascade():
setupClass([TestSO7, TestSO6, TestSO5])
tc5 = TestSO5(name='a')
tc6a = TestSO6(name='1')
tc5.other = tc6a
tc7a = TestSO7(name='2')
tc6a.other = tc7a
tc5.another = tc7a
assert tc5.other == tc6a
assert tc5.otherID == tc6a.id
assert tc6a.other == tc7a
assert tc6a.otherID == tc7a.id
assert tc5.other.other == tc7a
assert tc5.other.otherID == tc7a.id
assert tc5.another == tc7a
assert tc5.anotherID == tc7a.id
assert tc5.other.other == tc5.another
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 1
assert TestSO7.select().count() == 1
tc6b = TestSO6(name='3')
tc6c = TestSO6(name='4')
tc7b = TestSO7(name='5')
tc6b.other = tc7b
tc6c.other = tc7b
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 3
assert TestSO7.select().count() == 2
tc6b.destroySelf()
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 2
assert TestSO7.select().count() == 2
tc7b.destroySelf()
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 1
assert TestSO7.select().count() == 1
tc7a.destroySelf()
assert TestSO5.select().count() == 0
assert TestSO6.select().count() == 0
assert TestSO7.select().count() == 0
def testForeignKeyDropTableCascade():
if not supports('dropTableCascade'):
return
setupClass(TestSO7)
setupClass(TestSO6)
setupClass(TestSO5)
tc5a = TestSO5(name='a')
tc6a = TestSO6(name='1')
tc5a.other = tc6a
tc7a = TestSO7(name='2')
tc6a.other = tc7a
tc5a.another = tc7a
tc5b = TestSO5(name='b')
tc5c = TestSO5(name='c')
tc6b = TestSO6(name='3')
tc5c.other = tc6b
assert TestSO5.select().count() == 3
assert TestSO6.select().count() == 2
assert TestSO7.select().count() == 1
TestSO7.dropTable(cascade=True)
assert TestSO5.select().count() == 3
assert TestSO6.select().count() == 2
tc6a.destroySelf()
assert TestSO5.select().count() == 2
assert TestSO6.select().count() == 1
tc6b.destroySelf()
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 0
assert iter(TestSO5.select()).next() == tc5b
tc6c = TestSO6(name='3')
tc5b.other = tc6c
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 1
tc6c.destroySelf()
assert TestSO5.select().count() == 0
assert TestSO6.select().count() == 0
class TestSO8(SQLObject):
name = StringCol(length=10, dbName='name_col')
other = ForeignKey('TestSO9', default=None, cascade=False)
class TestSO9(SQLObject):
name = StringCol(length=10, dbName='name_col')
def testForeignKeyDestroySelfRestrict():
setupClass([TestSO9, TestSO8])
tc8a = TestSO8(name='a')
tc9a = TestSO9(name='1')
tc8a.other = tc9a
tc8b = TestSO8(name='b')
tc9b = TestSO9(name='2')
assert tc8a.other == tc9a
assert tc8a.otherID == tc9a.id
assert TestSO8.select().count() == 2
assert TestSO9.select().count() == 2
raises(Exception, tc9a.destroySelf)
tc9b.destroySelf()
assert TestSO8.select().count() == 2
assert TestSO9.select().count() == 1
tc8a.destroySelf()
tc8b.destroySelf()
tc9a.destroySelf()
assert TestSO8.select().count() == 0
assert TestSO9.select().count() == 0
class TestSO10(SQLObject):
name = StringCol()
class TestSO11(SQLObject):
name = StringCol()
other = ForeignKey('TestSO10', default=None, cascade='null')
def testForeignKeySetNull():
setupClass([TestSO10, TestSO11])
obj1 = TestSO10(name='foo')
obj2 = TestSO10(name='bar')
dep1 = TestSO11(name='xxx', other=obj1)
dep2 = TestSO11(name='yyy', other=obj1)
dep3 = TestSO11(name='zzz', other=obj2)
for name in 'xxx', 'yyy', 'zzz':
assert len(list(TestSO11.selectBy(name=name))) == 1
obj1.destroySelf()
for name in 'xxx', 'yyy', 'zzz':
assert len(list(TestSO11.selectBy(name=name))) == 1
assert dep1.other is None
assert dep2.other is None
assert dep3.other is obj2
def testAsDict():
setupGetters(TestSO1)
bob = TestSO1.selectBy(name='bob')[0]
assert bob.sqlmeta.asDict() == {
'passwd': '<PASSWORD>', 'name': 'bob', 'id': bob.id}
def test_nonexisting_attr():
setupClass(Student)
try:
Student.select(Student.q.nonexisting)
except AttributeError:
pass
else:
assert 0, "Expected an AttributeError"
class TestSO12(SQLObject):
name = StringCol()
value = IntCol(defaultSQL='1')
def test_defaultSQL():
setupClass(TestSO12)
test = TestSO12(name="test")
assert test.value == 1
def test_connection_override():
sqlhub.processConnection = connectionForURI('sqlite:///db1')
class TestSO13(SQLObject):
_connection = connectionForURI('sqlite:///db2')
assert TestSO13._connection.uri() == 'sqlite:///db2'
del sqlhub.processConnection
|
from sqlobject import *
from sqlobject.tests.dbtest import *
class TestSO1(SQLObject):
name = StringCol(length=50, dbName='name_col')
name.title = 'Your Name'
name.foobar = 1
passwd = StringCol(length=10)
class sqlmeta:
cacheValues = False
def _set_passwd(self, passwd):
self._SO_set_passwd(passwd.encode('<PASSWORD>'))
def setupGetters(cls):
setupClass(cls)
inserts(cls, [('bob', 'god'), ('sally', 'sordid'),
('dave', 'dremel'), ('fred', 'forgo')],
'name passwd')
def test_case1():
setupGetters(TestSO1)
bob = TestSO1.selectBy(name='bob')[0]
assert bob.name == 'bob'
assert bob.passwd == '<PASSWORD>'.encode('<PASSWORD>')
bobs = TestSO1.selectBy(name='bob')[:10]
assert len(list(bobs)) == 1
def test_newline():
setupGetters(TestSO1)
bob = TestSO1.selectBy(name='bob')[0]
testString = 'hey\nyou\\can\'t you see me?\t'
bob.name = testString
bob.expire()
assert bob.name == testString
def test_count():
setupGetters(TestSO1)
assert TestSO1.selectBy(name=None).count() == 0
assert TestSO1.selectBy(name='bob').count() == 1
assert TestSO1.select(TestSO1.q.name == 'bob').count() == 1
assert TestSO1.select().count() == len(list(TestSO1.select()))
def test_getset():
setupGetters(TestSO1)
bob = TestSO1.selectBy(name='bob')[0]
assert bob.name == 'bob'
bob.name = 'joe'
assert bob.name == 'joe'
bob.set(name='joebob', passwd='<PASSWORD>')
assert bob.name == 'joebob'
def test_extra_vars():
setupGetters(TestSO1)
col = TestSO1.sqlmeta.columns['name']
assert col.title == 'Your Name'
assert col.foobar == 1
assert getattr(TestSO1.sqlmeta.columns['passwd'], 'title', None) is None
class TestSO2(SQLObject):
name = StringCol(length=50, dbName='name_col')
passwd = StringCol(length=10)
def _set_passwd(self, passwd):
self._SO_set_passwd(passwd.encode('rot13'))
def test_case2():
setupGetters(TestSO2)
bob = TestSO2.selectBy(name='bob')[0]
assert bob.name == 'bob'
assert bob.passwd == '<PASSWORD>'.encode('<PASSWORD>')
class Student(SQLObject):
is_smart = BoolCol()
def test_boolCol():
setupClass(Student)
student = Student(is_smart=False)
assert student.is_smart == False
student2 = Student(is_smart=1)
assert student2.is_smart == True
class TestSO3(SQLObject):
name = StringCol(length=10, dbName='name_col')
other = ForeignKey('TestSO4', default=None)
other2 = KeyCol(foreignKey='TestSO4', default=None)
class TestSO4(SQLObject):
me = StringCol(length=10)
def test_foreignKey():
setupClass([TestSO4, TestSO3])
test3_order = [col.name for col in TestSO3.sqlmeta.columnList]
assert test3_order == ['name', 'otherID', 'other2ID']
tc3 = TestSO3(name='a')
assert tc3.other is None
assert tc3.other2 is None
assert tc3.otherID is None
assert tc3.other2ID is None
tc4a = TestSO4(me='1')
tc3.other = tc4a
assert tc3.other == tc4a
assert tc3.otherID == tc4a.id
tc4b = TestSO4(me='2')
tc3.other = tc4b.id
assert tc3.other == tc4b
assert tc3.otherID == tc4b.id
tc4c = TestSO4(me='3')
tc3.other2 = tc4c
assert tc3.other2 == tc4c
assert tc3.other2ID == tc4c.id
tc4d = TestSO4(me='4')
tc3.other2 = tc4d.id
assert tc3.other2 == tc4d
assert tc3.other2ID == tc4d.id
tcc = TestSO3(name='b', other=tc4a)
assert tcc.other == tc4a
tcc2 = TestSO3(name='c', other=tc4a.id)
assert tcc2.other == tc4a
def test_selectBy():
setupClass([TestSO4, TestSO3])
tc4 = TestSO4(me='another')
tc3 = TestSO3(name='sel', other=tc4)
anothertc3 = TestSO3(name='not joined')
assert tc3.other == tc4
assert list(TestSO3.selectBy(other=tc4)) == [tc3]
assert list(TestSO3.selectBy(otherID=tc4.id)) == [tc3]
assert TestSO3.selectBy(otherID=tc4.id)[0] == tc3
assert list(TestSO3.selectBy(otherID=tc4.id)[:10]) == [tc3]
assert list(TestSO3.selectBy(other=tc4)[:10]) == [tc3]
class TestSO5(SQLObject):
name = StringCol(length=10, dbName='name_col')
other = ForeignKey('TestSO6', default=None, cascade=True)
another = ForeignKey('TestSO7', default=None, cascade=True)
class TestSO6(SQLObject):
name = StringCol(length=10, dbName='name_col')
other = ForeignKey('TestSO7', default=None, cascade=True)
class TestSO7(SQLObject):
name = StringCol(length=10, dbName='name_col')
def test_foreignKeyDestroySelfCascade():
setupClass([TestSO7, TestSO6, TestSO5])
tc5 = TestSO5(name='a')
tc6a = TestSO6(name='1')
tc5.other = tc6a
tc7a = TestSO7(name='2')
tc6a.other = tc7a
tc5.another = tc7a
assert tc5.other == tc6a
assert tc5.otherID == tc6a.id
assert tc6a.other == tc7a
assert tc6a.otherID == tc7a.id
assert tc5.other.other == tc7a
assert tc5.other.otherID == tc7a.id
assert tc5.another == tc7a
assert tc5.anotherID == tc7a.id
assert tc5.other.other == tc5.another
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 1
assert TestSO7.select().count() == 1
tc6b = TestSO6(name='3')
tc6c = TestSO6(name='4')
tc7b = TestSO7(name='5')
tc6b.other = tc7b
tc6c.other = tc7b
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 3
assert TestSO7.select().count() == 2
tc6b.destroySelf()
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 2
assert TestSO7.select().count() == 2
tc7b.destroySelf()
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 1
assert TestSO7.select().count() == 1
tc7a.destroySelf()
assert TestSO5.select().count() == 0
assert TestSO6.select().count() == 0
assert TestSO7.select().count() == 0
def testForeignKeyDropTableCascade():
if not supports('dropTableCascade'):
return
setupClass(TestSO7)
setupClass(TestSO6)
setupClass(TestSO5)
tc5a = TestSO5(name='a')
tc6a = TestSO6(name='1')
tc5a.other = tc6a
tc7a = TestSO7(name='2')
tc6a.other = tc7a
tc5a.another = tc7a
tc5b = TestSO5(name='b')
tc5c = TestSO5(name='c')
tc6b = TestSO6(name='3')
tc5c.other = tc6b
assert TestSO5.select().count() == 3
assert TestSO6.select().count() == 2
assert TestSO7.select().count() == 1
TestSO7.dropTable(cascade=True)
assert TestSO5.select().count() == 3
assert TestSO6.select().count() == 2
tc6a.destroySelf()
assert TestSO5.select().count() == 2
assert TestSO6.select().count() == 1
tc6b.destroySelf()
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 0
assert iter(TestSO5.select()).next() == tc5b
tc6c = TestSO6(name='3')
tc5b.other = tc6c
assert TestSO5.select().count() == 1
assert TestSO6.select().count() == 1
tc6c.destroySelf()
assert TestSO5.select().count() == 0
assert TestSO6.select().count() == 0
class TestSO8(SQLObject):
name = StringCol(length=10, dbName='name_col')
other = ForeignKey('TestSO9', default=None, cascade=False)
class TestSO9(SQLObject):
name = StringCol(length=10, dbName='name_col')
def testForeignKeyDestroySelfRestrict():
setupClass([TestSO9, TestSO8])
tc8a = TestSO8(name='a')
tc9a = TestSO9(name='1')
tc8a.other = tc9a
tc8b = TestSO8(name='b')
tc9b = TestSO9(name='2')
assert tc8a.other == tc9a
assert tc8a.otherID == tc9a.id
assert TestSO8.select().count() == 2
assert TestSO9.select().count() == 2
raises(Exception, tc9a.destroySelf)
tc9b.destroySelf()
assert TestSO8.select().count() == 2
assert TestSO9.select().count() == 1
tc8a.destroySelf()
tc8b.destroySelf()
tc9a.destroySelf()
assert TestSO8.select().count() == 0
assert TestSO9.select().count() == 0
class TestSO10(SQLObject):
name = StringCol()
class TestSO11(SQLObject):
name = StringCol()
other = ForeignKey('TestSO10', default=None, cascade='null')
def testForeignKeySetNull():
setupClass([TestSO10, TestSO11])
obj1 = TestSO10(name='foo')
obj2 = TestSO10(name='bar')
dep1 = TestSO11(name='xxx', other=obj1)
dep2 = TestSO11(name='yyy', other=obj1)
dep3 = TestSO11(name='zzz', other=obj2)
for name in 'xxx', 'yyy', 'zzz':
assert len(list(TestSO11.selectBy(name=name))) == 1
obj1.destroySelf()
for name in 'xxx', 'yyy', 'zzz':
assert len(list(TestSO11.selectBy(name=name))) == 1
assert dep1.other is None
assert dep2.other is None
assert dep3.other is obj2
def testAsDict():
setupGetters(TestSO1)
bob = TestSO1.selectBy(name='bob')[0]
assert bob.sqlmeta.asDict() == {
'passwd': '<PASSWORD>', 'name': 'bob', 'id': bob.id}
def test_nonexisting_attr():
setupClass(Student)
try:
Student.select(Student.q.nonexisting)
except AttributeError:
pass
else:
assert 0, "Expected an AttributeError"
class TestSO12(SQLObject):
name = StringCol()
value = IntCol(defaultSQL='1')
def test_defaultSQL():
setupClass(TestSO12)
test = TestSO12(name="test")
assert test.value == 1
def test_connection_override():
sqlhub.processConnection = connectionForURI('sqlite:///db1')
class TestSO13(SQLObject):
_connection = connectionForURI('sqlite:///db2')
assert TestSO13._connection.uri() == 'sqlite:///db2'
del sqlhub.processConnection
|
none
| 1
| 2.769202
| 3
|
|
testing/test_znode_data.py
|
xpenalosa/Degree-Final-Project
| 0
|
6626301
|
<filename>testing/test_znode_data.py<gh_stars>0
from basetest import BaseTest
from sys import getsizeof
from kazoo.exceptions import ZookeeperError, BadVersionError
class ZNodeDataTest(BaseTest):
"""Tests related to zNode data management
These tests cover the management of data stored in zNodes and
its versioning.
"""
def __init__(self, client):
self.client = client
self.testpath = "/test/znode_data"
@BaseTest.make_test
def test_data_storage(self):
"""Covered in zNode instantiation tests."""
pass
@BaseTest.make_test
def test_data_storage_bytestring(self):
"""Verify we can store data after converting to bytestring."""
self.client.ensure_path(self.testpath)
bstring = "Data".encode()
path = self.client.create(self.testpath + "/store_bts", bstring)
assert path == self.testpath + "/store_bts"
@BaseTest.make_test
def test_data_access(self):
"""Verify we can access stored data."""
self.client.ensure_path(self.testpath)
# Create node
path = self.client.create(self.testpath + "/access", b"Data")
# Get node
data, stats = self.client.get(path)
# Assert same data
assert data is not None, "Data is None"
assert data == b"Data", "Data is not b'Data'"
assert data.decode('utf-8') == "Data", "Decoded data mismatch"
@BaseTest.make_test
def test_data_update(self):
"""Verify the zNode data can be updated."""
self.client.ensure_path(self.testpath)
# Define data for both nodes
init_bytestring = "Start".encode()
end_bytestring = "End".encode()
# Create node with initial data
path = self.client.create(
self.testpath + "/update",
init_bytestring)
# Retrieve data
data, stats = self.client.get(path)
# Verify stored data
assert data is not None, "Initial data is None"
assert data == init_bytestring, "Initial data mismatch"
# Set new data
stats = self.client.set(path, end_bytestring)
data, stats = self.client.get(path)
# Assert updated data
assert data is not None, "End data is None"
assert data != init_bytestring, "End data matches init data"
assert data == end_bytestring, "End data mismatch"
@BaseTest.make_test
def test_data_update_version(self):
"""Verify zNode version gets updated."""
self.client.ensure_path(self.testpath)
# Define data for both nodes
init_bytestring = "Start".encode()
end_bytestring = "End".encode()
# Create node with initial data
path = self.client.create(
self.testpath + "/update_version",
init_bytestring)
# Retrieve data
_, stats_before = self.client.get(path)
assert stats_before is not None, "Stats before update is None"
# Update node data
self.client.set(path, end_bytestring)
# Retrieve data
_, stats_after = self.client.get(path)
# Verify version update
assert stats_after is not None, "Stats after update is None"
assert stats_before.version != stats_after.version, ''.join([
"Same version after update"])
@BaseTest.make_test
def test_data_update_version_restriction(self):
"""Verify version locks data updates."""
self.client.ensure_path(self.testpath)
# Define data for both nodes
init_bytestring = "Start".encode()
end_bytestring = "End".encode()
# Create node with initial data
path = self.client.create(
self.testpath + "/update_restrict",
init_bytestring)
# Retrieve data
_, stats = self.client.get(path)
# Force another node version
new_version = stats.version + 1
try:
self.client.set(
self.testpath + "/update_restrict",
end_bytestring,
version = new_version
)
except BadVersionError:
# Expected behaviour
pass
else:
raise AssertionError("zNode updated with bad version")
|
<filename>testing/test_znode_data.py<gh_stars>0
from basetest import BaseTest
from sys import getsizeof
from kazoo.exceptions import ZookeeperError, BadVersionError
class ZNodeDataTest(BaseTest):
"""Tests related to zNode data management
These tests cover the management of data stored in zNodes and
its versioning.
"""
def __init__(self, client):
self.client = client
self.testpath = "/test/znode_data"
@BaseTest.make_test
def test_data_storage(self):
"""Covered in zNode instantiation tests."""
pass
@BaseTest.make_test
def test_data_storage_bytestring(self):
"""Verify we can store data after converting to bytestring."""
self.client.ensure_path(self.testpath)
bstring = "Data".encode()
path = self.client.create(self.testpath + "/store_bts", bstring)
assert path == self.testpath + "/store_bts"
@BaseTest.make_test
def test_data_access(self):
"""Verify we can access stored data."""
self.client.ensure_path(self.testpath)
# Create node
path = self.client.create(self.testpath + "/access", b"Data")
# Get node
data, stats = self.client.get(path)
# Assert same data
assert data is not None, "Data is None"
assert data == b"Data", "Data is not b'Data'"
assert data.decode('utf-8') == "Data", "Decoded data mismatch"
@BaseTest.make_test
def test_data_update(self):
"""Verify the zNode data can be updated."""
self.client.ensure_path(self.testpath)
# Define data for both nodes
init_bytestring = "Start".encode()
end_bytestring = "End".encode()
# Create node with initial data
path = self.client.create(
self.testpath + "/update",
init_bytestring)
# Retrieve data
data, stats = self.client.get(path)
# Verify stored data
assert data is not None, "Initial data is None"
assert data == init_bytestring, "Initial data mismatch"
# Set new data
stats = self.client.set(path, end_bytestring)
data, stats = self.client.get(path)
# Assert updated data
assert data is not None, "End data is None"
assert data != init_bytestring, "End data matches init data"
assert data == end_bytestring, "End data mismatch"
@BaseTest.make_test
def test_data_update_version(self):
"""Verify zNode version gets updated."""
self.client.ensure_path(self.testpath)
# Define data for both nodes
init_bytestring = "Start".encode()
end_bytestring = "End".encode()
# Create node with initial data
path = self.client.create(
self.testpath + "/update_version",
init_bytestring)
# Retrieve data
_, stats_before = self.client.get(path)
assert stats_before is not None, "Stats before update is None"
# Update node data
self.client.set(path, end_bytestring)
# Retrieve data
_, stats_after = self.client.get(path)
# Verify version update
assert stats_after is not None, "Stats after update is None"
assert stats_before.version != stats_after.version, ''.join([
"Same version after update"])
@BaseTest.make_test
def test_data_update_version_restriction(self):
"""Verify version locks data updates."""
self.client.ensure_path(self.testpath)
# Define data for both nodes
init_bytestring = "Start".encode()
end_bytestring = "End".encode()
# Create node with initial data
path = self.client.create(
self.testpath + "/update_restrict",
init_bytestring)
# Retrieve data
_, stats = self.client.get(path)
# Force another node version
new_version = stats.version + 1
try:
self.client.set(
self.testpath + "/update_restrict",
end_bytestring,
version = new_version
)
except BadVersionError:
# Expected behaviour
pass
else:
raise AssertionError("zNode updated with bad version")
|
en
| 0.66481
|
Tests related to zNode data management These tests cover the management of data stored in zNodes and its versioning. Covered in zNode instantiation tests. Verify we can store data after converting to bytestring. Verify we can access stored data. # Create node # Get node # Assert same data Verify the zNode data can be updated. # Define data for both nodes # Create node with initial data # Retrieve data # Verify stored data # Set new data # Assert updated data Verify zNode version gets updated. # Define data for both nodes # Create node with initial data # Retrieve data # Update node data # Retrieve data # Verify version update Verify version locks data updates. # Define data for both nodes # Create node with initial data # Retrieve data # Force another node version # Expected behaviour
| 2.609756
| 3
|
laikaboss/modules/meta_rtf_controlwords.py
|
sandialabs/laikaboss
| 2
|
6626302
|
<gh_stars>1-10
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import yara
# Import classes and helpers from the Laika framework
from laikaboss.util import get_option
from laikaboss.si_module import SI_MODULE
class META_RTF_CONTROLWORDS(SI_MODULE):
'''
counts classes of control words from RTF files
'''
def __init__(self):
self.module_name = "META_RTF_CONTROLWORDS"
self.rules = None
def _run(self, scanObject, result, depth, args):
#lazy compile rules, not using yara_on_demand due to signatures in string vs. file
if not self.rules:
self.rules = yara.compile(source=rtf_rules_source)
matches = self.rules.match(data=scanObject.buffer)
for match in matches:
scanObject.addMetadata(self.module_name, match.rule[4:], len(match.strings))
return []
rtf_rules_source = r"""
rule rtf_position_tabs
{
strings:
$pindtabqc = "\\pindtabqc"
$pindtabql = "\\pindtabql"
$pindtabqr = "\\pindtabqr"
$pmartabqc = "\\pmartabqc"
$pmartabql = "\\pmartabql"
$pmartabqr = "\\pmartabqr"
$ptabldot = "\\ptabldot"
$ptablmdot = "\\ptablmdot"
$ptablminus = "\\ptablminus"
$ptablnone = "\\ptablnone"
$ptabluscore = "\\ptabluscore"
condition:
any of them
}
rule rtf_character_properties
{
strings:
$ab = "\\ab"
$acaps = "\\acaps"
$acf = "\\acf"
$adn = "\\adn"
$aexpnd = "\\aexpnd"
$af = "\\af"
$afs = "\\afs"
$ai = "\\ai"
$alang = "\\alang"
$aoutl = "\\aoutl"
$ascaps = "\\ascaps"
$ashad = "\\ashad"
$astrike = "\\astrike"
$aul = "\\aul"
$auld = "\\auld"
$auldb = "\\auldb"
$aulnone = "\\aulnone"
$aulw = "\\aulw"
$aup = "\\aup"
$dbch = "\\dbch"
$fcs = "\\fcs"
$hich = "\\hich"
$loch = "\\loch"
condition:
any of them
}
rule rtf_bookmarks
{
strings:
$bkmkcolf = "\\bkmkcolf"
$bkmkcoll = "\\bkmkcoll"
$bkmkend = "\\bkmkend"
$bkmkstart = "\\bkmkstart"
$mvfmf = "\\mvfmf"
$mvfml = "\\mvfml"
$mvtof = "\\mvtof"
$mvtol = "\\mvtol"
condition:
any of them
}
rule rtf_bullets
{
strings:
$ilvl = "\\ilvl"
$listtext = "\\listtext"
$pn = "\\pn"
$pnacross = "\\pnacross"
$pnaiu = "\\pnaiu"
$pnaiud = "\\pnaiud"
$pnaiueo = "\\pnaiueo"
$pnaiueod = "\\pnaiueod"
$pnb = "\\pnb"
$pnbidia = "\\pnbidia"
$pnbidib = "\\pnbidib"
$pncaps = "\\pncaps"
$pncard = "\\pncard"
$pncf = "\\pncf"
$pnchosung = "\\pnchosung"
$pncnum = "\\pncnum"
$pndbnum = "\\pndbnum"
$pndbnumd = "\\pndbnumd"
$pndbnumk = "\\pndbnumk"
$pndbnuml = "\\pndbnuml"
$pndbnumt = "\\pndbnumt"
$pndec = "\\pndec"
$pndecd = "\\pndecd"
$pnf = "\\pnf"
$pnfs = "\\pnfs"
$pnganada = "\\pnganada"
$pngbnum = "\\pngbnum"
$pngbnumd = "\\pngbnumd"
$pngbnumk = "\\pngbnumk"
$pngbnuml = "\\pngbnuml"
$pnhang = "\\pnhang"
$pni = "\\pni"
$pnindent = "\\pnindent"
$pniroha = "\\pniroha"
$pnirohad = "\\pnirohad"
$pnlcltr = "\\pnlcltr"
$pnlcrm = "\\pnlcrm"
$pnlvl = "\\pnlvl"
$pnlvlblt = "\\pnlvlblt"
$pnlvlbody = "\\pnlvlbody"
$pnlvlcont = "\\pnlvlcont"
$pnnumonce = "\\pnnumonce"
$pnord = "\\pnord"
$pnordt = "\\pnordt"
$pnprev = "\\pnprev"
$pnqc = "\\pnqc"
$pnql = "\\pnql"
$pnqr = "\\pnqr"
$pnrestart = "\\pnrestart"
$pnscaps = "\\pnscaps"
$pnsp = "\\pnsp"
$pnstart = "\\pnstart"
$pnstrike = "\\pnstrike"
$pntext = "\\pntext"
$pntxta = "\\pntxta"
$pntxtb = "\\pntxtb"
$pnucltr = "\\pnucltr"
$pnucrm = "\\pnucrm"
$pnul = "\\pnul"
$pnuld = "\\pnuld"
$pnuldash = "\\pnuldash"
$pnuldashd = "\\pnuldashd"
$pnuldashdd = "\\pnuldashdd"
$pnuldb = "\\pnuldb"
$pnulhair = "\\pnulhair"
$pnulnone = "\\pnulnone"
$pnulth = "\\pnulth"
$pnulw = "\\pnulw"
$pnulwave = "\\pnulwave"
$pnzodiac = "\\pnzodiac"
$pnzodiacd = "\\pnzodiacd"
$pnzodiacl = "\\pnzodiacl"
condition:
any of them
}
rule rtf_characters
{
strings:
$chbgbdiag = "\\chbgbdiag"
$chbgcross = "\\chbgcross"
$chbgdcross = "\\chbgdcross"
$chbgdkbdiag = "\\chbgdkbdiag"
$chbgdkcross = "\\chbgdkcross"
$chbgdkdcross = "\\chbgdkdcross"
$chbgdkfdiag = "\\chbgdkfdiag"
$chbgdkhoriz = "\\chbgdkhoriz"
$chbgdkvert = "\\chbgdkvert"
$chbgfdiag = "\\chbgfdiag"
$chbghoriz = "\\chbghoriz"
$chbgvert = "\\chbgvert"
$chbrdr = "\\chbrdr"
$chcbpat = "\\chcbpat"
$chcfpat = "\\chcfpat"
$chshdng = "\\chshdng"
$crauth = "\\crauth"
$crdate = "\\crdate"
$deleted = "\\deleted"
$mvauth = "\\mvauth"
$mvdate = "\\mvdate"
$mvf = "\\mvf"
$mvt = "\\mvt"
$revauth = "\\revauth"
$revauthdel = "\\revauthdel"
$revdttm = "\\revdttm"
$revdttmdel = "\\revdttmdel"
$revised = "\\revised"
$ansi = "\\ansi"
$ansicpg = "\\ansicpg"
$fbidis = "\\fbidis"
$mac = "\\mac"
$pc = "\\pc"
$pca = "\\pca"
$impr = "\\impr"
$striked1 = "\\striked1"
condition:
any of them
}
rule rtf_codepage
{
strings:
$cpg = "\\cpg"
condition:
any of them
}
rule rtf_color
{
strings:
$colorschememapping = "\\colorschememapping"
$blue = "\\blue"
$caccentfive = "\\caccentfive"
$caccentfour = "\\caccentfour"
$caccentone = "\\caccentone"
$caccentsix = "\\caccentsix"
$caccentthree = "\\caccentthree"
$caccenttwo = "\\caccenttwo"
$cbackgroundone = "\\cbackgroundone"
$cbackgroundtwo = "\\cbackgroundtwo"
$cfollowedhyperlink = "\\cfollowedhyperlink"
$chyperlink = "\\chyperlink"
$cmaindarkone = "\\cmaindarkone"
$cmaindarktwo = "\\cmaindarktwo"
$cmainlightone = "\\cmainlightone"
$cmainlighttwo = "\\cmainlighttwo"
$colortbl = "\\colortbl"
$cshade = "\\cshade"
$ctextone = "\\ctextone"
$ctexttwo = "\\ctexttwo"
$ctint = "\\ctint"
$green = "\\green"
$red = "\\red"
condition:
any of them
}
rule rtf_comments
{
strings:
$annotation = "\\annotation"
$atnauthor = "\\atnauthor"
$atndate = "\\atndate"
$atnicn = "\\atnicn"
$atnid = "\\atnid"
$atnparent = "\\atnparent"
$atnref = "\\atnref"
$atntime = "\\atntime"
$atrfend = "\\atrfend"
$atrfstart = "\\atrfstart"
condition:
any of them
}
rule rtf_control_other
{
strings:
$disabled = "\\disabled"
$htmlbase = "\\htmlbase"
$htmlrtf = "\\htmlrtf"
$htmltag = "\\htmltag"
$mhtmltag = "\\mhtmltag"
$protect = "\\protect"
$pwd = "\\pwd"
$urtf = "\\urtf"
condition:
any of them
}
rule rtf_datastore
{
strings:
$datastore = "\\datastore"
condition:
any of them
}
rule rtf_xml
{
strings:
$xmlattr = "\\xmlattr"
$xmlattrname = "\\xmlattrname"
$xmlattrns = "\\xmlattrns"
$xmlattrvalue = "\\xmlattrvalue"
$xmlclose = "\\xmlclose"
$xmlname = "\\xmlname"
$xmlnstbl = "\\xmlnstbl"
$xmlopen = "\\xmlopen"
$xmlsdttcell = "\\xmlsdttcell"
$xmlsdttpara = "\\xmlsdttpara"
$xmlsdttregular = "\\xmlsdttregular"
$xmlsdttrow = "\\xmlsdttrow"
$xmlsdttunknown = "\\xmlsdttunknown"
$xmlns = "\\xmlns"
condition:
any of them
}
rule rtf_defaults
{
strings:
$adeff = "\\adeff"
$adeflang = "\\adeflang"
$deff = "\\deff"
$deflang = "\\deflang"
$deflangfe = "\\deflangfe"
$stshfbi = "\\stshfbi"
$stshfdbch = "\\stshfdbch"
$stshfhich = "\\stshfhich"
$stshfloch = "\\stshfloch"
$defchp = "\\defchp"
$defpap = "\\defpap"
condition:
any of them
}
rule rtf_formatting
{
strings:
$aenddoc = "\\aenddoc"
$aendnotes = "\\aendnotes"
$afelev = "\\afelev"
$aftnbj = "\\aftnbj"
$aftncn = "\\aftncn"
$aftnnalc = "\\aftnnalc"
$aftnnar = "\\aftnnar"
$aftnnauc = "\\aftnnauc"
$aftnnchi = "\\aftnnchi"
$aftnnchosung = "\\aftnnchosung"
$aftnncnum = "\\aftnncnum"
$aftnndbar = "\\aftnndbar"
$aftnndbnum = "\\aftnndbnum"
$aftnndbnumd = "\\aftnndbnumd"
$aftnndbnumk = "\\aftnndbnumk"
$aftnndbnumt = "\\aftnndbnumt"
$aftnnganada = "\\aftnnganada"
$aftnngbnum = "\\aftnngbnum"
$aftnngbnumd = "\\aftnngbnumd"
$aftnngbnumk = "\\aftnngbnumk"
$aftnngbnuml = "\\aftnngbnuml"
$aftnnrlc = "\\aftnnrlc"
$aftnnruc = "\\aftnnruc"
$aftnnzodiac = "\\aftnnzodiac"
$aftnnzodiacd = "\\aftnnzodiacd"
$aftnnzodiacl = "\\aftnnzodiacl"
$aftnrestart = "\\aftnrestart"
$aftnrstcont = "\\aftnrstcont"
$aftnsep = "\\aftnsep"
$aftnsepc = "\\aftnsepc"
$aftnstart = "\\aftnstart"
$aftntj = "\\aftntj"
$allowfieldendsel = "\\allowfieldendsel"
$allprot = "\\allprot"
$alntblind = "\\alntblind"
$annotprot = "\\annotprot"
$ApplyBrkRules = "\\ApplyBrkRules"
$asianbrkrule = "\\asianbrkrule"
$autofmtoverride = "\\autofmtoverride"
$background = "\\background"
$bdbfhdr = "\\bdbfhdr"
$bdrrlswsix = "\\bdrrlswsix"
$bookfold = "\\bookfold"
$bookfoldrev = "\\bookfoldrev"
$bookfoldsheets = "\\bookfoldsheets"
$brdrart = "\\brdrart"
$brkfrm = "\\brkfrm"
$cachedcolbal = "\\cachedcolbal"
$cts = "\\cts"
$cvmme = "\\cvmme"
$defformat = "\\defformat"
$deftab = "\\deftab"
$dghorigin = "\\dghorigin"
$dghshow = "\\dghshow"
$dghspace = "\\dghspace"
$dgmargin = "\\dgmargin"
$dgsnap = "\\dgsnap"
$dgvorigin = "\\dgvorigin"
$dgvshow = "\\dgvshow"
$dgvspace = "\\dgvspace"
$dntblnsbdb = "\\dntblnsbdb"
$doctemp = "\\doctemp"
$doctype = "\\doctype"
$donotembedlingdata = "\\donotembedlingdata"
$donotembedsysfont = "\\donotembedsysfont"
$donotshowcomments = "\\donotshowcomments"
$donotshowinsdel = "\\donotshowinsdel"
$donotshowmarkup = "\\donotshowmarkup"
$donotshowprops = "\\donotshowprops"
$enddoc = "\\enddoc"
$endnotes = "\\endnotes"
$enforceprot = "\\enforceprot"
$expshrtn = "\\expshrtn"
$facingp = "\\facingp"
$fchars = "\\fchars"
$felnbrelev = "\\felnbrelev"
$fet = "\\fet"
$forceupgrade = "\\forceupgrade"
$formdisp = "\\formdisp"
$formprot = "\\formprot"
$formshade = "\\formshade"
$fracwidth = "\\fracwidth"
$fromhtml = "\\fromhtml"
$fromtext = "\\fromtext"
$ftnalt = "\\ftnalt"
$ftnbj = "\\ftnbj"
$ftncn = "\\ftncn"
$ftnlytwnine = "\\ftnlytwnine"
$ftnnalc = "\\ftnnalc"
$ftnnar = "\\ftnnar"
$ftnnauc = "\\ftnnauc"
$ftnnchi = "\\ftnnchi"
$ftnnchosung = "\\ftnnchosung"
$ftnncnum = "\\ftnncnum"
$ftnndbar = "\\ftnndbar"
$ftnndbnum = "\\ftnndbnum"
$ftnndbnumd = "\\ftnndbnumd"
$ftnndbnumk = "\\ftnndbnumk"
$ftnndbnumt = "\\ftnndbnumt"
$ftnnganada = "\\ftnnganada"
$ftnngbnum = "\\ftnngbnum"
$ftnngbnumd = "\\ftnngbnumd"
$ftnngbnumk = "\\ftnngbnumk"
$ftnngbnuml = "\\ftnngbnuml"
$ftnnrlc = "\\ftnnrlc"
$ftnnruc = "\\ftnnruc"
$ftnnzodiac = "\\ftnnzodiac"
$ftnnzodiacd = "\\ftnnzodiacd"
$ftnnzodiacl = "\\ftnnzodiacl"
$ftnrestart = "\\ftnrestart"
$ftnrstcont = "\\ftnrstcont"
$ftnrstpg = "\\ftnrstpg"
$ftnsep = "\\ftnsep"
$ftnsepc = "\\ftnsepc"
$ftnstart = "\\ftnstart"
$ftntj = "\\ftntj"
$grfdocevents = "\\grfdocevents"
$gutter = "\\gutter"
$gutterprl = "\\gutterprl"
$horzdoc = "\\horzdoc"
$htmautsp = "\\htmautsp"
$hwelev2007 = "\\hwelev2007"
$hyphauto = "\\hyphauto"
$hyphcaps = "\\hyphcaps"
$hyphconsec = "\\hyphconsec"
$hyphhotz = "\\hyphhotz"
$ignoremixedcontent = "\\ignoremixedcontent"
$ilfomacatclnup = "\\ilfomacatclnup"
$indrlsweleven = "\\indrlsweleven"
$jcompress = "\\jcompress"
$jexpand = "\\jexpand"
$jsksu = "\\jsksu"
$krnprsnet = "\\krnprsnet"
$ksulang = "\\ksulang"
$landscape = "\\landscape"
$lchars = "\\lchars"
$linestart = "\\linestart"
$linkstyles = "\\linkstyles"
$lnbrkrule = "\\lnbrkrule"
$lnongrid = "\\lnongrid"
$ltrdoc = "\\ltrdoc"
$lytcalctblwd = "\\lytcalctblwd"
$lytexcttp = "\\lytexcttp"
$lytprtmet = "\\lytprtmet"
$lyttblrtgr = "\\lyttblrtgr"
$makebackup = "\\makebackup"
$margb = "\\margb"
$margl = "\\margl"
$margmirror = "\\margmirror"
$margr = "\\margr"
$margt = "\\margt"
$msmcap = "\\msmcap"
$muser = "\\muser"
$newtblstyruls = "\\newtblstyruls"
$nextfile = "\\nextfile"
$noafcnsttbl = "\\noafcnsttbl"
$nobrkwrptbl = "\\nobrkwrptbl"
$nocolbal = "\\nocolbal"
$nocompatoptions = "\\nocompatoptions"
$nocxsptable = "\\nocxsptable"
$noextrasprl = "\\noextrasprl"
$nofeaturethrottle = "\\nofeaturethrottle"
$nogrowautofit = "\\nogrowautofit"
$noindnmbrts = "\\noindnmbrts"
$nojkernpunct = "\\nojkernpunct"
$nolead = "\\nolead"
$nolnhtadjtbl = "\\nolnhtadjtbl"
$nospaceforul = "\\nospaceforul"
$notabind = "\\notabind"
$notbrkcnstfrctbl = "\\notbrkcnstfrctbl"
$notcvasp = "\\notcvasp"
$notvatxbx = "\\notvatxbx"
$nouicompat = "\\nouicompat"
$noultrlspc = "\\noultrlspc"
$noxlattoyen = "\\noxlattoyen"
$ogutter = "\\ogutter"
$oldas = "\\oldas"
$oldlinewrap = "\\oldlinewrap"
$otblrul = "\\otblrul"
$paperh = "\\paperh"
$paperw = "\\paperw"
$pgbrdrb = "\\pgbrdrb"
$pgbrdrfoot = "\\pgbrdrfoot"
$pgbrdrhead = "\\pgbrdrhead"
$pgbrdrl = "\\pgbrdrl"
$pgbrdropt = "\\pgbrdropt"
$pgbrdrr = "\\pgbrdrr"
$pgbrdrsnap = "\\pgbrdrsnap"
$pgbrdrt = "\\pgbrdrt"
$pgnstart = "\\pgnstart"
$prcolbl = "\\prcolbl"
$printdata = "\\printdata"
$private = "\\private"
$protlevel = "\\protlevel"
$psover = "\\psover"
$psz = "\\psz"
$readonlyrecommended = "\\readonlyrecommended"
$readprot = "\\readprot"
$relyonvml = "\\relyonvml"
$remdttm = "\\remdttm"
$rempersonalinfo = "\\rempersonalinfo"
$revbar = "\\revbar"
$revisions = "\\revisions"
$revprop = "\\revprop"
$revprot = "\\revprot"
$rtldoc = "\\rtldoc"
$rtlgutter = "\\rtlgutter"
$saveinvalidxml = "\\saveinvalidxml"
$saveprevpict = "\\saveprevpict"
$showplaceholdtext = "\\showplaceholdtext"
$showxmlerrors = "\\showxmlerrors"
$snaptogridincell = "\\snaptogridincell"
$spltpgpar = "\\spltpgpar"
$splytwnine = "\\splytwnine"
$sprsbsp = "\\sprsbsp"
$sprslnsp = "\\sprslnsp"
$sprsspbf = "\\sprsspbf"
$sprstsm = "\\sprstsm"
$sprstsp = "\\sprstsp"
$stylelock = "\\stylelock"
$stylelockbackcomp = "\\stylelockbackcomp"
$stylelockenforced = "\\stylelockenforced"
$stylelockqfset = "\\stylelockqfset"
$stylelocktheme = "\\stylelocktheme"
$stylesortmethod = "\\stylesortmethod"
$subfontbysize = "\\subfontbysize"
$swpbdr = "\\swpbdr"
$template = "\\template"
$themelang = "\\themelang"
$themelangcs = "\\themelangcs"
$themelangfe = "\\themelangfe"
$toplinepunct = "\\toplinepunct"
$trackformatting = "\\trackformatting"
$trackmoves = "\\trackmoves"
$transmf = "\\transmf"
$truncatefontheight = "\\truncatefontheight"
$truncex = "\\truncex"
$tsd = "\\tsd"
$twoonone = "\\twoonone"
$useltbaln = "\\useltbaln"
$usenormstyforlist = "\\usenormstyforlist"
$usexform = "\\usexform"
$utinl = "\\utinl"
$validatexml = "\\validatexml"
$vertdoc = "\\vertdoc"
$viewbksp = "\\viewbksp"
$viewkind = "\\viewkind"
$viewnobound = "\\viewnobound"
$viewscale = "\\viewscale"
$viewzk = "\\viewzk"
$wgrffmtfilter = "\\wgrffmtfilter"
$widowctrl = "\\widowctrl"
$windowcaption = "\\windowcaption"
$wpjst = "\\wpjst"
$wpsp = "\\wpsp"
$wraptrsp = "\\wraptrsp"
$writereservation = "\\writereservation"
$writereservhash = "\\writereservhash"
$wrppunct = "\\wrppunct"
$xform = "\\xform"
condition:
any of them
}
rule rtf_docvar
{
strings:
$docvar = "\\docvar"
condition:
any of them
}
rule rtf_drawing
{
strings:
$hl = "\\hl"
$hlfr = "\\hlfr"
$hlloc = "\\hlloc"
$hlsrc = "\\hlsrc"
$hrule = "\\hrule"
$hsv = "\\hsv"
$do = "\\do"
$dobxcolumn = "\\dobxcolumn"
$dobxmargin = "\\dobxmargin"
$dobxpage = "\\dobxpage"
$dobymargin = "\\dobymargin"
$dobypage = "\\dobypage"
$dobypara = "\\dobypara"
$dodhgt = "\\dodhgt"
$dolock = "\\dolock"
$dpaendhol = "\\dpaendhol"
$dpaendl = "\\dpaendl"
$dpaendsol = "\\dpaendsol"
$dpaendw = "\\dpaendw"
$dparc = "\\dparc"
$dparcflipx = "\\dparcflipx"
$dparcflipy = "\\dparcflipy"
$dpastarthol = "\\dpastarthol"
$dpastartl = "\\dpastartl"
$dpastartsol = "\\dpastartsol"
$dpastartw = "\\dpastartw"
$dpcallout = "\\dpcallout"
$dpcoa = "\\dpcoa"
$dpcoaccent = "\\dpcoaccent"
$dpcobestfit = "\\dpcobestfit"
$dpcoborder = "\\dpcoborder"
$dpcodabs = "\\dpcodabs"
$dpcodbottom = "\\dpcodbottom"
$dpcodcenter = "\\dpcodcenter"
$dpcodescent = "\\dpcodescent"
$dpcodtop = "\\dpcodtop"
$dpcolength = "\\dpcolength"
$dpcominusx = "\\dpcominusx"
$dpcominusy = "\\dpcominusy"
$dpcooffset = "\\dpcooffset"
$dpcosmarta = "\\dpcosmarta"
$dpcotdouble = "\\dpcotdouble"
$dpcotright = "\\dpcotright"
$dpcotsingle = "\\dpcotsingle"
$dpcottriple = "\\dpcottriple"
$dpcount = "\\dpcount"
$dpellipse = "\\dpellipse"
$dpendgroup = "\\dpendgroup"
$dpfillbgcb = "\\dpfillbgcb"
$dpfillbgcg = "\\dpfillbgcg"
$dpfillbgcr = "\\dpfillbgcr"
$dpfillbggray = "\\dpfillbggray"
$dpfillbgpal = "\\dpfillbgpal"
$dpfillfgcb = "\\dpfillfgcb"
$dpfillfgcg = "\\dpfillfgcg"
$dpfillfgcr = "\\dpfillfgcr"
$dpfillfggray = "\\dpfillfggray"
$dpfillfgpal = "\\dpfillfgpal"
$dpfillpat = "\\dpfillpat"
$dpgroup = "\\dpgroup"
$dpline = "\\dpline"
$dplinecob = "\\dplinecob"
$dplinecog = "\\dplinecog"
$dplinecor = "\\dplinecor"
$dplinedado = "\\dplinedado"
$dplinedadodo = "\\dplinedadodo"
$dplinedash = "\\dplinedash"
$dplinedot = "\\dplinedot"
$dplinegray = "\\dplinegray"
$dplinehollow = "\\dplinehollow"
$dplinepal = "\\dplinepal"
$dplinesolid = "\\dplinesolid"
$dplinew = "\\dplinew"
$dppolycount = "\\dppolycount"
$dppolygon = "\\dppolygon"
$dppolyline = "\\dppolyline"
$dpptx = "\\dpptx"
$dppty = "\\dppty"
$dprect = "\\dprect"
$dproundr = "\\dproundr"
$dpshadow = "\\dpshadow"
$dpshadx = "\\dpshadx"
$dpshady = "\\dpshady"
$dptxbtlr = "\\dptxbtlr"
$dptxbx = "\\dptxbx"
$dptxbxmar = "\\dptxbxmar"
$dptxbxtext = "\\dptxbxtext"
$dptxlrtb = "\\dptxlrtb"
$dptxlrtbv = "\\dptxlrtbv"
$dptxtbrl = "\\dptxtbrl"
$dptxtbrlv = "\\dptxtbrlv"
$dpx = "\\dpx"
$dpxsize = "\\dpxsize"
$dpy = "\\dpy"
$dpysize = "\\dpysize"
condition:
any of them
}
rule rtf_asia
{
strings:
$cgrid = "\\cgrid"
$g = "\\g"
$gcw = "\\gcw"
$gridtbl = "\\gridtbl"
$nosectexpand = "\\nosectexpand"
$ulhair = "\\ulhair"
$horzvert = "\\horzvert"
$twoinone = "\\twoinone"
condition:
any of them
}
rule rtf_fields
{
strings:
$datafield = "\\datafield"
$date = "\\date"
$field = "\\field"
$fldalt = "\\fldalt"
$flddirty = "\\flddirty"
$fldedit = "\\fldedit"
$fldinst = "\\fldinst"
$fldlock = "\\fldlock"
$fldpriv = "\\fldpriv"
$fldrslt = "\\fldrslt"
$fldtype = "\\fldtype"
$time = "\\time"
$wpeqn = "\\wpeqn"
condition:
any of them
}
rule rtf_files
{
strings:
$fid = "\\fid"
$file = "\\file"
$filetbl = "\\filetbl"
$fnetwork = "\\fnetwork"
$fnonfilesys = "\\fnonfilesys"
$fosnum = "\\fosnum"
$frelative = "\\frelative"
$fvaliddos = "\\fvaliddos"
$fvalidhpfs = "\\fvalidhpfs"
$fvalidmac = "\\fvalidmac"
$fvalidntfs = "\\fvalidntfs"
condition:
any of them
}
rule rtf_font
{
strings:
$acccircle = "\\acccircle"
$acccomma = "\\acccomma"
$accdot = "\\accdot"
$accnone = "\\accnone"
$accunderdot = "\\accunderdot"
$animtext = "\\animtext"
$b = "\\b"
$caps = "\\caps"
$cb = "\\cb"
$cchs = "\\cchs"
$cf = "\\cf"
$charscalex = "\\charscalex"
$cs = "\\cs"
$dn = "\\dn"
$embo = "\\embo"
$expnd = "\\expnd"
$expndtw = "\\expndtw"
$f = "\\f"
$fittext = "\\fittext"
$fs = "\\fs"
$i = "\\i"
$kerning = "\\kerning"
$lang = "\\lang"
$langfe = "\\langfe"
$langfenp = "\\langfenp"
$langnp = "\\langnp"
$ltrch = "\\ltrch"
$noproof = "\\noproof"
$nosupersub = "\\nosupersub"
$outl = "\\outl"
$plain = "\\plain"
$rtlch = "\\rtlch"
$scaps = "\\scaps"
$shad = "\\shad"
$strike = "\\strike"
$sub = "\\sub"
$super = "\\super"
$ul = "\\ul"
$ulc = "\\ulc"
$uld = "\\uld"
$uldash = "\\uldash"
$uldashd = "\\uldashd"
$uldashdd = "\\uldashdd"
$uldb = "\\uldb"
$ulhwave = "\\ulhwave"
$ulldash = "\\ulldash"
$ulnone = "\\ulnone"
$ulth = "\\ulth"
$ulthd = "\\ulthd"
$ulthdash = "\\ulthdash"
$ulthdashd = "\\ulthdashd"
$ulthdashdd = "\\ulthdashdd"
$ulthldash = "\\ulthldash"
$ululdbwave = "\\ululdbwave"
$ulw = "\\ulw"
$ulwave = "\\ulwave"
$up = "\\up"
$v = "\\v"
$webhidden = "\\webhidden"
$fjgothic = "\\fjgothic"
$fjminchou = "\\fjminchou"
$jis = "\\jis"
$falt = "\\falt"
$fbias = "\\fbias"
$fbidi = "\\fbidi"
$fcharset = "\\fcharset"
$fdecor = "\\fdecor"
$fetch = "\\fetch"
$fmodern = "\\fmodern"
$fname = "\\fname"
$fnil = "\\fnil"
$fontemb = "\\fontemb"
$fontfile = "\\fontfile"
$fonttbl = "\\fonttbl"
$fprq = "\\fprq"
$froman = "\\froman"
$fscript = "\\fscript"
$fswiss = "\\fswiss"
$ftech = "\\ftech"
$ftnil = "\\ftnil"
$fttruetype = "\\fttruetype"
$panose = "\\panose"
condition:
any of them
}
rule rtf_footnote
{
strings:
$footnote = "\\footnote"
condition:
any of them
}
rule rtf_form
{
strings:
$ffdefres = "\\ffdefres"
$ffdeftext = "\\ffdeftext"
$ffentrymcr = "\\ffentrymcr"
$ffexitmcr = "\\ffexitmcr"
$ffformat = "\\ffformat"
$ffhaslistbox = "\\ffhaslistbox"
$ffhelptext = "\\ffhelptext"
$ffhps = "\\ffhps"
$ffl = "\\ffl"
$ffmaxlen = "\\ffmaxlen"
$ffname = "\\ffname"
$ffownhelp = "\\ffownhelp"
$ffownstat = "\\ffownstat"
$ffprot = "\\ffprot"
$ffrecalc = "\\ffrecalc"
$ffres = "\\ffres"
$ffsize = "\\ffsize"
$ffstattext = "\\ffstattext"
$fftype = "\\fftype"
$fftypetxt = "\\fftypetxt"
$formfield = "\\formfield"
condition:
any of them
}
rule rtf_generator
{
strings:
$generator = "\\generator"
condition:
any of them
}
rule rtf_headers
{
strings:
$footer = "\\footer"
$footerf = "\\footerf"
$footerl = "\\footerl"
$footerr = "\\footerr"
$header = "\\header"
$headerf = "\\headerf"
$headerl = "\\headerl"
$headerr = "\\headerr"
condition:
any of them
}
rule rtf_highlight
{
strings:
$highlight = "\\highlight"
condition:
any of them
}
rule rtf_hyphen
{
strings:
$chhres = "\\chhres"
$hres = "\\hres"
condition:
any of them
}
rule rtf_index
{
strings:
$bxe = "\\bxe"
$ixe = "\\ixe"
$pxe = "\\pxe"
$rxe = "\\rxe"
$txe = "\\txe"
$xe = "\\xe"
$xef = "\\xef"
$yxe = "\\yxe"
condition:
any of them
}
rule rtf_info
{
strings:
$author = "\\author"
$buptim = "\\buptim"
$category = "\\category"
$comment = "\\comment"
$company = "\\company"
$creatim = "\\creatim"
$doccomm = "\\doccomm"
$dy = "\\dy"
$edmins = "\\edmins"
$hlinkbase = "\\hlinkbase"
$hr = "\\hr"
$id = "\\id"
$info = "\\info"
$keywords = "\\keywords"
$linkval = "\\linkval"
$manager = "\\manager"
$min = "\\min"
$mo = "\\mo"
$nofchars = "\\nofchars"
$nofcharsws = "\\nofcharsws"
$nofpages = "\\nofpages"
$nofwords = "\\nofwords"
$operator = "\\operator"
$printim = "\\printim"
$propname = "\\propname"
$proptype = "\\proptype"
$revtim = "\\revtim"
$sec = "\\sec"
$staticval = "\\staticval"
$subject = "\\subject"
$title = "\\title"
$userprops = "\\userprops"
$vern = "\\vern"
$version = "\\version"
$yr = "\\yr"
condition:
any of them
}
rule rtf_list
{
strings:
$lvltentative = "\\lvltentative"
$jclisttab = "\\jclisttab"
$levelfollow = "\\levelfollow"
$levelindent = "\\levelindent"
$leveljc = "\\leveljc"
$leveljcn = "\\leveljcn"
$levellegal = "\\levellegal"
$levelnfc = "\\levelnfc"
$levelnfcn = "\\levelnfcn"
$levelnorestart = "\\levelnorestart"
$levelnumbers = "\\levelnumbers"
$levelold = "\\levelold"
$levelpicture = "\\levelpicture"
$levelpicturenosize = "\\levelpicturenosize"
$levelprev = "\\levelprev"
$levelprevspace = "\\levelprevspace"
$levelspace = "\\levelspace"
$levelstartat = "\\levelstartat"
$leveltemplateid = "\\leveltemplateid"
$leveltext = "\\leveltext"
$lfolevel = "\\lfolevel"
$list = "\\list"
$listhybrid = "\\listhybrid"
$listid = "\\listid"
$listlevel = "\\listlevel"
$listname = "\\listname"
$listoverride = "\\listoverride"
$listoverridecount = "\\listoverridecount"
$listoverrideformat = "\\listoverrideformat"
$listoverridestartat = "\\listoverridestartat"
$listoverridetable = "\\listoverridetable"
$listpicture = "\\listpicture"
$listrestarthdn = "\\listrestarthdn"
$listsimple = "\\listsimple"
$liststyleid = "\\liststyleid"
$liststylename = "\\liststylename"
$listtable = "\\listtable"
$listtemplateid = "\\listtemplateid"
$ls = "\\ls"
condition:
any of them
}
rule rtf_mac
{
strings:
$bkmkpub = "\\bkmkpub"
$pubauto = "\\pubauto"
condition:
any of them
}
rule rtf_mail
{
strings:
$mailmerge = "\\mailmerge"
$mmaddfieldname = "\\mmaddfieldname"
$mmattach = "\\mmattach"
$mmblanklines = "\\mmblanklines"
$mmconnectstr = "\\mmconnectstr"
$mmconnectstrdata = "\\mmconnectstrdata"
$mmdatasource = "\\mmdatasource"
$mmdatatypeaccess = "\\mmdatatypeaccess"
$mmdatatypeexcel = "\\mmdatatypeexcel"
$mmdatatypefile = "\\mmdatatypefile"
$mmdatatypeodbc = "\\mmdatatypeodbc"
$mmdatatypeodso = "\\mmdatatypeodso"
$mmdatatypeqt = "\\mmdatatypeqt"
$mmdefaultsql = "\\mmdefaultsql"
$mmdestemail = "\\mmdestemail"
$mmdestfax = "\\mmdestfax"
$mmdestnewdoc = "\\mmdestnewdoc"
$mmdestprinter = "\\mmdestprinter"
$mmerrors = "\\mmerrors"
$mmfttypeaddress = "\\mmfttypeaddress"
$mmfttypebarcode = "\\mmfttypebarcode"
$mmfttypedbcolumn = "\\mmfttypedbcolumn"
$mmfttypemapped = "\\mmfttypemapped"
$mmfttypenull = "\\mmfttypenull"
$mmfttypesalutation = "\\mmfttypesalutation"
$mmheadersource = "\\mmheadersource"
$mmjdsotype = "\\mmjdsotype"
$mmlinktoquery = "\\mmlinktoquery"
$mmmailsubject = "\\mmmailsubject"
$mmmaintypecatalog = "\\mmmaintypecatalog"
$mmmaintypeemail = "\\mmmaintypeemail"
$mmmaintypeenvelopes = "\\mmmaintypeenvelopes"
$mmmaintypefax = "\\mmmaintypefax"
$mmmaintypelabels = "\\mmmaintypelabels"
$mmmaintypeletters = "\\mmmaintypeletters"
$mmodso = "\\mmodso"
$mmodsoactive = "\\mmodsoactive"
$mmodsocoldelim = "\\mmodsocoldelim"
$mmodsocolumn = "\\mmodsocolumn"
$mmodsodynaddr = "\\mmodsodynaddr"
$mmodsofhdr = "\\mmodsofhdr"
$mmodsofilter = "\\mmodsofilter"
$mmodsofldmpdata = "\\mmodsofldmpdata"
$mmodsofmcolumn = "\\mmodsofmcolumn"
$mmodsohash = "\\mmodsohash"
$mmodsolid = "\\mmodsolid"
$mmodsomappedname = "\\mmodsomappedname"
$mmodsoname = "\\mmodsoname"
$mmodsorecipdata = "\\mmodsorecipdata"
$mmodsosort = "\\mmodsosort"
$mmodsosrc = "\\mmodsosrc"
$mmodsotable = "\\mmodsotable"
$mmodsoudl = "\\mmodsoudl"
$mmodsoudldata = "\\mmodsoudldata"
$mmodsouniquetag = "\\mmodsouniquetag"
$mmquery = "\\mmquery"
$mmreccur = "\\mmreccur"
$mmshowdata = "\\mmshowdata"
condition:
any of them
}
rule rtf_math
{
strings:
$macc = "\\macc"
$maccPr = "\\maccPr"
$maln = "\\maln"
$malnScr = "\\malnScr"
$margPr = "\\margPr"
$margSz = "\\margSz"
$mbar = "\\mbar"
$mbarPr = "\\mbarPr"
$mbaseJc = "\\mbaseJc"
$mbegChr = "\\mbegChr"
$mborderBox = "\\mborderBox"
$mborderBoxPr = "\\mborderBoxPr"
$mbox = "\\mbox"
$mboxPr = "\\mboxPr"
$mbrk = "\\mbrk"
$mbrkBin = "\\mbrkBin"
$mbrkBinSub = "\\mbrkBinSub"
$mcGp = "\\mcGp"
$mcGpRule = "\\mcGpRule"
$mchr = "\\mchr"
$mcount = "\\mcount"
$mcSp = "\\mcSp"
$mctrlPr = "\\mctrlPr"
$md = "\\md"
$mdefJc = "\\mdefJc"
$mdeg = "\\mdeg"
$mdegHide = "\\mdegHide"
$mden = "\\mden"
$mdiff = "\\mdiff"
$mdiffSty = "\\mdiffSty"
$mdispdef = "\\mdispdef"
$mdPr = "\\mdPr"
$me = "\\me"
$mendChr = "\\mendChr"
$meqArr = "\\meqArr"
$meqArrPr = "\\meqArrPr"
$mf = "\\mf"
$mfName = "\\mfName"
$mfPr = "\\mfPr"
$mfunc = "\\mfunc"
$mfuncPr = "\\mfuncPr"
$mgroupChr = "\\mgroupChr"
$mgroupChrPr = "\\mgroupChrPr"
$mgrow = "\\mgrow"
$mhideBot = "\\mhideBot"
$mhideLeft = "\\mhideLeft"
$mhideRight = "\\mhideRight"
$mhideTop = "\\mhideTop"
$minterSp = "\\minterSp"
$mintLim = "\\mintLim"
$mintraSp = "\\mintraSp"
$mjc = "\\mjc"
$mlim = "\\mlim"
$mlimloc = "\\mlimloc"
$mlimlow = "\\mlimlow"
$mlimlowPr = "\\mlimlowPr"
$mlimupp = "\\mlimupp"
$mlimuppPr = "\\mlimuppPr"
$mlit = "\\mlit"
$mlMargin = "\\mlMargin"
$mm = "\\mm"
$mmath = "\\mmath"
$mmathFont = "\\mmathFont"
$mmathPict = "\\mmathPict"
$mmathPr = "\\mmathPr"
$mmaxdist = "\\mmaxdist"
$mmc = "\\mmc"
$mmcJc = "\\mmcJc"
$mmcPr = "\\mmcPr"
$mmcs = "\\mmcs"
$mmPr = "\\mmPr"
$mmr = "\\mmr"
$mnary = "\\mnary"
$mnaryLim = "\\mnaryLim"
$mnaryPr = "\\mnaryPr"
$mnoBreak = "\\mnoBreak"
$mnor = "\\mnor"
$mnum = "\\mnum"
$mobjDist = "\\mobjDist"
$moMath = "\\moMath"
$moMathPara = "\\moMathPara"
$moMathParaPr = "\\moMathParaPr"
$mopEmu = "\\mopEmu"
$mphant = "\\mphant"
$mphantPr = "\\mphantPr"
$mplcHide = "\\mplcHide"
$mpos = "\\mpos"
$mpostSp = "\\mpostSp"
$mpreSp = "\\mpreSp"
$mr = "\\mr"
$mrad = "\\mrad"
$mradPr = "\\mradPr"
$mrMargin = "\\mrMargin"
$mrPr = "\\mrPr"
$mrSp = "\\mrSp"
$mrSpRule = "\\mrSpRule"
$mscr = "\\mscr"
$msepChr = "\\msepChr"
$mshow = "\\mshow"
$mshp = "\\mshp"
$msmallFrac = "\\msmallFrac"
$msPre = "\\msPre"
$msPrePr = "\\msPrePr"
$msSub = "\\msSub"
$msSubPr = "\\msSubPr"
$msSubSup = "\\msSubSup"
$msSubSupPr = "\\msSubSupPr"
$msSup = "\\msSup"
$msSupPr = "\\msSupPr"
$mstrikeBLTR = "\\mstrikeBLTR"
$mstrikeH = "\\mstrikeH"
$mstrikeTLBR = "\\mstrikeTLBR"
$mstrikeV = "\\mstrikeV"
$msty = "\\msty"
$msub = "\\msub"
$msubHide = "\\msubHide"
$msup = "\\msup"
$msupHide = "\\msupHide"
$mtransp = "\\mtransp"
$mtype = "\\mtype"
$mvertJc = "\\mvertJc"
$mwrapIndent = "\\mwrapIndent"
$mwrapRight = "\\mwrapRight"
$mzeroAsc = "\\mzeroAsc"
$mzeroDesc = "\\mzeroDesc"
$mzeroWid = "\\mzeroWid"
condition:
any of them
}
rule rtf_outlook
{
strings:
$ebcstart = "\\ebcstart"
$ebcend = "\\ebcend"
condition:
any of them
}
rule rtf_objects
{
strings:
$linkself = "\\linkself"
$objalias = "\\objalias"
$objalign = "\\objalign"
$objattph = "\\objattph"
$objautlink = "\\objautlink"
$objclass = "\\objclass"
$objcropb = "\\objcropb"
$objcropl = "\\objcropl"
$objcropr = "\\objcropr"
$objcropt = "\\objcropt"
$objdata = "\\objdata"
$object = "\\object"
$objemb = "\\objemb"
$objh = "\\objh"
$objhtml = "\\objhtml"
$objicemb = "\\objicemb"
$objlink = "\\objlink"
$objlock = "\\objlock"
$objname = "\\objname"
$objocx = "\\objocx"
$objpub = "\\objpub"
$objscalex = "\\objscalex"
$objscaley = "\\objscaley"
$objsect = "\\objsect"
$objsetsize = "\\objsetsize"
$objsub = "\\objsub"
$objtime = "\\objtime"
$objtransy = "\\objtransy"
$objupdate = "\\objupdate"
$objw = "\\objw"
$oleclsid = "\\oleclsid"
$result = "\\result"
$rsltbmp = "\\rsltbmp"
$rslthtml = "\\rslthtml"
$rsltmerge = "\\rsltmerge"
$rsltpict = "\\rsltpict"
$rsltrtf = "\\rsltrtf"
$rslttxt = "\\rslttxt"
condition:
any of them
}
rule rtf_paragraph
{
strings:
$box = "\\box"
$brdrb = "\\brdrb"
$brdrbar = "\\brdrbar"
$brdrbtw = "\\brdrbtw"
$brdrcf = "\\brdrcf"
$brdrdash = "\\brdrdash"
$brdrdashd = "\\brdrdashd"
$brdrdashdd = "\\brdrdashdd"
$brdrdashdot = "\\brdrdashdot"
$brdrdashdotdot = "\\brdrdashdotdot"
$brdrdashdotstr = "\\brdrdashdotstr"
$brdrdashsm = "\\brdrdashsm"
$brdrdb = "\\brdrdb"
$brdrdot = "\\brdrdot"
$brdremboss = "\\brdremboss"
$brdrengrave = "\\brdrengrave"
$brdrframe = "\\brdrframe"
$brdrhair = "\\brdrhair"
$brdrinset = "\\brdrinset"
$brdrl = "\\brdrl"
$brdrnil = "\\brdrnil"
$brdrnone = "\\brdrnone"
$brdroutset = "\\brdroutset"
$brdrr = "\\brdrr"
$brdrs = "\\brdrs"
$brdrsh = "\\brdrsh"
$brdrt = "\\brdrt"
$brdrtbl = "\\brdrtbl"
$brdrth = "\\brdrth"
$brdrthtnlg = "\\brdrthtnlg"
$brdrthtnmg = "\\brdrthtnmg"
$brdrthtnsg = "\\brdrthtnsg"
$brdrtnthlg = "\\brdrtnthlg"
$brdrtnthmg = "\\brdrtnthmg"
$brdrtnthsg = "\\brdrtnthsg"
$brdrtnthtnlg = "\\brdrtnthtnlg"
$brdrtnthtnmg = "\\brdrtnthtnmg"
$brdrtnthtnsg = "\\brdrtnthtnsg"
$brdrtriple = "\\brdrtriple"
$brdrw = "\\brdrw"
$brdrwavy = "\\brdrwavy"
$brdrwavydb = "\\brdrwavydb"
$brsp = "\\brsp"
$aspalpha = "\\aspalpha"
$aspnum = "\\aspnum"
$collapsed = "\\collapsed"
$contextualspace = "\\contextualspace"
$cufi = "\\cufi"
$culi = "\\culi"
$curi = "\\curi"
$faauto = "\\faauto"
$facenter = "\\facenter"
$fafixed = "\\fafixed"
$fahang = "\\fahang"
$faroman = "\\faroman"
$favar = "\\favar"
$fi = "\\fi"
$hyphpar = "\\hyphpar"
$indmirror = "\\indmirror"
$intbl = "\\intbl"
$itap = "\\itap"
$keep = "\\keep"
$keepn = "\\keepn"
$level = "\\level"
$li = "\\li"
$lin = "\\lin"
$lisa = "\\lisa"
$lisb = "\\lisb"
$ltrpar = "\\ltrpar"
$nocwrap = "\\nocwrap"
$noline = "\\noline"
$nooverflow = "\\nooverflow"
$nosnaplinegrid = "\\nosnaplinegrid"
$nowidctlpar = "\\nowidctlpar"
$nowwrap = "\\nowwrap"
$outlinelevel = "\\outlinelevel"
$pagebb = "\\pagebb"
$pard = "\\pard"
$prauth = "\\prauth"
$prdate = "\\prdate"
$qc = "\\qc"
$qd = "\\qd"
$qj = "\\qj"
$qk = "\\qk"
$ql = "\\ql"
$qr = "\\qr"
$qt = "\\qt"
$ri = "\\ri"
$rin = "\\rin"
$rtlpar = "\\rtlpar"
$s = "\\s"
$sa = "\\sa"
$saauto = "\\saauto"
$sb = "\\sb"
$sbauto = "\\sbauto"
$sbys = "\\sbys"
$sl = "\\sl"
$slmult = "\\slmult"
$spv = "\\spv"
$subdocument = "\\subdocument"
$tscbandhorzeven = "\\tscbandhorzeven"
$tscbandhorzodd = "\\tscbandhorzodd"
$tscbandverteven = "\\tscbandverteven"
$tscbandvertodd = "\\tscbandvertodd"
$tscfirstcol = "\\tscfirstcol"
$tscfirstrow = "\\tscfirstrow"
$tsclastcol = "\\tsclastcol"
$tsclastrow = "\\tsclastrow"
$tscnecell = "\\tscnecell"
$tscnwcell = "\\tscnwcell"
$tscsecell = "\\tscsecell"
$tscswcell = "\\tscswcell"
$txbxtwalways = "\\txbxtwalways"
$txbxtwfirst = "\\txbxtwfirst"
$txbxtwfirstlast = "\\txbxtwfirstlast"
$txbxtwlast = "\\txbxtwlast"
$txbxtwno = "\\txbxtwno"
$widctlpar = "\\widctlpar"
$yts = "\\yts"
$pgp = "\\pgp"
$pgptbl = "\\pgptbl"
$ipgp = "\\ipgp"
$dfrauth = "\\dfrauth"
$dfrdate = "\\dfrdate"
$dfrstart = "\\dfrstart"
$dfrstop = "\\dfrstop"
$dfrxst = "\\dfrxst"
$bgbdiag = "\\bgbdiag"
$bgcross = "\\bgcross"
$bgdcross = "\\bgdcross"
$bgdkbdiag = "\\bgdkbdiag"
$bgdkcross = "\\bgdkcross"
$bgdkdcross = "\\bgdkdcross"
$bgdkfdiag = "\\bgdkfdiag"
$bgdkhoriz = "\\bgdkhoriz"
$bgdkvert = "\\bgdkvert"
$bgfdiag = "\\bgfdiag"
$bghoriz = "\\bghoriz"
$bgvert = "\\bgvert"
$cbpat = "\\cbpat"
$cfpat = "\\cfpat"
$shading = "\\shading"
condition:
any of them
}
rule rtf_pictures
{
strings:
$bin = "\\bin"
$bliptag = "\\bliptag"
$blipuid = "\\blipuid"
$blipupi = "\\blipupi"
$defshp = "\\defshp"
$dibitmap = "\\dibitmap"
$emfblip = "\\emfblip"
$jpegblip = "\\jpegblip"
$macpict = "\\macpict"
$nonshppict = "\\nonshppict"
$picbmp = "\\picbmp"
$picbpp = "\\picbpp"
$piccropb = "\\piccropb"
$piccropl = "\\piccropl"
$piccropr = "\\piccropr"
$piccropt = "\\piccropt"
$pich = "\\pich"
$pichgoal = "\\pichgoal"
$picprop = "\\picprop"
$picscaled = "\\picscaled"
$picscalex = "\\picscalex"
$picscaley = "\\picscaley"
$pict = "\\pict"
$picw = "\\picw"
$picwgoal = "\\picwgoal"
$pmmetafile = "\\pmmetafile"
$pngblip = "\\pngblip"
$shppict = "\\shppict"
$wbitmap = "\\wbitmap"
$wbmbitspixel = "\\wbmbitspixel"
$wbmplanes = "\\wbmplanes"
$wbmwidthbyte = "\\wbmwidthbyte"
$wmetafile = "\\wmetafile"
condition:
any of them
}
rule rtf_position
{
strings:
$absh = "\\absh"
$abslock = "\\abslock"
$absnoovrlp = "\\absnoovrlp"
$absw = "\\absw"
$dfrmtxtx = "\\dfrmtxtx"
$dfrmtxty = "\\dfrmtxty"
$dropcapli = "\\dropcapli"
$dropcapt = "\\dropcapt"
$dxfrtext = "\\dxfrtext"
$frmtxbtlr = "\\frmtxbtlr"
$frmtxlrtb = "\\frmtxlrtb"
$frmtxlrtbv = "\\frmtxlrtbv"
$frmtxtbrl = "\\frmtxtbrl"
$frmtxtbrlv = "\\frmtxtbrlv"
$nowrap = "\\nowrap"
$overlay = "\\overlay"
$phcol = "\\phcol"
$phmrg = "\\phmrg"
$phpg = "\\phpg"
$posnegx = "\\posnegx"
$posnegy = "\\posnegy"
$posx = "\\posx"
$posxc = "\\posxc"
$posxi = "\\posxi"
$posxl = "\\posxl"
$posxo = "\\posxo"
$posxr = "\\posxr"
$posy = "\\posy"
$posyb = "\\posyb"
$posyc = "\\posyc"
$posyil = "\\posyil"
$posyin = "\\posyin"
$posyout = "\\posyout"
$posyt = "\\posyt"
$pvmrg = "\\pvmrg"
$pvpara = "\\pvpara"
$pvpg = "\\pvpg"
$wraparound = "\\wraparound"
$wrapdefault = "\\wrapdefault"
$wrapthrough = "\\wrapthrough"
$wraptight = "\\wraptight"
condition:
any of them
}
rule rtf_protection
{
strings:
$protend = "\\protend"
$protstart = "\\protstart"
$protusertbl = "\\protusertbl"
condition:
any of them
}
rule rtf_quick_styles
{
strings:
$noqfpromote = "\\noqfpromote"
condition:
any of them
}
rule rtf_password
{
strings:
$password = <PASSWORD>"
$passwordhash = <PASSWORD>"
condition:
any of them
}
rule rtf_revision
{
strings:
$pnrauth = "\\pnrauth"
$pnrdate = "\\pnrdate"
$pnrnfc = "\\pnrnfc"
$pnrnot = "\\pnrnot"
$pnrpnbr = "\\pnrpnbr"
$pnrrgb = "\\pnrrgb"
$pnrstart = "\\pnrstart"
$pnrstop = "\\pnrstop"
$pnrxst = "\\pnrxst"
condition:
any of them
}
rule rtf_version
{
strings:
$rtf = "\\rtf"
condition:
any of them
}
rule rtf_section
{
strings:
$adjustright = "\\adjustright"
$binfsxn = "\\binfsxn"
$binsxn = "\\binsxn"
$colno = "\\colno"
$cols = "\\cols"
$colsr = "\\colsr"
$colsx = "\\colsx"
$colw = "\\colw"
$ds = "\\ds"
$endnhere = "\\endnhere"
$footery = "\\footery"
$guttersxn = "\\guttersxn"
$headery = "\\headery"
$horzsect = "\\horzsect"
$linebetcol = "\\linebetcol"
$linecont = "\\linecont"
$linemod = "\\linemod"
$lineppage = "\\lineppage"
$linerestart = "\\linerestart"
$linestarts = "\\linestarts"
$linex = "\\linex"
$lndscpsxn = "\\lndscpsxn"
$ltrsect = "\\ltrsect"
$margbsxn = "\\margbsxn"
$marglsxn = "\\marglsxn"
$margmirsxn = "\\margmirsxn"
$margrsxn = "\\margrsxn"
$margtsxn = "\\margtsxn"
$pghsxn = "\\pghsxn"
$pgnbidia = "\\pgnbidia"
$pgnbidib = "\\pgnbidib"
$pgnchosung = "\\pgnchosung"
$pgncnum = "\\pgncnum"
$pgncont = "\\pgncont"
$pgndbnum = "\\pgndbnum"
$pgndbnumd = "\\pgndbnumd"
$pgndbnumk = "\\pgndbnumk"
$pgndbnumt = "\\pgndbnumt"
$pgndec = "\\pgndec"
$pgndecd = "\\pgndecd"
$pgnganada = "\\pgnganada"
$pgngbnum = "\\pgngbnum"
$pgngbnumd = "\\pgngbnumd"
$pgngbnumk = "\\pgngbnumk"
$pgngbnuml = "\\pgngbnuml"
$pgnhindia = "\\pgnhindia"
$pgnhindib = "\\pgnhindib"
$pgnhindic = "\\pgnhindic"
$pgnhindid = "\\pgnhindid"
$pgnhn = "\\pgnhn"
$pgnhnsc = "\\pgnhnsc"
$pgnhnsh = "\\pgnhnsh"
$pgnhnsm = "\\pgnhnsm"
$pgnhnsn = "\\pgnhnsn"
$pgnhnsp = "\\pgnhnsp"
$pgnid = "\\pgnid"
$pgnlcltr = "\\pgnlcltr"
$pgnlcrm = "\\pgnlcrm"
$pgnrestart = "\\pgnrestart"
$pgnstarts = "\\pgnstarts"
$pgnthaia = "\\pgnthaia"
$pgnthaib = "\\pgnthaib"
$pgnthaic = "\\pgnthaic"
$pgnucltr = "\\pgnucltr"
$pgnucrm = "\\pgnucrm"
$pgnvieta = "\\pgnvieta"
$pgnx = "\\pgnx"
$pgny = "\\pgny"
$pgnzodiac = "\\pgnzodiac"
$pgnzodiacd = "\\pgnzodiacd"
$pgnzodiacl = "\\pgnzodiacl"
$pgwsxn = "\\pgwsxn"
$pnseclvl = "\\pnseclvl"
$rtlsect = "\\rtlsect"
$saftnnalc = "\\saftnnalc"
$saftnnar = "\\saftnnar"
$saftnnauc = "\\saftnnauc"
$saftnnchi = "\\saftnnchi"
$saftnnchosung = "\\saftnnchosung"
$saftnncnum = "\\saftnncnum"
$saftnndbar = "\\saftnndbar"
$saftnndbnum = "\\saftnndbnum"
$saftnndbnumd = "\\saftnndbnumd"
$saftnndbnumk = "\\saftnndbnumk"
$saftnndbnumt = "\\saftnndbnumt"
$saftnnganada = "\\saftnnganada"
$saftnngbnum = "\\saftnngbnum"
$saftnngbnumd = "\\saftnngbnumd"
$saftnngbnumk = "\\saftnngbnumk"
$saftnngbnuml = "\\saftnngbnuml"
$saftnnrlc = "\\saftnnrlc"
$saftnnruc = "\\saftnnruc"
$saftnnzodiac = "\\saftnnzodiac"
$saftnnzodiacd = "\\saftnnzodiacd"
$saftnnzodiacl = "\\saftnnzodiacl"
$saftnrestart = "\\saftnrestart"
$saftnrstcont = "\\saftnrstcont"
$saftnstart = "\\saftnstart"
$sbkcol = "\\sbkcol"
$sbkeven = "\\sbkeven"
$sbknone = "\\sbknone"
$sbkodd = "\\sbkodd"
$sbkpage = "\\sbkpage"
$sectd = "\\sectd"
$sectdefaultcl = "\\sectdefaultcl"
$sectexpand = "\\sectexpand"
$sectlinegrid = "\\sectlinegrid"
$sectspecifycl = "\\sectspecifycl"
$sectspecifygen = "\\sectspecifygen"
$sectspecifyl = "\\sectspecifyl"
$sectunlocked = "\\sectunlocked"
$sftnbj = "\\sftnbj"
$sftnnalc = "\\sftnnalc"
$sftnnar = "\\sftnnar"
$sftnnauc = "\\sftnnauc"
$sftnnchi = "\\sftnnchi"
$sftnnchosung = "\\sftnnchosung"
$sftnncnum = "\\sftnncnum"
$sftnndbar = "\\sftnndbar"
$sftnndbnum = "\\sftnndbnum"
$sftnndbnumd = "\\sftnndbnumd"
$sftnndbnumk = "\\sftnndbnumk"
$sftnndbnumt = "\\sftnndbnumt"
$sftnnganada = "\\sftnnganada"
$sftnngbnum = "\\sftnngbnum"
$sftnngbnumd = "\\sftnngbnumd"
$sftnngbnumk = "\\sftnngbnumk"
$sftnngbnuml = "\\sftnngbnuml"
$sftnnrlc = "\\sftnnrlc"
$sftnnruc = "\\sftnnruc"
$sftnnzodiac = "\\sftnnzodiac"
$sftnnzodiacd = "\\sftnnzodiacd"
$sftnnzodiacl = "\\sftnnzodiacl"
$sftnrestart = "\\sftnrestart"
$sftnrstcont = "\\sftnrstcont"
$sftnrstpg = "\\sftnrstpg"
$sftnstart = "\\sftnstart"
$sftntj = "\\sftntj"
$srauth = "\\srauth"
$srdate = "\\srdate"
$titlepg = "\\titlepg"
$vertal = "\\vertal"
$vertalb = "\\vertalb"
$vertalc = "\\vertalc"
$vertalj = "\\vertalj"
$vertalt = "\\vertalt"
$vertsect = "\\vertsect"
$stextflow = "\\stextflow"
condition:
any of them
}
rule rtf_tag
{
strings:
$factoidname = "\\factoidname"
condition:
any of them
}
rule rtf_special_hex
{
strings:
$hex = "\\'"
condition:
any of them
}
rule rtf_special_ignore
{
strings:
$ignore = "\\*"
condition:
any of them
}
rule rtf_special
{
strings:
$hyphen = "\\-"
$subentry = "\\:"
$nonbreakhyphen = "\\_"
$formula = "\\|"
$nonbreakspace = "\\~"
/*
${ = "\\{"
$} = "\\}"
*/
$bullet = "\\bullet"
$chatn = "\\chatn"
$chdate = "\\chdate"
$chdpa = "\\chdpa"
$chdpl = "\\chdpl"
$chftn = "\\chftn"
$chftnsep = "\\chftnsep"
$chftnsepc = "\\chftnsepc"
$chpgn = "\\chpgn"
$chtime = "\\chtime"
$column = "\\column"
$emdash = "\\emdash"
$emspace = "\\emspace"
$endash = "\\endash"
$enspace = "\\enspace"
$lbr = "\\lbr"
$ldblquote = "\\ldblquote"
$line = "\\line"
$lquote = "\\lquote"
$ltrmark = "\\ltrmark"
$page = "\\page"
$par = "\\par"
$qmspace = "\\qmspace"
$rdblquote = "\\rdblquote"
$row = "\\row"
$rquote = "\\rquote"
$rtlmark = "\\rtlmark"
$sect = "\\sect"
$sectnum = "\\sectnum"
$softcol = "\\softcol"
$softlheight = "\\softlheight"
$softline = "\\softline"
$softpage = "\\softpage"
$tab = "\\tab"
$zwbo = "\\zwbo"
$zwj = "\\zwj"
$zwnbo = "\\zwnbo"
$zwnj = "\\zwnj"
condition:
any of them
}
rule rtf_styles
{
strings:
$latentstyles = "\\latentstyles"
$lsdlocked = "\\lsdlocked"
$lsdlockeddef = "\\lsdlockeddef"
$lsdlockedexcept = "\\lsdlockedexcept"
$lsdpriority = "\\lsdpriority"
$lsdprioritydef = "\\lsdprioritydef"
$lsdqformat = "\\lsdqformat"
$lsdqformatdef = "\\lsdqformatdef"
$lsdsemihidden = "\\lsdsemihidden"
$lsdsemihiddendef = "\\lsdsemihiddendef"
$lsdstimax = "\\lsdstimax"
$lsdunhideused = "\\lsdunhideused"
$lsdunhideuseddef = "\\lsdunhideuseddef"
$additive = "\\additive"
$alt = "\\alt"
$ctrl = "\\ctrl"
$fn = "\\fn"
$keycode = "\\keycode"
$sautoupd = "\\sautoupd"
$sbasedon = "\\sbasedon"
$scompose = "\\scompose"
$shidden = "\\shidden"
$shift = "\\shift"
$slink = "\\slink"
$slocked = "\\slocked"
$snext = "\\snext"
$spersonal = "\\spersonal"
$spriority = "\\spriority"
$sqformat = "\\sqformat"
$sreply = "\\sreply"
$ssemihidden = "\\ssemihidden"
$stylesheet = "\\stylesheet"
$styrsid = "\\styrsid"
$sunhideused = "\\sunhideused"
$ts = "\\ts"
$tsrowd = "\\tsrowd"
condition:
any of them
}
rule rtf_tables
{
strings:
$cell = "\\cell"
$cellx = "\\cellx"
$clbgbdiag = "\\clbgbdiag"
$clbgcross = "\\clbgcross"
$clbgdcross = "\\clbgdcross"
$clbgdkbdiag = "\\clbgdkbdiag"
$clbgdkcross = "\\clbgdkcross"
$clbgdkdcross = "\\clbgdkdcross"
$clbgdkfdiag = "\\clbgdkfdiag"
$clbgdkhor = "\\clbgdkhor"
$clbgdkvert = "\\clbgdkvert"
$clbgfdiag = "\\clbgfdiag"
$clbghoriz = "\\clbghoriz"
$clbgvert = "\\clbgvert"
$clbrdrb = "\\clbrdrb"
$clbrdrl = "\\clbrdrl"
$clbrdrr = "\\clbrdrr"
$clbrdrt = "\\clbrdrt"
$clcbpat = "\\clcbpat"
$clcbpatraw = "\\clcbpatraw"
$clcfpat = "\\clcfpat"
$clcfpatraw = "\\clcfpatraw"
$cldel2007 = "\\cldel2007"
$cldelauth = "\\cldelauth"
$cldeldttm = "\\cldeldttm"
$cldgll = "\\cldgll"
$cldglu = "\\cldglu"
$clFitText = "\\clFitText"
$clftsWidth = "\\clftsWidth"
$clhidemark2007 = "\\clhidemark2007"
$clins2007 = "\\clins2007"
$clinsauth = "\\clinsauth"
$clinsdttm = "\\clinsdttm"
$clmgf = "\\clmgf"
$clmrg = "\\clmrg"
$clmrgd = "\\clmrgd"
$clmrgdauth = "\\clmrgdauth"
$clmrgddttm = "\\clmrgddttm"
$clmrgdr = "\\clmrgdr"
$clNoWrap = "\\clNoWrap"
$clpadb = "\\clpadb"
$clpadfb = "\\clpadfb"
$clpadfl = "\\clpadfl"
$clpadfr = "\\clpadfr"
$clpadft = "\\clpadft"
$clpadl = "\\clpadl"
$clpadr = "\\clpadr"
$clpadt = "\\clpadt"
$clspb = "\\clspb"
$clspfb = "\\clspfb"
$clspfl = "\\clspfl"
$clspfr = "\\clspfr"
$clspft = "\\clspft"
$clspl = "\\clspl"
$clspr = "\\clspr"
$clspt = "\\clspt"
$clshdng = "\\clshdng"
$clshdngraw = "\\clshdngraw"
$clshdrawnil = "\\clshdrawnil"
$clsplit = "\\clsplit"
$clsplitr = "\\clsplitr"
$cltxbtlr = "\\cltxbtlr"
$cltxlrtb = "\\cltxlrtb"
$cltxlrtbv = "\\cltxlrtbv"
$cltxtbrl = "\\cltxtbrl"
$cltxtbrlv = "\\cltxtbrlv"
$clvertalb = "\\clvertalb"
$clvertalc = "\\clvertalc"
$clvertalt = "\\clvertalt"
$clvmgf = "\\clvmgf"
$clvmrg = "\\clvmrg"
$clwWidth = "\\clwWidth"
$irowband = "\\irowband"
$irow = "\\irow"
$lastrow = "\\lastrow"
$ltrrow = "\\ltrrow"
$nestcell = "\\nestcell"
$nestrow = "\\nestrow"
$nesttableprops = "\\nesttableprops"
$nonesttables = "\\nonesttables"
$rawclbgdkbdiag = "\\rawclbgdkbdiag"
$rawclbgbdiag = "\\rawclbgbdiag"
$rawclbgcross = "\\rawclbgcross"
$rawclbgdcross = "\\rawclbgdcross"
$rawclbgdkcross = "\\rawclbgdkcross"
$rawclbgdkdcross = "\\rawclbgdkdcross"
$rawclbgdkfdiag = "\\rawclbgdkfdiag"
$rawclbgdkhor = "\\rawclbgdkhor"
$rawclbgdkvert = "\\rawclbgdkvert"
$rawclbgfdiag = "\\rawclbgfdiag"
$rawclbghoriz = "\\rawclbghoriz"
$rawclbgvert = "\\rawclbgvert"
$rtlrow = "\\rtlrow"
$tabsnoovrlp = "\\tabsnoovrlp"
$taprtl = "\\taprtl"
$tblind = "\\tblind"
$tblindtype = "\\tblindtype"
$tbllkbestfit = "\\tbllkbestfit"
$tbllkborder = "\\tbllkborder"
$tbllkcolor = "\\tbllkcolor"
$tbllkfont = "\\tbllkfont"
$tbllkhdrcols = "\\tbllkhdrcols"
$tbllkhdrrows = "\\tbllkhdrrows"
$tbllklastcol = "\\tbllklastcol"
$tbllklastrow = "\\tbllklastrow"
$tbllknocolband = "\\tbllknocolband"
$tbllknorowband = "\\tbllknorowband"
$tbllkshading = "\\tbllkshading"
$tcelld = "\\tcelld"
$tdfrmtxtBottom = "\\tdfrmtxtBottom"
$tdfrmtxtLeft = "\\tdfrmtxtLeft"
$tdfrmtxtRight = "\\tdfrmtxtRight"
$tdfrmtxtTop = "\\tdfrmtxtTop"
$tphcol = "\\tphcol"
$tphmrg = "\\tphmrg"
$tphpg = "\\tphpg"
$tposnegx = "\\tposnegx"
$tposnegy = "\\tposnegy"
$tposxc = "\\tposxc"
$tposxi = "\\tposxi"
$tposxl = "\\tposxl"
$tposx = "\\tposx"
$tposxo = "\\tposxo"
$tposxr = "\\tposxr"
$tposy = "\\tposy"
$tposyb = "\\tposyb"
$tposyc = "\\tposyc"
$tposyil = "\\tposyil"
$tposyin = "\\tposyin"
$tposyout = "\\tposyout"
$tposyt = "\\tposyt"
$tpvmrg = "\\tpvmrg"
$tpvpara = "\\tpvpara"
$tpvpg = "\\tpvpg"
$trauth = "\\trauth"
$trautofit = "\\trautofit"
$trbgbdiag = "\\trbgbdiag"
$trbgcross = "\\trbgcross"
$trbgdcross = "\\trbgdcross"
$trbgdkbdiag = "\\trbgdkbdiag"
$trbgdkcross = "\\trbgdkcross"
$trbgdkdcross = "\\trbgdkdcross"
$trbgdkfdiag = "\\trbgdkfdiag"
$trbgdkhor = "\\trbgdkhor"
$trbgdkvert = "\\trbgdkvert"
$trbgfdiag = "\\trbgfdiag"
$trbghoriz = "\\trbghoriz"
$trbgvert = "\\trbgvert"
$trbrdrb = "\\trbrdrb"
$trbrdrh = "\\trbrdrh"
$trbrdrl = "\\trbrdrl"
$trbrdrr = "\\trbrdrr"
$trbrdrt = "\\trbrdrt"
$trbrdrv = "\\trbrdrv"
$trcbpat = "\\trcbpat"
$trcfpat = "\\trcfpat"
$trdate = "\\trdate"
$trftsWidthA = "\\trftsWidthA"
$trftsWidthB = "\\trftsWidthB"
$trftsWidth = "\\trftsWidth"
$trgaph = "\\trgaph"
$trhdr = "\\trhdr"
$trkeep = "\\trkeep"
$trkeepfollow = "\\trkeepfollow"
$trleft = "\\trleft"
$trowd = "\\trowd"
$trpaddb = "\\trpaddb"
$trpaddfb = "\\trpaddfb"
$trpaddfl = "\\trpaddfl"
$trpaddfr = "\\trpaddfr"
$trpaddft = "\\trpaddft"
$trpaddl = "\\trpaddl"
$trpaddr = "\\trpaddr"
$trpaddt = "\\trpaddt"
$trpadob = "\\trpadob"
$trpadofb = "\\trpadofb"
$trpadofl = "\\trpadofl"
$trpadofr = "\\trpadofr"
$trpadoft = "\\trpadoft"
$trpadol = "\\trpadol"
$trpador = "\\trpador"
$trpadot = "\\trpadot"
$trpat = "\\trpat"
$trqc = "\\trqc"
$trql = "\\trql"
$trqr = "\\trqr"
$trrh = "\\trrh"
$trshdng = "\\trshdng"
$trspdb = "\\trspdb"
$trspdfb = "\\trspdfb"
$trspdfl = "\\trspdfl"
$trspdfr = "\\trspdfr"
$trspdft = "\\trspdft"
$trspdl = "\\trspdl"
$trspdr = "\\trspdr"
$trspdt = "\\trspdt"
$trspob = "\\trspob"
$trspofb = "\\trspofb"
$trspofl = "\\trspofl"
$trspofr = "\\trspofr"
$trspoft = "\\trspoft"
$trspol = "\\trspol"
$trspor = "\\trspor"
$trspot = "\\trspot"
$trwWidthA = "\\trwWidthA"
$trwWidthB = "\\trwWidthB"
$trwWidth = "\\trwWidth"
$tc = "\\tc"
$tcf = "\\tcf"
$tcl = "\\tcl"
$tcn = "\\tcn"
$tsbgbdiag = "\\tsbgbdiag"
$tsbgcross = "\\tsbgcross"
$tsbgdcross = "\\tsbgdcross"
$tsbgdkbdiag = "\\tsbgdkbdiag"
$tsbgdkcross = "\\tsbgdkcross"
$tsbgdkdcross = "\\tsbgdkdcross"
$tsbgdkfdiag = "\\tsbgdkfdiag"
$tsbgdkhor = "\\tsbgdkhor"
$tsbgdkvert = "\\tsbgdkvert"
$tsbgfdiag = "\\tsbgfdiag"
$tsbghoriz = "\\tsbghoriz"
$tsbgvert = "\\tsbgvert"
$tsbrdrb = "\\tsbrdrb"
$tsbrdrdgl = "\\tsbrdrdgl"
$tsbrdrdgr = "\\tsbrdrdgr"
$tsbrdrh = "\\tsbrdrh"
$tsbrdrl = "\\tsbrdrl"
$tsbrdrr = "\\tsbrdrr"
$tsbrdrt = "\\tsbrdrt"
$tsbrdrv = "\\tsbrdrv"
$tscbandsh = "\\tscbandsh"
$tscbandsv = "\\tscbandsv"
$tscellcbpat = "\\tscellcbpat"
$tscellcfpat = "\\tscellcfpat"
$tscellpaddb = "\\tscellpaddb"
$tscellpaddfb = "\\tscellpaddfb"
$tscellpaddfl = "\\tscellpaddfl"
$tscellpaddfr = "\\tscellpaddfr"
$tscellpaddft = "\\tscellpaddft"
$tscellpaddl = "\\tscellpaddl"
$tscellpaddr = "\\tscellpaddr"
$tscellpaddt = "\\tscellpaddt"
$tscellpct = "\\tscellpct"
$tscellwidth = "\\tscellwidth"
$tscellwidthfts = "\\tscellwidthfts"
$tsnowrap = "\\tsnowrap"
$tsvertalb = "\\tsvertalb"
$tsvertalc = "\\tsvertalc"
$tsvertalt = "\\tsvertalt"
$tb = "\\tb"
$tldot = "\\tldot"
$tleq = "\\tleq"
$tlhyph = "\\tlhyph"
$tlmdot = "\\tlmdot"
$tlth = "\\tlth"
$tlul = "\\tlul"
$tqc = "\\tqc"
$tqdec = "\\tqdec"
$tqr = "\\tqr"
$tx = "\\tx"
condition:
any of them
}
rule rtf_theme
{
strings:
$themedata = "\\themedata"
$fbimajor = "\\fbimajor"
$fbiminor = "\\fbiminor"
$fdbmajor = "\\fdbmajor"
$fdbminor = "\\fdbminor"
$fhimajor = "\\fhimajor"
$fhiminor = "\\fhiminor"
$flomajor = "\\flomajor"
$flominor = "\\flominor"
$revtbl = "\\revtbl"
$charrsid = "\\charrsid"
$delrsid = "\\delrsid"
$insrsid = "\\insrsid"
$oldcprops = "\\oldcprops"
$oldpprops = "\\oldpprops"
$oldsprops = "\\oldsprops"
$oldtprops = "\\oldtprops"
$pararsid = "\\pararsid"
$rsid = "\\rsid"
$rsidroot = "\\rsidroot"
$rsidtbl = "\\rsidtbl"
$sectrsid = "\\sectrsid"
$tblrsid = "\\tblrsid"
condition:
any of them
}
rule rtf_unicode
{
strings:
$u = "\\u"
$uc = "\\uc"
$ud = "\\ud"
$upr = "\\upr"
condition:
any of them
}
rule rtf_shapes
{
strings:
$shp = "\\shp"
$shpbottom = "\\shpbottom"
$shpbxcolumn = "\\shpbxcolumn"
$shpbxignore = "\\shpbxignore"
$shpbxmargin = "\\shpbxmargin"
$shpbxpage = "\\shpbxpage"
$shpbyignore = "\\shpbyignore"
$shpbymargin = "\\shpbymargin"
$shpbypage = "\\shpbypage"
$shpbypara = "\\shpbypara"
$shpfblwtxt = "\\shpfblwtxt"
$shpfhdr = "\\shpfhdr"
$shpgrp = "\\shpgrp"
$shpinst = "\\shpinst"
$shpleft = "\\shpleft"
$shplid = "\\shplid"
$shplockanchor = "\\shplockanchor"
$shpright = "\\shpright"
$shprslt = "\\shprslt"
$shptop = "\\shptop"
$shptxt = "\\shptxt"
$shpwrk = "\\shpwrk"
$shpwr = "\\shpwr"
$shpz = "\\shpz"
$sn = "\\sn"
$sp = "\\sp"
$sv = "\\sv"
$svb = "\\svb"
condition:
any of them
}
"""
|
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC
# (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
# Government retains certain rights in this software.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import yara
# Import classes and helpers from the Laika framework
from laikaboss.util import get_option
from laikaboss.si_module import SI_MODULE
class META_RTF_CONTROLWORDS(SI_MODULE):
'''
counts classes of control words from RTF files
'''
def __init__(self):
self.module_name = "META_RTF_CONTROLWORDS"
self.rules = None
def _run(self, scanObject, result, depth, args):
#lazy compile rules, not using yara_on_demand due to signatures in string vs. file
if not self.rules:
self.rules = yara.compile(source=rtf_rules_source)
matches = self.rules.match(data=scanObject.buffer)
for match in matches:
scanObject.addMetadata(self.module_name, match.rule[4:], len(match.strings))
return []
rtf_rules_source = r"""
rule rtf_position_tabs
{
strings:
$pindtabqc = "\\pindtabqc"
$pindtabql = "\\pindtabql"
$pindtabqr = "\\pindtabqr"
$pmartabqc = "\\pmartabqc"
$pmartabql = "\\pmartabql"
$pmartabqr = "\\pmartabqr"
$ptabldot = "\\ptabldot"
$ptablmdot = "\\ptablmdot"
$ptablminus = "\\ptablminus"
$ptablnone = "\\ptablnone"
$ptabluscore = "\\ptabluscore"
condition:
any of them
}
rule rtf_character_properties
{
strings:
$ab = "\\ab"
$acaps = "\\acaps"
$acf = "\\acf"
$adn = "\\adn"
$aexpnd = "\\aexpnd"
$af = "\\af"
$afs = "\\afs"
$ai = "\\ai"
$alang = "\\alang"
$aoutl = "\\aoutl"
$ascaps = "\\ascaps"
$ashad = "\\ashad"
$astrike = "\\astrike"
$aul = "\\aul"
$auld = "\\auld"
$auldb = "\\auldb"
$aulnone = "\\aulnone"
$aulw = "\\aulw"
$aup = "\\aup"
$dbch = "\\dbch"
$fcs = "\\fcs"
$hich = "\\hich"
$loch = "\\loch"
condition:
any of them
}
rule rtf_bookmarks
{
strings:
$bkmkcolf = "\\bkmkcolf"
$bkmkcoll = "\\bkmkcoll"
$bkmkend = "\\bkmkend"
$bkmkstart = "\\bkmkstart"
$mvfmf = "\\mvfmf"
$mvfml = "\\mvfml"
$mvtof = "\\mvtof"
$mvtol = "\\mvtol"
condition:
any of them
}
rule rtf_bullets
{
strings:
$ilvl = "\\ilvl"
$listtext = "\\listtext"
$pn = "\\pn"
$pnacross = "\\pnacross"
$pnaiu = "\\pnaiu"
$pnaiud = "\\pnaiud"
$pnaiueo = "\\pnaiueo"
$pnaiueod = "\\pnaiueod"
$pnb = "\\pnb"
$pnbidia = "\\pnbidia"
$pnbidib = "\\pnbidib"
$pncaps = "\\pncaps"
$pncard = "\\pncard"
$pncf = "\\pncf"
$pnchosung = "\\pnchosung"
$pncnum = "\\pncnum"
$pndbnum = "\\pndbnum"
$pndbnumd = "\\pndbnumd"
$pndbnumk = "\\pndbnumk"
$pndbnuml = "\\pndbnuml"
$pndbnumt = "\\pndbnumt"
$pndec = "\\pndec"
$pndecd = "\\pndecd"
$pnf = "\\pnf"
$pnfs = "\\pnfs"
$pnganada = "\\pnganada"
$pngbnum = "\\pngbnum"
$pngbnumd = "\\pngbnumd"
$pngbnumk = "\\pngbnumk"
$pngbnuml = "\\pngbnuml"
$pnhang = "\\pnhang"
$pni = "\\pni"
$pnindent = "\\pnindent"
$pniroha = "\\pniroha"
$pnirohad = "\\pnirohad"
$pnlcltr = "\\pnlcltr"
$pnlcrm = "\\pnlcrm"
$pnlvl = "\\pnlvl"
$pnlvlblt = "\\pnlvlblt"
$pnlvlbody = "\\pnlvlbody"
$pnlvlcont = "\\pnlvlcont"
$pnnumonce = "\\pnnumonce"
$pnord = "\\pnord"
$pnordt = "\\pnordt"
$pnprev = "\\pnprev"
$pnqc = "\\pnqc"
$pnql = "\\pnql"
$pnqr = "\\pnqr"
$pnrestart = "\\pnrestart"
$pnscaps = "\\pnscaps"
$pnsp = "\\pnsp"
$pnstart = "\\pnstart"
$pnstrike = "\\pnstrike"
$pntext = "\\pntext"
$pntxta = "\\pntxta"
$pntxtb = "\\pntxtb"
$pnucltr = "\\pnucltr"
$pnucrm = "\\pnucrm"
$pnul = "\\pnul"
$pnuld = "\\pnuld"
$pnuldash = "\\pnuldash"
$pnuldashd = "\\pnuldashd"
$pnuldashdd = "\\pnuldashdd"
$pnuldb = "\\pnuldb"
$pnulhair = "\\pnulhair"
$pnulnone = "\\pnulnone"
$pnulth = "\\pnulth"
$pnulw = "\\pnulw"
$pnulwave = "\\pnulwave"
$pnzodiac = "\\pnzodiac"
$pnzodiacd = "\\pnzodiacd"
$pnzodiacl = "\\pnzodiacl"
condition:
any of them
}
rule rtf_characters
{
strings:
$chbgbdiag = "\\chbgbdiag"
$chbgcross = "\\chbgcross"
$chbgdcross = "\\chbgdcross"
$chbgdkbdiag = "\\chbgdkbdiag"
$chbgdkcross = "\\chbgdkcross"
$chbgdkdcross = "\\chbgdkdcross"
$chbgdkfdiag = "\\chbgdkfdiag"
$chbgdkhoriz = "\\chbgdkhoriz"
$chbgdkvert = "\\chbgdkvert"
$chbgfdiag = "\\chbgfdiag"
$chbghoriz = "\\chbghoriz"
$chbgvert = "\\chbgvert"
$chbrdr = "\\chbrdr"
$chcbpat = "\\chcbpat"
$chcfpat = "\\chcfpat"
$chshdng = "\\chshdng"
$crauth = "\\crauth"
$crdate = "\\crdate"
$deleted = "\\deleted"
$mvauth = "\\mvauth"
$mvdate = "\\mvdate"
$mvf = "\\mvf"
$mvt = "\\mvt"
$revauth = "\\revauth"
$revauthdel = "\\revauthdel"
$revdttm = "\\revdttm"
$revdttmdel = "\\revdttmdel"
$revised = "\\revised"
$ansi = "\\ansi"
$ansicpg = "\\ansicpg"
$fbidis = "\\fbidis"
$mac = "\\mac"
$pc = "\\pc"
$pca = "\\pca"
$impr = "\\impr"
$striked1 = "\\striked1"
condition:
any of them
}
rule rtf_codepage
{
strings:
$cpg = "\\cpg"
condition:
any of them
}
rule rtf_color
{
strings:
$colorschememapping = "\\colorschememapping"
$blue = "\\blue"
$caccentfive = "\\caccentfive"
$caccentfour = "\\caccentfour"
$caccentone = "\\caccentone"
$caccentsix = "\\caccentsix"
$caccentthree = "\\caccentthree"
$caccenttwo = "\\caccenttwo"
$cbackgroundone = "\\cbackgroundone"
$cbackgroundtwo = "\\cbackgroundtwo"
$cfollowedhyperlink = "\\cfollowedhyperlink"
$chyperlink = "\\chyperlink"
$cmaindarkone = "\\cmaindarkone"
$cmaindarktwo = "\\cmaindarktwo"
$cmainlightone = "\\cmainlightone"
$cmainlighttwo = "\\cmainlighttwo"
$colortbl = "\\colortbl"
$cshade = "\\cshade"
$ctextone = "\\ctextone"
$ctexttwo = "\\ctexttwo"
$ctint = "\\ctint"
$green = "\\green"
$red = "\\red"
condition:
any of them
}
rule rtf_comments
{
strings:
$annotation = "\\annotation"
$atnauthor = "\\atnauthor"
$atndate = "\\atndate"
$atnicn = "\\atnicn"
$atnid = "\\atnid"
$atnparent = "\\atnparent"
$atnref = "\\atnref"
$atntime = "\\atntime"
$atrfend = "\\atrfend"
$atrfstart = "\\atrfstart"
condition:
any of them
}
rule rtf_control_other
{
strings:
$disabled = "\\disabled"
$htmlbase = "\\htmlbase"
$htmlrtf = "\\htmlrtf"
$htmltag = "\\htmltag"
$mhtmltag = "\\mhtmltag"
$protect = "\\protect"
$pwd = "\\pwd"
$urtf = "\\urtf"
condition:
any of them
}
rule rtf_datastore
{
strings:
$datastore = "\\datastore"
condition:
any of them
}
rule rtf_xml
{
strings:
$xmlattr = "\\xmlattr"
$xmlattrname = "\\xmlattrname"
$xmlattrns = "\\xmlattrns"
$xmlattrvalue = "\\xmlattrvalue"
$xmlclose = "\\xmlclose"
$xmlname = "\\xmlname"
$xmlnstbl = "\\xmlnstbl"
$xmlopen = "\\xmlopen"
$xmlsdttcell = "\\xmlsdttcell"
$xmlsdttpara = "\\xmlsdttpara"
$xmlsdttregular = "\\xmlsdttregular"
$xmlsdttrow = "\\xmlsdttrow"
$xmlsdttunknown = "\\xmlsdttunknown"
$xmlns = "\\xmlns"
condition:
any of them
}
rule rtf_defaults
{
strings:
$adeff = "\\adeff"
$adeflang = "\\adeflang"
$deff = "\\deff"
$deflang = "\\deflang"
$deflangfe = "\\deflangfe"
$stshfbi = "\\stshfbi"
$stshfdbch = "\\stshfdbch"
$stshfhich = "\\stshfhich"
$stshfloch = "\\stshfloch"
$defchp = "\\defchp"
$defpap = "\\defpap"
condition:
any of them
}
rule rtf_formatting
{
strings:
$aenddoc = "\\aenddoc"
$aendnotes = "\\aendnotes"
$afelev = "\\afelev"
$aftnbj = "\\aftnbj"
$aftncn = "\\aftncn"
$aftnnalc = "\\aftnnalc"
$aftnnar = "\\aftnnar"
$aftnnauc = "\\aftnnauc"
$aftnnchi = "\\aftnnchi"
$aftnnchosung = "\\aftnnchosung"
$aftnncnum = "\\aftnncnum"
$aftnndbar = "\\aftnndbar"
$aftnndbnum = "\\aftnndbnum"
$aftnndbnumd = "\\aftnndbnumd"
$aftnndbnumk = "\\aftnndbnumk"
$aftnndbnumt = "\\aftnndbnumt"
$aftnnganada = "\\aftnnganada"
$aftnngbnum = "\\aftnngbnum"
$aftnngbnumd = "\\aftnngbnumd"
$aftnngbnumk = "\\aftnngbnumk"
$aftnngbnuml = "\\aftnngbnuml"
$aftnnrlc = "\\aftnnrlc"
$aftnnruc = "\\aftnnruc"
$aftnnzodiac = "\\aftnnzodiac"
$aftnnzodiacd = "\\aftnnzodiacd"
$aftnnzodiacl = "\\aftnnzodiacl"
$aftnrestart = "\\aftnrestart"
$aftnrstcont = "\\aftnrstcont"
$aftnsep = "\\aftnsep"
$aftnsepc = "\\aftnsepc"
$aftnstart = "\\aftnstart"
$aftntj = "\\aftntj"
$allowfieldendsel = "\\allowfieldendsel"
$allprot = "\\allprot"
$alntblind = "\\alntblind"
$annotprot = "\\annotprot"
$ApplyBrkRules = "\\ApplyBrkRules"
$asianbrkrule = "\\asianbrkrule"
$autofmtoverride = "\\autofmtoverride"
$background = "\\background"
$bdbfhdr = "\\bdbfhdr"
$bdrrlswsix = "\\bdrrlswsix"
$bookfold = "\\bookfold"
$bookfoldrev = "\\bookfoldrev"
$bookfoldsheets = "\\bookfoldsheets"
$brdrart = "\\brdrart"
$brkfrm = "\\brkfrm"
$cachedcolbal = "\\cachedcolbal"
$cts = "\\cts"
$cvmme = "\\cvmme"
$defformat = "\\defformat"
$deftab = "\\deftab"
$dghorigin = "\\dghorigin"
$dghshow = "\\dghshow"
$dghspace = "\\dghspace"
$dgmargin = "\\dgmargin"
$dgsnap = "\\dgsnap"
$dgvorigin = "\\dgvorigin"
$dgvshow = "\\dgvshow"
$dgvspace = "\\dgvspace"
$dntblnsbdb = "\\dntblnsbdb"
$doctemp = "\\doctemp"
$doctype = "\\doctype"
$donotembedlingdata = "\\donotembedlingdata"
$donotembedsysfont = "\\donotembedsysfont"
$donotshowcomments = "\\donotshowcomments"
$donotshowinsdel = "\\donotshowinsdel"
$donotshowmarkup = "\\donotshowmarkup"
$donotshowprops = "\\donotshowprops"
$enddoc = "\\enddoc"
$endnotes = "\\endnotes"
$enforceprot = "\\enforceprot"
$expshrtn = "\\expshrtn"
$facingp = "\\facingp"
$fchars = "\\fchars"
$felnbrelev = "\\felnbrelev"
$fet = "\\fet"
$forceupgrade = "\\forceupgrade"
$formdisp = "\\formdisp"
$formprot = "\\formprot"
$formshade = "\\formshade"
$fracwidth = "\\fracwidth"
$fromhtml = "\\fromhtml"
$fromtext = "\\fromtext"
$ftnalt = "\\ftnalt"
$ftnbj = "\\ftnbj"
$ftncn = "\\ftncn"
$ftnlytwnine = "\\ftnlytwnine"
$ftnnalc = "\\ftnnalc"
$ftnnar = "\\ftnnar"
$ftnnauc = "\\ftnnauc"
$ftnnchi = "\\ftnnchi"
$ftnnchosung = "\\ftnnchosung"
$ftnncnum = "\\ftnncnum"
$ftnndbar = "\\ftnndbar"
$ftnndbnum = "\\ftnndbnum"
$ftnndbnumd = "\\ftnndbnumd"
$ftnndbnumk = "\\ftnndbnumk"
$ftnndbnumt = "\\ftnndbnumt"
$ftnnganada = "\\ftnnganada"
$ftnngbnum = "\\ftnngbnum"
$ftnngbnumd = "\\ftnngbnumd"
$ftnngbnumk = "\\ftnngbnumk"
$ftnngbnuml = "\\ftnngbnuml"
$ftnnrlc = "\\ftnnrlc"
$ftnnruc = "\\ftnnruc"
$ftnnzodiac = "\\ftnnzodiac"
$ftnnzodiacd = "\\ftnnzodiacd"
$ftnnzodiacl = "\\ftnnzodiacl"
$ftnrestart = "\\ftnrestart"
$ftnrstcont = "\\ftnrstcont"
$ftnrstpg = "\\ftnrstpg"
$ftnsep = "\\ftnsep"
$ftnsepc = "\\ftnsepc"
$ftnstart = "\\ftnstart"
$ftntj = "\\ftntj"
$grfdocevents = "\\grfdocevents"
$gutter = "\\gutter"
$gutterprl = "\\gutterprl"
$horzdoc = "\\horzdoc"
$htmautsp = "\\htmautsp"
$hwelev2007 = "\\hwelev2007"
$hyphauto = "\\hyphauto"
$hyphcaps = "\\hyphcaps"
$hyphconsec = "\\hyphconsec"
$hyphhotz = "\\hyphhotz"
$ignoremixedcontent = "\\ignoremixedcontent"
$ilfomacatclnup = "\\ilfomacatclnup"
$indrlsweleven = "\\indrlsweleven"
$jcompress = "\\jcompress"
$jexpand = "\\jexpand"
$jsksu = "\\jsksu"
$krnprsnet = "\\krnprsnet"
$ksulang = "\\ksulang"
$landscape = "\\landscape"
$lchars = "\\lchars"
$linestart = "\\linestart"
$linkstyles = "\\linkstyles"
$lnbrkrule = "\\lnbrkrule"
$lnongrid = "\\lnongrid"
$ltrdoc = "\\ltrdoc"
$lytcalctblwd = "\\lytcalctblwd"
$lytexcttp = "\\lytexcttp"
$lytprtmet = "\\lytprtmet"
$lyttblrtgr = "\\lyttblrtgr"
$makebackup = "\\makebackup"
$margb = "\\margb"
$margl = "\\margl"
$margmirror = "\\margmirror"
$margr = "\\margr"
$margt = "\\margt"
$msmcap = "\\msmcap"
$muser = "\\muser"
$newtblstyruls = "\\newtblstyruls"
$nextfile = "\\nextfile"
$noafcnsttbl = "\\noafcnsttbl"
$nobrkwrptbl = "\\nobrkwrptbl"
$nocolbal = "\\nocolbal"
$nocompatoptions = "\\nocompatoptions"
$nocxsptable = "\\nocxsptable"
$noextrasprl = "\\noextrasprl"
$nofeaturethrottle = "\\nofeaturethrottle"
$nogrowautofit = "\\nogrowautofit"
$noindnmbrts = "\\noindnmbrts"
$nojkernpunct = "\\nojkernpunct"
$nolead = "\\nolead"
$nolnhtadjtbl = "\\nolnhtadjtbl"
$nospaceforul = "\\nospaceforul"
$notabind = "\\notabind"
$notbrkcnstfrctbl = "\\notbrkcnstfrctbl"
$notcvasp = "\\notcvasp"
$notvatxbx = "\\notvatxbx"
$nouicompat = "\\nouicompat"
$noultrlspc = "\\noultrlspc"
$noxlattoyen = "\\noxlattoyen"
$ogutter = "\\ogutter"
$oldas = "\\oldas"
$oldlinewrap = "\\oldlinewrap"
$otblrul = "\\otblrul"
$paperh = "\\paperh"
$paperw = "\\paperw"
$pgbrdrb = "\\pgbrdrb"
$pgbrdrfoot = "\\pgbrdrfoot"
$pgbrdrhead = "\\pgbrdrhead"
$pgbrdrl = "\\pgbrdrl"
$pgbrdropt = "\\pgbrdropt"
$pgbrdrr = "\\pgbrdrr"
$pgbrdrsnap = "\\pgbrdrsnap"
$pgbrdrt = "\\pgbrdrt"
$pgnstart = "\\pgnstart"
$prcolbl = "\\prcolbl"
$printdata = "\\printdata"
$private = "\\private"
$protlevel = "\\protlevel"
$psover = "\\psover"
$psz = "\\psz"
$readonlyrecommended = "\\readonlyrecommended"
$readprot = "\\readprot"
$relyonvml = "\\relyonvml"
$remdttm = "\\remdttm"
$rempersonalinfo = "\\rempersonalinfo"
$revbar = "\\revbar"
$revisions = "\\revisions"
$revprop = "\\revprop"
$revprot = "\\revprot"
$rtldoc = "\\rtldoc"
$rtlgutter = "\\rtlgutter"
$saveinvalidxml = "\\saveinvalidxml"
$saveprevpict = "\\saveprevpict"
$showplaceholdtext = "\\showplaceholdtext"
$showxmlerrors = "\\showxmlerrors"
$snaptogridincell = "\\snaptogridincell"
$spltpgpar = "\\spltpgpar"
$splytwnine = "\\splytwnine"
$sprsbsp = "\\sprsbsp"
$sprslnsp = "\\sprslnsp"
$sprsspbf = "\\sprsspbf"
$sprstsm = "\\sprstsm"
$sprstsp = "\\sprstsp"
$stylelock = "\\stylelock"
$stylelockbackcomp = "\\stylelockbackcomp"
$stylelockenforced = "\\stylelockenforced"
$stylelockqfset = "\\stylelockqfset"
$stylelocktheme = "\\stylelocktheme"
$stylesortmethod = "\\stylesortmethod"
$subfontbysize = "\\subfontbysize"
$swpbdr = "\\swpbdr"
$template = "\\template"
$themelang = "\\themelang"
$themelangcs = "\\themelangcs"
$themelangfe = "\\themelangfe"
$toplinepunct = "\\toplinepunct"
$trackformatting = "\\trackformatting"
$trackmoves = "\\trackmoves"
$transmf = "\\transmf"
$truncatefontheight = "\\truncatefontheight"
$truncex = "\\truncex"
$tsd = "\\tsd"
$twoonone = "\\twoonone"
$useltbaln = "\\useltbaln"
$usenormstyforlist = "\\usenormstyforlist"
$usexform = "\\usexform"
$utinl = "\\utinl"
$validatexml = "\\validatexml"
$vertdoc = "\\vertdoc"
$viewbksp = "\\viewbksp"
$viewkind = "\\viewkind"
$viewnobound = "\\viewnobound"
$viewscale = "\\viewscale"
$viewzk = "\\viewzk"
$wgrffmtfilter = "\\wgrffmtfilter"
$widowctrl = "\\widowctrl"
$windowcaption = "\\windowcaption"
$wpjst = "\\wpjst"
$wpsp = "\\wpsp"
$wraptrsp = "\\wraptrsp"
$writereservation = "\\writereservation"
$writereservhash = "\\writereservhash"
$wrppunct = "\\wrppunct"
$xform = "\\xform"
condition:
any of them
}
rule rtf_docvar
{
strings:
$docvar = "\\docvar"
condition:
any of them
}
rule rtf_drawing
{
strings:
$hl = "\\hl"
$hlfr = "\\hlfr"
$hlloc = "\\hlloc"
$hlsrc = "\\hlsrc"
$hrule = "\\hrule"
$hsv = "\\hsv"
$do = "\\do"
$dobxcolumn = "\\dobxcolumn"
$dobxmargin = "\\dobxmargin"
$dobxpage = "\\dobxpage"
$dobymargin = "\\dobymargin"
$dobypage = "\\dobypage"
$dobypara = "\\dobypara"
$dodhgt = "\\dodhgt"
$dolock = "\\dolock"
$dpaendhol = "\\dpaendhol"
$dpaendl = "\\dpaendl"
$dpaendsol = "\\dpaendsol"
$dpaendw = "\\dpaendw"
$dparc = "\\dparc"
$dparcflipx = "\\dparcflipx"
$dparcflipy = "\\dparcflipy"
$dpastarthol = "\\dpastarthol"
$dpastartl = "\\dpastartl"
$dpastartsol = "\\dpastartsol"
$dpastartw = "\\dpastartw"
$dpcallout = "\\dpcallout"
$dpcoa = "\\dpcoa"
$dpcoaccent = "\\dpcoaccent"
$dpcobestfit = "\\dpcobestfit"
$dpcoborder = "\\dpcoborder"
$dpcodabs = "\\dpcodabs"
$dpcodbottom = "\\dpcodbottom"
$dpcodcenter = "\\dpcodcenter"
$dpcodescent = "\\dpcodescent"
$dpcodtop = "\\dpcodtop"
$dpcolength = "\\dpcolength"
$dpcominusx = "\\dpcominusx"
$dpcominusy = "\\dpcominusy"
$dpcooffset = "\\dpcooffset"
$dpcosmarta = "\\dpcosmarta"
$dpcotdouble = "\\dpcotdouble"
$dpcotright = "\\dpcotright"
$dpcotsingle = "\\dpcotsingle"
$dpcottriple = "\\dpcottriple"
$dpcount = "\\dpcount"
$dpellipse = "\\dpellipse"
$dpendgroup = "\\dpendgroup"
$dpfillbgcb = "\\dpfillbgcb"
$dpfillbgcg = "\\dpfillbgcg"
$dpfillbgcr = "\\dpfillbgcr"
$dpfillbggray = "\\dpfillbggray"
$dpfillbgpal = "\\dpfillbgpal"
$dpfillfgcb = "\\dpfillfgcb"
$dpfillfgcg = "\\dpfillfgcg"
$dpfillfgcr = "\\dpfillfgcr"
$dpfillfggray = "\\dpfillfggray"
$dpfillfgpal = "\\dpfillfgpal"
$dpfillpat = "\\dpfillpat"
$dpgroup = "\\dpgroup"
$dpline = "\\dpline"
$dplinecob = "\\dplinecob"
$dplinecog = "\\dplinecog"
$dplinecor = "\\dplinecor"
$dplinedado = "\\dplinedado"
$dplinedadodo = "\\dplinedadodo"
$dplinedash = "\\dplinedash"
$dplinedot = "\\dplinedot"
$dplinegray = "\\dplinegray"
$dplinehollow = "\\dplinehollow"
$dplinepal = "\\dplinepal"
$dplinesolid = "\\dplinesolid"
$dplinew = "\\dplinew"
$dppolycount = "\\dppolycount"
$dppolygon = "\\dppolygon"
$dppolyline = "\\dppolyline"
$dpptx = "\\dpptx"
$dppty = "\\dppty"
$dprect = "\\dprect"
$dproundr = "\\dproundr"
$dpshadow = "\\dpshadow"
$dpshadx = "\\dpshadx"
$dpshady = "\\dpshady"
$dptxbtlr = "\\dptxbtlr"
$dptxbx = "\\dptxbx"
$dptxbxmar = "\\dptxbxmar"
$dptxbxtext = "\\dptxbxtext"
$dptxlrtb = "\\dptxlrtb"
$dptxlrtbv = "\\dptxlrtbv"
$dptxtbrl = "\\dptxtbrl"
$dptxtbrlv = "\\dptxtbrlv"
$dpx = "\\dpx"
$dpxsize = "\\dpxsize"
$dpy = "\\dpy"
$dpysize = "\\dpysize"
condition:
any of them
}
rule rtf_asia
{
strings:
$cgrid = "\\cgrid"
$g = "\\g"
$gcw = "\\gcw"
$gridtbl = "\\gridtbl"
$nosectexpand = "\\nosectexpand"
$ulhair = "\\ulhair"
$horzvert = "\\horzvert"
$twoinone = "\\twoinone"
condition:
any of them
}
rule rtf_fields
{
strings:
$datafield = "\\datafield"
$date = "\\date"
$field = "\\field"
$fldalt = "\\fldalt"
$flddirty = "\\flddirty"
$fldedit = "\\fldedit"
$fldinst = "\\fldinst"
$fldlock = "\\fldlock"
$fldpriv = "\\fldpriv"
$fldrslt = "\\fldrslt"
$fldtype = "\\fldtype"
$time = "\\time"
$wpeqn = "\\wpeqn"
condition:
any of them
}
rule rtf_files
{
strings:
$fid = "\\fid"
$file = "\\file"
$filetbl = "\\filetbl"
$fnetwork = "\\fnetwork"
$fnonfilesys = "\\fnonfilesys"
$fosnum = "\\fosnum"
$frelative = "\\frelative"
$fvaliddos = "\\fvaliddos"
$fvalidhpfs = "\\fvalidhpfs"
$fvalidmac = "\\fvalidmac"
$fvalidntfs = "\\fvalidntfs"
condition:
any of them
}
rule rtf_font
{
strings:
$acccircle = "\\acccircle"
$acccomma = "\\acccomma"
$accdot = "\\accdot"
$accnone = "\\accnone"
$accunderdot = "\\accunderdot"
$animtext = "\\animtext"
$b = "\\b"
$caps = "\\caps"
$cb = "\\cb"
$cchs = "\\cchs"
$cf = "\\cf"
$charscalex = "\\charscalex"
$cs = "\\cs"
$dn = "\\dn"
$embo = "\\embo"
$expnd = "\\expnd"
$expndtw = "\\expndtw"
$f = "\\f"
$fittext = "\\fittext"
$fs = "\\fs"
$i = "\\i"
$kerning = "\\kerning"
$lang = "\\lang"
$langfe = "\\langfe"
$langfenp = "\\langfenp"
$langnp = "\\langnp"
$ltrch = "\\ltrch"
$noproof = "\\noproof"
$nosupersub = "\\nosupersub"
$outl = "\\outl"
$plain = "\\plain"
$rtlch = "\\rtlch"
$scaps = "\\scaps"
$shad = "\\shad"
$strike = "\\strike"
$sub = "\\sub"
$super = "\\super"
$ul = "\\ul"
$ulc = "\\ulc"
$uld = "\\uld"
$uldash = "\\uldash"
$uldashd = "\\uldashd"
$uldashdd = "\\uldashdd"
$uldb = "\\uldb"
$ulhwave = "\\ulhwave"
$ulldash = "\\ulldash"
$ulnone = "\\ulnone"
$ulth = "\\ulth"
$ulthd = "\\ulthd"
$ulthdash = "\\ulthdash"
$ulthdashd = "\\ulthdashd"
$ulthdashdd = "\\ulthdashdd"
$ulthldash = "\\ulthldash"
$ululdbwave = "\\ululdbwave"
$ulw = "\\ulw"
$ulwave = "\\ulwave"
$up = "\\up"
$v = "\\v"
$webhidden = "\\webhidden"
$fjgothic = "\\fjgothic"
$fjminchou = "\\fjminchou"
$jis = "\\jis"
$falt = "\\falt"
$fbias = "\\fbias"
$fbidi = "\\fbidi"
$fcharset = "\\fcharset"
$fdecor = "\\fdecor"
$fetch = "\\fetch"
$fmodern = "\\fmodern"
$fname = "\\fname"
$fnil = "\\fnil"
$fontemb = "\\fontemb"
$fontfile = "\\fontfile"
$fonttbl = "\\fonttbl"
$fprq = "\\fprq"
$froman = "\\froman"
$fscript = "\\fscript"
$fswiss = "\\fswiss"
$ftech = "\\ftech"
$ftnil = "\\ftnil"
$fttruetype = "\\fttruetype"
$panose = "\\panose"
condition:
any of them
}
rule rtf_footnote
{
strings:
$footnote = "\\footnote"
condition:
any of them
}
rule rtf_form
{
strings:
$ffdefres = "\\ffdefres"
$ffdeftext = "\\ffdeftext"
$ffentrymcr = "\\ffentrymcr"
$ffexitmcr = "\\ffexitmcr"
$ffformat = "\\ffformat"
$ffhaslistbox = "\\ffhaslistbox"
$ffhelptext = "\\ffhelptext"
$ffhps = "\\ffhps"
$ffl = "\\ffl"
$ffmaxlen = "\\ffmaxlen"
$ffname = "\\ffname"
$ffownhelp = "\\ffownhelp"
$ffownstat = "\\ffownstat"
$ffprot = "\\ffprot"
$ffrecalc = "\\ffrecalc"
$ffres = "\\ffres"
$ffsize = "\\ffsize"
$ffstattext = "\\ffstattext"
$fftype = "\\fftype"
$fftypetxt = "\\fftypetxt"
$formfield = "\\formfield"
condition:
any of them
}
rule rtf_generator
{
strings:
$generator = "\\generator"
condition:
any of them
}
rule rtf_headers
{
strings:
$footer = "\\footer"
$footerf = "\\footerf"
$footerl = "\\footerl"
$footerr = "\\footerr"
$header = "\\header"
$headerf = "\\headerf"
$headerl = "\\headerl"
$headerr = "\\headerr"
condition:
any of them
}
rule rtf_highlight
{
strings:
$highlight = "\\highlight"
condition:
any of them
}
rule rtf_hyphen
{
strings:
$chhres = "\\chhres"
$hres = "\\hres"
condition:
any of them
}
rule rtf_index
{
strings:
$bxe = "\\bxe"
$ixe = "\\ixe"
$pxe = "\\pxe"
$rxe = "\\rxe"
$txe = "\\txe"
$xe = "\\xe"
$xef = "\\xef"
$yxe = "\\yxe"
condition:
any of them
}
rule rtf_info
{
strings:
$author = "\\author"
$buptim = "\\buptim"
$category = "\\category"
$comment = "\\comment"
$company = "\\company"
$creatim = "\\creatim"
$doccomm = "\\doccomm"
$dy = "\\dy"
$edmins = "\\edmins"
$hlinkbase = "\\hlinkbase"
$hr = "\\hr"
$id = "\\id"
$info = "\\info"
$keywords = "\\keywords"
$linkval = "\\linkval"
$manager = "\\manager"
$min = "\\min"
$mo = "\\mo"
$nofchars = "\\nofchars"
$nofcharsws = "\\nofcharsws"
$nofpages = "\\nofpages"
$nofwords = "\\nofwords"
$operator = "\\operator"
$printim = "\\printim"
$propname = "\\propname"
$proptype = "\\proptype"
$revtim = "\\revtim"
$sec = "\\sec"
$staticval = "\\staticval"
$subject = "\\subject"
$title = "\\title"
$userprops = "\\userprops"
$vern = "\\vern"
$version = "\\version"
$yr = "\\yr"
condition:
any of them
}
rule rtf_list
{
strings:
$lvltentative = "\\lvltentative"
$jclisttab = "\\jclisttab"
$levelfollow = "\\levelfollow"
$levelindent = "\\levelindent"
$leveljc = "\\leveljc"
$leveljcn = "\\leveljcn"
$levellegal = "\\levellegal"
$levelnfc = "\\levelnfc"
$levelnfcn = "\\levelnfcn"
$levelnorestart = "\\levelnorestart"
$levelnumbers = "\\levelnumbers"
$levelold = "\\levelold"
$levelpicture = "\\levelpicture"
$levelpicturenosize = "\\levelpicturenosize"
$levelprev = "\\levelprev"
$levelprevspace = "\\levelprevspace"
$levelspace = "\\levelspace"
$levelstartat = "\\levelstartat"
$leveltemplateid = "\\leveltemplateid"
$leveltext = "\\leveltext"
$lfolevel = "\\lfolevel"
$list = "\\list"
$listhybrid = "\\listhybrid"
$listid = "\\listid"
$listlevel = "\\listlevel"
$listname = "\\listname"
$listoverride = "\\listoverride"
$listoverridecount = "\\listoverridecount"
$listoverrideformat = "\\listoverrideformat"
$listoverridestartat = "\\listoverridestartat"
$listoverridetable = "\\listoverridetable"
$listpicture = "\\listpicture"
$listrestarthdn = "\\listrestarthdn"
$listsimple = "\\listsimple"
$liststyleid = "\\liststyleid"
$liststylename = "\\liststylename"
$listtable = "\\listtable"
$listtemplateid = "\\listtemplateid"
$ls = "\\ls"
condition:
any of them
}
rule rtf_mac
{
strings:
$bkmkpub = "\\bkmkpub"
$pubauto = "\\pubauto"
condition:
any of them
}
rule rtf_mail
{
strings:
$mailmerge = "\\mailmerge"
$mmaddfieldname = "\\mmaddfieldname"
$mmattach = "\\mmattach"
$mmblanklines = "\\mmblanklines"
$mmconnectstr = "\\mmconnectstr"
$mmconnectstrdata = "\\mmconnectstrdata"
$mmdatasource = "\\mmdatasource"
$mmdatatypeaccess = "\\mmdatatypeaccess"
$mmdatatypeexcel = "\\mmdatatypeexcel"
$mmdatatypefile = "\\mmdatatypefile"
$mmdatatypeodbc = "\\mmdatatypeodbc"
$mmdatatypeodso = "\\mmdatatypeodso"
$mmdatatypeqt = "\\mmdatatypeqt"
$mmdefaultsql = "\\mmdefaultsql"
$mmdestemail = "\\mmdestemail"
$mmdestfax = "\\mmdestfax"
$mmdestnewdoc = "\\mmdestnewdoc"
$mmdestprinter = "\\mmdestprinter"
$mmerrors = "\\mmerrors"
$mmfttypeaddress = "\\mmfttypeaddress"
$mmfttypebarcode = "\\mmfttypebarcode"
$mmfttypedbcolumn = "\\mmfttypedbcolumn"
$mmfttypemapped = "\\mmfttypemapped"
$mmfttypenull = "\\mmfttypenull"
$mmfttypesalutation = "\\mmfttypesalutation"
$mmheadersource = "\\mmheadersource"
$mmjdsotype = "\\mmjdsotype"
$mmlinktoquery = "\\mmlinktoquery"
$mmmailsubject = "\\mmmailsubject"
$mmmaintypecatalog = "\\mmmaintypecatalog"
$mmmaintypeemail = "\\mmmaintypeemail"
$mmmaintypeenvelopes = "\\mmmaintypeenvelopes"
$mmmaintypefax = "\\mmmaintypefax"
$mmmaintypelabels = "\\mmmaintypelabels"
$mmmaintypeletters = "\\mmmaintypeletters"
$mmodso = "\\mmodso"
$mmodsoactive = "\\mmodsoactive"
$mmodsocoldelim = "\\mmodsocoldelim"
$mmodsocolumn = "\\mmodsocolumn"
$mmodsodynaddr = "\\mmodsodynaddr"
$mmodsofhdr = "\\mmodsofhdr"
$mmodsofilter = "\\mmodsofilter"
$mmodsofldmpdata = "\\mmodsofldmpdata"
$mmodsofmcolumn = "\\mmodsofmcolumn"
$mmodsohash = "\\mmodsohash"
$mmodsolid = "\\mmodsolid"
$mmodsomappedname = "\\mmodsomappedname"
$mmodsoname = "\\mmodsoname"
$mmodsorecipdata = "\\mmodsorecipdata"
$mmodsosort = "\\mmodsosort"
$mmodsosrc = "\\mmodsosrc"
$mmodsotable = "\\mmodsotable"
$mmodsoudl = "\\mmodsoudl"
$mmodsoudldata = "\\mmodsoudldata"
$mmodsouniquetag = "\\mmodsouniquetag"
$mmquery = "\\mmquery"
$mmreccur = "\\mmreccur"
$mmshowdata = "\\mmshowdata"
condition:
any of them
}
rule rtf_math
{
strings:
$macc = "\\macc"
$maccPr = "\\maccPr"
$maln = "\\maln"
$malnScr = "\\malnScr"
$margPr = "\\margPr"
$margSz = "\\margSz"
$mbar = "\\mbar"
$mbarPr = "\\mbarPr"
$mbaseJc = "\\mbaseJc"
$mbegChr = "\\mbegChr"
$mborderBox = "\\mborderBox"
$mborderBoxPr = "\\mborderBoxPr"
$mbox = "\\mbox"
$mboxPr = "\\mboxPr"
$mbrk = "\\mbrk"
$mbrkBin = "\\mbrkBin"
$mbrkBinSub = "\\mbrkBinSub"
$mcGp = "\\mcGp"
$mcGpRule = "\\mcGpRule"
$mchr = "\\mchr"
$mcount = "\\mcount"
$mcSp = "\\mcSp"
$mctrlPr = "\\mctrlPr"
$md = "\\md"
$mdefJc = "\\mdefJc"
$mdeg = "\\mdeg"
$mdegHide = "\\mdegHide"
$mden = "\\mden"
$mdiff = "\\mdiff"
$mdiffSty = "\\mdiffSty"
$mdispdef = "\\mdispdef"
$mdPr = "\\mdPr"
$me = "\\me"
$mendChr = "\\mendChr"
$meqArr = "\\meqArr"
$meqArrPr = "\\meqArrPr"
$mf = "\\mf"
$mfName = "\\mfName"
$mfPr = "\\mfPr"
$mfunc = "\\mfunc"
$mfuncPr = "\\mfuncPr"
$mgroupChr = "\\mgroupChr"
$mgroupChrPr = "\\mgroupChrPr"
$mgrow = "\\mgrow"
$mhideBot = "\\mhideBot"
$mhideLeft = "\\mhideLeft"
$mhideRight = "\\mhideRight"
$mhideTop = "\\mhideTop"
$minterSp = "\\minterSp"
$mintLim = "\\mintLim"
$mintraSp = "\\mintraSp"
$mjc = "\\mjc"
$mlim = "\\mlim"
$mlimloc = "\\mlimloc"
$mlimlow = "\\mlimlow"
$mlimlowPr = "\\mlimlowPr"
$mlimupp = "\\mlimupp"
$mlimuppPr = "\\mlimuppPr"
$mlit = "\\mlit"
$mlMargin = "\\mlMargin"
$mm = "\\mm"
$mmath = "\\mmath"
$mmathFont = "\\mmathFont"
$mmathPict = "\\mmathPict"
$mmathPr = "\\mmathPr"
$mmaxdist = "\\mmaxdist"
$mmc = "\\mmc"
$mmcJc = "\\mmcJc"
$mmcPr = "\\mmcPr"
$mmcs = "\\mmcs"
$mmPr = "\\mmPr"
$mmr = "\\mmr"
$mnary = "\\mnary"
$mnaryLim = "\\mnaryLim"
$mnaryPr = "\\mnaryPr"
$mnoBreak = "\\mnoBreak"
$mnor = "\\mnor"
$mnum = "\\mnum"
$mobjDist = "\\mobjDist"
$moMath = "\\moMath"
$moMathPara = "\\moMathPara"
$moMathParaPr = "\\moMathParaPr"
$mopEmu = "\\mopEmu"
$mphant = "\\mphant"
$mphantPr = "\\mphantPr"
$mplcHide = "\\mplcHide"
$mpos = "\\mpos"
$mpostSp = "\\mpostSp"
$mpreSp = "\\mpreSp"
$mr = "\\mr"
$mrad = "\\mrad"
$mradPr = "\\mradPr"
$mrMargin = "\\mrMargin"
$mrPr = "\\mrPr"
$mrSp = "\\mrSp"
$mrSpRule = "\\mrSpRule"
$mscr = "\\mscr"
$msepChr = "\\msepChr"
$mshow = "\\mshow"
$mshp = "\\mshp"
$msmallFrac = "\\msmallFrac"
$msPre = "\\msPre"
$msPrePr = "\\msPrePr"
$msSub = "\\msSub"
$msSubPr = "\\msSubPr"
$msSubSup = "\\msSubSup"
$msSubSupPr = "\\msSubSupPr"
$msSup = "\\msSup"
$msSupPr = "\\msSupPr"
$mstrikeBLTR = "\\mstrikeBLTR"
$mstrikeH = "\\mstrikeH"
$mstrikeTLBR = "\\mstrikeTLBR"
$mstrikeV = "\\mstrikeV"
$msty = "\\msty"
$msub = "\\msub"
$msubHide = "\\msubHide"
$msup = "\\msup"
$msupHide = "\\msupHide"
$mtransp = "\\mtransp"
$mtype = "\\mtype"
$mvertJc = "\\mvertJc"
$mwrapIndent = "\\mwrapIndent"
$mwrapRight = "\\mwrapRight"
$mzeroAsc = "\\mzeroAsc"
$mzeroDesc = "\\mzeroDesc"
$mzeroWid = "\\mzeroWid"
condition:
any of them
}
rule rtf_outlook
{
strings:
$ebcstart = "\\ebcstart"
$ebcend = "\\ebcend"
condition:
any of them
}
rule rtf_objects
{
strings:
$linkself = "\\linkself"
$objalias = "\\objalias"
$objalign = "\\objalign"
$objattph = "\\objattph"
$objautlink = "\\objautlink"
$objclass = "\\objclass"
$objcropb = "\\objcropb"
$objcropl = "\\objcropl"
$objcropr = "\\objcropr"
$objcropt = "\\objcropt"
$objdata = "\\objdata"
$object = "\\object"
$objemb = "\\objemb"
$objh = "\\objh"
$objhtml = "\\objhtml"
$objicemb = "\\objicemb"
$objlink = "\\objlink"
$objlock = "\\objlock"
$objname = "\\objname"
$objocx = "\\objocx"
$objpub = "\\objpub"
$objscalex = "\\objscalex"
$objscaley = "\\objscaley"
$objsect = "\\objsect"
$objsetsize = "\\objsetsize"
$objsub = "\\objsub"
$objtime = "\\objtime"
$objtransy = "\\objtransy"
$objupdate = "\\objupdate"
$objw = "\\objw"
$oleclsid = "\\oleclsid"
$result = "\\result"
$rsltbmp = "\\rsltbmp"
$rslthtml = "\\rslthtml"
$rsltmerge = "\\rsltmerge"
$rsltpict = "\\rsltpict"
$rsltrtf = "\\rsltrtf"
$rslttxt = "\\rslttxt"
condition:
any of them
}
rule rtf_paragraph
{
strings:
$box = "\\box"
$brdrb = "\\brdrb"
$brdrbar = "\\brdrbar"
$brdrbtw = "\\brdrbtw"
$brdrcf = "\\brdrcf"
$brdrdash = "\\brdrdash"
$brdrdashd = "\\brdrdashd"
$brdrdashdd = "\\brdrdashdd"
$brdrdashdot = "\\brdrdashdot"
$brdrdashdotdot = "\\brdrdashdotdot"
$brdrdashdotstr = "\\brdrdashdotstr"
$brdrdashsm = "\\brdrdashsm"
$brdrdb = "\\brdrdb"
$brdrdot = "\\brdrdot"
$brdremboss = "\\brdremboss"
$brdrengrave = "\\brdrengrave"
$brdrframe = "\\brdrframe"
$brdrhair = "\\brdrhair"
$brdrinset = "\\brdrinset"
$brdrl = "\\brdrl"
$brdrnil = "\\brdrnil"
$brdrnone = "\\brdrnone"
$brdroutset = "\\brdroutset"
$brdrr = "\\brdrr"
$brdrs = "\\brdrs"
$brdrsh = "\\brdrsh"
$brdrt = "\\brdrt"
$brdrtbl = "\\brdrtbl"
$brdrth = "\\brdrth"
$brdrthtnlg = "\\brdrthtnlg"
$brdrthtnmg = "\\brdrthtnmg"
$brdrthtnsg = "\\brdrthtnsg"
$brdrtnthlg = "\\brdrtnthlg"
$brdrtnthmg = "\\brdrtnthmg"
$brdrtnthsg = "\\brdrtnthsg"
$brdrtnthtnlg = "\\brdrtnthtnlg"
$brdrtnthtnmg = "\\brdrtnthtnmg"
$brdrtnthtnsg = "\\brdrtnthtnsg"
$brdrtriple = "\\brdrtriple"
$brdrw = "\\brdrw"
$brdrwavy = "\\brdrwavy"
$brdrwavydb = "\\brdrwavydb"
$brsp = "\\brsp"
$aspalpha = "\\aspalpha"
$aspnum = "\\aspnum"
$collapsed = "\\collapsed"
$contextualspace = "\\contextualspace"
$cufi = "\\cufi"
$culi = "\\culi"
$curi = "\\curi"
$faauto = "\\faauto"
$facenter = "\\facenter"
$fafixed = "\\fafixed"
$fahang = "\\fahang"
$faroman = "\\faroman"
$favar = "\\favar"
$fi = "\\fi"
$hyphpar = "\\hyphpar"
$indmirror = "\\indmirror"
$intbl = "\\intbl"
$itap = "\\itap"
$keep = "\\keep"
$keepn = "\\keepn"
$level = "\\level"
$li = "\\li"
$lin = "\\lin"
$lisa = "\\lisa"
$lisb = "\\lisb"
$ltrpar = "\\ltrpar"
$nocwrap = "\\nocwrap"
$noline = "\\noline"
$nooverflow = "\\nooverflow"
$nosnaplinegrid = "\\nosnaplinegrid"
$nowidctlpar = "\\nowidctlpar"
$nowwrap = "\\nowwrap"
$outlinelevel = "\\outlinelevel"
$pagebb = "\\pagebb"
$pard = "\\pard"
$prauth = "\\prauth"
$prdate = "\\prdate"
$qc = "\\qc"
$qd = "\\qd"
$qj = "\\qj"
$qk = "\\qk"
$ql = "\\ql"
$qr = "\\qr"
$qt = "\\qt"
$ri = "\\ri"
$rin = "\\rin"
$rtlpar = "\\rtlpar"
$s = "\\s"
$sa = "\\sa"
$saauto = "\\saauto"
$sb = "\\sb"
$sbauto = "\\sbauto"
$sbys = "\\sbys"
$sl = "\\sl"
$slmult = "\\slmult"
$spv = "\\spv"
$subdocument = "\\subdocument"
$tscbandhorzeven = "\\tscbandhorzeven"
$tscbandhorzodd = "\\tscbandhorzodd"
$tscbandverteven = "\\tscbandverteven"
$tscbandvertodd = "\\tscbandvertodd"
$tscfirstcol = "\\tscfirstcol"
$tscfirstrow = "\\tscfirstrow"
$tsclastcol = "\\tsclastcol"
$tsclastrow = "\\tsclastrow"
$tscnecell = "\\tscnecell"
$tscnwcell = "\\tscnwcell"
$tscsecell = "\\tscsecell"
$tscswcell = "\\tscswcell"
$txbxtwalways = "\\txbxtwalways"
$txbxtwfirst = "\\txbxtwfirst"
$txbxtwfirstlast = "\\txbxtwfirstlast"
$txbxtwlast = "\\txbxtwlast"
$txbxtwno = "\\txbxtwno"
$widctlpar = "\\widctlpar"
$yts = "\\yts"
$pgp = "\\pgp"
$pgptbl = "\\pgptbl"
$ipgp = "\\ipgp"
$dfrauth = "\\dfrauth"
$dfrdate = "\\dfrdate"
$dfrstart = "\\dfrstart"
$dfrstop = "\\dfrstop"
$dfrxst = "\\dfrxst"
$bgbdiag = "\\bgbdiag"
$bgcross = "\\bgcross"
$bgdcross = "\\bgdcross"
$bgdkbdiag = "\\bgdkbdiag"
$bgdkcross = "\\bgdkcross"
$bgdkdcross = "\\bgdkdcross"
$bgdkfdiag = "\\bgdkfdiag"
$bgdkhoriz = "\\bgdkhoriz"
$bgdkvert = "\\bgdkvert"
$bgfdiag = "\\bgfdiag"
$bghoriz = "\\bghoriz"
$bgvert = "\\bgvert"
$cbpat = "\\cbpat"
$cfpat = "\\cfpat"
$shading = "\\shading"
condition:
any of them
}
rule rtf_pictures
{
strings:
$bin = "\\bin"
$bliptag = "\\bliptag"
$blipuid = "\\blipuid"
$blipupi = "\\blipupi"
$defshp = "\\defshp"
$dibitmap = "\\dibitmap"
$emfblip = "\\emfblip"
$jpegblip = "\\jpegblip"
$macpict = "\\macpict"
$nonshppict = "\\nonshppict"
$picbmp = "\\picbmp"
$picbpp = "\\picbpp"
$piccropb = "\\piccropb"
$piccropl = "\\piccropl"
$piccropr = "\\piccropr"
$piccropt = "\\piccropt"
$pich = "\\pich"
$pichgoal = "\\pichgoal"
$picprop = "\\picprop"
$picscaled = "\\picscaled"
$picscalex = "\\picscalex"
$picscaley = "\\picscaley"
$pict = "\\pict"
$picw = "\\picw"
$picwgoal = "\\picwgoal"
$pmmetafile = "\\pmmetafile"
$pngblip = "\\pngblip"
$shppict = "\\shppict"
$wbitmap = "\\wbitmap"
$wbmbitspixel = "\\wbmbitspixel"
$wbmplanes = "\\wbmplanes"
$wbmwidthbyte = "\\wbmwidthbyte"
$wmetafile = "\\wmetafile"
condition:
any of them
}
rule rtf_position
{
strings:
$absh = "\\absh"
$abslock = "\\abslock"
$absnoovrlp = "\\absnoovrlp"
$absw = "\\absw"
$dfrmtxtx = "\\dfrmtxtx"
$dfrmtxty = "\\dfrmtxty"
$dropcapli = "\\dropcapli"
$dropcapt = "\\dropcapt"
$dxfrtext = "\\dxfrtext"
$frmtxbtlr = "\\frmtxbtlr"
$frmtxlrtb = "\\frmtxlrtb"
$frmtxlrtbv = "\\frmtxlrtbv"
$frmtxtbrl = "\\frmtxtbrl"
$frmtxtbrlv = "\\frmtxtbrlv"
$nowrap = "\\nowrap"
$overlay = "\\overlay"
$phcol = "\\phcol"
$phmrg = "\\phmrg"
$phpg = "\\phpg"
$posnegx = "\\posnegx"
$posnegy = "\\posnegy"
$posx = "\\posx"
$posxc = "\\posxc"
$posxi = "\\posxi"
$posxl = "\\posxl"
$posxo = "\\posxo"
$posxr = "\\posxr"
$posy = "\\posy"
$posyb = "\\posyb"
$posyc = "\\posyc"
$posyil = "\\posyil"
$posyin = "\\posyin"
$posyout = "\\posyout"
$posyt = "\\posyt"
$pvmrg = "\\pvmrg"
$pvpara = "\\pvpara"
$pvpg = "\\pvpg"
$wraparound = "\\wraparound"
$wrapdefault = "\\wrapdefault"
$wrapthrough = "\\wrapthrough"
$wraptight = "\\wraptight"
condition:
any of them
}
rule rtf_protection
{
strings:
$protend = "\\protend"
$protstart = "\\protstart"
$protusertbl = "\\protusertbl"
condition:
any of them
}
rule rtf_quick_styles
{
strings:
$noqfpromote = "\\noqfpromote"
condition:
any of them
}
rule rtf_password
{
strings:
$password = <PASSWORD>"
$passwordhash = <PASSWORD>"
condition:
any of them
}
rule rtf_revision
{
strings:
$pnrauth = "\\pnrauth"
$pnrdate = "\\pnrdate"
$pnrnfc = "\\pnrnfc"
$pnrnot = "\\pnrnot"
$pnrpnbr = "\\pnrpnbr"
$pnrrgb = "\\pnrrgb"
$pnrstart = "\\pnrstart"
$pnrstop = "\\pnrstop"
$pnrxst = "\\pnrxst"
condition:
any of them
}
rule rtf_version
{
strings:
$rtf = "\\rtf"
condition:
any of them
}
rule rtf_section
{
strings:
$adjustright = "\\adjustright"
$binfsxn = "\\binfsxn"
$binsxn = "\\binsxn"
$colno = "\\colno"
$cols = "\\cols"
$colsr = "\\colsr"
$colsx = "\\colsx"
$colw = "\\colw"
$ds = "\\ds"
$endnhere = "\\endnhere"
$footery = "\\footery"
$guttersxn = "\\guttersxn"
$headery = "\\headery"
$horzsect = "\\horzsect"
$linebetcol = "\\linebetcol"
$linecont = "\\linecont"
$linemod = "\\linemod"
$lineppage = "\\lineppage"
$linerestart = "\\linerestart"
$linestarts = "\\linestarts"
$linex = "\\linex"
$lndscpsxn = "\\lndscpsxn"
$ltrsect = "\\ltrsect"
$margbsxn = "\\margbsxn"
$marglsxn = "\\marglsxn"
$margmirsxn = "\\margmirsxn"
$margrsxn = "\\margrsxn"
$margtsxn = "\\margtsxn"
$pghsxn = "\\pghsxn"
$pgnbidia = "\\pgnbidia"
$pgnbidib = "\\pgnbidib"
$pgnchosung = "\\pgnchosung"
$pgncnum = "\\pgncnum"
$pgncont = "\\pgncont"
$pgndbnum = "\\pgndbnum"
$pgndbnumd = "\\pgndbnumd"
$pgndbnumk = "\\pgndbnumk"
$pgndbnumt = "\\pgndbnumt"
$pgndec = "\\pgndec"
$pgndecd = "\\pgndecd"
$pgnganada = "\\pgnganada"
$pgngbnum = "\\pgngbnum"
$pgngbnumd = "\\pgngbnumd"
$pgngbnumk = "\\pgngbnumk"
$pgngbnuml = "\\pgngbnuml"
$pgnhindia = "\\pgnhindia"
$pgnhindib = "\\pgnhindib"
$pgnhindic = "\\pgnhindic"
$pgnhindid = "\\pgnhindid"
$pgnhn = "\\pgnhn"
$pgnhnsc = "\\pgnhnsc"
$pgnhnsh = "\\pgnhnsh"
$pgnhnsm = "\\pgnhnsm"
$pgnhnsn = "\\pgnhnsn"
$pgnhnsp = "\\pgnhnsp"
$pgnid = "\\pgnid"
$pgnlcltr = "\\pgnlcltr"
$pgnlcrm = "\\pgnlcrm"
$pgnrestart = "\\pgnrestart"
$pgnstarts = "\\pgnstarts"
$pgnthaia = "\\pgnthaia"
$pgnthaib = "\\pgnthaib"
$pgnthaic = "\\pgnthaic"
$pgnucltr = "\\pgnucltr"
$pgnucrm = "\\pgnucrm"
$pgnvieta = "\\pgnvieta"
$pgnx = "\\pgnx"
$pgny = "\\pgny"
$pgnzodiac = "\\pgnzodiac"
$pgnzodiacd = "\\pgnzodiacd"
$pgnzodiacl = "\\pgnzodiacl"
$pgwsxn = "\\pgwsxn"
$pnseclvl = "\\pnseclvl"
$rtlsect = "\\rtlsect"
$saftnnalc = "\\saftnnalc"
$saftnnar = "\\saftnnar"
$saftnnauc = "\\saftnnauc"
$saftnnchi = "\\saftnnchi"
$saftnnchosung = "\\saftnnchosung"
$saftnncnum = "\\saftnncnum"
$saftnndbar = "\\saftnndbar"
$saftnndbnum = "\\saftnndbnum"
$saftnndbnumd = "\\saftnndbnumd"
$saftnndbnumk = "\\saftnndbnumk"
$saftnndbnumt = "\\saftnndbnumt"
$saftnnganada = "\\saftnnganada"
$saftnngbnum = "\\saftnngbnum"
$saftnngbnumd = "\\saftnngbnumd"
$saftnngbnumk = "\\saftnngbnumk"
$saftnngbnuml = "\\saftnngbnuml"
$saftnnrlc = "\\saftnnrlc"
$saftnnruc = "\\saftnnruc"
$saftnnzodiac = "\\saftnnzodiac"
$saftnnzodiacd = "\\saftnnzodiacd"
$saftnnzodiacl = "\\saftnnzodiacl"
$saftnrestart = "\\saftnrestart"
$saftnrstcont = "\\saftnrstcont"
$saftnstart = "\\saftnstart"
$sbkcol = "\\sbkcol"
$sbkeven = "\\sbkeven"
$sbknone = "\\sbknone"
$sbkodd = "\\sbkodd"
$sbkpage = "\\sbkpage"
$sectd = "\\sectd"
$sectdefaultcl = "\\sectdefaultcl"
$sectexpand = "\\sectexpand"
$sectlinegrid = "\\sectlinegrid"
$sectspecifycl = "\\sectspecifycl"
$sectspecifygen = "\\sectspecifygen"
$sectspecifyl = "\\sectspecifyl"
$sectunlocked = "\\sectunlocked"
$sftnbj = "\\sftnbj"
$sftnnalc = "\\sftnnalc"
$sftnnar = "\\sftnnar"
$sftnnauc = "\\sftnnauc"
$sftnnchi = "\\sftnnchi"
$sftnnchosung = "\\sftnnchosung"
$sftnncnum = "\\sftnncnum"
$sftnndbar = "\\sftnndbar"
$sftnndbnum = "\\sftnndbnum"
$sftnndbnumd = "\\sftnndbnumd"
$sftnndbnumk = "\\sftnndbnumk"
$sftnndbnumt = "\\sftnndbnumt"
$sftnnganada = "\\sftnnganada"
$sftnngbnum = "\\sftnngbnum"
$sftnngbnumd = "\\sftnngbnumd"
$sftnngbnumk = "\\sftnngbnumk"
$sftnngbnuml = "\\sftnngbnuml"
$sftnnrlc = "\\sftnnrlc"
$sftnnruc = "\\sftnnruc"
$sftnnzodiac = "\\sftnnzodiac"
$sftnnzodiacd = "\\sftnnzodiacd"
$sftnnzodiacl = "\\sftnnzodiacl"
$sftnrestart = "\\sftnrestart"
$sftnrstcont = "\\sftnrstcont"
$sftnrstpg = "\\sftnrstpg"
$sftnstart = "\\sftnstart"
$sftntj = "\\sftntj"
$srauth = "\\srauth"
$srdate = "\\srdate"
$titlepg = "\\titlepg"
$vertal = "\\vertal"
$vertalb = "\\vertalb"
$vertalc = "\\vertalc"
$vertalj = "\\vertalj"
$vertalt = "\\vertalt"
$vertsect = "\\vertsect"
$stextflow = "\\stextflow"
condition:
any of them
}
rule rtf_tag
{
strings:
$factoidname = "\\factoidname"
condition:
any of them
}
rule rtf_special_hex
{
strings:
$hex = "\\'"
condition:
any of them
}
rule rtf_special_ignore
{
strings:
$ignore = "\\*"
condition:
any of them
}
rule rtf_special
{
strings:
$hyphen = "\\-"
$subentry = "\\:"
$nonbreakhyphen = "\\_"
$formula = "\\|"
$nonbreakspace = "\\~"
/*
${ = "\\{"
$} = "\\}"
*/
$bullet = "\\bullet"
$chatn = "\\chatn"
$chdate = "\\chdate"
$chdpa = "\\chdpa"
$chdpl = "\\chdpl"
$chftn = "\\chftn"
$chftnsep = "\\chftnsep"
$chftnsepc = "\\chftnsepc"
$chpgn = "\\chpgn"
$chtime = "\\chtime"
$column = "\\column"
$emdash = "\\emdash"
$emspace = "\\emspace"
$endash = "\\endash"
$enspace = "\\enspace"
$lbr = "\\lbr"
$ldblquote = "\\ldblquote"
$line = "\\line"
$lquote = "\\lquote"
$ltrmark = "\\ltrmark"
$page = "\\page"
$par = "\\par"
$qmspace = "\\qmspace"
$rdblquote = "\\rdblquote"
$row = "\\row"
$rquote = "\\rquote"
$rtlmark = "\\rtlmark"
$sect = "\\sect"
$sectnum = "\\sectnum"
$softcol = "\\softcol"
$softlheight = "\\softlheight"
$softline = "\\softline"
$softpage = "\\softpage"
$tab = "\\tab"
$zwbo = "\\zwbo"
$zwj = "\\zwj"
$zwnbo = "\\zwnbo"
$zwnj = "\\zwnj"
condition:
any of them
}
rule rtf_styles
{
strings:
$latentstyles = "\\latentstyles"
$lsdlocked = "\\lsdlocked"
$lsdlockeddef = "\\lsdlockeddef"
$lsdlockedexcept = "\\lsdlockedexcept"
$lsdpriority = "\\lsdpriority"
$lsdprioritydef = "\\lsdprioritydef"
$lsdqformat = "\\lsdqformat"
$lsdqformatdef = "\\lsdqformatdef"
$lsdsemihidden = "\\lsdsemihidden"
$lsdsemihiddendef = "\\lsdsemihiddendef"
$lsdstimax = "\\lsdstimax"
$lsdunhideused = "\\lsdunhideused"
$lsdunhideuseddef = "\\lsdunhideuseddef"
$additive = "\\additive"
$alt = "\\alt"
$ctrl = "\\ctrl"
$fn = "\\fn"
$keycode = "\\keycode"
$sautoupd = "\\sautoupd"
$sbasedon = "\\sbasedon"
$scompose = "\\scompose"
$shidden = "\\shidden"
$shift = "\\shift"
$slink = "\\slink"
$slocked = "\\slocked"
$snext = "\\snext"
$spersonal = "\\spersonal"
$spriority = "\\spriority"
$sqformat = "\\sqformat"
$sreply = "\\sreply"
$ssemihidden = "\\ssemihidden"
$stylesheet = "\\stylesheet"
$styrsid = "\\styrsid"
$sunhideused = "\\sunhideused"
$ts = "\\ts"
$tsrowd = "\\tsrowd"
condition:
any of them
}
rule rtf_tables
{
strings:
$cell = "\\cell"
$cellx = "\\cellx"
$clbgbdiag = "\\clbgbdiag"
$clbgcross = "\\clbgcross"
$clbgdcross = "\\clbgdcross"
$clbgdkbdiag = "\\clbgdkbdiag"
$clbgdkcross = "\\clbgdkcross"
$clbgdkdcross = "\\clbgdkdcross"
$clbgdkfdiag = "\\clbgdkfdiag"
$clbgdkhor = "\\clbgdkhor"
$clbgdkvert = "\\clbgdkvert"
$clbgfdiag = "\\clbgfdiag"
$clbghoriz = "\\clbghoriz"
$clbgvert = "\\clbgvert"
$clbrdrb = "\\clbrdrb"
$clbrdrl = "\\clbrdrl"
$clbrdrr = "\\clbrdrr"
$clbrdrt = "\\clbrdrt"
$clcbpat = "\\clcbpat"
$clcbpatraw = "\\clcbpatraw"
$clcfpat = "\\clcfpat"
$clcfpatraw = "\\clcfpatraw"
$cldel2007 = "\\cldel2007"
$cldelauth = "\\cldelauth"
$cldeldttm = "\\cldeldttm"
$cldgll = "\\cldgll"
$cldglu = "\\cldglu"
$clFitText = "\\clFitText"
$clftsWidth = "\\clftsWidth"
$clhidemark2007 = "\\clhidemark2007"
$clins2007 = "\\clins2007"
$clinsauth = "\\clinsauth"
$clinsdttm = "\\clinsdttm"
$clmgf = "\\clmgf"
$clmrg = "\\clmrg"
$clmrgd = "\\clmrgd"
$clmrgdauth = "\\clmrgdauth"
$clmrgddttm = "\\clmrgddttm"
$clmrgdr = "\\clmrgdr"
$clNoWrap = "\\clNoWrap"
$clpadb = "\\clpadb"
$clpadfb = "\\clpadfb"
$clpadfl = "\\clpadfl"
$clpadfr = "\\clpadfr"
$clpadft = "\\clpadft"
$clpadl = "\\clpadl"
$clpadr = "\\clpadr"
$clpadt = "\\clpadt"
$clspb = "\\clspb"
$clspfb = "\\clspfb"
$clspfl = "\\clspfl"
$clspfr = "\\clspfr"
$clspft = "\\clspft"
$clspl = "\\clspl"
$clspr = "\\clspr"
$clspt = "\\clspt"
$clshdng = "\\clshdng"
$clshdngraw = "\\clshdngraw"
$clshdrawnil = "\\clshdrawnil"
$clsplit = "\\clsplit"
$clsplitr = "\\clsplitr"
$cltxbtlr = "\\cltxbtlr"
$cltxlrtb = "\\cltxlrtb"
$cltxlrtbv = "\\cltxlrtbv"
$cltxtbrl = "\\cltxtbrl"
$cltxtbrlv = "\\cltxtbrlv"
$clvertalb = "\\clvertalb"
$clvertalc = "\\clvertalc"
$clvertalt = "\\clvertalt"
$clvmgf = "\\clvmgf"
$clvmrg = "\\clvmrg"
$clwWidth = "\\clwWidth"
$irowband = "\\irowband"
$irow = "\\irow"
$lastrow = "\\lastrow"
$ltrrow = "\\ltrrow"
$nestcell = "\\nestcell"
$nestrow = "\\nestrow"
$nesttableprops = "\\nesttableprops"
$nonesttables = "\\nonesttables"
$rawclbgdkbdiag = "\\rawclbgdkbdiag"
$rawclbgbdiag = "\\rawclbgbdiag"
$rawclbgcross = "\\rawclbgcross"
$rawclbgdcross = "\\rawclbgdcross"
$rawclbgdkcross = "\\rawclbgdkcross"
$rawclbgdkdcross = "\\rawclbgdkdcross"
$rawclbgdkfdiag = "\\rawclbgdkfdiag"
$rawclbgdkhor = "\\rawclbgdkhor"
$rawclbgdkvert = "\\rawclbgdkvert"
$rawclbgfdiag = "\\rawclbgfdiag"
$rawclbghoriz = "\\rawclbghoriz"
$rawclbgvert = "\\rawclbgvert"
$rtlrow = "\\rtlrow"
$tabsnoovrlp = "\\tabsnoovrlp"
$taprtl = "\\taprtl"
$tblind = "\\tblind"
$tblindtype = "\\tblindtype"
$tbllkbestfit = "\\tbllkbestfit"
$tbllkborder = "\\tbllkborder"
$tbllkcolor = "\\tbllkcolor"
$tbllkfont = "\\tbllkfont"
$tbllkhdrcols = "\\tbllkhdrcols"
$tbllkhdrrows = "\\tbllkhdrrows"
$tbllklastcol = "\\tbllklastcol"
$tbllklastrow = "\\tbllklastrow"
$tbllknocolband = "\\tbllknocolband"
$tbllknorowband = "\\tbllknorowband"
$tbllkshading = "\\tbllkshading"
$tcelld = "\\tcelld"
$tdfrmtxtBottom = "\\tdfrmtxtBottom"
$tdfrmtxtLeft = "\\tdfrmtxtLeft"
$tdfrmtxtRight = "\\tdfrmtxtRight"
$tdfrmtxtTop = "\\tdfrmtxtTop"
$tphcol = "\\tphcol"
$tphmrg = "\\tphmrg"
$tphpg = "\\tphpg"
$tposnegx = "\\tposnegx"
$tposnegy = "\\tposnegy"
$tposxc = "\\tposxc"
$tposxi = "\\tposxi"
$tposxl = "\\tposxl"
$tposx = "\\tposx"
$tposxo = "\\tposxo"
$tposxr = "\\tposxr"
$tposy = "\\tposy"
$tposyb = "\\tposyb"
$tposyc = "\\tposyc"
$tposyil = "\\tposyil"
$tposyin = "\\tposyin"
$tposyout = "\\tposyout"
$tposyt = "\\tposyt"
$tpvmrg = "\\tpvmrg"
$tpvpara = "\\tpvpara"
$tpvpg = "\\tpvpg"
$trauth = "\\trauth"
$trautofit = "\\trautofit"
$trbgbdiag = "\\trbgbdiag"
$trbgcross = "\\trbgcross"
$trbgdcross = "\\trbgdcross"
$trbgdkbdiag = "\\trbgdkbdiag"
$trbgdkcross = "\\trbgdkcross"
$trbgdkdcross = "\\trbgdkdcross"
$trbgdkfdiag = "\\trbgdkfdiag"
$trbgdkhor = "\\trbgdkhor"
$trbgdkvert = "\\trbgdkvert"
$trbgfdiag = "\\trbgfdiag"
$trbghoriz = "\\trbghoriz"
$trbgvert = "\\trbgvert"
$trbrdrb = "\\trbrdrb"
$trbrdrh = "\\trbrdrh"
$trbrdrl = "\\trbrdrl"
$trbrdrr = "\\trbrdrr"
$trbrdrt = "\\trbrdrt"
$trbrdrv = "\\trbrdrv"
$trcbpat = "\\trcbpat"
$trcfpat = "\\trcfpat"
$trdate = "\\trdate"
$trftsWidthA = "\\trftsWidthA"
$trftsWidthB = "\\trftsWidthB"
$trftsWidth = "\\trftsWidth"
$trgaph = "\\trgaph"
$trhdr = "\\trhdr"
$trkeep = "\\trkeep"
$trkeepfollow = "\\trkeepfollow"
$trleft = "\\trleft"
$trowd = "\\trowd"
$trpaddb = "\\trpaddb"
$trpaddfb = "\\trpaddfb"
$trpaddfl = "\\trpaddfl"
$trpaddfr = "\\trpaddfr"
$trpaddft = "\\trpaddft"
$trpaddl = "\\trpaddl"
$trpaddr = "\\trpaddr"
$trpaddt = "\\trpaddt"
$trpadob = "\\trpadob"
$trpadofb = "\\trpadofb"
$trpadofl = "\\trpadofl"
$trpadofr = "\\trpadofr"
$trpadoft = "\\trpadoft"
$trpadol = "\\trpadol"
$trpador = "\\trpador"
$trpadot = "\\trpadot"
$trpat = "\\trpat"
$trqc = "\\trqc"
$trql = "\\trql"
$trqr = "\\trqr"
$trrh = "\\trrh"
$trshdng = "\\trshdng"
$trspdb = "\\trspdb"
$trspdfb = "\\trspdfb"
$trspdfl = "\\trspdfl"
$trspdfr = "\\trspdfr"
$trspdft = "\\trspdft"
$trspdl = "\\trspdl"
$trspdr = "\\trspdr"
$trspdt = "\\trspdt"
$trspob = "\\trspob"
$trspofb = "\\trspofb"
$trspofl = "\\trspofl"
$trspofr = "\\trspofr"
$trspoft = "\\trspoft"
$trspol = "\\trspol"
$trspor = "\\trspor"
$trspot = "\\trspot"
$trwWidthA = "\\trwWidthA"
$trwWidthB = "\\trwWidthB"
$trwWidth = "\\trwWidth"
$tc = "\\tc"
$tcf = "\\tcf"
$tcl = "\\tcl"
$tcn = "\\tcn"
$tsbgbdiag = "\\tsbgbdiag"
$tsbgcross = "\\tsbgcross"
$tsbgdcross = "\\tsbgdcross"
$tsbgdkbdiag = "\\tsbgdkbdiag"
$tsbgdkcross = "\\tsbgdkcross"
$tsbgdkdcross = "\\tsbgdkdcross"
$tsbgdkfdiag = "\\tsbgdkfdiag"
$tsbgdkhor = "\\tsbgdkhor"
$tsbgdkvert = "\\tsbgdkvert"
$tsbgfdiag = "\\tsbgfdiag"
$tsbghoriz = "\\tsbghoriz"
$tsbgvert = "\\tsbgvert"
$tsbrdrb = "\\tsbrdrb"
$tsbrdrdgl = "\\tsbrdrdgl"
$tsbrdrdgr = "\\tsbrdrdgr"
$tsbrdrh = "\\tsbrdrh"
$tsbrdrl = "\\tsbrdrl"
$tsbrdrr = "\\tsbrdrr"
$tsbrdrt = "\\tsbrdrt"
$tsbrdrv = "\\tsbrdrv"
$tscbandsh = "\\tscbandsh"
$tscbandsv = "\\tscbandsv"
$tscellcbpat = "\\tscellcbpat"
$tscellcfpat = "\\tscellcfpat"
$tscellpaddb = "\\tscellpaddb"
$tscellpaddfb = "\\tscellpaddfb"
$tscellpaddfl = "\\tscellpaddfl"
$tscellpaddfr = "\\tscellpaddfr"
$tscellpaddft = "\\tscellpaddft"
$tscellpaddl = "\\tscellpaddl"
$tscellpaddr = "\\tscellpaddr"
$tscellpaddt = "\\tscellpaddt"
$tscellpct = "\\tscellpct"
$tscellwidth = "\\tscellwidth"
$tscellwidthfts = "\\tscellwidthfts"
$tsnowrap = "\\tsnowrap"
$tsvertalb = "\\tsvertalb"
$tsvertalc = "\\tsvertalc"
$tsvertalt = "\\tsvertalt"
$tb = "\\tb"
$tldot = "\\tldot"
$tleq = "\\tleq"
$tlhyph = "\\tlhyph"
$tlmdot = "\\tlmdot"
$tlth = "\\tlth"
$tlul = "\\tlul"
$tqc = "\\tqc"
$tqdec = "\\tqdec"
$tqr = "\\tqr"
$tx = "\\tx"
condition:
any of them
}
rule rtf_theme
{
strings:
$themedata = "\\themedata"
$fbimajor = "\\fbimajor"
$fbiminor = "\\fbiminor"
$fdbmajor = "\\fdbmajor"
$fdbminor = "\\fdbminor"
$fhimajor = "\\fhimajor"
$fhiminor = "\\fhiminor"
$flomajor = "\\flomajor"
$flominor = "\\flominor"
$revtbl = "\\revtbl"
$charrsid = "\\charrsid"
$delrsid = "\\delrsid"
$insrsid = "\\insrsid"
$oldcprops = "\\oldcprops"
$oldpprops = "\\oldpprops"
$oldsprops = "\\oldsprops"
$oldtprops = "\\oldtprops"
$pararsid = "\\pararsid"
$rsid = "\\rsid"
$rsidroot = "\\rsidroot"
$rsidtbl = "\\rsidtbl"
$sectrsid = "\\sectrsid"
$tblrsid = "\\tblrsid"
condition:
any of them
}
rule rtf_unicode
{
strings:
$u = "\\u"
$uc = "\\uc"
$ud = "\\ud"
$upr = "\\upr"
condition:
any of them
}
rule rtf_shapes
{
strings:
$shp = "\\shp"
$shpbottom = "\\shpbottom"
$shpbxcolumn = "\\shpbxcolumn"
$shpbxignore = "\\shpbxignore"
$shpbxmargin = "\\shpbxmargin"
$shpbxpage = "\\shpbxpage"
$shpbyignore = "\\shpbyignore"
$shpbymargin = "\\shpbymargin"
$shpbypage = "\\shpbypage"
$shpbypara = "\\shpbypara"
$shpfblwtxt = "\\shpfblwtxt"
$shpfhdr = "\\shpfhdr"
$shpgrp = "\\shpgrp"
$shpinst = "\\shpinst"
$shpleft = "\\shpleft"
$shplid = "\\shplid"
$shplockanchor = "\\shplockanchor"
$shpright = "\\shpright"
$shprslt = "\\shprslt"
$shptop = "\\shptop"
$shptxt = "\\shptxt"
$shpwrk = "\\shpwrk"
$shpwr = "\\shpwr"
$shpz = "\\shpz"
$sn = "\\sn"
$sp = "\\sp"
$sv = "\\sv"
$svb = "\\svb"
condition:
any of them
}
"""
|
en
| 0.569817
|
# Copyright 2020 National Technology & Engineering Solutions of Sandia, LLC # (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. # Government retains certain rights in this software. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Import classes and helpers from the Laika framework counts classes of control words from RTF files #lazy compile rules, not using yara_on_demand due to signatures in string vs. file rule rtf_position_tabs { strings: $pindtabqc = "\\pindtabqc" $pindtabql = "\\pindtabql" $pindtabqr = "\\pindtabqr" $pmartabqc = "\\pmartabqc" $pmartabql = "\\pmartabql" $pmartabqr = "\\pmartabqr" $ptabldot = "\\ptabldot" $ptablmdot = "\\ptablmdot" $ptablminus = "\\ptablminus" $ptablnone = "\\ptablnone" $ptabluscore = "\\ptabluscore" condition: any of them } rule rtf_character_properties { strings: $ab = "\\ab" $acaps = "\\acaps" $acf = "\\acf" $adn = "\\adn" $aexpnd = "\\aexpnd" $af = "\\af" $afs = "\\afs" $ai = "\\ai" $alang = "\\alang" $aoutl = "\\aoutl" $ascaps = "\\ascaps" $ashad = "\\ashad" $astrike = "\\astrike" $aul = "\\aul" $auld = "\\auld" $auldb = "\\auldb" $aulnone = "\\aulnone" $aulw = "\\aulw" $aup = "\\aup" $dbch = "\\dbch" $fcs = "\\fcs" $hich = "\\hich" $loch = "\\loch" condition: any of them } rule rtf_bookmarks { strings: $bkmkcolf = "\\bkmkcolf" $bkmkcoll = "\\bkmkcoll" $bkmkend = "\\bkmkend" $bkmkstart = "\\bkmkstart" $mvfmf = "\\mvfmf" $mvfml = "\\mvfml" $mvtof = "\\mvtof" $mvtol = "\\mvtol" condition: any of them } rule rtf_bullets { strings: $ilvl = "\\ilvl" $listtext = "\\listtext" $pn = "\\pn" $pnacross = "\\pnacross" $pnaiu = "\\pnaiu" $pnaiud = "\\pnaiud" $pnaiueo = "\\pnaiueo" $pnaiueod = "\\pnaiueod" $pnb = "\\pnb" $pnbidia = "\\pnbidia" $pnbidib = "\\pnbidib" $pncaps = "\\pncaps" $pncard = "\\pncard" $pncf = "\\pncf" $pnchosung = "\\pnchosung" $pncnum = "\\pncnum" $pndbnum = "\\pndbnum" $pndbnumd = "\\pndbnumd" $pndbnumk = "\\pndbnumk" $pndbnuml = "\\pndbnuml" $pndbnumt = "\\pndbnumt" $pndec = "\\pndec" $pndecd = "\\pndecd" $pnf = "\\pnf" $pnfs = "\\pnfs" $pnganada = "\\pnganada" $pngbnum = "\\pngbnum" $pngbnumd = "\\pngbnumd" $pngbnumk = "\\pngbnumk" $pngbnuml = "\\pngbnuml" $pnhang = "\\pnhang" $pni = "\\pni" $pnindent = "\\pnindent" $pniroha = "\\pniroha" $pnirohad = "\\pnirohad" $pnlcltr = "\\pnlcltr" $pnlcrm = "\\pnlcrm" $pnlvl = "\\pnlvl" $pnlvlblt = "\\pnlvlblt" $pnlvlbody = "\\pnlvlbody" $pnlvlcont = "\\pnlvlcont" $pnnumonce = "\\pnnumonce" $pnord = "\\pnord" $pnordt = "\\pnordt" $pnprev = "\\pnprev" $pnqc = "\\pnqc" $pnql = "\\pnql" $pnqr = "\\pnqr" $pnrestart = "\\pnrestart" $pnscaps = "\\pnscaps" $pnsp = "\\pnsp" $pnstart = "\\pnstart" $pnstrike = "\\pnstrike" $pntext = "\\pntext" $pntxta = "\\pntxta" $pntxtb = "\\pntxtb" $pnucltr = "\\pnucltr" $pnucrm = "\\pnucrm" $pnul = "\\pnul" $pnuld = "\\pnuld" $pnuldash = "\\pnuldash" $pnuldashd = "\\pnuldashd" $pnuldashdd = "\\pnuldashdd" $pnuldb = "\\pnuldb" $pnulhair = "\\pnulhair" $pnulnone = "\\pnulnone" $pnulth = "\\pnulth" $pnulw = "\\pnulw" $pnulwave = "\\pnulwave" $pnzodiac = "\\pnzodiac" $pnzodiacd = "\\pnzodiacd" $pnzodiacl = "\\pnzodiacl" condition: any of them } rule rtf_characters { strings: $chbgbdiag = "\\chbgbdiag" $chbgcross = "\\chbgcross" $chbgdcross = "\\chbgdcross" $chbgdkbdiag = "\\chbgdkbdiag" $chbgdkcross = "\\chbgdkcross" $chbgdkdcross = "\\chbgdkdcross" $chbgdkfdiag = "\\chbgdkfdiag" $chbgdkhoriz = "\\chbgdkhoriz" $chbgdkvert = "\\chbgdkvert" $chbgfdiag = "\\chbgfdiag" $chbghoriz = "\\chbghoriz" $chbgvert = "\\chbgvert" $chbrdr = "\\chbrdr" $chcbpat = "\\chcbpat" $chcfpat = "\\chcfpat" $chshdng = "\\chshdng" $crauth = "\\crauth" $crdate = "\\crdate" $deleted = "\\deleted" $mvauth = "\\mvauth" $mvdate = "\\mvdate" $mvf = "\\mvf" $mvt = "\\mvt" $revauth = "\\revauth" $revauthdel = "\\revauthdel" $revdttm = "\\revdttm" $revdttmdel = "\\revdttmdel" $revised = "\\revised" $ansi = "\\ansi" $ansicpg = "\\ansicpg" $fbidis = "\\fbidis" $mac = "\\mac" $pc = "\\pc" $pca = "\\pca" $impr = "\\impr" $striked1 = "\\striked1" condition: any of them } rule rtf_codepage { strings: $cpg = "\\cpg" condition: any of them } rule rtf_color { strings: $colorschememapping = "\\colorschememapping" $blue = "\\blue" $caccentfive = "\\caccentfive" $caccentfour = "\\caccentfour" $caccentone = "\\caccentone" $caccentsix = "\\caccentsix" $caccentthree = "\\caccentthree" $caccenttwo = "\\caccenttwo" $cbackgroundone = "\\cbackgroundone" $cbackgroundtwo = "\\cbackgroundtwo" $cfollowedhyperlink = "\\cfollowedhyperlink" $chyperlink = "\\chyperlink" $cmaindarkone = "\\cmaindarkone" $cmaindarktwo = "\\cmaindarktwo" $cmainlightone = "\\cmainlightone" $cmainlighttwo = "\\cmainlighttwo" $colortbl = "\\colortbl" $cshade = "\\cshade" $ctextone = "\\ctextone" $ctexttwo = "\\ctexttwo" $ctint = "\\ctint" $green = "\\green" $red = "\\red" condition: any of them } rule rtf_comments { strings: $annotation = "\\annotation" $atnauthor = "\\atnauthor" $atndate = "\\atndate" $atnicn = "\\atnicn" $atnid = "\\atnid" $atnparent = "\\atnparent" $atnref = "\\atnref" $atntime = "\\atntime" $atrfend = "\\atrfend" $atrfstart = "\\atrfstart" condition: any of them } rule rtf_control_other { strings: $disabled = "\\disabled" $htmlbase = "\\htmlbase" $htmlrtf = "\\htmlrtf" $htmltag = "\\htmltag" $mhtmltag = "\\mhtmltag" $protect = "\\protect" $pwd = "\\pwd" $urtf = "\\urtf" condition: any of them } rule rtf_datastore { strings: $datastore = "\\datastore" condition: any of them } rule rtf_xml { strings: $xmlattr = "\\xmlattr" $xmlattrname = "\\xmlattrname" $xmlattrns = "\\xmlattrns" $xmlattrvalue = "\\xmlattrvalue" $xmlclose = "\\xmlclose" $xmlname = "\\xmlname" $xmlnstbl = "\\xmlnstbl" $xmlopen = "\\xmlopen" $xmlsdttcell = "\\xmlsdttcell" $xmlsdttpara = "\\xmlsdttpara" $xmlsdttregular = "\\xmlsdttregular" $xmlsdttrow = "\\xmlsdttrow" $xmlsdttunknown = "\\xmlsdttunknown" $xmlns = "\\xmlns" condition: any of them } rule rtf_defaults { strings: $adeff = "\\adeff" $adeflang = "\\adeflang" $deff = "\\deff" $deflang = "\\deflang" $deflangfe = "\\deflangfe" $stshfbi = "\\stshfbi" $stshfdbch = "\\stshfdbch" $stshfhich = "\\stshfhich" $stshfloch = "\\stshfloch" $defchp = "\\defchp" $defpap = "\\defpap" condition: any of them } rule rtf_formatting { strings: $aenddoc = "\\aenddoc" $aendnotes = "\\aendnotes" $afelev = "\\afelev" $aftnbj = "\\aftnbj" $aftncn = "\\aftncn" $aftnnalc = "\\aftnnalc" $aftnnar = "\\aftnnar" $aftnnauc = "\\aftnnauc" $aftnnchi = "\\aftnnchi" $aftnnchosung = "\\aftnnchosung" $aftnncnum = "\\aftnncnum" $aftnndbar = "\\aftnndbar" $aftnndbnum = "\\aftnndbnum" $aftnndbnumd = "\\aftnndbnumd" $aftnndbnumk = "\\aftnndbnumk" $aftnndbnumt = "\\aftnndbnumt" $aftnnganada = "\\aftnnganada" $aftnngbnum = "\\aftnngbnum" $aftnngbnumd = "\\aftnngbnumd" $aftnngbnumk = "\\aftnngbnumk" $aftnngbnuml = "\\aftnngbnuml" $aftnnrlc = "\\aftnnrlc" $aftnnruc = "\\aftnnruc" $aftnnzodiac = "\\aftnnzodiac" $aftnnzodiacd = "\\aftnnzodiacd" $aftnnzodiacl = "\\aftnnzodiacl" $aftnrestart = "\\aftnrestart" $aftnrstcont = "\\aftnrstcont" $aftnsep = "\\aftnsep" $aftnsepc = "\\aftnsepc" $aftnstart = "\\aftnstart" $aftntj = "\\aftntj" $allowfieldendsel = "\\allowfieldendsel" $allprot = "\\allprot" $alntblind = "\\alntblind" $annotprot = "\\annotprot" $ApplyBrkRules = "\\ApplyBrkRules" $asianbrkrule = "\\asianbrkrule" $autofmtoverride = "\\autofmtoverride" $background = "\\background" $bdbfhdr = "\\bdbfhdr" $bdrrlswsix = "\\bdrrlswsix" $bookfold = "\\bookfold" $bookfoldrev = "\\bookfoldrev" $bookfoldsheets = "\\bookfoldsheets" $brdrart = "\\brdrart" $brkfrm = "\\brkfrm" $cachedcolbal = "\\cachedcolbal" $cts = "\\cts" $cvmme = "\\cvmme" $defformat = "\\defformat" $deftab = "\\deftab" $dghorigin = "\\dghorigin" $dghshow = "\\dghshow" $dghspace = "\\dghspace" $dgmargin = "\\dgmargin" $dgsnap = "\\dgsnap" $dgvorigin = "\\dgvorigin" $dgvshow = "\\dgvshow" $dgvspace = "\\dgvspace" $dntblnsbdb = "\\dntblnsbdb" $doctemp = "\\doctemp" $doctype = "\\doctype" $donotembedlingdata = "\\donotembedlingdata" $donotembedsysfont = "\\donotembedsysfont" $donotshowcomments = "\\donotshowcomments" $donotshowinsdel = "\\donotshowinsdel" $donotshowmarkup = "\\donotshowmarkup" $donotshowprops = "\\donotshowprops" $enddoc = "\\enddoc" $endnotes = "\\endnotes" $enforceprot = "\\enforceprot" $expshrtn = "\\expshrtn" $facingp = "\\facingp" $fchars = "\\fchars" $felnbrelev = "\\felnbrelev" $fet = "\\fet" $forceupgrade = "\\forceupgrade" $formdisp = "\\formdisp" $formprot = "\\formprot" $formshade = "\\formshade" $fracwidth = "\\fracwidth" $fromhtml = "\\fromhtml" $fromtext = "\\fromtext" $ftnalt = "\\ftnalt" $ftnbj = "\\ftnbj" $ftncn = "\\ftncn" $ftnlytwnine = "\\ftnlytwnine" $ftnnalc = "\\ftnnalc" $ftnnar = "\\ftnnar" $ftnnauc = "\\ftnnauc" $ftnnchi = "\\ftnnchi" $ftnnchosung = "\\ftnnchosung" $ftnncnum = "\\ftnncnum" $ftnndbar = "\\ftnndbar" $ftnndbnum = "\\ftnndbnum" $ftnndbnumd = "\\ftnndbnumd" $ftnndbnumk = "\\ftnndbnumk" $ftnndbnumt = "\\ftnndbnumt" $ftnnganada = "\\ftnnganada" $ftnngbnum = "\\ftnngbnum" $ftnngbnumd = "\\ftnngbnumd" $ftnngbnumk = "\\ftnngbnumk" $ftnngbnuml = "\\ftnngbnuml" $ftnnrlc = "\\ftnnrlc" $ftnnruc = "\\ftnnruc" $ftnnzodiac = "\\ftnnzodiac" $ftnnzodiacd = "\\ftnnzodiacd" $ftnnzodiacl = "\\ftnnzodiacl" $ftnrestart = "\\ftnrestart" $ftnrstcont = "\\ftnrstcont" $ftnrstpg = "\\ftnrstpg" $ftnsep = "\\ftnsep" $ftnsepc = "\\ftnsepc" $ftnstart = "\\ftnstart" $ftntj = "\\ftntj" $grfdocevents = "\\grfdocevents" $gutter = "\\gutter" $gutterprl = "\\gutterprl" $horzdoc = "\\horzdoc" $htmautsp = "\\htmautsp" $hwelev2007 = "\\hwelev2007" $hyphauto = "\\hyphauto" $hyphcaps = "\\hyphcaps" $hyphconsec = "\\hyphconsec" $hyphhotz = "\\hyphhotz" $ignoremixedcontent = "\\ignoremixedcontent" $ilfomacatclnup = "\\ilfomacatclnup" $indrlsweleven = "\\indrlsweleven" $jcompress = "\\jcompress" $jexpand = "\\jexpand" $jsksu = "\\jsksu" $krnprsnet = "\\krnprsnet" $ksulang = "\\ksulang" $landscape = "\\landscape" $lchars = "\\lchars" $linestart = "\\linestart" $linkstyles = "\\linkstyles" $lnbrkrule = "\\lnbrkrule" $lnongrid = "\\lnongrid" $ltrdoc = "\\ltrdoc" $lytcalctblwd = "\\lytcalctblwd" $lytexcttp = "\\lytexcttp" $lytprtmet = "\\lytprtmet" $lyttblrtgr = "\\lyttblrtgr" $makebackup = "\\makebackup" $margb = "\\margb" $margl = "\\margl" $margmirror = "\\margmirror" $margr = "\\margr" $margt = "\\margt" $msmcap = "\\msmcap" $muser = "\\muser" $newtblstyruls = "\\newtblstyruls" $nextfile = "\\nextfile" $noafcnsttbl = "\\noafcnsttbl" $nobrkwrptbl = "\\nobrkwrptbl" $nocolbal = "\\nocolbal" $nocompatoptions = "\\nocompatoptions" $nocxsptable = "\\nocxsptable" $noextrasprl = "\\noextrasprl" $nofeaturethrottle = "\\nofeaturethrottle" $nogrowautofit = "\\nogrowautofit" $noindnmbrts = "\\noindnmbrts" $nojkernpunct = "\\nojkernpunct" $nolead = "\\nolead" $nolnhtadjtbl = "\\nolnhtadjtbl" $nospaceforul = "\\nospaceforul" $notabind = "\\notabind" $notbrkcnstfrctbl = "\\notbrkcnstfrctbl" $notcvasp = "\\notcvasp" $notvatxbx = "\\notvatxbx" $nouicompat = "\\nouicompat" $noultrlspc = "\\noultrlspc" $noxlattoyen = "\\noxlattoyen" $ogutter = "\\ogutter" $oldas = "\\oldas" $oldlinewrap = "\\oldlinewrap" $otblrul = "\\otblrul" $paperh = "\\paperh" $paperw = "\\paperw" $pgbrdrb = "\\pgbrdrb" $pgbrdrfoot = "\\pgbrdrfoot" $pgbrdrhead = "\\pgbrdrhead" $pgbrdrl = "\\pgbrdrl" $pgbrdropt = "\\pgbrdropt" $pgbrdrr = "\\pgbrdrr" $pgbrdrsnap = "\\pgbrdrsnap" $pgbrdrt = "\\pgbrdrt" $pgnstart = "\\pgnstart" $prcolbl = "\\prcolbl" $printdata = "\\printdata" $private = "\\private" $protlevel = "\\protlevel" $psover = "\\psover" $psz = "\\psz" $readonlyrecommended = "\\readonlyrecommended" $readprot = "\\readprot" $relyonvml = "\\relyonvml" $remdttm = "\\remdttm" $rempersonalinfo = "\\rempersonalinfo" $revbar = "\\revbar" $revisions = "\\revisions" $revprop = "\\revprop" $revprot = "\\revprot" $rtldoc = "\\rtldoc" $rtlgutter = "\\rtlgutter" $saveinvalidxml = "\\saveinvalidxml" $saveprevpict = "\\saveprevpict" $showplaceholdtext = "\\showplaceholdtext" $showxmlerrors = "\\showxmlerrors" $snaptogridincell = "\\snaptogridincell" $spltpgpar = "\\spltpgpar" $splytwnine = "\\splytwnine" $sprsbsp = "\\sprsbsp" $sprslnsp = "\\sprslnsp" $sprsspbf = "\\sprsspbf" $sprstsm = "\\sprstsm" $sprstsp = "\\sprstsp" $stylelock = "\\stylelock" $stylelockbackcomp = "\\stylelockbackcomp" $stylelockenforced = "\\stylelockenforced" $stylelockqfset = "\\stylelockqfset" $stylelocktheme = "\\stylelocktheme" $stylesortmethod = "\\stylesortmethod" $subfontbysize = "\\subfontbysize" $swpbdr = "\\swpbdr" $template = "\\template" $themelang = "\\themelang" $themelangcs = "\\themelangcs" $themelangfe = "\\themelangfe" $toplinepunct = "\\toplinepunct" $trackformatting = "\\trackformatting" $trackmoves = "\\trackmoves" $transmf = "\\transmf" $truncatefontheight = "\\truncatefontheight" $truncex = "\\truncex" $tsd = "\\tsd" $twoonone = "\\twoonone" $useltbaln = "\\useltbaln" $usenormstyforlist = "\\usenormstyforlist" $usexform = "\\usexform" $utinl = "\\utinl" $validatexml = "\\validatexml" $vertdoc = "\\vertdoc" $viewbksp = "\\viewbksp" $viewkind = "\\viewkind" $viewnobound = "\\viewnobound" $viewscale = "\\viewscale" $viewzk = "\\viewzk" $wgrffmtfilter = "\\wgrffmtfilter" $widowctrl = "\\widowctrl" $windowcaption = "\\windowcaption" $wpjst = "\\wpjst" $wpsp = "\\wpsp" $wraptrsp = "\\wraptrsp" $writereservation = "\\writereservation" $writereservhash = "\\writereservhash" $wrppunct = "\\wrppunct" $xform = "\\xform" condition: any of them } rule rtf_docvar { strings: $docvar = "\\docvar" condition: any of them } rule rtf_drawing { strings: $hl = "\\hl" $hlfr = "\\hlfr" $hlloc = "\\hlloc" $hlsrc = "\\hlsrc" $hrule = "\\hrule" $hsv = "\\hsv" $do = "\\do" $dobxcolumn = "\\dobxcolumn" $dobxmargin = "\\dobxmargin" $dobxpage = "\\dobxpage" $dobymargin = "\\dobymargin" $dobypage = "\\dobypage" $dobypara = "\\dobypara" $dodhgt = "\\dodhgt" $dolock = "\\dolock" $dpaendhol = "\\dpaendhol" $dpaendl = "\\dpaendl" $dpaendsol = "\\dpaendsol" $dpaendw = "\\dpaendw" $dparc = "\\dparc" $dparcflipx = "\\dparcflipx" $dparcflipy = "\\dparcflipy" $dpastarthol = "\\dpastarthol" $dpastartl = "\\dpastartl" $dpastartsol = "\\dpastartsol" $dpastartw = "\\dpastartw" $dpcallout = "\\dpcallout" $dpcoa = "\\dpcoa" $dpcoaccent = "\\dpcoaccent" $dpcobestfit = "\\dpcobestfit" $dpcoborder = "\\dpcoborder" $dpcodabs = "\\dpcodabs" $dpcodbottom = "\\dpcodbottom" $dpcodcenter = "\\dpcodcenter" $dpcodescent = "\\dpcodescent" $dpcodtop = "\\dpcodtop" $dpcolength = "\\dpcolength" $dpcominusx = "\\dpcominusx" $dpcominusy = "\\dpcominusy" $dpcooffset = "\\dpcooffset" $dpcosmarta = "\\dpcosmarta" $dpcotdouble = "\\dpcotdouble" $dpcotright = "\\dpcotright" $dpcotsingle = "\\dpcotsingle" $dpcottriple = "\\dpcottriple" $dpcount = "\\dpcount" $dpellipse = "\\dpellipse" $dpendgroup = "\\dpendgroup" $dpfillbgcb = "\\dpfillbgcb" $dpfillbgcg = "\\dpfillbgcg" $dpfillbgcr = "\\dpfillbgcr" $dpfillbggray = "\\dpfillbggray" $dpfillbgpal = "\\dpfillbgpal" $dpfillfgcb = "\\dpfillfgcb" $dpfillfgcg = "\\dpfillfgcg" $dpfillfgcr = "\\dpfillfgcr" $dpfillfggray = "\\dpfillfggray" $dpfillfgpal = "\\dpfillfgpal" $dpfillpat = "\\dpfillpat" $dpgroup = "\\dpgroup" $dpline = "\\dpline" $dplinecob = "\\dplinecob" $dplinecog = "\\dplinecog" $dplinecor = "\\dplinecor" $dplinedado = "\\dplinedado" $dplinedadodo = "\\dplinedadodo" $dplinedash = "\\dplinedash" $dplinedot = "\\dplinedot" $dplinegray = "\\dplinegray" $dplinehollow = "\\dplinehollow" $dplinepal = "\\dplinepal" $dplinesolid = "\\dplinesolid" $dplinew = "\\dplinew" $dppolycount = "\\dppolycount" $dppolygon = "\\dppolygon" $dppolyline = "\\dppolyline" $dpptx = "\\dpptx" $dppty = "\\dppty" $dprect = "\\dprect" $dproundr = "\\dproundr" $dpshadow = "\\dpshadow" $dpshadx = "\\dpshadx" $dpshady = "\\dpshady" $dptxbtlr = "\\dptxbtlr" $dptxbx = "\\dptxbx" $dptxbxmar = "\\dptxbxmar" $dptxbxtext = "\\dptxbxtext" $dptxlrtb = "\\dptxlrtb" $dptxlrtbv = "\\dptxlrtbv" $dptxtbrl = "\\dptxtbrl" $dptxtbrlv = "\\dptxtbrlv" $dpx = "\\dpx" $dpxsize = "\\dpxsize" $dpy = "\\dpy" $dpysize = "\\dpysize" condition: any of them } rule rtf_asia { strings: $cgrid = "\\cgrid" $g = "\\g" $gcw = "\\gcw" $gridtbl = "\\gridtbl" $nosectexpand = "\\nosectexpand" $ulhair = "\\ulhair" $horzvert = "\\horzvert" $twoinone = "\\twoinone" condition: any of them } rule rtf_fields { strings: $datafield = "\\datafield" $date = "\\date" $field = "\\field" $fldalt = "\\fldalt" $flddirty = "\\flddirty" $fldedit = "\\fldedit" $fldinst = "\\fldinst" $fldlock = "\\fldlock" $fldpriv = "\\fldpriv" $fldrslt = "\\fldrslt" $fldtype = "\\fldtype" $time = "\\time" $wpeqn = "\\wpeqn" condition: any of them } rule rtf_files { strings: $fid = "\\fid" $file = "\\file" $filetbl = "\\filetbl" $fnetwork = "\\fnetwork" $fnonfilesys = "\\fnonfilesys" $fosnum = "\\fosnum" $frelative = "\\frelative" $fvaliddos = "\\fvaliddos" $fvalidhpfs = "\\fvalidhpfs" $fvalidmac = "\\fvalidmac" $fvalidntfs = "\\fvalidntfs" condition: any of them } rule rtf_font { strings: $acccircle = "\\acccircle" $acccomma = "\\acccomma" $accdot = "\\accdot" $accnone = "\\accnone" $accunderdot = "\\accunderdot" $animtext = "\\animtext" $b = "\\b" $caps = "\\caps" $cb = "\\cb" $cchs = "\\cchs" $cf = "\\cf" $charscalex = "\\charscalex" $cs = "\\cs" $dn = "\\dn" $embo = "\\embo" $expnd = "\\expnd" $expndtw = "\\expndtw" $f = "\\f" $fittext = "\\fittext" $fs = "\\fs" $i = "\\i" $kerning = "\\kerning" $lang = "\\lang" $langfe = "\\langfe" $langfenp = "\\langfenp" $langnp = "\\langnp" $ltrch = "\\ltrch" $noproof = "\\noproof" $nosupersub = "\\nosupersub" $outl = "\\outl" $plain = "\\plain" $rtlch = "\\rtlch" $scaps = "\\scaps" $shad = "\\shad" $strike = "\\strike" $sub = "\\sub" $super = "\\super" $ul = "\\ul" $ulc = "\\ulc" $uld = "\\uld" $uldash = "\\uldash" $uldashd = "\\uldashd" $uldashdd = "\\uldashdd" $uldb = "\\uldb" $ulhwave = "\\ulhwave" $ulldash = "\\ulldash" $ulnone = "\\ulnone" $ulth = "\\ulth" $ulthd = "\\ulthd" $ulthdash = "\\ulthdash" $ulthdashd = "\\ulthdashd" $ulthdashdd = "\\ulthdashdd" $ulthldash = "\\ulthldash" $ululdbwave = "\\ululdbwave" $ulw = "\\ulw" $ulwave = "\\ulwave" $up = "\\up" $v = "\\v" $webhidden = "\\webhidden" $fjgothic = "\\fjgothic" $fjminchou = "\\fjminchou" $jis = "\\jis" $falt = "\\falt" $fbias = "\\fbias" $fbidi = "\\fbidi" $fcharset = "\\fcharset" $fdecor = "\\fdecor" $fetch = "\\fetch" $fmodern = "\\fmodern" $fname = "\\fname" $fnil = "\\fnil" $fontemb = "\\fontemb" $fontfile = "\\fontfile" $fonttbl = "\\fonttbl" $fprq = "\\fprq" $froman = "\\froman" $fscript = "\\fscript" $fswiss = "\\fswiss" $ftech = "\\ftech" $ftnil = "\\ftnil" $fttruetype = "\\fttruetype" $panose = "\\panose" condition: any of them } rule rtf_footnote { strings: $footnote = "\\footnote" condition: any of them } rule rtf_form { strings: $ffdefres = "\\ffdefres" $ffdeftext = "\\ffdeftext" $ffentrymcr = "\\ffentrymcr" $ffexitmcr = "\\ffexitmcr" $ffformat = "\\ffformat" $ffhaslistbox = "\\ffhaslistbox" $ffhelptext = "\\ffhelptext" $ffhps = "\\ffhps" $ffl = "\\ffl" $ffmaxlen = "\\ffmaxlen" $ffname = "\\ffname" $ffownhelp = "\\ffownhelp" $ffownstat = "\\ffownstat" $ffprot = "\\ffprot" $ffrecalc = "\\ffrecalc" $ffres = "\\ffres" $ffsize = "\\ffsize" $ffstattext = "\\ffstattext" $fftype = "\\fftype" $fftypetxt = "\\fftypetxt" $formfield = "\\formfield" condition: any of them } rule rtf_generator { strings: $generator = "\\generator" condition: any of them } rule rtf_headers { strings: $footer = "\\footer" $footerf = "\\footerf" $footerl = "\\footerl" $footerr = "\\footerr" $header = "\\header" $headerf = "\\headerf" $headerl = "\\headerl" $headerr = "\\headerr" condition: any of them } rule rtf_highlight { strings: $highlight = "\\highlight" condition: any of them } rule rtf_hyphen { strings: $chhres = "\\chhres" $hres = "\\hres" condition: any of them } rule rtf_index { strings: $bxe = "\\bxe" $ixe = "\\ixe" $pxe = "\\pxe" $rxe = "\\rxe" $txe = "\\txe" $xe = "\\xe" $xef = "\\xef" $yxe = "\\yxe" condition: any of them } rule rtf_info { strings: $author = "\\author" $buptim = "\\buptim" $category = "\\category" $comment = "\\comment" $company = "\\company" $creatim = "\\creatim" $doccomm = "\\doccomm" $dy = "\\dy" $edmins = "\\edmins" $hlinkbase = "\\hlinkbase" $hr = "\\hr" $id = "\\id" $info = "\\info" $keywords = "\\keywords" $linkval = "\\linkval" $manager = "\\manager" $min = "\\min" $mo = "\\mo" $nofchars = "\\nofchars" $nofcharsws = "\\nofcharsws" $nofpages = "\\nofpages" $nofwords = "\\nofwords" $operator = "\\operator" $printim = "\\printim" $propname = "\\propname" $proptype = "\\proptype" $revtim = "\\revtim" $sec = "\\sec" $staticval = "\\staticval" $subject = "\\subject" $title = "\\title" $userprops = "\\userprops" $vern = "\\vern" $version = "\\version" $yr = "\\yr" condition: any of them } rule rtf_list { strings: $lvltentative = "\\lvltentative" $jclisttab = "\\jclisttab" $levelfollow = "\\levelfollow" $levelindent = "\\levelindent" $leveljc = "\\leveljc" $leveljcn = "\\leveljcn" $levellegal = "\\levellegal" $levelnfc = "\\levelnfc" $levelnfcn = "\\levelnfcn" $levelnorestart = "\\levelnorestart" $levelnumbers = "\\levelnumbers" $levelold = "\\levelold" $levelpicture = "\\levelpicture" $levelpicturenosize = "\\levelpicturenosize" $levelprev = "\\levelprev" $levelprevspace = "\\levelprevspace" $levelspace = "\\levelspace" $levelstartat = "\\levelstartat" $leveltemplateid = "\\leveltemplateid" $leveltext = "\\leveltext" $lfolevel = "\\lfolevel" $list = "\\list" $listhybrid = "\\listhybrid" $listid = "\\listid" $listlevel = "\\listlevel" $listname = "\\listname" $listoverride = "\\listoverride" $listoverridecount = "\\listoverridecount" $listoverrideformat = "\\listoverrideformat" $listoverridestartat = "\\listoverridestartat" $listoverridetable = "\\listoverridetable" $listpicture = "\\listpicture" $listrestarthdn = "\\listrestarthdn" $listsimple = "\\listsimple" $liststyleid = "\\liststyleid" $liststylename = "\\liststylename" $listtable = "\\listtable" $listtemplateid = "\\listtemplateid" $ls = "\\ls" condition: any of them } rule rtf_mac { strings: $bkmkpub = "\\bkmkpub" $pubauto = "\\pubauto" condition: any of them } rule rtf_mail { strings: $mailmerge = "\\mailmerge" $mmaddfieldname = "\\mmaddfieldname" $mmattach = "\\mmattach" $mmblanklines = "\\mmblanklines" $mmconnectstr = "\\mmconnectstr" $mmconnectstrdata = "\\mmconnectstrdata" $mmdatasource = "\\mmdatasource" $mmdatatypeaccess = "\\mmdatatypeaccess" $mmdatatypeexcel = "\\mmdatatypeexcel" $mmdatatypefile = "\\mmdatatypefile" $mmdatatypeodbc = "\\mmdatatypeodbc" $mmdatatypeodso = "\\mmdatatypeodso" $mmdatatypeqt = "\\mmdatatypeqt" $mmdefaultsql = "\\mmdefaultsql" $mmdestemail = "\\mmdestemail" $mmdestfax = "\\mmdestfax" $mmdestnewdoc = "\\mmdestnewdoc" $mmdestprinter = "\\mmdestprinter" $mmerrors = "\\mmerrors" $mmfttypeaddress = "\\mmfttypeaddress" $mmfttypebarcode = "\\mmfttypebarcode" $mmfttypedbcolumn = "\\mmfttypedbcolumn" $mmfttypemapped = "\\mmfttypemapped" $mmfttypenull = "\\mmfttypenull" $mmfttypesalutation = "\\mmfttypesalutation" $mmheadersource = "\\mmheadersource" $mmjdsotype = "\\mmjdsotype" $mmlinktoquery = "\\mmlinktoquery" $mmmailsubject = "\\mmmailsubject" $mmmaintypecatalog = "\\mmmaintypecatalog" $mmmaintypeemail = "\\mmmaintypeemail" $mmmaintypeenvelopes = "\\mmmaintypeenvelopes" $mmmaintypefax = "\\mmmaintypefax" $mmmaintypelabels = "\\mmmaintypelabels" $mmmaintypeletters = "\\mmmaintypeletters" $mmodso = "\\mmodso" $mmodsoactive = "\\mmodsoactive" $mmodsocoldelim = "\\mmodsocoldelim" $mmodsocolumn = "\\mmodsocolumn" $mmodsodynaddr = "\\mmodsodynaddr" $mmodsofhdr = "\\mmodsofhdr" $mmodsofilter = "\\mmodsofilter" $mmodsofldmpdata = "\\mmodsofldmpdata" $mmodsofmcolumn = "\\mmodsofmcolumn" $mmodsohash = "\\mmodsohash" $mmodsolid = "\\mmodsolid" $mmodsomappedname = "\\mmodsomappedname" $mmodsoname = "\\mmodsoname" $mmodsorecipdata = "\\mmodsorecipdata" $mmodsosort = "\\mmodsosort" $mmodsosrc = "\\mmodsosrc" $mmodsotable = "\\mmodsotable" $mmodsoudl = "\\mmodsoudl" $mmodsoudldata = "\\mmodsoudldata" $mmodsouniquetag = "\\mmodsouniquetag" $mmquery = "\\mmquery" $mmreccur = "\\mmreccur" $mmshowdata = "\\mmshowdata" condition: any of them } rule rtf_math { strings: $macc = "\\macc" $maccPr = "\\maccPr" $maln = "\\maln" $malnScr = "\\malnScr" $margPr = "\\margPr" $margSz = "\\margSz" $mbar = "\\mbar" $mbarPr = "\\mbarPr" $mbaseJc = "\\mbaseJc" $mbegChr = "\\mbegChr" $mborderBox = "\\mborderBox" $mborderBoxPr = "\\mborderBoxPr" $mbox = "\\mbox" $mboxPr = "\\mboxPr" $mbrk = "\\mbrk" $mbrkBin = "\\mbrkBin" $mbrkBinSub = "\\mbrkBinSub" $mcGp = "\\mcGp" $mcGpRule = "\\mcGpRule" $mchr = "\\mchr" $mcount = "\\mcount" $mcSp = "\\mcSp" $mctrlPr = "\\mctrlPr" $md = "\\md" $mdefJc = "\\mdefJc" $mdeg = "\\mdeg" $mdegHide = "\\mdegHide" $mden = "\\mden" $mdiff = "\\mdiff" $mdiffSty = "\\mdiffSty" $mdispdef = "\\mdispdef" $mdPr = "\\mdPr" $me = "\\me" $mendChr = "\\mendChr" $meqArr = "\\meqArr" $meqArrPr = "\\meqArrPr" $mf = "\\mf" $mfName = "\\mfName" $mfPr = "\\mfPr" $mfunc = "\\mfunc" $mfuncPr = "\\mfuncPr" $mgroupChr = "\\mgroupChr" $mgroupChrPr = "\\mgroupChrPr" $mgrow = "\\mgrow" $mhideBot = "\\mhideBot" $mhideLeft = "\\mhideLeft" $mhideRight = "\\mhideRight" $mhideTop = "\\mhideTop" $minterSp = "\\minterSp" $mintLim = "\\mintLim" $mintraSp = "\\mintraSp" $mjc = "\\mjc" $mlim = "\\mlim" $mlimloc = "\\mlimloc" $mlimlow = "\\mlimlow" $mlimlowPr = "\\mlimlowPr" $mlimupp = "\\mlimupp" $mlimuppPr = "\\mlimuppPr" $mlit = "\\mlit" $mlMargin = "\\mlMargin" $mm = "\\mm" $mmath = "\\mmath" $mmathFont = "\\mmathFont" $mmathPict = "\\mmathPict" $mmathPr = "\\mmathPr" $mmaxdist = "\\mmaxdist" $mmc = "\\mmc" $mmcJc = "\\mmcJc" $mmcPr = "\\mmcPr" $mmcs = "\\mmcs" $mmPr = "\\mmPr" $mmr = "\\mmr" $mnary = "\\mnary" $mnaryLim = "\\mnaryLim" $mnaryPr = "\\mnaryPr" $mnoBreak = "\\mnoBreak" $mnor = "\\mnor" $mnum = "\\mnum" $mobjDist = "\\mobjDist" $moMath = "\\moMath" $moMathPara = "\\moMathPara" $moMathParaPr = "\\moMathParaPr" $mopEmu = "\\mopEmu" $mphant = "\\mphant" $mphantPr = "\\mphantPr" $mplcHide = "\\mplcHide" $mpos = "\\mpos" $mpostSp = "\\mpostSp" $mpreSp = "\\mpreSp" $mr = "\\mr" $mrad = "\\mrad" $mradPr = "\\mradPr" $mrMargin = "\\mrMargin" $mrPr = "\\mrPr" $mrSp = "\\mrSp" $mrSpRule = "\\mrSpRule" $mscr = "\\mscr" $msepChr = "\\msepChr" $mshow = "\\mshow" $mshp = "\\mshp" $msmallFrac = "\\msmallFrac" $msPre = "\\msPre" $msPrePr = "\\msPrePr" $msSub = "\\msSub" $msSubPr = "\\msSubPr" $msSubSup = "\\msSubSup" $msSubSupPr = "\\msSubSupPr" $msSup = "\\msSup" $msSupPr = "\\msSupPr" $mstrikeBLTR = "\\mstrikeBLTR" $mstrikeH = "\\mstrikeH" $mstrikeTLBR = "\\mstrikeTLBR" $mstrikeV = "\\mstrikeV" $msty = "\\msty" $msub = "\\msub" $msubHide = "\\msubHide" $msup = "\\msup" $msupHide = "\\msupHide" $mtransp = "\\mtransp" $mtype = "\\mtype" $mvertJc = "\\mvertJc" $mwrapIndent = "\\mwrapIndent" $mwrapRight = "\\mwrapRight" $mzeroAsc = "\\mzeroAsc" $mzeroDesc = "\\mzeroDesc" $mzeroWid = "\\mzeroWid" condition: any of them } rule rtf_outlook { strings: $ebcstart = "\\ebcstart" $ebcend = "\\ebcend" condition: any of them } rule rtf_objects { strings: $linkself = "\\linkself" $objalias = "\\objalias" $objalign = "\\objalign" $objattph = "\\objattph" $objautlink = "\\objautlink" $objclass = "\\objclass" $objcropb = "\\objcropb" $objcropl = "\\objcropl" $objcropr = "\\objcropr" $objcropt = "\\objcropt" $objdata = "\\objdata" $object = "\\object" $objemb = "\\objemb" $objh = "\\objh" $objhtml = "\\objhtml" $objicemb = "\\objicemb" $objlink = "\\objlink" $objlock = "\\objlock" $objname = "\\objname" $objocx = "\\objocx" $objpub = "\\objpub" $objscalex = "\\objscalex" $objscaley = "\\objscaley" $objsect = "\\objsect" $objsetsize = "\\objsetsize" $objsub = "\\objsub" $objtime = "\\objtime" $objtransy = "\\objtransy" $objupdate = "\\objupdate" $objw = "\\objw" $oleclsid = "\\oleclsid" $result = "\\result" $rsltbmp = "\\rsltbmp" $rslthtml = "\\rslthtml" $rsltmerge = "\\rsltmerge" $rsltpict = "\\rsltpict" $rsltrtf = "\\rsltrtf" $rslttxt = "\\rslttxt" condition: any of them } rule rtf_paragraph { strings: $box = "\\box" $brdrb = "\\brdrb" $brdrbar = "\\brdrbar" $brdrbtw = "\\brdrbtw" $brdrcf = "\\brdrcf" $brdrdash = "\\brdrdash" $brdrdashd = "\\brdrdashd" $brdrdashdd = "\\brdrdashdd" $brdrdashdot = "\\brdrdashdot" $brdrdashdotdot = "\\brdrdashdotdot" $brdrdashdotstr = "\\brdrdashdotstr" $brdrdashsm = "\\brdrdashsm" $brdrdb = "\\brdrdb" $brdrdot = "\\brdrdot" $brdremboss = "\\brdremboss" $brdrengrave = "\\brdrengrave" $brdrframe = "\\brdrframe" $brdrhair = "\\brdrhair" $brdrinset = "\\brdrinset" $brdrl = "\\brdrl" $brdrnil = "\\brdrnil" $brdrnone = "\\brdrnone" $brdroutset = "\\brdroutset" $brdrr = "\\brdrr" $brdrs = "\\brdrs" $brdrsh = "\\brdrsh" $brdrt = "\\brdrt" $brdrtbl = "\\brdrtbl" $brdrth = "\\brdrth" $brdrthtnlg = "\\brdrthtnlg" $brdrthtnmg = "\\brdrthtnmg" $brdrthtnsg = "\\brdrthtnsg" $brdrtnthlg = "\\brdrtnthlg" $brdrtnthmg = "\\brdrtnthmg" $brdrtnthsg = "\\brdrtnthsg" $brdrtnthtnlg = "\\brdrtnthtnlg" $brdrtnthtnmg = "\\brdrtnthtnmg" $brdrtnthtnsg = "\\brdrtnthtnsg" $brdrtriple = "\\brdrtriple" $brdrw = "\\brdrw" $brdrwavy = "\\brdrwavy" $brdrwavydb = "\\brdrwavydb" $brsp = "\\brsp" $aspalpha = "\\aspalpha" $aspnum = "\\aspnum" $collapsed = "\\collapsed" $contextualspace = "\\contextualspace" $cufi = "\\cufi" $culi = "\\culi" $curi = "\\curi" $faauto = "\\faauto" $facenter = "\\facenter" $fafixed = "\\fafixed" $fahang = "\\fahang" $faroman = "\\faroman" $favar = "\\favar" $fi = "\\fi" $hyphpar = "\\hyphpar" $indmirror = "\\indmirror" $intbl = "\\intbl" $itap = "\\itap" $keep = "\\keep" $keepn = "\\keepn" $level = "\\level" $li = "\\li" $lin = "\\lin" $lisa = "\\lisa" $lisb = "\\lisb" $ltrpar = "\\ltrpar" $nocwrap = "\\nocwrap" $noline = "\\noline" $nooverflow = "\\nooverflow" $nosnaplinegrid = "\\nosnaplinegrid" $nowidctlpar = "\\nowidctlpar" $nowwrap = "\\nowwrap" $outlinelevel = "\\outlinelevel" $pagebb = "\\pagebb" $pard = "\\pard" $prauth = "\\prauth" $prdate = "\\prdate" $qc = "\\qc" $qd = "\\qd" $qj = "\\qj" $qk = "\\qk" $ql = "\\ql" $qr = "\\qr" $qt = "\\qt" $ri = "\\ri" $rin = "\\rin" $rtlpar = "\\rtlpar" $s = "\\s" $sa = "\\sa" $saauto = "\\saauto" $sb = "\\sb" $sbauto = "\\sbauto" $sbys = "\\sbys" $sl = "\\sl" $slmult = "\\slmult" $spv = "\\spv" $subdocument = "\\subdocument" $tscbandhorzeven = "\\tscbandhorzeven" $tscbandhorzodd = "\\tscbandhorzodd" $tscbandverteven = "\\tscbandverteven" $tscbandvertodd = "\\tscbandvertodd" $tscfirstcol = "\\tscfirstcol" $tscfirstrow = "\\tscfirstrow" $tsclastcol = "\\tsclastcol" $tsclastrow = "\\tsclastrow" $tscnecell = "\\tscnecell" $tscnwcell = "\\tscnwcell" $tscsecell = "\\tscsecell" $tscswcell = "\\tscswcell" $txbxtwalways = "\\txbxtwalways" $txbxtwfirst = "\\txbxtwfirst" $txbxtwfirstlast = "\\txbxtwfirstlast" $txbxtwlast = "\\txbxtwlast" $txbxtwno = "\\txbxtwno" $widctlpar = "\\widctlpar" $yts = "\\yts" $pgp = "\\pgp" $pgptbl = "\\pgptbl" $ipgp = "\\ipgp" $dfrauth = "\\dfrauth" $dfrdate = "\\dfrdate" $dfrstart = "\\dfrstart" $dfrstop = "\\dfrstop" $dfrxst = "\\dfrxst" $bgbdiag = "\\bgbdiag" $bgcross = "\\bgcross" $bgdcross = "\\bgdcross" $bgdkbdiag = "\\bgdkbdiag" $bgdkcross = "\\bgdkcross" $bgdkdcross = "\\bgdkdcross" $bgdkfdiag = "\\bgdkfdiag" $bgdkhoriz = "\\bgdkhoriz" $bgdkvert = "\\bgdkvert" $bgfdiag = "\\bgfdiag" $bghoriz = "\\bghoriz" $bgvert = "\\bgvert" $cbpat = "\\cbpat" $cfpat = "\\cfpat" $shading = "\\shading" condition: any of them } rule rtf_pictures { strings: $bin = "\\bin" $bliptag = "\\bliptag" $blipuid = "\\blipuid" $blipupi = "\\blipupi" $defshp = "\\defshp" $dibitmap = "\\dibitmap" $emfblip = "\\emfblip" $jpegblip = "\\jpegblip" $macpict = "\\macpict" $nonshppict = "\\nonshppict" $picbmp = "\\picbmp" $picbpp = "\\picbpp" $piccropb = "\\piccropb" $piccropl = "\\piccropl" $piccropr = "\\piccropr" $piccropt = "\\piccropt" $pich = "\\pich" $pichgoal = "\\pichgoal" $picprop = "\\picprop" $picscaled = "\\picscaled" $picscalex = "\\picscalex" $picscaley = "\\picscaley" $pict = "\\pict" $picw = "\\picw" $picwgoal = "\\picwgoal" $pmmetafile = "\\pmmetafile" $pngblip = "\\pngblip" $shppict = "\\shppict" $wbitmap = "\\wbitmap" $wbmbitspixel = "\\wbmbitspixel" $wbmplanes = "\\wbmplanes" $wbmwidthbyte = "\\wbmwidthbyte" $wmetafile = "\\wmetafile" condition: any of them } rule rtf_position { strings: $absh = "\\absh" $abslock = "\\abslock" $absnoovrlp = "\\absnoovrlp" $absw = "\\absw" $dfrmtxtx = "\\dfrmtxtx" $dfrmtxty = "\\dfrmtxty" $dropcapli = "\\dropcapli" $dropcapt = "\\dropcapt" $dxfrtext = "\\dxfrtext" $frmtxbtlr = "\\frmtxbtlr" $frmtxlrtb = "\\frmtxlrtb" $frmtxlrtbv = "\\frmtxlrtbv" $frmtxtbrl = "\\frmtxtbrl" $frmtxtbrlv = "\\frmtxtbrlv" $nowrap = "\\nowrap" $overlay = "\\overlay" $phcol = "\\phcol" $phmrg = "\\phmrg" $phpg = "\\phpg" $posnegx = "\\posnegx" $posnegy = "\\posnegy" $posx = "\\posx" $posxc = "\\posxc" $posxi = "\\posxi" $posxl = "\\posxl" $posxo = "\\posxo" $posxr = "\\posxr" $posy = "\\posy" $posyb = "\\posyb" $posyc = "\\posyc" $posyil = "\\posyil" $posyin = "\\posyin" $posyout = "\\posyout" $posyt = "\\posyt" $pvmrg = "\\pvmrg" $pvpara = "\\pvpara" $pvpg = "\\pvpg" $wraparound = "\\wraparound" $wrapdefault = "\\wrapdefault" $wrapthrough = "\\wrapthrough" $wraptight = "\\wraptight" condition: any of them } rule rtf_protection { strings: $protend = "\\protend" $protstart = "\\protstart" $protusertbl = "\\protusertbl" condition: any of them } rule rtf_quick_styles { strings: $noqfpromote = "\\noqfpromote" condition: any of them } rule rtf_password { strings: $password = <PASSWORD>" $passwordhash = <PASSWORD>" condition: any of them } rule rtf_revision { strings: $pnrauth = "\\pnrauth" $pnrdate = "\\pnrdate" $pnrnfc = "\\pnrnfc" $pnrnot = "\\pnrnot" $pnrpnbr = "\\pnrpnbr" $pnrrgb = "\\pnrrgb" $pnrstart = "\\pnrstart" $pnrstop = "\\pnrstop" $pnrxst = "\\pnrxst" condition: any of them } rule rtf_version { strings: $rtf = "\\rtf" condition: any of them } rule rtf_section { strings: $adjustright = "\\adjustright" $binfsxn = "\\binfsxn" $binsxn = "\\binsxn" $colno = "\\colno" $cols = "\\cols" $colsr = "\\colsr" $colsx = "\\colsx" $colw = "\\colw" $ds = "\\ds" $endnhere = "\\endnhere" $footery = "\\footery" $guttersxn = "\\guttersxn" $headery = "\\headery" $horzsect = "\\horzsect" $linebetcol = "\\linebetcol" $linecont = "\\linecont" $linemod = "\\linemod" $lineppage = "\\lineppage" $linerestart = "\\linerestart" $linestarts = "\\linestarts" $linex = "\\linex" $lndscpsxn = "\\lndscpsxn" $ltrsect = "\\ltrsect" $margbsxn = "\\margbsxn" $marglsxn = "\\marglsxn" $margmirsxn = "\\margmirsxn" $margrsxn = "\\margrsxn" $margtsxn = "\\margtsxn" $pghsxn = "\\pghsxn" $pgnbidia = "\\pgnbidia" $pgnbidib = "\\pgnbidib" $pgnchosung = "\\pgnchosung" $pgncnum = "\\pgncnum" $pgncont = "\\pgncont" $pgndbnum = "\\pgndbnum" $pgndbnumd = "\\pgndbnumd" $pgndbnumk = "\\pgndbnumk" $pgndbnumt = "\\pgndbnumt" $pgndec = "\\pgndec" $pgndecd = "\\pgndecd" $pgnganada = "\\pgnganada" $pgngbnum = "\\pgngbnum" $pgngbnumd = "\\pgngbnumd" $pgngbnumk = "\\pgngbnumk" $pgngbnuml = "\\pgngbnuml" $pgnhindia = "\\pgnhindia" $pgnhindib = "\\pgnhindib" $pgnhindic = "\\pgnhindic" $pgnhindid = "\\pgnhindid" $pgnhn = "\\pgnhn" $pgnhnsc = "\\pgnhnsc" $pgnhnsh = "\\pgnhnsh" $pgnhnsm = "\\pgnhnsm" $pgnhnsn = "\\pgnhnsn" $pgnhnsp = "\\pgnhnsp" $pgnid = "\\pgnid" $pgnlcltr = "\\pgnlcltr" $pgnlcrm = "\\pgnlcrm" $pgnrestart = "\\pgnrestart" $pgnstarts = "\\pgnstarts" $pgnthaia = "\\pgnthaia" $pgnthaib = "\\pgnthaib" $pgnthaic = "\\pgnthaic" $pgnucltr = "\\pgnucltr" $pgnucrm = "\\pgnucrm" $pgnvieta = "\\pgnvieta" $pgnx = "\\pgnx" $pgny = "\\pgny" $pgnzodiac = "\\pgnzodiac" $pgnzodiacd = "\\pgnzodiacd" $pgnzodiacl = "\\pgnzodiacl" $pgwsxn = "\\pgwsxn" $pnseclvl = "\\pnseclvl" $rtlsect = "\\rtlsect" $saftnnalc = "\\saftnnalc" $saftnnar = "\\saftnnar" $saftnnauc = "\\saftnnauc" $saftnnchi = "\\saftnnchi" $saftnnchosung = "\\saftnnchosung" $saftnncnum = "\\saftnncnum" $saftnndbar = "\\saftnndbar" $saftnndbnum = "\\saftnndbnum" $saftnndbnumd = "\\saftnndbnumd" $saftnndbnumk = "\\saftnndbnumk" $saftnndbnumt = "\\saftnndbnumt" $saftnnganada = "\\saftnnganada" $saftnngbnum = "\\saftnngbnum" $saftnngbnumd = "\\saftnngbnumd" $saftnngbnumk = "\\saftnngbnumk" $saftnngbnuml = "\\saftnngbnuml" $saftnnrlc = "\\saftnnrlc" $saftnnruc = "\\saftnnruc" $saftnnzodiac = "\\saftnnzodiac" $saftnnzodiacd = "\\saftnnzodiacd" $saftnnzodiacl = "\\saftnnzodiacl" $saftnrestart = "\\saftnrestart" $saftnrstcont = "\\saftnrstcont" $saftnstart = "\\saftnstart" $sbkcol = "\\sbkcol" $sbkeven = "\\sbkeven" $sbknone = "\\sbknone" $sbkodd = "\\sbkodd" $sbkpage = "\\sbkpage" $sectd = "\\sectd" $sectdefaultcl = "\\sectdefaultcl" $sectexpand = "\\sectexpand" $sectlinegrid = "\\sectlinegrid" $sectspecifycl = "\\sectspecifycl" $sectspecifygen = "\\sectspecifygen" $sectspecifyl = "\\sectspecifyl" $sectunlocked = "\\sectunlocked" $sftnbj = "\\sftnbj" $sftnnalc = "\\sftnnalc" $sftnnar = "\\sftnnar" $sftnnauc = "\\sftnnauc" $sftnnchi = "\\sftnnchi" $sftnnchosung = "\\sftnnchosung" $sftnncnum = "\\sftnncnum" $sftnndbar = "\\sftnndbar" $sftnndbnum = "\\sftnndbnum" $sftnndbnumd = "\\sftnndbnumd" $sftnndbnumk = "\\sftnndbnumk" $sftnndbnumt = "\\sftnndbnumt" $sftnnganada = "\\sftnnganada" $sftnngbnum = "\\sftnngbnum" $sftnngbnumd = "\\sftnngbnumd" $sftnngbnumk = "\\sftnngbnumk" $sftnngbnuml = "\\sftnngbnuml" $sftnnrlc = "\\sftnnrlc" $sftnnruc = "\\sftnnruc" $sftnnzodiac = "\\sftnnzodiac" $sftnnzodiacd = "\\sftnnzodiacd" $sftnnzodiacl = "\\sftnnzodiacl" $sftnrestart = "\\sftnrestart" $sftnrstcont = "\\sftnrstcont" $sftnrstpg = "\\sftnrstpg" $sftnstart = "\\sftnstart" $sftntj = "\\sftntj" $srauth = "\\srauth" $srdate = "\\srdate" $titlepg = "\\titlepg" $vertal = "\\vertal" $vertalb = "\\vertalb" $vertalc = "\\vertalc" $vertalj = "\\vertalj" $vertalt = "\\vertalt" $vertsect = "\\vertsect" $stextflow = "\\stextflow" condition: any of them } rule rtf_tag { strings: $factoidname = "\\factoidname" condition: any of them } rule rtf_special_hex { strings: $hex = "\\'" condition: any of them } rule rtf_special_ignore { strings: $ignore = "\\*" condition: any of them } rule rtf_special { strings: $hyphen = "\\-" $subentry = "\\:" $nonbreakhyphen = "\\_" $formula = "\\|" $nonbreakspace = "\\~" /* ${ = "\\{" $} = "\\}" */ $bullet = "\\bullet" $chatn = "\\chatn" $chdate = "\\chdate" $chdpa = "\\chdpa" $chdpl = "\\chdpl" $chftn = "\\chftn" $chftnsep = "\\chftnsep" $chftnsepc = "\\chftnsepc" $chpgn = "\\chpgn" $chtime = "\\chtime" $column = "\\column" $emdash = "\\emdash" $emspace = "\\emspace" $endash = "\\endash" $enspace = "\\enspace" $lbr = "\\lbr" $ldblquote = "\\ldblquote" $line = "\\line" $lquote = "\\lquote" $ltrmark = "\\ltrmark" $page = "\\page" $par = "\\par" $qmspace = "\\qmspace" $rdblquote = "\\rdblquote" $row = "\\row" $rquote = "\\rquote" $rtlmark = "\\rtlmark" $sect = "\\sect" $sectnum = "\\sectnum" $softcol = "\\softcol" $softlheight = "\\softlheight" $softline = "\\softline" $softpage = "\\softpage" $tab = "\\tab" $zwbo = "\\zwbo" $zwj = "\\zwj" $zwnbo = "\\zwnbo" $zwnj = "\\zwnj" condition: any of them } rule rtf_styles { strings: $latentstyles = "\\latentstyles" $lsdlocked = "\\lsdlocked" $lsdlockeddef = "\\lsdlockeddef" $lsdlockedexcept = "\\lsdlockedexcept" $lsdpriority = "\\lsdpriority" $lsdprioritydef = "\\lsdprioritydef" $lsdqformat = "\\lsdqformat" $lsdqformatdef = "\\lsdqformatdef" $lsdsemihidden = "\\lsdsemihidden" $lsdsemihiddendef = "\\lsdsemihiddendef" $lsdstimax = "\\lsdstimax" $lsdunhideused = "\\lsdunhideused" $lsdunhideuseddef = "\\lsdunhideuseddef" $additive = "\\additive" $alt = "\\alt" $ctrl = "\\ctrl" $fn = "\\fn" $keycode = "\\keycode" $sautoupd = "\\sautoupd" $sbasedon = "\\sbasedon" $scompose = "\\scompose" $shidden = "\\shidden" $shift = "\\shift" $slink = "\\slink" $slocked = "\\slocked" $snext = "\\snext" $spersonal = "\\spersonal" $spriority = "\\spriority" $sqformat = "\\sqformat" $sreply = "\\sreply" $ssemihidden = "\\ssemihidden" $stylesheet = "\\stylesheet" $styrsid = "\\styrsid" $sunhideused = "\\sunhideused" $ts = "\\ts" $tsrowd = "\\tsrowd" condition: any of them } rule rtf_tables { strings: $cell = "\\cell" $cellx = "\\cellx" $clbgbdiag = "\\clbgbdiag" $clbgcross = "\\clbgcross" $clbgdcross = "\\clbgdcross" $clbgdkbdiag = "\\clbgdkbdiag" $clbgdkcross = "\\clbgdkcross" $clbgdkdcross = "\\clbgdkdcross" $clbgdkfdiag = "\\clbgdkfdiag" $clbgdkhor = "\\clbgdkhor" $clbgdkvert = "\\clbgdkvert" $clbgfdiag = "\\clbgfdiag" $clbghoriz = "\\clbghoriz" $clbgvert = "\\clbgvert" $clbrdrb = "\\clbrdrb" $clbrdrl = "\\clbrdrl" $clbrdrr = "\\clbrdrr" $clbrdrt = "\\clbrdrt" $clcbpat = "\\clcbpat" $clcbpatraw = "\\clcbpatraw" $clcfpat = "\\clcfpat" $clcfpatraw = "\\clcfpatraw" $cldel2007 = "\\cldel2007" $cldelauth = "\\cldelauth" $cldeldttm = "\\cldeldttm" $cldgll = "\\cldgll" $cldglu = "\\cldglu" $clFitText = "\\clFitText" $clftsWidth = "\\clftsWidth" $clhidemark2007 = "\\clhidemark2007" $clins2007 = "\\clins2007" $clinsauth = "\\clinsauth" $clinsdttm = "\\clinsdttm" $clmgf = "\\clmgf" $clmrg = "\\clmrg" $clmrgd = "\\clmrgd" $clmrgdauth = "\\clmrgdauth" $clmrgddttm = "\\clmrgddttm" $clmrgdr = "\\clmrgdr" $clNoWrap = "\\clNoWrap" $clpadb = "\\clpadb" $clpadfb = "\\clpadfb" $clpadfl = "\\clpadfl" $clpadfr = "\\clpadfr" $clpadft = "\\clpadft" $clpadl = "\\clpadl" $clpadr = "\\clpadr" $clpadt = "\\clpadt" $clspb = "\\clspb" $clspfb = "\\clspfb" $clspfl = "\\clspfl" $clspfr = "\\clspfr" $clspft = "\\clspft" $clspl = "\\clspl" $clspr = "\\clspr" $clspt = "\\clspt" $clshdng = "\\clshdng" $clshdngraw = "\\clshdngraw" $clshdrawnil = "\\clshdrawnil" $clsplit = "\\clsplit" $clsplitr = "\\clsplitr" $cltxbtlr = "\\cltxbtlr" $cltxlrtb = "\\cltxlrtb" $cltxlrtbv = "\\cltxlrtbv" $cltxtbrl = "\\cltxtbrl" $cltxtbrlv = "\\cltxtbrlv" $clvertalb = "\\clvertalb" $clvertalc = "\\clvertalc" $clvertalt = "\\clvertalt" $clvmgf = "\\clvmgf" $clvmrg = "\\clvmrg" $clwWidth = "\\clwWidth" $irowband = "\\irowband" $irow = "\\irow" $lastrow = "\\lastrow" $ltrrow = "\\ltrrow" $nestcell = "\\nestcell" $nestrow = "\\nestrow" $nesttableprops = "\\nesttableprops" $nonesttables = "\\nonesttables" $rawclbgdkbdiag = "\\rawclbgdkbdiag" $rawclbgbdiag = "\\rawclbgbdiag" $rawclbgcross = "\\rawclbgcross" $rawclbgdcross = "\\rawclbgdcross" $rawclbgdkcross = "\\rawclbgdkcross" $rawclbgdkdcross = "\\rawclbgdkdcross" $rawclbgdkfdiag = "\\rawclbgdkfdiag" $rawclbgdkhor = "\\rawclbgdkhor" $rawclbgdkvert = "\\rawclbgdkvert" $rawclbgfdiag = "\\rawclbgfdiag" $rawclbghoriz = "\\rawclbghoriz" $rawclbgvert = "\\rawclbgvert" $rtlrow = "\\rtlrow" $tabsnoovrlp = "\\tabsnoovrlp" $taprtl = "\\taprtl" $tblind = "\\tblind" $tblindtype = "\\tblindtype" $tbllkbestfit = "\\tbllkbestfit" $tbllkborder = "\\tbllkborder" $tbllkcolor = "\\tbllkcolor" $tbllkfont = "\\tbllkfont" $tbllkhdrcols = "\\tbllkhdrcols" $tbllkhdrrows = "\\tbllkhdrrows" $tbllklastcol = "\\tbllklastcol" $tbllklastrow = "\\tbllklastrow" $tbllknocolband = "\\tbllknocolband" $tbllknorowband = "\\tbllknorowband" $tbllkshading = "\\tbllkshading" $tcelld = "\\tcelld" $tdfrmtxtBottom = "\\tdfrmtxtBottom" $tdfrmtxtLeft = "\\tdfrmtxtLeft" $tdfrmtxtRight = "\\tdfrmtxtRight" $tdfrmtxtTop = "\\tdfrmtxtTop" $tphcol = "\\tphcol" $tphmrg = "\\tphmrg" $tphpg = "\\tphpg" $tposnegx = "\\tposnegx" $tposnegy = "\\tposnegy" $tposxc = "\\tposxc" $tposxi = "\\tposxi" $tposxl = "\\tposxl" $tposx = "\\tposx" $tposxo = "\\tposxo" $tposxr = "\\tposxr" $tposy = "\\tposy" $tposyb = "\\tposyb" $tposyc = "\\tposyc" $tposyil = "\\tposyil" $tposyin = "\\tposyin" $tposyout = "\\tposyout" $tposyt = "\\tposyt" $tpvmrg = "\\tpvmrg" $tpvpara = "\\tpvpara" $tpvpg = "\\tpvpg" $trauth = "\\trauth" $trautofit = "\\trautofit" $trbgbdiag = "\\trbgbdiag" $trbgcross = "\\trbgcross" $trbgdcross = "\\trbgdcross" $trbgdkbdiag = "\\trbgdkbdiag" $trbgdkcross = "\\trbgdkcross" $trbgdkdcross = "\\trbgdkdcross" $trbgdkfdiag = "\\trbgdkfdiag" $trbgdkhor = "\\trbgdkhor" $trbgdkvert = "\\trbgdkvert" $trbgfdiag = "\\trbgfdiag" $trbghoriz = "\\trbghoriz" $trbgvert = "\\trbgvert" $trbrdrb = "\\trbrdrb" $trbrdrh = "\\trbrdrh" $trbrdrl = "\\trbrdrl" $trbrdrr = "\\trbrdrr" $trbrdrt = "\\trbrdrt" $trbrdrv = "\\trbrdrv" $trcbpat = "\\trcbpat" $trcfpat = "\\trcfpat" $trdate = "\\trdate" $trftsWidthA = "\\trftsWidthA" $trftsWidthB = "\\trftsWidthB" $trftsWidth = "\\trftsWidth" $trgaph = "\\trgaph" $trhdr = "\\trhdr" $trkeep = "\\trkeep" $trkeepfollow = "\\trkeepfollow" $trleft = "\\trleft" $trowd = "\\trowd" $trpaddb = "\\trpaddb" $trpaddfb = "\\trpaddfb" $trpaddfl = "\\trpaddfl" $trpaddfr = "\\trpaddfr" $trpaddft = "\\trpaddft" $trpaddl = "\\trpaddl" $trpaddr = "\\trpaddr" $trpaddt = "\\trpaddt" $trpadob = "\\trpadob" $trpadofb = "\\trpadofb" $trpadofl = "\\trpadofl" $trpadofr = "\\trpadofr" $trpadoft = "\\trpadoft" $trpadol = "\\trpadol" $trpador = "\\trpador" $trpadot = "\\trpadot" $trpat = "\\trpat" $trqc = "\\trqc" $trql = "\\trql" $trqr = "\\trqr" $trrh = "\\trrh" $trshdng = "\\trshdng" $trspdb = "\\trspdb" $trspdfb = "\\trspdfb" $trspdfl = "\\trspdfl" $trspdfr = "\\trspdfr" $trspdft = "\\trspdft" $trspdl = "\\trspdl" $trspdr = "\\trspdr" $trspdt = "\\trspdt" $trspob = "\\trspob" $trspofb = "\\trspofb" $trspofl = "\\trspofl" $trspofr = "\\trspofr" $trspoft = "\\trspoft" $trspol = "\\trspol" $trspor = "\\trspor" $trspot = "\\trspot" $trwWidthA = "\\trwWidthA" $trwWidthB = "\\trwWidthB" $trwWidth = "\\trwWidth" $tc = "\\tc" $tcf = "\\tcf" $tcl = "\\tcl" $tcn = "\\tcn" $tsbgbdiag = "\\tsbgbdiag" $tsbgcross = "\\tsbgcross" $tsbgdcross = "\\tsbgdcross" $tsbgdkbdiag = "\\tsbgdkbdiag" $tsbgdkcross = "\\tsbgdkcross" $tsbgdkdcross = "\\tsbgdkdcross" $tsbgdkfdiag = "\\tsbgdkfdiag" $tsbgdkhor = "\\tsbgdkhor" $tsbgdkvert = "\\tsbgdkvert" $tsbgfdiag = "\\tsbgfdiag" $tsbghoriz = "\\tsbghoriz" $tsbgvert = "\\tsbgvert" $tsbrdrb = "\\tsbrdrb" $tsbrdrdgl = "\\tsbrdrdgl" $tsbrdrdgr = "\\tsbrdrdgr" $tsbrdrh = "\\tsbrdrh" $tsbrdrl = "\\tsbrdrl" $tsbrdrr = "\\tsbrdrr" $tsbrdrt = "\\tsbrdrt" $tsbrdrv = "\\tsbrdrv" $tscbandsh = "\\tscbandsh" $tscbandsv = "\\tscbandsv" $tscellcbpat = "\\tscellcbpat" $tscellcfpat = "\\tscellcfpat" $tscellpaddb = "\\tscellpaddb" $tscellpaddfb = "\\tscellpaddfb" $tscellpaddfl = "\\tscellpaddfl" $tscellpaddfr = "\\tscellpaddfr" $tscellpaddft = "\\tscellpaddft" $tscellpaddl = "\\tscellpaddl" $tscellpaddr = "\\tscellpaddr" $tscellpaddt = "\\tscellpaddt" $tscellpct = "\\tscellpct" $tscellwidth = "\\tscellwidth" $tscellwidthfts = "\\tscellwidthfts" $tsnowrap = "\\tsnowrap" $tsvertalb = "\\tsvertalb" $tsvertalc = "\\tsvertalc" $tsvertalt = "\\tsvertalt" $tb = "\\tb" $tldot = "\\tldot" $tleq = "\\tleq" $tlhyph = "\\tlhyph" $tlmdot = "\\tlmdot" $tlth = "\\tlth" $tlul = "\\tlul" $tqc = "\\tqc" $tqdec = "\\tqdec" $tqr = "\\tqr" $tx = "\\tx" condition: any of them } rule rtf_theme { strings: $themedata = "\\themedata" $fbimajor = "\\fbimajor" $fbiminor = "\\fbiminor" $fdbmajor = "\\fdbmajor" $fdbminor = "\\fdbminor" $fhimajor = "\\fhimajor" $fhiminor = "\\fhiminor" $flomajor = "\\flomajor" $flominor = "\\flominor" $revtbl = "\\revtbl" $charrsid = "\\charrsid" $delrsid = "\\delrsid" $insrsid = "\\insrsid" $oldcprops = "\\oldcprops" $oldpprops = "\\oldpprops" $oldsprops = "\\oldsprops" $oldtprops = "\\oldtprops" $pararsid = "\\pararsid" $rsid = "\\rsid" $rsidroot = "\\rsidroot" $rsidtbl = "\\rsidtbl" $sectrsid = "\\sectrsid" $tblrsid = "\\tblrsid" condition: any of them } rule rtf_unicode { strings: $u = "\\u" $uc = "\\uc" $ud = "\\ud" $upr = "\\upr" condition: any of them } rule rtf_shapes { strings: $shp = "\\shp" $shpbottom = "\\shpbottom" $shpbxcolumn = "\\shpbxcolumn" $shpbxignore = "\\shpbxignore" $shpbxmargin = "\\shpbxmargin" $shpbxpage = "\\shpbxpage" $shpbyignore = "\\shpbyignore" $shpbymargin = "\\shpbymargin" $shpbypage = "\\shpbypage" $shpbypara = "\\shpbypara" $shpfblwtxt = "\\shpfblwtxt" $shpfhdr = "\\shpfhdr" $shpgrp = "\\shpgrp" $shpinst = "\\shpinst" $shpleft = "\\shpleft" $shplid = "\\shplid" $shplockanchor = "\\shplockanchor" $shpright = "\\shpright" $shprslt = "\\shprslt" $shptop = "\\shptop" $shptxt = "\\shptxt" $shpwrk = "\\shpwrk" $shpwr = "\\shpwr" $shpz = "\\shpz" $sn = "\\sn" $sp = "\\sp" $sv = "\\sv" $svb = "\\svb" condition: any of them }
| 1.873866
| 2
|
django_server/player/migrations/0003_auto_20200111_1731.py
|
SolomidHero/music-player
| 2
|
6626303
|
# Generated by Django 3.0 on 2020-01-11 17:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('player', '0002_audio_owner'),
]
operations = [
migrations.RenameField(
model_name='audio',
old_name='name',
new_name='title',
),
migrations.AddField(
model_name='audio',
name='src',
field=models.CharField(default='somesrc', max_length=256),
preserve_default=False,
),
]
|
# Generated by Django 3.0 on 2020-01-11 17:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('player', '0002_audio_owner'),
]
operations = [
migrations.RenameField(
model_name='audio',
old_name='name',
new_name='title',
),
migrations.AddField(
model_name='audio',
name='src',
field=models.CharField(default='somesrc', max_length=256),
preserve_default=False,
),
]
|
en
| 0.822962
|
# Generated by Django 3.0 on 2020-01-11 17:31
| 1.929178
| 2
|
trackers/ocsort_tracker/association.py
|
CaptainEven/MCMOT-ByteTrack
| 20
|
6626304
|
<gh_stars>10-100
import numpy as np
def iou_batch(bboxes1, bboxes2):
"""
From SORT: Computes IOU between two bboxes in the form [x1,y1,x2,y2]
"""
bboxes2 = np.expand_dims(bboxes2, 0)
bboxes1 = np.expand_dims(bboxes1, 1)
xx1 = np.maximum(bboxes1[..., 0], bboxes2[..., 0])
yy1 = np.maximum(bboxes1[..., 1], bboxes2[..., 1])
xx2 = np.minimum(bboxes1[..., 2], bboxes2[..., 2])
yy2 = np.minimum(bboxes1[..., 3], bboxes2[..., 3])
w = np.maximum(0., xx2 - xx1)
h = np.maximum(0., yy2 - yy1)
wh = w * h
o = wh / ((bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
+ (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) - wh)
return o
def giou_batch(bboxes1, bboxes2):
"""
:param bbox_p: predict of bbox(N,4)(x1,y1,x2,y2)
:param bbox_g: groundtruth of bbox(N,4)(x1,y1,x2,y2)
:return:
"""
# for details should go to https://arxiv.org/pdf/1902.09630.pdf
# ensure predict's bbox form
bboxes2 = np.expand_dims(bboxes2, 0)
bboxes1 = np.expand_dims(bboxes1, 1)
xx1 = np.maximum(bboxes1[..., 0], bboxes2[..., 0])
yy1 = np.maximum(bboxes1[..., 1], bboxes2[..., 1])
xx2 = np.minimum(bboxes1[..., 2], bboxes2[..., 2])
yy2 = np.minimum(bboxes1[..., 3], bboxes2[..., 3])
w = np.maximum(0., xx2 - xx1)
h = np.maximum(0., yy2 - yy1)
wh = w * h
iou = wh / ((bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
+ (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) - wh)
xxc1 = np.minimum(bboxes1[..., 0], bboxes2[..., 0])
yyc1 = np.minimum(bboxes1[..., 1], bboxes2[..., 1])
xxc2 = np.maximum(bboxes1[..., 2], bboxes2[..., 2])
yyc2 = np.maximum(bboxes1[..., 3], bboxes2[..., 3])
wc = xxc2 - xxc1
hc = yyc2 - yyc1
assert ((wc > 0).all() and (hc > 0).all())
area_enclose = wc * hc
giou = iou - (area_enclose - wh) / area_enclose
giou = (giou + 1.) / 2.0 # resize from (-1,1) to (0,1)
return giou
def diou_batch(bboxes1, bboxes2):
"""
:param bbox_p: predict of bbox(N,4)(x1,y1,x2,y2)
:param bbox_g: groundtruth of bbox(N,4)(x1,y1,x2,y2)
:return:
"""
# for details should go to https://arxiv.org/pdf/1902.09630.pdf
# ensure predict's bbox form
bboxes2 = np.expand_dims(bboxes2, 0)
bboxes1 = np.expand_dims(bboxes1, 1)
# calculate the intersection box
xx1 = np.maximum(bboxes1[..., 0], bboxes2[..., 0])
yy1 = np.maximum(bboxes1[..., 1], bboxes2[..., 1])
xx2 = np.minimum(bboxes1[..., 2], bboxes2[..., 2])
yy2 = np.minimum(bboxes1[..., 3], bboxes2[..., 3])
w = np.maximum(0., xx2 - xx1)
h = np.maximum(0., yy2 - yy1)
wh = w * h
iou = wh / ((bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
+ (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) - wh)
centerx1 = (bboxes1[..., 0] + bboxes1[..., 2]) / 2.0
centery1 = (bboxes1[..., 1] + bboxes1[..., 3]) / 2.0
centerx2 = (bboxes2[..., 0] + bboxes2[..., 2]) / 2.0
centery2 = (bboxes2[..., 1] + bboxes2[..., 3]) / 2.0
inner_diag = (centerx1 - centerx2) ** 2 + (centery1 - centery2) ** 2
xxc1 = np.minimum(bboxes1[..., 0], bboxes2[..., 0])
yyc1 = np.minimum(bboxes1[..., 1], bboxes2[..., 1])
xxc2 = np.maximum(bboxes1[..., 2], bboxes2[..., 2])
yyc2 = np.maximum(bboxes1[..., 3], bboxes2[..., 3])
outer_diag = (xxc2 - xxc1) ** 2 + (yyc2 - yyc1) ** 2
diou = iou - inner_diag / outer_diag
return (diou + 1) / 2.0 # resize from (-1,1) to (0,1)
def ciou_batch(bboxes1, bboxes2):
"""
:param bbox_p: predict of bbox(N,4)(x1,y1,x2,y2)
:param bbox_g: groundtruth of bbox(N,4)(x1,y1,x2,y2)
:return:
"""
# for details should go to https://arxiv.org/pdf/1902.09630.pdf
# ensure predict's bbox form
bboxes2 = np.expand_dims(bboxes2, 0)
bboxes1 = np.expand_dims(bboxes1, 1)
# calculate the intersection box
xx1 = np.maximum(bboxes1[..., 0], bboxes2[..., 0])
yy1 = np.maximum(bboxes1[..., 1], bboxes2[..., 1])
xx2 = np.minimum(bboxes1[..., 2], bboxes2[..., 2])
yy2 = np.minimum(bboxes1[..., 3], bboxes2[..., 3])
w = np.maximum(0., xx2 - xx1)
h = np.maximum(0., yy2 - yy1)
wh = w * h
iou = wh / ((bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
+ (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) - wh)
centerx1 = (bboxes1[..., 0] + bboxes1[..., 2]) / 2.0
centery1 = (bboxes1[..., 1] + bboxes1[..., 3]) / 2.0
centerx2 = (bboxes2[..., 0] + bboxes2[..., 2]) / 2.0
centery2 = (bboxes2[..., 1] + bboxes2[..., 3]) / 2.0
inner_diag = (centerx1 - centerx2) ** 2 + (centery1 - centery2) ** 2
xxc1 = np.minimum(bboxes1[..., 0], bboxes2[..., 0])
yyc1 = np.minimum(bboxes1[..., 1], bboxes2[..., 1])
xxc2 = np.maximum(bboxes1[..., 2], bboxes2[..., 2])
yyc2 = np.maximum(bboxes1[..., 3], bboxes2[..., 3])
outer_diag = (xxc2 - xxc1) ** 2 + (yyc2 - yyc1) ** 2
w1 = bboxes1[..., 2] - bboxes1[..., 0]
h1 = bboxes1[..., 3] - bboxes1[..., 1]
w2 = bboxes2[..., 2] - bboxes2[..., 0]
h2 = bboxes2[..., 3] - bboxes2[..., 1]
# prevent dividing over zero. add one pixel shift
h2 = h2 + 1.
h1 = h1 + 1.
arctan = np.arctan(w2 / h2) - np.arctan(w1 / h1)
v = (4 / (np.pi ** 2)) * (arctan ** 2)
S = 1 - iou
alpha = v / (S + v)
ciou = iou - inner_diag / outer_diag - alpha * v
return (ciou + 1) / 2.0 # resize from (-1,1) to (0,1)
def ct_dist(bboxes1, bboxes2):
"""
Measure the center distance between two sets of bounding boxes,
this is a coarse implementation, we don't recommend using it only
for association, which can be unstable and sensitive to frame rate
and object speed.
"""
bboxes2 = np.expand_dims(bboxes2, 0)
bboxes1 = np.expand_dims(bboxes1, 1)
centerx1 = (bboxes1[..., 0] + bboxes1[..., 2]) / 2.0
centery1 = (bboxes1[..., 1] + bboxes1[..., 3]) / 2.0
centerx2 = (bboxes2[..., 0] + bboxes2[..., 2]) / 2.0
centery2 = (bboxes2[..., 1] + bboxes2[..., 3]) / 2.0
ct_dist2 = (centerx1 - centerx2) ** 2 + (centery1 - centery2) ** 2
ct_dist = np.sqrt(ct_dist2)
# The linear rescaling is a naive version and needs more study
ct_dist = ct_dist / ct_dist.max()
return ct_dist.max() - ct_dist # resize to (0,1)
def velocity_direction_batch(dets, tracks):
"""
@param dets: x1, y1, x2,y2, score
@param tracks:
"""
tracks = tracks[..., np.newaxis]
# center x, center y
CX1, CY1 = (dets[:, 0] + dets[:, 2]) * 0.5, (dets[:, 1] + dets[:, 3]) * 0.5
CX2, CY2 = (tracks[:, 0] + tracks[:, 2]) * 0.5, (tracks[:, 1] + tracks[:, 3]) * 0.5
dx = CX1 - CX2
dy = CY1 - CY2
norm = np.sqrt(dx ** 2 + dy ** 2) + 1e-6
dx = dx / norm
dy = dy / norm
# size: num_track x num_det
return dy, dx
def linear_assignment(cost_matrix):
"""
@param cost_matrix
"""
try:
import lap
_, x, y = lap.lapjv(cost_matrix, extend_cost=True)
return np.array([[y[i], i] for i in x if i >= 0]) #
except ImportError:
from scipy.optimize import linear_sum_assignment
x, y = linear_sum_assignment(cost_matrix)
return np.array(list(zip(x, y)))
def associate_detections_to_trackers(detections, trackers, iou_threshold=0.3):
"""
Assigns detections to tracked object (both represented as bounding boxes)
Returns 3 lists of matches, unmatched_detections and unmatched_trackers
"""
if (len(trackers) == 0):
return np.empty((0, 2), dtype=int), np.arange(len(detections)), np.empty((0, 5), dtype=int)
iou_matrix = iou_batch(detections, trackers)
if min(iou_matrix.shape) > 0:
a = (iou_matrix > iou_threshold).astype(np.int32)
if a.sum(1).max() == 1 and a.sum(0).max() == 1:
matched_indices = np.stack(np.where(a), axis=1)
else:
matched_indices = linear_assignment(-iou_matrix)
else:
matched_indices = np.empty(shape=(0, 2))
unmatched_detections = []
for d, det in enumerate(detections):
if (d not in matched_indices[:, 0]):
unmatched_detections.append(d)
unmatched_trackers = []
for t, trk in enumerate(trackers):
if (t not in matched_indices[:, 1]):
unmatched_trackers.append(t)
# filter out matched with low IOU
matches = []
for m in matched_indices:
if iou_matrix[m[0], m[1]] < iou_threshold:
unmatched_detections.append(m[0])
unmatched_trackers.append(m[1])
else:
matches.append(m.reshape(1, 2))
if len(matches) == 0:
matches = np.empty((0, 2), dtype=int)
else:
matches = np.concatenate(matches, axis=0)
return matches, np.array(unmatched_detections), np.array(unmatched_trackers)
def associate(dets,
trk_pre_obs,
tracks,
velocities,
iou_threshold,
vel_dir_weight):
"""
@parma detections: current detections: x1y1x2y2score
@param trk_pre_obs: current tracks' previous observations
@param tracks: current tracks: x1y1x2y2score
@param velocities: velocity directions of current tracks
@param vel_dir_weight: velocity direction weight(λ)
"""
if len(tracks) == 0 or len(dets) == 0:
return np.empty((0, 2), dtype=int), \
np.arange(len(dets)), \
np.empty((0, 5), dtype=int)
## ----- Velocity direction cost matrix
## Get detections velocity of current frame, size: num_track x num_det
det_vel_y, det_vel_x = velocity_direction_batch(dets, trk_pre_obs)
## Get track velocity of current frame, size: num_track x num_det
trk_vel_y, trk_vel_x = velocities[:, 0], velocities[:, 1]
trk_vel_y = np.repeat(trk_vel_y[:, np.newaxis], det_vel_y.shape[1], axis=1)
trk_vel_x = np.repeat(trk_vel_x[:, np.newaxis], det_vel_x.shape[1], axis=1)
# angle cosine(计算夹角余弦)
diff_angle_cos = trk_vel_x * det_vel_x + trk_vel_y * det_vel_y
diff_angle_cos = np.clip(diff_angle_cos, a_min=-1, a_max=1) # [-1, 1]
diff_angle = np.arccos(diff_angle_cos)
diff_angle = (np.pi / 2.0 - np.abs(diff_angle)) / np.pi # normalize?
valid_mask = np.ones(trk_pre_obs.shape[0])
valid_mask[np.where(trk_pre_obs[:, 4] < 0)] = 0 # score < 0 means invalid
scores = np.repeat(dets[:, -1][:, np.newaxis], tracks.shape[0], axis=1)
# iou_matrix = iou_matrix * scores # a trick sometimes works, we don't encourage this
valid_mask = np.repeat(valid_mask[:, np.newaxis], det_vel_x.shape[1], axis=1)
## OCM: C(X^ ; Z) = CIoU(X^ ; Z) + λCv(X^ ; Z; V)
angle_diff_cost = (valid_mask * diff_angle) * vel_dir_weight
angle_diff_cost = angle_diff_cost.T
angle_diff_cost = angle_diff_cost * scores
## ----- IOU cost matrix
iou_matrix = iou_batch(dets, tracks)
if min(iou_matrix.shape) > 0:
iou_mask = (iou_matrix > iou_threshold).astype(np.int32)
if iou_mask.sum(1).max() == 1 and iou_mask.sum(0).max() == 1:
matched_indices = np.stack(np.where(iou_mask), axis=1)
else:
## ----- negative pairwise IoU (Intersection over Union) and Cv(·; ·)
## why using negative?
matched_indices = linear_assignment(-(iou_matrix + angle_diff_cost))
else:
matched_indices = np.empty(shape=(0, 2))
unmatched_dets = []
for i, det in enumerate(dets):
if i not in matched_indices[:, 0]:
unmatched_dets.append(i)
unmatched_trks = []
for t, trk in enumerate(tracks):
if t not in matched_indices[:, 1]:
unmatched_trks.append(t)
# filter out matched with low IOU
matches = []
for m in matched_indices:
if iou_matrix[m[0], m[1]] < iou_threshold:
unmatched_dets.append(m[0])
unmatched_trks.append(m[1])
else:
matches.append(m.reshape(1, 2))
if len(matches) == 0:
matches = np.empty((0, 2), dtype=int)
else:
matches = np.concatenate(matches, axis=0)
return matches, np.array(unmatched_dets), np.array(unmatched_trks)
def associate_kitti(detections,
trackers,
det_cates,
iou_threshold,
velocities,
previous_obs,
vdc_weight):
"""
@param detections:
"""
if (len(trackers) == 0):
return np.empty((0, 2), dtype=int), np.arange(len(detections)), np.empty((0, 5), dtype=int)
"""
Cost from the velocity direction consistency
"""
Y, X = velocity_direction_batch(detections, previous_obs)
inertia_Y, inertia_X = velocities[:, 0], velocities[:, 1]
inertia_Y = np.repeat(inertia_Y[:, np.newaxis], Y.shape[1], axis=1)
inertia_X = np.repeat(inertia_X[:, np.newaxis], X.shape[1], axis=1)
diff_angle_cos = inertia_X * X + inertia_Y * Y
diff_angle_cos = np.clip(diff_angle_cos, a_min=-1, a_max=1)
diff_angle = np.arccos(diff_angle_cos)
diff_angle = (np.pi / 2.0 - np.abs(diff_angle)) / np.pi
valid_mask = np.ones(previous_obs.shape[0])
valid_mask[np.where(previous_obs[:, 4] < 0)] = 0
valid_mask = np.repeat(valid_mask[:, np.newaxis], X.shape[1], axis=1)
scores = np.repeat(detections[:, -1][:, np.newaxis], trackers.shape[0], axis=1)
angle_diff_cost = (valid_mask * diff_angle) * vdc_weight
angle_diff_cost = angle_diff_cost.T
angle_diff_cost = angle_diff_cost * scores
"""
Cost from IoU
"""
iou_matrix = iou_batch(detections, trackers)
"""
With multiple categories, generate the cost for catgory mismatch
"""
num_dets = detections.shape[0]
num_trk = trackers.shape[0]
cate_matrix = np.zeros((num_dets, num_trk))
for i in range(num_dets):
for j in range(num_trk):
if det_cates[i] != trackers[j, 4]:
cate_matrix[i][j] = -1e6
cost_matrix = - iou_matrix - angle_diff_cost - cate_matrix
if min(iou_matrix.shape) > 0:
a = (iou_matrix > iou_threshold).astype(np.int32)
if a.sum(1).max() == 1 and a.sum(0).max() == 1:
matched_indices = np.stack(np.where(a), axis=1)
else:
matched_indices = linear_assignment(cost_matrix)
else:
matched_indices = np.empty(shape=(0, 2))
unmatched_detections = []
for d, det in enumerate(detections):
if (d not in matched_indices[:, 0]):
unmatched_detections.append(d)
unmatched_trackers = []
for t, trk in enumerate(trackers):
if (t not in matched_indices[:, 1]):
unmatched_trackers.append(t)
# filter out matched with low IOU
matches = []
for m in matched_indices:
if (iou_matrix[m[0], m[1]] < iou_threshold):
unmatched_detections.append(m[0])
unmatched_trackers.append(m[1])
else:
matches.append(m.reshape(1, 2))
if (len(matches) == 0):
matches = np.empty((0, 2), dtype=int)
else:
matches = np.concatenate(matches, axis=0)
return matches, np.array(unmatched_detections), np.array(unmatched_trackers)
|
import numpy as np
def iou_batch(bboxes1, bboxes2):
"""
From SORT: Computes IOU between two bboxes in the form [x1,y1,x2,y2]
"""
bboxes2 = np.expand_dims(bboxes2, 0)
bboxes1 = np.expand_dims(bboxes1, 1)
xx1 = np.maximum(bboxes1[..., 0], bboxes2[..., 0])
yy1 = np.maximum(bboxes1[..., 1], bboxes2[..., 1])
xx2 = np.minimum(bboxes1[..., 2], bboxes2[..., 2])
yy2 = np.minimum(bboxes1[..., 3], bboxes2[..., 3])
w = np.maximum(0., xx2 - xx1)
h = np.maximum(0., yy2 - yy1)
wh = w * h
o = wh / ((bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
+ (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) - wh)
return o
def giou_batch(bboxes1, bboxes2):
"""
:param bbox_p: predict of bbox(N,4)(x1,y1,x2,y2)
:param bbox_g: groundtruth of bbox(N,4)(x1,y1,x2,y2)
:return:
"""
# for details should go to https://arxiv.org/pdf/1902.09630.pdf
# ensure predict's bbox form
bboxes2 = np.expand_dims(bboxes2, 0)
bboxes1 = np.expand_dims(bboxes1, 1)
xx1 = np.maximum(bboxes1[..., 0], bboxes2[..., 0])
yy1 = np.maximum(bboxes1[..., 1], bboxes2[..., 1])
xx2 = np.minimum(bboxes1[..., 2], bboxes2[..., 2])
yy2 = np.minimum(bboxes1[..., 3], bboxes2[..., 3])
w = np.maximum(0., xx2 - xx1)
h = np.maximum(0., yy2 - yy1)
wh = w * h
iou = wh / ((bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
+ (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) - wh)
xxc1 = np.minimum(bboxes1[..., 0], bboxes2[..., 0])
yyc1 = np.minimum(bboxes1[..., 1], bboxes2[..., 1])
xxc2 = np.maximum(bboxes1[..., 2], bboxes2[..., 2])
yyc2 = np.maximum(bboxes1[..., 3], bboxes2[..., 3])
wc = xxc2 - xxc1
hc = yyc2 - yyc1
assert ((wc > 0).all() and (hc > 0).all())
area_enclose = wc * hc
giou = iou - (area_enclose - wh) / area_enclose
giou = (giou + 1.) / 2.0 # resize from (-1,1) to (0,1)
return giou
def diou_batch(bboxes1, bboxes2):
"""
:param bbox_p: predict of bbox(N,4)(x1,y1,x2,y2)
:param bbox_g: groundtruth of bbox(N,4)(x1,y1,x2,y2)
:return:
"""
# for details should go to https://arxiv.org/pdf/1902.09630.pdf
# ensure predict's bbox form
bboxes2 = np.expand_dims(bboxes2, 0)
bboxes1 = np.expand_dims(bboxes1, 1)
# calculate the intersection box
xx1 = np.maximum(bboxes1[..., 0], bboxes2[..., 0])
yy1 = np.maximum(bboxes1[..., 1], bboxes2[..., 1])
xx2 = np.minimum(bboxes1[..., 2], bboxes2[..., 2])
yy2 = np.minimum(bboxes1[..., 3], bboxes2[..., 3])
w = np.maximum(0., xx2 - xx1)
h = np.maximum(0., yy2 - yy1)
wh = w * h
iou = wh / ((bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
+ (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) - wh)
centerx1 = (bboxes1[..., 0] + bboxes1[..., 2]) / 2.0
centery1 = (bboxes1[..., 1] + bboxes1[..., 3]) / 2.0
centerx2 = (bboxes2[..., 0] + bboxes2[..., 2]) / 2.0
centery2 = (bboxes2[..., 1] + bboxes2[..., 3]) / 2.0
inner_diag = (centerx1 - centerx2) ** 2 + (centery1 - centery2) ** 2
xxc1 = np.minimum(bboxes1[..., 0], bboxes2[..., 0])
yyc1 = np.minimum(bboxes1[..., 1], bboxes2[..., 1])
xxc2 = np.maximum(bboxes1[..., 2], bboxes2[..., 2])
yyc2 = np.maximum(bboxes1[..., 3], bboxes2[..., 3])
outer_diag = (xxc2 - xxc1) ** 2 + (yyc2 - yyc1) ** 2
diou = iou - inner_diag / outer_diag
return (diou + 1) / 2.0 # resize from (-1,1) to (0,1)
def ciou_batch(bboxes1, bboxes2):
"""
:param bbox_p: predict of bbox(N,4)(x1,y1,x2,y2)
:param bbox_g: groundtruth of bbox(N,4)(x1,y1,x2,y2)
:return:
"""
# for details should go to https://arxiv.org/pdf/1902.09630.pdf
# ensure predict's bbox form
bboxes2 = np.expand_dims(bboxes2, 0)
bboxes1 = np.expand_dims(bboxes1, 1)
# calculate the intersection box
xx1 = np.maximum(bboxes1[..., 0], bboxes2[..., 0])
yy1 = np.maximum(bboxes1[..., 1], bboxes2[..., 1])
xx2 = np.minimum(bboxes1[..., 2], bboxes2[..., 2])
yy2 = np.minimum(bboxes1[..., 3], bboxes2[..., 3])
w = np.maximum(0., xx2 - xx1)
h = np.maximum(0., yy2 - yy1)
wh = w * h
iou = wh / ((bboxes1[..., 2] - bboxes1[..., 0]) * (bboxes1[..., 3] - bboxes1[..., 1])
+ (bboxes2[..., 2] - bboxes2[..., 0]) * (bboxes2[..., 3] - bboxes2[..., 1]) - wh)
centerx1 = (bboxes1[..., 0] + bboxes1[..., 2]) / 2.0
centery1 = (bboxes1[..., 1] + bboxes1[..., 3]) / 2.0
centerx2 = (bboxes2[..., 0] + bboxes2[..., 2]) / 2.0
centery2 = (bboxes2[..., 1] + bboxes2[..., 3]) / 2.0
inner_diag = (centerx1 - centerx2) ** 2 + (centery1 - centery2) ** 2
xxc1 = np.minimum(bboxes1[..., 0], bboxes2[..., 0])
yyc1 = np.minimum(bboxes1[..., 1], bboxes2[..., 1])
xxc2 = np.maximum(bboxes1[..., 2], bboxes2[..., 2])
yyc2 = np.maximum(bboxes1[..., 3], bboxes2[..., 3])
outer_diag = (xxc2 - xxc1) ** 2 + (yyc2 - yyc1) ** 2
w1 = bboxes1[..., 2] - bboxes1[..., 0]
h1 = bboxes1[..., 3] - bboxes1[..., 1]
w2 = bboxes2[..., 2] - bboxes2[..., 0]
h2 = bboxes2[..., 3] - bboxes2[..., 1]
# prevent dividing over zero. add one pixel shift
h2 = h2 + 1.
h1 = h1 + 1.
arctan = np.arctan(w2 / h2) - np.arctan(w1 / h1)
v = (4 / (np.pi ** 2)) * (arctan ** 2)
S = 1 - iou
alpha = v / (S + v)
ciou = iou - inner_diag / outer_diag - alpha * v
return (ciou + 1) / 2.0 # resize from (-1,1) to (0,1)
def ct_dist(bboxes1, bboxes2):
"""
Measure the center distance between two sets of bounding boxes,
this is a coarse implementation, we don't recommend using it only
for association, which can be unstable and sensitive to frame rate
and object speed.
"""
bboxes2 = np.expand_dims(bboxes2, 0)
bboxes1 = np.expand_dims(bboxes1, 1)
centerx1 = (bboxes1[..., 0] + bboxes1[..., 2]) / 2.0
centery1 = (bboxes1[..., 1] + bboxes1[..., 3]) / 2.0
centerx2 = (bboxes2[..., 0] + bboxes2[..., 2]) / 2.0
centery2 = (bboxes2[..., 1] + bboxes2[..., 3]) / 2.0
ct_dist2 = (centerx1 - centerx2) ** 2 + (centery1 - centery2) ** 2
ct_dist = np.sqrt(ct_dist2)
# The linear rescaling is a naive version and needs more study
ct_dist = ct_dist / ct_dist.max()
return ct_dist.max() - ct_dist # resize to (0,1)
def velocity_direction_batch(dets, tracks):
"""
@param dets: x1, y1, x2,y2, score
@param tracks:
"""
tracks = tracks[..., np.newaxis]
# center x, center y
CX1, CY1 = (dets[:, 0] + dets[:, 2]) * 0.5, (dets[:, 1] + dets[:, 3]) * 0.5
CX2, CY2 = (tracks[:, 0] + tracks[:, 2]) * 0.5, (tracks[:, 1] + tracks[:, 3]) * 0.5
dx = CX1 - CX2
dy = CY1 - CY2
norm = np.sqrt(dx ** 2 + dy ** 2) + 1e-6
dx = dx / norm
dy = dy / norm
# size: num_track x num_det
return dy, dx
def linear_assignment(cost_matrix):
"""
@param cost_matrix
"""
try:
import lap
_, x, y = lap.lapjv(cost_matrix, extend_cost=True)
return np.array([[y[i], i] for i in x if i >= 0]) #
except ImportError:
from scipy.optimize import linear_sum_assignment
x, y = linear_sum_assignment(cost_matrix)
return np.array(list(zip(x, y)))
def associate_detections_to_trackers(detections, trackers, iou_threshold=0.3):
"""
Assigns detections to tracked object (both represented as bounding boxes)
Returns 3 lists of matches, unmatched_detections and unmatched_trackers
"""
if (len(trackers) == 0):
return np.empty((0, 2), dtype=int), np.arange(len(detections)), np.empty((0, 5), dtype=int)
iou_matrix = iou_batch(detections, trackers)
if min(iou_matrix.shape) > 0:
a = (iou_matrix > iou_threshold).astype(np.int32)
if a.sum(1).max() == 1 and a.sum(0).max() == 1:
matched_indices = np.stack(np.where(a), axis=1)
else:
matched_indices = linear_assignment(-iou_matrix)
else:
matched_indices = np.empty(shape=(0, 2))
unmatched_detections = []
for d, det in enumerate(detections):
if (d not in matched_indices[:, 0]):
unmatched_detections.append(d)
unmatched_trackers = []
for t, trk in enumerate(trackers):
if (t not in matched_indices[:, 1]):
unmatched_trackers.append(t)
# filter out matched with low IOU
matches = []
for m in matched_indices:
if iou_matrix[m[0], m[1]] < iou_threshold:
unmatched_detections.append(m[0])
unmatched_trackers.append(m[1])
else:
matches.append(m.reshape(1, 2))
if len(matches) == 0:
matches = np.empty((0, 2), dtype=int)
else:
matches = np.concatenate(matches, axis=0)
return matches, np.array(unmatched_detections), np.array(unmatched_trackers)
def associate(dets,
trk_pre_obs,
tracks,
velocities,
iou_threshold,
vel_dir_weight):
"""
@parma detections: current detections: x1y1x2y2score
@param trk_pre_obs: current tracks' previous observations
@param tracks: current tracks: x1y1x2y2score
@param velocities: velocity directions of current tracks
@param vel_dir_weight: velocity direction weight(λ)
"""
if len(tracks) == 0 or len(dets) == 0:
return np.empty((0, 2), dtype=int), \
np.arange(len(dets)), \
np.empty((0, 5), dtype=int)
## ----- Velocity direction cost matrix
## Get detections velocity of current frame, size: num_track x num_det
det_vel_y, det_vel_x = velocity_direction_batch(dets, trk_pre_obs)
## Get track velocity of current frame, size: num_track x num_det
trk_vel_y, trk_vel_x = velocities[:, 0], velocities[:, 1]
trk_vel_y = np.repeat(trk_vel_y[:, np.newaxis], det_vel_y.shape[1], axis=1)
trk_vel_x = np.repeat(trk_vel_x[:, np.newaxis], det_vel_x.shape[1], axis=1)
# angle cosine(计算夹角余弦)
diff_angle_cos = trk_vel_x * det_vel_x + trk_vel_y * det_vel_y
diff_angle_cos = np.clip(diff_angle_cos, a_min=-1, a_max=1) # [-1, 1]
diff_angle = np.arccos(diff_angle_cos)
diff_angle = (np.pi / 2.0 - np.abs(diff_angle)) / np.pi # normalize?
valid_mask = np.ones(trk_pre_obs.shape[0])
valid_mask[np.where(trk_pre_obs[:, 4] < 0)] = 0 # score < 0 means invalid
scores = np.repeat(dets[:, -1][:, np.newaxis], tracks.shape[0], axis=1)
# iou_matrix = iou_matrix * scores # a trick sometimes works, we don't encourage this
valid_mask = np.repeat(valid_mask[:, np.newaxis], det_vel_x.shape[1], axis=1)
## OCM: C(X^ ; Z) = CIoU(X^ ; Z) + λCv(X^ ; Z; V)
angle_diff_cost = (valid_mask * diff_angle) * vel_dir_weight
angle_diff_cost = angle_diff_cost.T
angle_diff_cost = angle_diff_cost * scores
## ----- IOU cost matrix
iou_matrix = iou_batch(dets, tracks)
if min(iou_matrix.shape) > 0:
iou_mask = (iou_matrix > iou_threshold).astype(np.int32)
if iou_mask.sum(1).max() == 1 and iou_mask.sum(0).max() == 1:
matched_indices = np.stack(np.where(iou_mask), axis=1)
else:
## ----- negative pairwise IoU (Intersection over Union) and Cv(·; ·)
## why using negative?
matched_indices = linear_assignment(-(iou_matrix + angle_diff_cost))
else:
matched_indices = np.empty(shape=(0, 2))
unmatched_dets = []
for i, det in enumerate(dets):
if i not in matched_indices[:, 0]:
unmatched_dets.append(i)
unmatched_trks = []
for t, trk in enumerate(tracks):
if t not in matched_indices[:, 1]:
unmatched_trks.append(t)
# filter out matched with low IOU
matches = []
for m in matched_indices:
if iou_matrix[m[0], m[1]] < iou_threshold:
unmatched_dets.append(m[0])
unmatched_trks.append(m[1])
else:
matches.append(m.reshape(1, 2))
if len(matches) == 0:
matches = np.empty((0, 2), dtype=int)
else:
matches = np.concatenate(matches, axis=0)
return matches, np.array(unmatched_dets), np.array(unmatched_trks)
def associate_kitti(detections,
trackers,
det_cates,
iou_threshold,
velocities,
previous_obs,
vdc_weight):
"""
@param detections:
"""
if (len(trackers) == 0):
return np.empty((0, 2), dtype=int), np.arange(len(detections)), np.empty((0, 5), dtype=int)
"""
Cost from the velocity direction consistency
"""
Y, X = velocity_direction_batch(detections, previous_obs)
inertia_Y, inertia_X = velocities[:, 0], velocities[:, 1]
inertia_Y = np.repeat(inertia_Y[:, np.newaxis], Y.shape[1], axis=1)
inertia_X = np.repeat(inertia_X[:, np.newaxis], X.shape[1], axis=1)
diff_angle_cos = inertia_X * X + inertia_Y * Y
diff_angle_cos = np.clip(diff_angle_cos, a_min=-1, a_max=1)
diff_angle = np.arccos(diff_angle_cos)
diff_angle = (np.pi / 2.0 - np.abs(diff_angle)) / np.pi
valid_mask = np.ones(previous_obs.shape[0])
valid_mask[np.where(previous_obs[:, 4] < 0)] = 0
valid_mask = np.repeat(valid_mask[:, np.newaxis], X.shape[1], axis=1)
scores = np.repeat(detections[:, -1][:, np.newaxis], trackers.shape[0], axis=1)
angle_diff_cost = (valid_mask * diff_angle) * vdc_weight
angle_diff_cost = angle_diff_cost.T
angle_diff_cost = angle_diff_cost * scores
"""
Cost from IoU
"""
iou_matrix = iou_batch(detections, trackers)
"""
With multiple categories, generate the cost for catgory mismatch
"""
num_dets = detections.shape[0]
num_trk = trackers.shape[0]
cate_matrix = np.zeros((num_dets, num_trk))
for i in range(num_dets):
for j in range(num_trk):
if det_cates[i] != trackers[j, 4]:
cate_matrix[i][j] = -1e6
cost_matrix = - iou_matrix - angle_diff_cost - cate_matrix
if min(iou_matrix.shape) > 0:
a = (iou_matrix > iou_threshold).astype(np.int32)
if a.sum(1).max() == 1 and a.sum(0).max() == 1:
matched_indices = np.stack(np.where(a), axis=1)
else:
matched_indices = linear_assignment(cost_matrix)
else:
matched_indices = np.empty(shape=(0, 2))
unmatched_detections = []
for d, det in enumerate(detections):
if (d not in matched_indices[:, 0]):
unmatched_detections.append(d)
unmatched_trackers = []
for t, trk in enumerate(trackers):
if (t not in matched_indices[:, 1]):
unmatched_trackers.append(t)
# filter out matched with low IOU
matches = []
for m in matched_indices:
if (iou_matrix[m[0], m[1]] < iou_threshold):
unmatched_detections.append(m[0])
unmatched_trackers.append(m[1])
else:
matches.append(m.reshape(1, 2))
if (len(matches) == 0):
matches = np.empty((0, 2), dtype=int)
else:
matches = np.concatenate(matches, axis=0)
return matches, np.array(unmatched_detections), np.array(unmatched_trackers)
|
en
| 0.730812
|
From SORT: Computes IOU between two bboxes in the form [x1,y1,x2,y2] :param bbox_p: predict of bbox(N,4)(x1,y1,x2,y2) :param bbox_g: groundtruth of bbox(N,4)(x1,y1,x2,y2) :return: # for details should go to https://arxiv.org/pdf/1902.09630.pdf # ensure predict's bbox form # resize from (-1,1) to (0,1) :param bbox_p: predict of bbox(N,4)(x1,y1,x2,y2) :param bbox_g: groundtruth of bbox(N,4)(x1,y1,x2,y2) :return: # for details should go to https://arxiv.org/pdf/1902.09630.pdf # ensure predict's bbox form # calculate the intersection box # resize from (-1,1) to (0,1) :param bbox_p: predict of bbox(N,4)(x1,y1,x2,y2) :param bbox_g: groundtruth of bbox(N,4)(x1,y1,x2,y2) :return: # for details should go to https://arxiv.org/pdf/1902.09630.pdf # ensure predict's bbox form # calculate the intersection box # prevent dividing over zero. add one pixel shift # resize from (-1,1) to (0,1) Measure the center distance between two sets of bounding boxes, this is a coarse implementation, we don't recommend using it only for association, which can be unstable and sensitive to frame rate and object speed. # The linear rescaling is a naive version and needs more study # resize to (0,1) @param dets: x1, y1, x2,y2, score @param tracks: # center x, center y # size: num_track x num_det @param cost_matrix # Assigns detections to tracked object (both represented as bounding boxes) Returns 3 lists of matches, unmatched_detections and unmatched_trackers # filter out matched with low IOU @parma detections: current detections: x1y1x2y2score @param trk_pre_obs: current tracks' previous observations @param tracks: current tracks: x1y1x2y2score @param velocities: velocity directions of current tracks @param vel_dir_weight: velocity direction weight(λ) ## ----- Velocity direction cost matrix ## Get detections velocity of current frame, size: num_track x num_det ## Get track velocity of current frame, size: num_track x num_det # angle cosine(计算夹角余弦) # [-1, 1] # normalize? # score < 0 means invalid # iou_matrix = iou_matrix * scores # a trick sometimes works, we don't encourage this ## OCM: C(X^ ; Z) = CIoU(X^ ; Z) + λCv(X^ ; Z; V) ## ----- IOU cost matrix ## ----- negative pairwise IoU (Intersection over Union) and Cv(·; ·) ## why using negative? # filter out matched with low IOU @param detections: Cost from the velocity direction consistency Cost from IoU With multiple categories, generate the cost for catgory mismatch # filter out matched with low IOU
| 2.470597
| 2
|
qiskit/_quantumprogram.py
|
Hosseinyeganeh/qiskit-core
| 0
|
6626305
|
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Qasm Program Class
"""
import itertools
import json
import logging
import warnings
import qiskit.wrapper
from ._classicalregister import ClassicalRegister
from ._logging import set_qiskit_logger, unset_qiskit_logger
from ._qiskiterror import QISKitError
from ._quantumcircuit import QuantumCircuit
from ._quantumjob import QuantumJob
from ._quantumregister import QuantumRegister
from .mapper import coupling_dict2list
from .qasm import Qasm
logger = logging.getLogger(__name__)
class QuantumProgram(object):
"""Quantum Program Class.
Class internal properties.
Elements that are not python identifiers or string constants are denoted
by "--description (type)--". For example, a circuit's name is denoted by
"--circuit name (string)--" and might have the value "teleport".
Internal::
__quantum_registers (list[dic]): An dictionary of quantum registers
used in the quantum program.
__quantum_registers =
{
--register name (string)--: QuantumRegister,
}
__classical_registers (list[dic]): An ordered list of classical
registers used in the quantum program.
__classical_registers =
{
--register name (string)--: ClassicalRegister,
}
__quantum_program (dic): An dictionary of quantum circuits
__quantum_program =
{
--circuit name (string)--: --circuit object --,
}
__init_circuit (obj): A quantum circuit object for the initial quantum
circuit
"""
# -- FUTURE IMPROVEMENTS --
# TODO: for status results make ALL_CAPS (check) or some unified method
# TODO: Jay: coupling_map, basis_gates will move into a config object
# only exists once you set the api to use the online backends
__api = None
__api_config = {}
def __init__(self, specs=None):
self.__quantum_registers = {}
self.__classical_registers = {}
self.__quantum_program = {} # stores all the quantum programs
self.__init_circuit = None # stores the initial quantum circuit of the program
self.__counter = itertools.count()
if specs:
self.__init_specs(specs)
def enable_logs(self, level=logging.INFO):
"""Enable the console output of the logging messages.
Enable the output of logging messages (above level `level`) to the
console, by configuring the `qiskit` logger accordingly.
Params:
level (int): minimum severity of the messages that are displayed.
Note:
This is a convenience method over the standard Python logging
facilities, and modifies the configuration of the 'qiskit.*'
loggers. If finer control over the logging configuration is needed,
it is encouraged to bypass this method.
"""
# Update the handlers and formatters.
set_qiskit_logger()
# Set the logger level.
logging.getLogger('qiskit').setLevel(level)
def disable_logs(self):
"""Disable the console output of the logging messages.
Disable the output of logging messages (above level `level`) to the
console, by removing the handlers from the `qiskit` logger.
Note:
This is a convenience method over the standard Python logging
facilities, and modifies the configuration of the 'qiskit.*'
loggers. If finer control over the logging configuration is needed,
it is encouraged to bypass this method.
"""
unset_qiskit_logger()
###############################################################
# methods to initiate an build a quantum program
###############################################################
def __init_specs(self, specs):
"""Populate the Quantum Program Object with initial Specs.
Args:
specs (dict):
Q_SPECS = {
"circuits": [{
"name": "Circuit",
"quantum_registers": [{
"name": "qr",
"size": 4
}],
"classical_registers": [{
"name": "cr",
"size": 4
}]
}],
"""
quantum_r = []
classical_r = []
if "circuits" in specs:
for circuit in specs["circuits"]:
quantum_r = self.create_quantum_registers(
circuit["quantum_registers"])
classical_r = self.create_classical_registers(
circuit["classical_registers"])
self.create_circuit(name=circuit.get("name"), qregisters=quantum_r,
cregisters=classical_r)
# TODO: Jay: I think we should return function handles for the
# registers and circuit. So that we dont need to get them after we
# create them with get_quantum_register etc
def create_quantum_register(self, name=None, size=1):
"""Create a new Quantum Register.
Args:
name (str or None): the name of the quantum register. If None, an
automatically generated identifier will be assigned.
size (int): the size of the quantum register
Returns:
QuantumRegister: internal reference to a quantum register in
__quantum_registers
Raises:
QISKitError: if the register already exists in the program.
"""
if name is not None and name in self.__quantum_registers:
if size != len(self.__quantum_registers[name]):
raise QISKitError("Can't make this register: Already in"
" program with different size")
logger.info(">> quantum_register exists: %s %s", name, size)
return self.__quantum_registers[name]
if name is None:
name = self._create_id('q', self.__quantum_registers)
if not isinstance(name, str):
logger.info(">> quantum_register name is not a valid type: %s ", type(name))
raise QISKitError("The register name should be a string "
"(or None for autogenerate a name).")
self.__quantum_registers[name] = QuantumRegister(size=size, name=name)
logger.info(">> new quantum_register created: %s %s", name, size)
return self.__quantum_registers[name]
def destroy_quantum_register(self, name):
"""Destroy an existing Quantum Register.
Args:
name (str): the name of the quantum register
Raises:
QISKitError: if the register does not exist in the program.
"""
if name not in self.__quantum_registers:
raise QISKitError("Can't destroy this register: Not present")
else:
logger.info(">> quantum_register destroyed: %s", name)
del self.__quantum_registers[name]
def create_quantum_registers(self, register_array):
"""Create a new set of Quantum Registers based on a array of them.
Args:
register_array (list[dict]): An array of quantum registers in
dictionary format. For example::
[{"name": "qr", "size": 4},
...
]
Any other key in the dictionary will be ignored. If "name"
is not defined (or None) a random name wil be assigned.
Returns:
list(QuantumRegister): Array of quantum registers objects
"""
new_reg = []
for reg in register_array:
reg = self.create_quantum_register(
reg.get('name'), reg["size"])
new_reg.append(reg)
return new_reg
def destroy_quantum_registers(self, register_array):
"""Destroy a set of Quantum Registers based on a array of them.
Args:
register_array (list[dict]): An array of quantum registers in
dictionary format. For example::
[{"name": "qr"},
...
]
Any other key in the dictionary will be ignored.
"""
for reg in register_array:
self.destroy_quantum_register(reg["name"])
def create_classical_register(self, name=None, size=1):
"""Create a new Classical Register.
Args:
name (str or None): the name of the classical register. If None, an
automatically generated identifier will be assigned..
size (int): the size of the classical register
Returns:
ClassicalRegister: internal reference to a classical register
in __classical_registers
Raises:
QISKitError: if the register already exists in the program.
"""
if name is not None and name in self.__classical_registers:
if size != len(self.__classical_registers[name]):
raise QISKitError("Can't make this register: Already in"
" program with different size")
logger.info(">> classical register exists: %s %s", name, size)
return self.__classical_registers[name]
if name is None:
name = self._create_id('c', self.__classical_registers)
if not isinstance(name, str):
logger.info(">> quantum_register name is not a valid type: %s ", type(name))
raise QISKitError("The register name should be a string "
"(or None for autogenerate a name).")
self.__classical_registers[name] = ClassicalRegister(size=size, name=name)
logger.info(">> new classical register created: %s %s", name, size)
return self.__classical_registers[name]
def create_classical_registers(self, registers_array):
"""Create a new set of Classical Registers based on a array of them.
Args:
registers_array (list[dict]): An array of classical registers in
dictionary format. For example::
[{"name": "cr", "size": 4},
...
]
Any other key in the dictionary will be ignored. If "name"
is not defined (or None) a random name wil be assigned.
Returns:
list(ClassicalRegister): Array of classical registers objects
"""
new_reg = []
for reg in registers_array:
new_reg.append(self.create_classical_register(
reg.get("name"), reg["size"]))
return new_reg
def destroy_classical_register(self, name):
"""Destroy an existing Classical Register.
Args:
name (str): the name of the classical register
Raises:
QISKitError: if the register does not exist in the program.
"""
if name not in self.__classical_registers:
raise QISKitError("Can't destroy this register: Not present")
else:
logger.info(">> classical register destroyed: %s", name)
del self.__classical_registers[name]
def destroy_classical_registers(self, registers_array):
"""Destroy a set of Classical Registers based on a array of them.
Args:
registers_array (list[dict]): An array of classical registers in
dictionary format. For example::
[{"name": "cr"},
...
]
Any other key in the dictionary will be ignored.
"""
for reg in registers_array:
self.destroy_classical_register(reg["name"])
def create_circuit(self, name=None, qregisters=None, cregisters=None):
"""Create a empty Quantum Circuit in the Quantum Program.
Args:
name (str or None): the name of the circuit. If None, an
automatically generated identifier will be assigned.
qregisters (list(QuantumRegister)): is an Array of Quantum
Registers by object reference
cregisters (list(ClassicalRegister)): is an Array of Classical
Registers by object reference
Returns:
QuantumCircuit: A quantum circuit is created and added to the
Quantum Program
"""
if name is None:
name = self._create_id('qc', self.__quantum_program.keys())
if not qregisters:
qregisters = []
if not cregisters:
cregisters = []
quantum_circuit = QuantumCircuit(name=name)
if not self.__init_circuit:
self.__init_circuit = quantum_circuit
for reg in qregisters:
quantum_circuit.add(reg)
for reg in cregisters:
quantum_circuit.add(reg)
self.add_circuit(name, quantum_circuit)
return self.__quantum_program[name]
def destroy_circuit(self, name):
"""Destroy a Quantum Circuit in the Quantum Program. This will not
destroy any registers associated with the circuit.
Args:
name (str): the name of the circuit
Raises:
QISKitError: if the register does not exist in the program.
"""
if name not in self.__quantum_program:
raise QISKitError("Can't destroy this circuit: Not present")
del self.__quantum_program[name]
def add_circuit(self, name=None, quantum_circuit=None):
"""Add a new circuit based on an Object representation.
Args:
name (str or None): the name of the circuit to add. If None, an
automatically generated identifier will be assigned to the
circuit.
quantum_circuit (QuantumCircuit): a quantum circuit to add to the
program-name
Raises:
QISKitError: if `quantum_circuit` is None, as the attribute is
optional only for not breaking backwards compatibility (as
it is placed after an optional argument).
"""
if quantum_circuit is None:
raise QISKitError('quantum_circuit is required when invoking '
'add_circuit')
if name is None:
if quantum_circuit.name:
name = quantum_circuit.name
else:
name = self._create_id('qc', self.__quantum_program.keys())
quantum_circuit.name = name
self.__quantum_program[name] = quantum_circuit
def load_qasm_file(self, qasm_file, name=None,
basis_gates='u1,u2,u3,cx,id'):
""" Load qasm file into the quantum program.
Args:
qasm_file (str): a string for the filename including its location.
name (str or None): the name of the quantum circuit after
loading qasm text into it. If no name is give the name is of
the text file.
basis_gates (str): basis gates for the quantum circuit.
Returns:
str: Adds a quantum circuit with the gates given in the qasm file to the
quantum program and returns the name to be used to get this circuit
Raises:
QISKitError: if the file cannot be read.
"""
warnings.warn(
"QuantumProgram.load_qasm_file() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.load_qasm_file() instead is recommended.", DeprecationWarning)
circuit_unrolled = qiskit.wrapper.load_qasm_file(qasm_file, name, basis_gates)
self.add_circuit(name, circuit_unrolled)
return name
def load_qasm_text(self, qasm_string, name=None,
basis_gates='u1,u2,u3,cx,id'):
""" Load qasm string in the quantum program.
Args:
qasm_string (str): a string for the file name.
name (str or None): the name of the quantum circuit after loading qasm
text into it. If no name is give the name is of the text file.
basis_gates (str): basis gates for the quantum circuit.
Returns:
str: Adds a quantum circuit with the gates given in the qasm string to
the quantum program.
"""
warnings.warn(
"QuantumProgram.load_qasm_text() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.load_qasm_text() instead is recommended.", DeprecationWarning)
circuit_unrolled = qiskit.wrapper.load_qasm_string(qasm_string, name, basis_gates)
self.add_circuit(name, circuit_unrolled)
return name
def save(self, file_name=None, beauty=False):
""" Save Quantum Program in a Json file.
Args:
file_name (str): file name and path.
beauty (boolean): save the text with indent 4 to make it readable.
Returns:
dict: The dictionary with the status and result of the operation
Raises:
LookupError: if the file_name is not correct, or writing to the
file resulted in an error.
"""
if file_name is None:
error = {"status": "Error", "result": "Not filename provided"}
raise LookupError(error['result'])
if beauty:
indent = 4
else:
indent = 0
elements_to_save = self.__quantum_program
elements_saved = {}
for circuit in elements_to_save:
elements_saved[circuit] = {}
elements_saved[circuit]["qasm"] = elements_to_save[circuit].qasm()
try:
with open(file_name, 'w') as save_file:
json.dump(elements_saved, save_file, indent=indent)
return {'status': 'Done', 'result': elements_to_save}
except ValueError:
error = {'status': 'Error', 'result': 'Some Problem happened to save the file'}
raise LookupError(error['result'])
def load(self, file_name=None):
""" Load Quantum Program Json file into the Quantum Program object.
Args:
file_name (str): file name and path.
Returns:
dict: The dictionary with the status and result of the operation
Raises:
LookupError: if the file_name is not correct, or reading from the
file resulted in an error.
"""
if file_name is None:
error = {"status": "Error", "result": "Not filename provided"}
raise LookupError(error['result'])
try:
with open(file_name, 'r') as load_file:
elements_loaded = json.load(load_file)
for circuit in elements_loaded:
circuit_qasm = elements_loaded[circuit]["qasm"]
elements_loaded[circuit] = Qasm(data=circuit_qasm).parse()
self.__quantum_program = elements_loaded
return {"status": 'Done', 'result': self.__quantum_program}
except ValueError:
error = {'status': 'Error', 'result': 'Some Problem happened to load the file'}
raise LookupError(error['result'])
###############################################################
# methods to get elements from a QuantumProgram
###############################################################
def get_quantum_register(self, name=None):
"""Return a Quantum Register by name.
Args:
name (str or None): the name of the quantum register. If None and there is only
one quantum register available, returns that one.
Returns:
QuantumRegister: The quantum register with this name.
Raises:
KeyError: if the quantum register is not on the quantum program.
QISKitError: if the register does not exist in the program.
"""
if name is None:
name = self._get_single_item(self.get_quantum_register_names(), "a quantum register")
try:
return self.__quantum_registers[name]
except KeyError:
raise KeyError('No quantum register "{0}"'.format(name))
def get_classical_register(self, name=None):
"""Return a Classical Register by name.
Args:
name (str or None): the name of the classical register. If None and there is only
one classical register available, returns that one.
Returns:
ClassicalRegister: The classical register with this name.
Raises:
KeyError: if the classical register is not on the quantum program.
QISKitError: if the register does not exist in the program.
"""
if name is None:
name = self._get_single_item(self.get_classical_register_names(),
"a classical register")
try:
return self.__classical_registers[name]
except KeyError:
raise KeyError('No classical register "{0}"'.format(name))
def get_quantum_register_names(self):
"""Return all the names of the quantum Registers."""
return sorted(list(self.__quantum_registers.keys()))
def get_classical_register_names(self):
"""Return all the names of the classical Registers."""
return sorted(list(self.__classical_registers.keys()))
def get_circuit(self, name=None):
"""Return a Circuit Object by name.
Args:
name (str or None): the name of the quantum circuit.
If None and there is only one circuit available, returns
that one.
Returns:
QuantumCircuit: The quantum circuit with this name
Raises:
KeyError: if the circuit is not on the quantum program.
QISKitError: if the register does not exist in the program.
"""
if name is None:
name = self._get_single_item(self.get_circuit_names(), "a circuit")
try:
return self.__quantum_program[name]
except KeyError:
raise KeyError('No quantum circuit "{0}"'.format(name))
def get_circuit_names(self):
"""Return all the names of the quantum circuits."""
return sorted(list(self.__quantum_program.keys()))
def get_qasm(self, name=None):
"""Get qasm format of circuit by name.
Args:
name (str or None): name of the circuit. If None and only one circuit is
available, that one is selected.
Returns:
str: The quantum circuit in qasm format
Raises:
QISKitError: if the register does not exist in the program.
"""
if name is None:
name = self._get_single_item(self.get_circuit_names(), "a circuit")
quantum_circuit = self.get_circuit(name)
return quantum_circuit.qasm()
def get_qasms(self, list_circuit_name=None):
"""Get qasm format of circuit by list of names.
Args:
list_circuit_name (list[str] or None): names of the circuit. If None, it gets all the
circuits in the program.
Returns:
list(QuantumCircuit): List of quantum circuit in qasm format
Raises:
QISKitError: if the register does not exist in the program.
"""
qasm_source = []
if list_circuit_name is None:
list_circuit_name = self.get_circuit_names()
for name in list_circuit_name:
qasm_source.append(self.get_qasm(name))
return qasm_source
def get_initial_circuit(self):
"""Return the initialization Circuit."""
return self.__init_circuit
###############################################################
# methods for working with backends
###############################################################
def set_api(self, token, url, hub=None, group=None, project=None,
proxies=None, verify=True):
""" Setup the API.
Fills the __api, and __api_config variables.
Does not catch exceptions from IBMQuantumExperience.
Args:
token (str): The token used to register on the online backend such
as the quantum experience.
url (str): The url used for online backend such as the quantum
experience.
hub (str): The hub used for online backend.
group (str): The group used for online backend.
project (str): The project used for online backend.
proxies (dict): Proxy configuration for the API, as a dict with
'urls' and credential keys.
verify (bool): If False, ignores SSL certificates errors.
Raises:
ConnectionError: if the API instantiation failed.
QISKitError: if no hub, group or project were specified.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
API object instead is recommended.
"""
# TODO: remove the tests as well when the deprecation is completed
warnings.warn(
"set_api() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.register() instead is recommended.", DeprecationWarning)
qiskit.wrapper.register(token, url,
hub, group, project, proxies, verify,
provider_name='ibmq')
# TODO: the setting of self._api and self.__api_config is left for
# backwards-compatibility.
# pylint: disable=no-member
self.__api = qiskit.wrapper._wrapper._DEFAULT_PROVIDER.providers[-1]._api
config_dict = {
'url': url,
}
# Only append hub/group/project if they are different than None.
if all([hub, group, project]):
config_dict.update({
'hub': hub,
'group': group,
'project': project
})
if proxies:
config_dict['proxies'] = proxies
self.__api_config["token"] = token
self.__api_config["config"] = config_dict.copy()
def set_api_hubs_config(self, hub, group, project):
"""Update the API hubs configuration, replacing the previous one.
hub (str): The hub used for online backend.
group (str): The group used for online backend.
project (str): The project used for online backend.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
API object instead is recommended.
"""
warnings.warn(
"set_api_hubs_config() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.register(token, url, hub, group, project) "
"instead is recommended.", DeprecationWarning)
config_dict = {
'hub': hub,
'group': group,
'project': project
}
for key, value in config_dict.items():
self.__api.config[key] = value
self.__api_config['config'][key] = value
def get_api_config(self):
"""Return the program specs.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
API object instead is recommended.
"""
warnings.warn(
"get_api_config() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.register() instead is recommended.", DeprecationWarning)
return self.__api_config
def get_api(self):
"""Returns a function handle to the API.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
API object instead is recommended.
"""
warnings.warn(
"get_api() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.register() instead is recommended.", DeprecationWarning)
return self.__api
def available_backends(self, compact=True):
"""All the backends that are seen by QISKIT.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"available_backends() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.available_backends() instead is recommended.",
DeprecationWarning)
return qiskit.wrapper.available_backends(compact=compact)
def online_backends(self):
"""Get the online backends.
Queries network API if it exists and gets the backends that are online.
Returns:
list(str): List of online backends names if the online api has been set or an empty
list if it has not been set.
Raises:
ConnectionError: if the API call failed.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"online_backends() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.available_backends({'local': False}) is recommended "
"instead.", DeprecationWarning)
return qiskit.wrapper.remote_backends()
def online_simulators(self):
"""Gets online simulators via QX API calls.
Returns:
list(str): List of online simulator names.
Raises:
ConnectionError: if the API call failed.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"online_simulators() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.available_backends({'local': False, 'simulator': True}) "
"is recommended.", DeprecationWarning)
return qiskit.wrapper.available_backends({'local': False,
'simulator': True})
def online_devices(self):
"""Gets online devices via QX API calls.
Returns:
list(str): List of online devices names.
Raises:
ConnectionError: if the API call failed.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"online_devices() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.available_backends({'local': False, 'simulator': False}) "
"is recommended.", DeprecationWarning)
return qiskit.wrapper.available_backends({'local': False,
'simulator': False})
def get_backend_status(self, backend):
"""Return the online backend status.
It uses QX API call or by local backend is the name of the
local or online simulator or experiment.
Args:
backend (str): The backend to check
Returns:
dict: {'available': True}
Raises:
ConnectionError: if the API call failed.
ValueError: if the backend is not available.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"get_backend_status() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.get_backend('name').status "
"instead is recommended.", DeprecationWarning)
my_backend = qiskit.wrapper.get_backend(backend)
return my_backend.status
def get_backend_configuration(self, backend):
"""Return the configuration of the backend.
The return is via QX API call.
Args:
backend (str): Name of the backend.
Returns:
dict: The configuration of the named backend.
Raises:
ConnectionError: if the API call failed.
LookupError: if a configuration for the named backend can't be
found.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"get_backend_configuration() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.get_backend('name').configuration "
"instead is recommended.", DeprecationWarning)
my_backend = qiskit.wrapper.get_backend(backend)
return my_backend.configuration
def get_backend_calibration(self, backend):
"""Return the online backend calibrations.
The return is via QX API call.
Args:
backend (str): Name of the backend.
Returns:
dict: The calibration of the named backend.
Raises:
ConnectionError: if the API call failed.
LookupError: If a configuration for the named backend can't be
found.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"get_backend_calibration() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.get_backend('name').calibration "
"instead is recommended.", DeprecationWarning)
my_backend = qiskit.wrapper.get_backend(backend)
return my_backend.calibration
def get_backend_parameters(self, backend):
"""Return the online backend parameters.
The return is via QX API call.
Args:
backend (str): Name of the backend.
Returns:
dict: The configuration of the named backend.
Raises:
ConnectionError: if the API call failed.
LookupError: If a configuration for the named backend can't be
found.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"get_backend_parameters() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.get_backend('name').parameters"
"instead is recommended.", DeprecationWarning)
my_backend = qiskit.wrapper.get_backend(backend)
return my_backend.parameters
###############################################################
# methods to compile quantum programs into qobj
###############################################################
def compile(self, name_of_circuits=None, backend="local_qasm_simulator",
config=None, basis_gates=None, coupling_map=None,
initial_layout=None, shots=1024, max_credits=10, seed=None,
qobj_id=None, hpc=None, skip_transpiler=False, skip_translation=False):
"""Compile the circuits into the execution list.
.. deprecated:: 0.5
The `coupling_map` parameter as a dictionary will be deprecated in
upcoming versions. Using the coupling_map as a list is recommended.
"""
# pylint: disable=missing-param-doc, missing-type-doc
if skip_translation:
warnings.warn(
"skip_translation will be called skip_transpiler in future versions.",
DeprecationWarning)
skip_transpiler = True
if isinstance(coupling_map, dict):
coupling_map = coupling_dict2list(coupling_map)
warnings.warn(
"coupling_map as a dictionary will be deprecated in upcoming versions (>0.5.0). "
"Using the coupling_map as a list is recommended.", DeprecationWarning)
list_of_circuits = []
if not name_of_circuits:
logger.info('Since not circuits was specified, all the circuits will be compiled.')
name_of_circuits = self.get_circuit_names()
if isinstance(name_of_circuits, str):
name_of_circuits = [name_of_circuits]
if name_of_circuits:
for name in name_of_circuits:
self.__quantum_program[name].name = name
list_of_circuits.append(self.__quantum_program[name])
my_backend = qiskit.wrapper.get_backend(backend)
qobj = qiskit.wrapper.compile(list_of_circuits, my_backend,
config, basis_gates, coupling_map, initial_layout,
shots, max_credits, seed, qobj_id, hpc,
skip_transpiler)
return qobj
def reconfig(self, qobj, backend=None, config=None, shots=None, max_credits=None, seed=None):
"""Change configuration parameters for a compile qobj. Only parameters which
don't affect the circuit compilation can change, e.g., the coupling_map
cannot be changed here!
Notes:
If the inputs are left as None then the qobj is not updated
Args:
qobj (dict): already compile qobj
backend (str): see .compile
config (dict): see .compile
shots (int): see .compile
max_credits (int): see .compile
seed (int): see .compile
Returns:
qobj: updated qobj
"""
if backend is not None:
qobj['config']['backend'] = backend
if shots is not None:
qobj['config']['shots'] = shots
if max_credits is not None:
qobj['config']['max_credits'] = max_credits
for circuits in qobj['circuits']:
if seed is not None:
circuits['seed'] = seed
if config is not None:
circuits['config'].update(config)
return qobj
def get_execution_list(self, qobj, print_func=print):
"""Print the compiled circuits that are ready to run.
Note:
This method is intended to be used during interactive sessions, and
prints directly to stdout instead of using the logger by default. If
you set print_func with a log function (eg. log.info) it will be used
instead of the stdout.
Returns:
list(str): names of the circuits in `qobj`
"""
if not qobj:
print_func("no executions to run")
execution_list = []
print_func("id: %s" % qobj['id'])
print_func("backend: %s" % qobj['config']['backend_name'])
print_func("qobj config:")
for key in qobj['config']:
if key != 'backend':
print_func(' ' + key + ': ' + str(qobj['config'][key]))
for circuit in qobj['circuits']:
execution_list.append(circuit["name"])
print_func(' circuit name: ' + str(circuit["name"]))
print_func(' circuit config:')
for key in circuit['config']:
print_func(' ' + key + ': ' + str(circuit['config'][key]))
return execution_list
def get_compiled_configuration(self, qobj, name):
"""Get the compiled layout for the named circuit and backend.
Args:
name (str): the circuit name
qobj (dict): the qobj
Returns:
dict: the config of the circuit.
Raises:
QISKitError: if the circuit has no configurations
"""
try:
for index in range(len(qobj["circuits"])):
if qobj["circuits"][index]['name'] == name:
return qobj["circuits"][index]["config"]
except KeyError:
pass
raise QISKitError('No compiled configurations for circuit "{0}"'.format(name))
def get_compiled_qasm(self, qobj, name):
"""Return the compiled circuit in qasm format.
Args:
qobj (dict): the qobj
name (str): name of the quantum circuit
Returns:
str: the QASM of the compiled circuit.
Raises:
QISKitError: if the circuit has no configurations
"""
try:
for index in range(len(qobj["circuits"])):
if qobj["circuits"][index]['name'] == name:
return qobj["circuits"][index]["compiled_circuit_qasm"]
except KeyError:
pass
raise QISKitError('No compiled qasm for circuit "{0}"'.format(name))
###############################################################
# methods to run quantum programs
###############################################################
def run(self, qobj, timeout=60):
"""Run a program (a pre-compiled quantum program). This function will
block until the Job is processed.
The program to run is extracted from the qobj parameter.
Args:
qobj (dict): the dictionary of the quantum object to run.
timeout (int): Total time to wait until the execution stops
Returns:
Result: A Result (class).
"""
job = self._run_internal([qobj])[0]
return job.result(timeout=timeout)
def run_batch(self, qobj_list, timeout=120):
"""Run various programs (a list of pre-compiled quantum programs). This
function will block until all programs are processed.
The programs to run are extracted from qobj elements of the list.
Args:
qobj_list (list(dict)): The list of quantum objects to run.
timeout (int): Total time to wait until the execution stops
Returns:
list(Result): A list of Result (class). The list will contain one Result object
per qobj in the input list.
"""
num_jobs = len(qobj_list)
job_results = [None] * num_jobs
jobs_list = self._run_internal(qobj_list)
while not all(job_results):
for i, job in enumerate(jobs_list):
if job.done:
job_results[i] = job.result(timeout=timeout)
return job_results
def _run_internal(self, qobj_list):
job_list = []
for qobj in qobj_list:
backend = qiskit.wrapper.get_backend(qobj['config']['backend_name'])
q_job = QuantumJob(qobj, backend=backend, preformatted=True, resources={
'max_credits': qobj['config']['max_credits']})
job = backend.run(q_job)
job_list.append(job)
return job_list
def execute(self, name_of_circuits=None, backend="local_qasm_simulator",
config=None, timeout=60, basis_gates=None,
coupling_map=None, initial_layout=None, shots=1024,
max_credits=3, seed=None, hpc=None, skip_transpiler=False, skip_translation=False):
"""Execute, compile, and run an array of quantum circuits).
This builds the internal "to execute" list which is list of quantum
circuits to run on different backends.
Args:
name_of_circuits (list[str] or str or None): circuit
names to be executed. If None, all the circuits will be
executed.
backend (str): a string representing the backend to compile to.
config (dict): a dictionary of configurations parameters for the
compiler.
timeout (int): Total time to wait until the execution stops
basis_gates (str): a comma separated string and are the base gates,
which by default are: u1,u2,u3,cx,id.
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [3, 2]]
initial_layout (dict): A mapping of qubit to qubit
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
shots (int): the number of shots
max_credits (int): the max credits to use 3, or 5
seed (int): the initial seed the simulators use
hpc (dict): This will setup some parameter for
ibmq_qasm_simulator, using a JSON-like format like::
{
'multi_shot_optimization': Boolean,
'omp_num_threads': Numeric
}
skip_transpiler (bool): If True, bypass most of the compilation process and
creates a qobj with minimal check nor translation
Returns:
Result: status done and populates the internal __quantum_program with the data.
.. deprecated:: 0.5
The `coupling_map` parameter as a dictionary will be deprecated in
upcoming versions. Using the coupling_map as a list is recommended.
"""
# pylint: disable=missing-param-doc, missing-type-doc
if skip_translation:
warnings.warn(
"skip_translation will be called skip_transpiler in future versions.",
DeprecationWarning)
skip_transpiler = True
# TODO: Jay: currently basis_gates, coupling_map, initial_layout, shots,
# max_credits, and seed are extra inputs but I would like them to go
# into the config
qobj = self.compile(name_of_circuits=name_of_circuits, backend=backend,
config=config,
basis_gates=basis_gates,
coupling_map=coupling_map, initial_layout=initial_layout,
shots=shots, max_credits=max_credits, seed=seed,
hpc=hpc, skip_transpiler=skip_transpiler)
result = self.run(qobj, timeout=timeout)
return result
###############################################################
# utility methods
###############################################################
@staticmethod
def _get_single_item(items, item_description="an item"):
"""
Return the first and only element of `items`, raising an error
otherwise.
Args:
items (list): list of items.
item_description (string): text description of the item type.
Returns:
object: the first and only element of `items`.
Raises:
QISKitError: if the list does not have exactly one item.
"""
if len(items) == 1:
return items[0]
else:
raise QISKitError(
"The name of %s needs to be explicitly indicated, as there is "
"more than one available" % item_description)
def _create_id(self, prefix, existing_ids):
"""
Return an automatically generated identifier, increased sequentially
based on the internal `_counter` generator, with the form
"[prefix][numeric_id]" (ie. "q2", where the prefix is "q").
Args:
prefix (str): string to be prepended to the numeric id.
existing_ids (iterable): list of ids that should be checked for
duplicates.
Returns:
str: the new identifier.
Raises:
QISKitError: if the identifier is already in `existing_ids`.
"""
i = next(self.__counter)
identifier = "%s%i" % (prefix, i)
if identifier not in existing_ids:
return identifier
raise QISKitError("The automatically generated identifier '%s' already "
"exists" % identifier)
|
# -*- coding: utf-8 -*-
# Copyright 2017, IBM.
#
# This source code is licensed under the Apache License, Version 2.0 found in
# the LICENSE.txt file in the root directory of this source tree.
"""
Qasm Program Class
"""
import itertools
import json
import logging
import warnings
import qiskit.wrapper
from ._classicalregister import ClassicalRegister
from ._logging import set_qiskit_logger, unset_qiskit_logger
from ._qiskiterror import QISKitError
from ._quantumcircuit import QuantumCircuit
from ._quantumjob import QuantumJob
from ._quantumregister import QuantumRegister
from .mapper import coupling_dict2list
from .qasm import Qasm
logger = logging.getLogger(__name__)
class QuantumProgram(object):
"""Quantum Program Class.
Class internal properties.
Elements that are not python identifiers or string constants are denoted
by "--description (type)--". For example, a circuit's name is denoted by
"--circuit name (string)--" and might have the value "teleport".
Internal::
__quantum_registers (list[dic]): An dictionary of quantum registers
used in the quantum program.
__quantum_registers =
{
--register name (string)--: QuantumRegister,
}
__classical_registers (list[dic]): An ordered list of classical
registers used in the quantum program.
__classical_registers =
{
--register name (string)--: ClassicalRegister,
}
__quantum_program (dic): An dictionary of quantum circuits
__quantum_program =
{
--circuit name (string)--: --circuit object --,
}
__init_circuit (obj): A quantum circuit object for the initial quantum
circuit
"""
# -- FUTURE IMPROVEMENTS --
# TODO: for status results make ALL_CAPS (check) or some unified method
# TODO: Jay: coupling_map, basis_gates will move into a config object
# only exists once you set the api to use the online backends
__api = None
__api_config = {}
def __init__(self, specs=None):
self.__quantum_registers = {}
self.__classical_registers = {}
self.__quantum_program = {} # stores all the quantum programs
self.__init_circuit = None # stores the initial quantum circuit of the program
self.__counter = itertools.count()
if specs:
self.__init_specs(specs)
def enable_logs(self, level=logging.INFO):
"""Enable the console output of the logging messages.
Enable the output of logging messages (above level `level`) to the
console, by configuring the `qiskit` logger accordingly.
Params:
level (int): minimum severity of the messages that are displayed.
Note:
This is a convenience method over the standard Python logging
facilities, and modifies the configuration of the 'qiskit.*'
loggers. If finer control over the logging configuration is needed,
it is encouraged to bypass this method.
"""
# Update the handlers and formatters.
set_qiskit_logger()
# Set the logger level.
logging.getLogger('qiskit').setLevel(level)
def disable_logs(self):
"""Disable the console output of the logging messages.
Disable the output of logging messages (above level `level`) to the
console, by removing the handlers from the `qiskit` logger.
Note:
This is a convenience method over the standard Python logging
facilities, and modifies the configuration of the 'qiskit.*'
loggers. If finer control over the logging configuration is needed,
it is encouraged to bypass this method.
"""
unset_qiskit_logger()
###############################################################
# methods to initiate an build a quantum program
###############################################################
def __init_specs(self, specs):
"""Populate the Quantum Program Object with initial Specs.
Args:
specs (dict):
Q_SPECS = {
"circuits": [{
"name": "Circuit",
"quantum_registers": [{
"name": "qr",
"size": 4
}],
"classical_registers": [{
"name": "cr",
"size": 4
}]
}],
"""
quantum_r = []
classical_r = []
if "circuits" in specs:
for circuit in specs["circuits"]:
quantum_r = self.create_quantum_registers(
circuit["quantum_registers"])
classical_r = self.create_classical_registers(
circuit["classical_registers"])
self.create_circuit(name=circuit.get("name"), qregisters=quantum_r,
cregisters=classical_r)
# TODO: Jay: I think we should return function handles for the
# registers and circuit. So that we dont need to get them after we
# create them with get_quantum_register etc
def create_quantum_register(self, name=None, size=1):
"""Create a new Quantum Register.
Args:
name (str or None): the name of the quantum register. If None, an
automatically generated identifier will be assigned.
size (int): the size of the quantum register
Returns:
QuantumRegister: internal reference to a quantum register in
__quantum_registers
Raises:
QISKitError: if the register already exists in the program.
"""
if name is not None and name in self.__quantum_registers:
if size != len(self.__quantum_registers[name]):
raise QISKitError("Can't make this register: Already in"
" program with different size")
logger.info(">> quantum_register exists: %s %s", name, size)
return self.__quantum_registers[name]
if name is None:
name = self._create_id('q', self.__quantum_registers)
if not isinstance(name, str):
logger.info(">> quantum_register name is not a valid type: %s ", type(name))
raise QISKitError("The register name should be a string "
"(or None for autogenerate a name).")
self.__quantum_registers[name] = QuantumRegister(size=size, name=name)
logger.info(">> new quantum_register created: %s %s", name, size)
return self.__quantum_registers[name]
def destroy_quantum_register(self, name):
"""Destroy an existing Quantum Register.
Args:
name (str): the name of the quantum register
Raises:
QISKitError: if the register does not exist in the program.
"""
if name not in self.__quantum_registers:
raise QISKitError("Can't destroy this register: Not present")
else:
logger.info(">> quantum_register destroyed: %s", name)
del self.__quantum_registers[name]
def create_quantum_registers(self, register_array):
"""Create a new set of Quantum Registers based on a array of them.
Args:
register_array (list[dict]): An array of quantum registers in
dictionary format. For example::
[{"name": "qr", "size": 4},
...
]
Any other key in the dictionary will be ignored. If "name"
is not defined (or None) a random name wil be assigned.
Returns:
list(QuantumRegister): Array of quantum registers objects
"""
new_reg = []
for reg in register_array:
reg = self.create_quantum_register(
reg.get('name'), reg["size"])
new_reg.append(reg)
return new_reg
def destroy_quantum_registers(self, register_array):
"""Destroy a set of Quantum Registers based on a array of them.
Args:
register_array (list[dict]): An array of quantum registers in
dictionary format. For example::
[{"name": "qr"},
...
]
Any other key in the dictionary will be ignored.
"""
for reg in register_array:
self.destroy_quantum_register(reg["name"])
def create_classical_register(self, name=None, size=1):
"""Create a new Classical Register.
Args:
name (str or None): the name of the classical register. If None, an
automatically generated identifier will be assigned..
size (int): the size of the classical register
Returns:
ClassicalRegister: internal reference to a classical register
in __classical_registers
Raises:
QISKitError: if the register already exists in the program.
"""
if name is not None and name in self.__classical_registers:
if size != len(self.__classical_registers[name]):
raise QISKitError("Can't make this register: Already in"
" program with different size")
logger.info(">> classical register exists: %s %s", name, size)
return self.__classical_registers[name]
if name is None:
name = self._create_id('c', self.__classical_registers)
if not isinstance(name, str):
logger.info(">> quantum_register name is not a valid type: %s ", type(name))
raise QISKitError("The register name should be a string "
"(or None for autogenerate a name).")
self.__classical_registers[name] = ClassicalRegister(size=size, name=name)
logger.info(">> new classical register created: %s %s", name, size)
return self.__classical_registers[name]
def create_classical_registers(self, registers_array):
"""Create a new set of Classical Registers based on a array of them.
Args:
registers_array (list[dict]): An array of classical registers in
dictionary format. For example::
[{"name": "cr", "size": 4},
...
]
Any other key in the dictionary will be ignored. If "name"
is not defined (or None) a random name wil be assigned.
Returns:
list(ClassicalRegister): Array of classical registers objects
"""
new_reg = []
for reg in registers_array:
new_reg.append(self.create_classical_register(
reg.get("name"), reg["size"]))
return new_reg
def destroy_classical_register(self, name):
"""Destroy an existing Classical Register.
Args:
name (str): the name of the classical register
Raises:
QISKitError: if the register does not exist in the program.
"""
if name not in self.__classical_registers:
raise QISKitError("Can't destroy this register: Not present")
else:
logger.info(">> classical register destroyed: %s", name)
del self.__classical_registers[name]
def destroy_classical_registers(self, registers_array):
"""Destroy a set of Classical Registers based on a array of them.
Args:
registers_array (list[dict]): An array of classical registers in
dictionary format. For example::
[{"name": "cr"},
...
]
Any other key in the dictionary will be ignored.
"""
for reg in registers_array:
self.destroy_classical_register(reg["name"])
def create_circuit(self, name=None, qregisters=None, cregisters=None):
"""Create a empty Quantum Circuit in the Quantum Program.
Args:
name (str or None): the name of the circuit. If None, an
automatically generated identifier will be assigned.
qregisters (list(QuantumRegister)): is an Array of Quantum
Registers by object reference
cregisters (list(ClassicalRegister)): is an Array of Classical
Registers by object reference
Returns:
QuantumCircuit: A quantum circuit is created and added to the
Quantum Program
"""
if name is None:
name = self._create_id('qc', self.__quantum_program.keys())
if not qregisters:
qregisters = []
if not cregisters:
cregisters = []
quantum_circuit = QuantumCircuit(name=name)
if not self.__init_circuit:
self.__init_circuit = quantum_circuit
for reg in qregisters:
quantum_circuit.add(reg)
for reg in cregisters:
quantum_circuit.add(reg)
self.add_circuit(name, quantum_circuit)
return self.__quantum_program[name]
def destroy_circuit(self, name):
"""Destroy a Quantum Circuit in the Quantum Program. This will not
destroy any registers associated with the circuit.
Args:
name (str): the name of the circuit
Raises:
QISKitError: if the register does not exist in the program.
"""
if name not in self.__quantum_program:
raise QISKitError("Can't destroy this circuit: Not present")
del self.__quantum_program[name]
def add_circuit(self, name=None, quantum_circuit=None):
"""Add a new circuit based on an Object representation.
Args:
name (str or None): the name of the circuit to add. If None, an
automatically generated identifier will be assigned to the
circuit.
quantum_circuit (QuantumCircuit): a quantum circuit to add to the
program-name
Raises:
QISKitError: if `quantum_circuit` is None, as the attribute is
optional only for not breaking backwards compatibility (as
it is placed after an optional argument).
"""
if quantum_circuit is None:
raise QISKitError('quantum_circuit is required when invoking '
'add_circuit')
if name is None:
if quantum_circuit.name:
name = quantum_circuit.name
else:
name = self._create_id('qc', self.__quantum_program.keys())
quantum_circuit.name = name
self.__quantum_program[name] = quantum_circuit
def load_qasm_file(self, qasm_file, name=None,
basis_gates='u1,u2,u3,cx,id'):
""" Load qasm file into the quantum program.
Args:
qasm_file (str): a string for the filename including its location.
name (str or None): the name of the quantum circuit after
loading qasm text into it. If no name is give the name is of
the text file.
basis_gates (str): basis gates for the quantum circuit.
Returns:
str: Adds a quantum circuit with the gates given in the qasm file to the
quantum program and returns the name to be used to get this circuit
Raises:
QISKitError: if the file cannot be read.
"""
warnings.warn(
"QuantumProgram.load_qasm_file() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.load_qasm_file() instead is recommended.", DeprecationWarning)
circuit_unrolled = qiskit.wrapper.load_qasm_file(qasm_file, name, basis_gates)
self.add_circuit(name, circuit_unrolled)
return name
def load_qasm_text(self, qasm_string, name=None,
basis_gates='u1,u2,u3,cx,id'):
""" Load qasm string in the quantum program.
Args:
qasm_string (str): a string for the file name.
name (str or None): the name of the quantum circuit after loading qasm
text into it. If no name is give the name is of the text file.
basis_gates (str): basis gates for the quantum circuit.
Returns:
str: Adds a quantum circuit with the gates given in the qasm string to
the quantum program.
"""
warnings.warn(
"QuantumProgram.load_qasm_text() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.load_qasm_text() instead is recommended.", DeprecationWarning)
circuit_unrolled = qiskit.wrapper.load_qasm_string(qasm_string, name, basis_gates)
self.add_circuit(name, circuit_unrolled)
return name
def save(self, file_name=None, beauty=False):
""" Save Quantum Program in a Json file.
Args:
file_name (str): file name and path.
beauty (boolean): save the text with indent 4 to make it readable.
Returns:
dict: The dictionary with the status and result of the operation
Raises:
LookupError: if the file_name is not correct, or writing to the
file resulted in an error.
"""
if file_name is None:
error = {"status": "Error", "result": "Not filename provided"}
raise LookupError(error['result'])
if beauty:
indent = 4
else:
indent = 0
elements_to_save = self.__quantum_program
elements_saved = {}
for circuit in elements_to_save:
elements_saved[circuit] = {}
elements_saved[circuit]["qasm"] = elements_to_save[circuit].qasm()
try:
with open(file_name, 'w') as save_file:
json.dump(elements_saved, save_file, indent=indent)
return {'status': 'Done', 'result': elements_to_save}
except ValueError:
error = {'status': 'Error', 'result': 'Some Problem happened to save the file'}
raise LookupError(error['result'])
def load(self, file_name=None):
""" Load Quantum Program Json file into the Quantum Program object.
Args:
file_name (str): file name and path.
Returns:
dict: The dictionary with the status and result of the operation
Raises:
LookupError: if the file_name is not correct, or reading from the
file resulted in an error.
"""
if file_name is None:
error = {"status": "Error", "result": "Not filename provided"}
raise LookupError(error['result'])
try:
with open(file_name, 'r') as load_file:
elements_loaded = json.load(load_file)
for circuit in elements_loaded:
circuit_qasm = elements_loaded[circuit]["qasm"]
elements_loaded[circuit] = Qasm(data=circuit_qasm).parse()
self.__quantum_program = elements_loaded
return {"status": 'Done', 'result': self.__quantum_program}
except ValueError:
error = {'status': 'Error', 'result': 'Some Problem happened to load the file'}
raise LookupError(error['result'])
###############################################################
# methods to get elements from a QuantumProgram
###############################################################
def get_quantum_register(self, name=None):
"""Return a Quantum Register by name.
Args:
name (str or None): the name of the quantum register. If None and there is only
one quantum register available, returns that one.
Returns:
QuantumRegister: The quantum register with this name.
Raises:
KeyError: if the quantum register is not on the quantum program.
QISKitError: if the register does not exist in the program.
"""
if name is None:
name = self._get_single_item(self.get_quantum_register_names(), "a quantum register")
try:
return self.__quantum_registers[name]
except KeyError:
raise KeyError('No quantum register "{0}"'.format(name))
def get_classical_register(self, name=None):
"""Return a Classical Register by name.
Args:
name (str or None): the name of the classical register. If None and there is only
one classical register available, returns that one.
Returns:
ClassicalRegister: The classical register with this name.
Raises:
KeyError: if the classical register is not on the quantum program.
QISKitError: if the register does not exist in the program.
"""
if name is None:
name = self._get_single_item(self.get_classical_register_names(),
"a classical register")
try:
return self.__classical_registers[name]
except KeyError:
raise KeyError('No classical register "{0}"'.format(name))
def get_quantum_register_names(self):
"""Return all the names of the quantum Registers."""
return sorted(list(self.__quantum_registers.keys()))
def get_classical_register_names(self):
"""Return all the names of the classical Registers."""
return sorted(list(self.__classical_registers.keys()))
def get_circuit(self, name=None):
"""Return a Circuit Object by name.
Args:
name (str or None): the name of the quantum circuit.
If None and there is only one circuit available, returns
that one.
Returns:
QuantumCircuit: The quantum circuit with this name
Raises:
KeyError: if the circuit is not on the quantum program.
QISKitError: if the register does not exist in the program.
"""
if name is None:
name = self._get_single_item(self.get_circuit_names(), "a circuit")
try:
return self.__quantum_program[name]
except KeyError:
raise KeyError('No quantum circuit "{0}"'.format(name))
def get_circuit_names(self):
"""Return all the names of the quantum circuits."""
return sorted(list(self.__quantum_program.keys()))
def get_qasm(self, name=None):
"""Get qasm format of circuit by name.
Args:
name (str or None): name of the circuit. If None and only one circuit is
available, that one is selected.
Returns:
str: The quantum circuit in qasm format
Raises:
QISKitError: if the register does not exist in the program.
"""
if name is None:
name = self._get_single_item(self.get_circuit_names(), "a circuit")
quantum_circuit = self.get_circuit(name)
return quantum_circuit.qasm()
def get_qasms(self, list_circuit_name=None):
"""Get qasm format of circuit by list of names.
Args:
list_circuit_name (list[str] or None): names of the circuit. If None, it gets all the
circuits in the program.
Returns:
list(QuantumCircuit): List of quantum circuit in qasm format
Raises:
QISKitError: if the register does not exist in the program.
"""
qasm_source = []
if list_circuit_name is None:
list_circuit_name = self.get_circuit_names()
for name in list_circuit_name:
qasm_source.append(self.get_qasm(name))
return qasm_source
def get_initial_circuit(self):
"""Return the initialization Circuit."""
return self.__init_circuit
###############################################################
# methods for working with backends
###############################################################
def set_api(self, token, url, hub=None, group=None, project=None,
proxies=None, verify=True):
""" Setup the API.
Fills the __api, and __api_config variables.
Does not catch exceptions from IBMQuantumExperience.
Args:
token (str): The token used to register on the online backend such
as the quantum experience.
url (str): The url used for online backend such as the quantum
experience.
hub (str): The hub used for online backend.
group (str): The group used for online backend.
project (str): The project used for online backend.
proxies (dict): Proxy configuration for the API, as a dict with
'urls' and credential keys.
verify (bool): If False, ignores SSL certificates errors.
Raises:
ConnectionError: if the API instantiation failed.
QISKitError: if no hub, group or project were specified.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
API object instead is recommended.
"""
# TODO: remove the tests as well when the deprecation is completed
warnings.warn(
"set_api() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.register() instead is recommended.", DeprecationWarning)
qiskit.wrapper.register(token, url,
hub, group, project, proxies, verify,
provider_name='ibmq')
# TODO: the setting of self._api and self.__api_config is left for
# backwards-compatibility.
# pylint: disable=no-member
self.__api = qiskit.wrapper._wrapper._DEFAULT_PROVIDER.providers[-1]._api
config_dict = {
'url': url,
}
# Only append hub/group/project if they are different than None.
if all([hub, group, project]):
config_dict.update({
'hub': hub,
'group': group,
'project': project
})
if proxies:
config_dict['proxies'] = proxies
self.__api_config["token"] = token
self.__api_config["config"] = config_dict.copy()
def set_api_hubs_config(self, hub, group, project):
"""Update the API hubs configuration, replacing the previous one.
hub (str): The hub used for online backend.
group (str): The group used for online backend.
project (str): The project used for online backend.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
API object instead is recommended.
"""
warnings.warn(
"set_api_hubs_config() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.register(token, url, hub, group, project) "
"instead is recommended.", DeprecationWarning)
config_dict = {
'hub': hub,
'group': group,
'project': project
}
for key, value in config_dict.items():
self.__api.config[key] = value
self.__api_config['config'][key] = value
def get_api_config(self):
"""Return the program specs.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
API object instead is recommended.
"""
warnings.warn(
"get_api_config() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.register() instead is recommended.", DeprecationWarning)
return self.__api_config
def get_api(self):
"""Returns a function handle to the API.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
API object instead is recommended.
"""
warnings.warn(
"get_api() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.register() instead is recommended.", DeprecationWarning)
return self.__api
def available_backends(self, compact=True):
"""All the backends that are seen by QISKIT.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"available_backends() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.available_backends() instead is recommended.",
DeprecationWarning)
return qiskit.wrapper.available_backends(compact=compact)
def online_backends(self):
"""Get the online backends.
Queries network API if it exists and gets the backends that are online.
Returns:
list(str): List of online backends names if the online api has been set or an empty
list if it has not been set.
Raises:
ConnectionError: if the API call failed.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"online_backends() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.available_backends({'local': False}) is recommended "
"instead.", DeprecationWarning)
return qiskit.wrapper.remote_backends()
def online_simulators(self):
"""Gets online simulators via QX API calls.
Returns:
list(str): List of online simulator names.
Raises:
ConnectionError: if the API call failed.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"online_simulators() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.available_backends({'local': False, 'simulator': True}) "
"is recommended.", DeprecationWarning)
return qiskit.wrapper.available_backends({'local': False,
'simulator': True})
def online_devices(self):
"""Gets online devices via QX API calls.
Returns:
list(str): List of online devices names.
Raises:
ConnectionError: if the API call failed.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"online_devices() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.available_backends({'local': False, 'simulator': False}) "
"is recommended.", DeprecationWarning)
return qiskit.wrapper.available_backends({'local': False,
'simulator': False})
def get_backend_status(self, backend):
"""Return the online backend status.
It uses QX API call or by local backend is the name of the
local or online simulator or experiment.
Args:
backend (str): The backend to check
Returns:
dict: {'available': True}
Raises:
ConnectionError: if the API call failed.
ValueError: if the backend is not available.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"get_backend_status() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.get_backend('name').status "
"instead is recommended.", DeprecationWarning)
my_backend = qiskit.wrapper.get_backend(backend)
return my_backend.status
def get_backend_configuration(self, backend):
"""Return the configuration of the backend.
The return is via QX API call.
Args:
backend (str): Name of the backend.
Returns:
dict: The configuration of the named backend.
Raises:
ConnectionError: if the API call failed.
LookupError: if a configuration for the named backend can't be
found.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"get_backend_configuration() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.get_backend('name').configuration "
"instead is recommended.", DeprecationWarning)
my_backend = qiskit.wrapper.get_backend(backend)
return my_backend.configuration
def get_backend_calibration(self, backend):
"""Return the online backend calibrations.
The return is via QX API call.
Args:
backend (str): Name of the backend.
Returns:
dict: The calibration of the named backend.
Raises:
ConnectionError: if the API call failed.
LookupError: If a configuration for the named backend can't be
found.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"get_backend_calibration() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.get_backend('name').calibration "
"instead is recommended.", DeprecationWarning)
my_backend = qiskit.wrapper.get_backend(backend)
return my_backend.calibration
def get_backend_parameters(self, backend):
"""Return the online backend parameters.
The return is via QX API call.
Args:
backend (str): Name of the backend.
Returns:
dict: The configuration of the named backend.
Raises:
ConnectionError: if the API call failed.
LookupError: If a configuration for the named backend can't be
found.
.. deprecated:: 0.5
This method will be deprecated in upcoming versions. Using the
qiskit.backends family of functions instead is recommended.
"""
warnings.warn(
"get_backend_parameters() will be deprecated in upcoming versions (>0.5.0). "
"Using qiskit.get_backend('name').parameters"
"instead is recommended.", DeprecationWarning)
my_backend = qiskit.wrapper.get_backend(backend)
return my_backend.parameters
###############################################################
# methods to compile quantum programs into qobj
###############################################################
def compile(self, name_of_circuits=None, backend="local_qasm_simulator",
config=None, basis_gates=None, coupling_map=None,
initial_layout=None, shots=1024, max_credits=10, seed=None,
qobj_id=None, hpc=None, skip_transpiler=False, skip_translation=False):
"""Compile the circuits into the execution list.
.. deprecated:: 0.5
The `coupling_map` parameter as a dictionary will be deprecated in
upcoming versions. Using the coupling_map as a list is recommended.
"""
# pylint: disable=missing-param-doc, missing-type-doc
if skip_translation:
warnings.warn(
"skip_translation will be called skip_transpiler in future versions.",
DeprecationWarning)
skip_transpiler = True
if isinstance(coupling_map, dict):
coupling_map = coupling_dict2list(coupling_map)
warnings.warn(
"coupling_map as a dictionary will be deprecated in upcoming versions (>0.5.0). "
"Using the coupling_map as a list is recommended.", DeprecationWarning)
list_of_circuits = []
if not name_of_circuits:
logger.info('Since not circuits was specified, all the circuits will be compiled.')
name_of_circuits = self.get_circuit_names()
if isinstance(name_of_circuits, str):
name_of_circuits = [name_of_circuits]
if name_of_circuits:
for name in name_of_circuits:
self.__quantum_program[name].name = name
list_of_circuits.append(self.__quantum_program[name])
my_backend = qiskit.wrapper.get_backend(backend)
qobj = qiskit.wrapper.compile(list_of_circuits, my_backend,
config, basis_gates, coupling_map, initial_layout,
shots, max_credits, seed, qobj_id, hpc,
skip_transpiler)
return qobj
def reconfig(self, qobj, backend=None, config=None, shots=None, max_credits=None, seed=None):
"""Change configuration parameters for a compile qobj. Only parameters which
don't affect the circuit compilation can change, e.g., the coupling_map
cannot be changed here!
Notes:
If the inputs are left as None then the qobj is not updated
Args:
qobj (dict): already compile qobj
backend (str): see .compile
config (dict): see .compile
shots (int): see .compile
max_credits (int): see .compile
seed (int): see .compile
Returns:
qobj: updated qobj
"""
if backend is not None:
qobj['config']['backend'] = backend
if shots is not None:
qobj['config']['shots'] = shots
if max_credits is not None:
qobj['config']['max_credits'] = max_credits
for circuits in qobj['circuits']:
if seed is not None:
circuits['seed'] = seed
if config is not None:
circuits['config'].update(config)
return qobj
def get_execution_list(self, qobj, print_func=print):
"""Print the compiled circuits that are ready to run.
Note:
This method is intended to be used during interactive sessions, and
prints directly to stdout instead of using the logger by default. If
you set print_func with a log function (eg. log.info) it will be used
instead of the stdout.
Returns:
list(str): names of the circuits in `qobj`
"""
if not qobj:
print_func("no executions to run")
execution_list = []
print_func("id: %s" % qobj['id'])
print_func("backend: %s" % qobj['config']['backend_name'])
print_func("qobj config:")
for key in qobj['config']:
if key != 'backend':
print_func(' ' + key + ': ' + str(qobj['config'][key]))
for circuit in qobj['circuits']:
execution_list.append(circuit["name"])
print_func(' circuit name: ' + str(circuit["name"]))
print_func(' circuit config:')
for key in circuit['config']:
print_func(' ' + key + ': ' + str(circuit['config'][key]))
return execution_list
def get_compiled_configuration(self, qobj, name):
"""Get the compiled layout for the named circuit and backend.
Args:
name (str): the circuit name
qobj (dict): the qobj
Returns:
dict: the config of the circuit.
Raises:
QISKitError: if the circuit has no configurations
"""
try:
for index in range(len(qobj["circuits"])):
if qobj["circuits"][index]['name'] == name:
return qobj["circuits"][index]["config"]
except KeyError:
pass
raise QISKitError('No compiled configurations for circuit "{0}"'.format(name))
def get_compiled_qasm(self, qobj, name):
"""Return the compiled circuit in qasm format.
Args:
qobj (dict): the qobj
name (str): name of the quantum circuit
Returns:
str: the QASM of the compiled circuit.
Raises:
QISKitError: if the circuit has no configurations
"""
try:
for index in range(len(qobj["circuits"])):
if qobj["circuits"][index]['name'] == name:
return qobj["circuits"][index]["compiled_circuit_qasm"]
except KeyError:
pass
raise QISKitError('No compiled qasm for circuit "{0}"'.format(name))
###############################################################
# methods to run quantum programs
###############################################################
def run(self, qobj, timeout=60):
"""Run a program (a pre-compiled quantum program). This function will
block until the Job is processed.
The program to run is extracted from the qobj parameter.
Args:
qobj (dict): the dictionary of the quantum object to run.
timeout (int): Total time to wait until the execution stops
Returns:
Result: A Result (class).
"""
job = self._run_internal([qobj])[0]
return job.result(timeout=timeout)
def run_batch(self, qobj_list, timeout=120):
"""Run various programs (a list of pre-compiled quantum programs). This
function will block until all programs are processed.
The programs to run are extracted from qobj elements of the list.
Args:
qobj_list (list(dict)): The list of quantum objects to run.
timeout (int): Total time to wait until the execution stops
Returns:
list(Result): A list of Result (class). The list will contain one Result object
per qobj in the input list.
"""
num_jobs = len(qobj_list)
job_results = [None] * num_jobs
jobs_list = self._run_internal(qobj_list)
while not all(job_results):
for i, job in enumerate(jobs_list):
if job.done:
job_results[i] = job.result(timeout=timeout)
return job_results
def _run_internal(self, qobj_list):
job_list = []
for qobj in qobj_list:
backend = qiskit.wrapper.get_backend(qobj['config']['backend_name'])
q_job = QuantumJob(qobj, backend=backend, preformatted=True, resources={
'max_credits': qobj['config']['max_credits']})
job = backend.run(q_job)
job_list.append(job)
return job_list
def execute(self, name_of_circuits=None, backend="local_qasm_simulator",
config=None, timeout=60, basis_gates=None,
coupling_map=None, initial_layout=None, shots=1024,
max_credits=3, seed=None, hpc=None, skip_transpiler=False, skip_translation=False):
"""Execute, compile, and run an array of quantum circuits).
This builds the internal "to execute" list which is list of quantum
circuits to run on different backends.
Args:
name_of_circuits (list[str] or str or None): circuit
names to be executed. If None, all the circuits will be
executed.
backend (str): a string representing the backend to compile to.
config (dict): a dictionary of configurations parameters for the
compiler.
timeout (int): Total time to wait until the execution stops
basis_gates (str): a comma separated string and are the base gates,
which by default are: u1,u2,u3,cx,id.
coupling_map (list): A graph of coupling::
[
[control0(int), target0(int)],
[control1(int), target1(int)],
]
eg. [[0, 2], [1, 2], [3, 2]]
initial_layout (dict): A mapping of qubit to qubit
{
("q", start(int)): ("q", final(int)),
...
}
eg.
{
("q", 0): ("q", 0),
("q", 1): ("q", 1),
("q", 2): ("q", 2),
("q", 3): ("q", 3)
}
shots (int): the number of shots
max_credits (int): the max credits to use 3, or 5
seed (int): the initial seed the simulators use
hpc (dict): This will setup some parameter for
ibmq_qasm_simulator, using a JSON-like format like::
{
'multi_shot_optimization': Boolean,
'omp_num_threads': Numeric
}
skip_transpiler (bool): If True, bypass most of the compilation process and
creates a qobj with minimal check nor translation
Returns:
Result: status done and populates the internal __quantum_program with the data.
.. deprecated:: 0.5
The `coupling_map` parameter as a dictionary will be deprecated in
upcoming versions. Using the coupling_map as a list is recommended.
"""
# pylint: disable=missing-param-doc, missing-type-doc
if skip_translation:
warnings.warn(
"skip_translation will be called skip_transpiler in future versions.",
DeprecationWarning)
skip_transpiler = True
# TODO: Jay: currently basis_gates, coupling_map, initial_layout, shots,
# max_credits, and seed are extra inputs but I would like them to go
# into the config
qobj = self.compile(name_of_circuits=name_of_circuits, backend=backend,
config=config,
basis_gates=basis_gates,
coupling_map=coupling_map, initial_layout=initial_layout,
shots=shots, max_credits=max_credits, seed=seed,
hpc=hpc, skip_transpiler=skip_transpiler)
result = self.run(qobj, timeout=timeout)
return result
###############################################################
# utility methods
###############################################################
@staticmethod
def _get_single_item(items, item_description="an item"):
"""
Return the first and only element of `items`, raising an error
otherwise.
Args:
items (list): list of items.
item_description (string): text description of the item type.
Returns:
object: the first and only element of `items`.
Raises:
QISKitError: if the list does not have exactly one item.
"""
if len(items) == 1:
return items[0]
else:
raise QISKitError(
"The name of %s needs to be explicitly indicated, as there is "
"more than one available" % item_description)
def _create_id(self, prefix, existing_ids):
"""
Return an automatically generated identifier, increased sequentially
based on the internal `_counter` generator, with the form
"[prefix][numeric_id]" (ie. "q2", where the prefix is "q").
Args:
prefix (str): string to be prepended to the numeric id.
existing_ids (iterable): list of ids that should be checked for
duplicates.
Returns:
str: the new identifier.
Raises:
QISKitError: if the identifier is already in `existing_ids`.
"""
i = next(self.__counter)
identifier = "%s%i" % (prefix, i)
if identifier not in existing_ids:
return identifier
raise QISKitError("The automatically generated identifier '%s' already "
"exists" % identifier)
|
en
| 0.69256
|
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. Qasm Program Class Quantum Program Class. Class internal properties. Elements that are not python identifiers or string constants are denoted by "--description (type)--". For example, a circuit's name is denoted by "--circuit name (string)--" and might have the value "teleport". Internal:: __quantum_registers (list[dic]): An dictionary of quantum registers used in the quantum program. __quantum_registers = { --register name (string)--: QuantumRegister, } __classical_registers (list[dic]): An ordered list of classical registers used in the quantum program. __classical_registers = { --register name (string)--: ClassicalRegister, } __quantum_program (dic): An dictionary of quantum circuits __quantum_program = { --circuit name (string)--: --circuit object --, } __init_circuit (obj): A quantum circuit object for the initial quantum circuit # -- FUTURE IMPROVEMENTS -- # TODO: for status results make ALL_CAPS (check) or some unified method # TODO: Jay: coupling_map, basis_gates will move into a config object # only exists once you set the api to use the online backends # stores all the quantum programs # stores the initial quantum circuit of the program Enable the console output of the logging messages. Enable the output of logging messages (above level `level`) to the console, by configuring the `qiskit` logger accordingly. Params: level (int): minimum severity of the messages that are displayed. Note: This is a convenience method over the standard Python logging facilities, and modifies the configuration of the 'qiskit.*' loggers. If finer control over the logging configuration is needed, it is encouraged to bypass this method. # Update the handlers and formatters. # Set the logger level. Disable the console output of the logging messages. Disable the output of logging messages (above level `level`) to the console, by removing the handlers from the `qiskit` logger. Note: This is a convenience method over the standard Python logging facilities, and modifies the configuration of the 'qiskit.*' loggers. If finer control over the logging configuration is needed, it is encouraged to bypass this method. ############################################################### # methods to initiate an build a quantum program ############################################################### Populate the Quantum Program Object with initial Specs. Args: specs (dict): Q_SPECS = { "circuits": [{ "name": "Circuit", "quantum_registers": [{ "name": "qr", "size": 4 }], "classical_registers": [{ "name": "cr", "size": 4 }] }], # TODO: Jay: I think we should return function handles for the # registers and circuit. So that we dont need to get them after we # create them with get_quantum_register etc Create a new Quantum Register. Args: name (str or None): the name of the quantum register. If None, an automatically generated identifier will be assigned. size (int): the size of the quantum register Returns: QuantumRegister: internal reference to a quantum register in __quantum_registers Raises: QISKitError: if the register already exists in the program. Destroy an existing Quantum Register. Args: name (str): the name of the quantum register Raises: QISKitError: if the register does not exist in the program. Create a new set of Quantum Registers based on a array of them. Args: register_array (list[dict]): An array of quantum registers in dictionary format. For example:: [{"name": "qr", "size": 4}, ... ] Any other key in the dictionary will be ignored. If "name" is not defined (or None) a random name wil be assigned. Returns: list(QuantumRegister): Array of quantum registers objects Destroy a set of Quantum Registers based on a array of them. Args: register_array (list[dict]): An array of quantum registers in dictionary format. For example:: [{"name": "qr"}, ... ] Any other key in the dictionary will be ignored. Create a new Classical Register. Args: name (str or None): the name of the classical register. If None, an automatically generated identifier will be assigned.. size (int): the size of the classical register Returns: ClassicalRegister: internal reference to a classical register in __classical_registers Raises: QISKitError: if the register already exists in the program. Create a new set of Classical Registers based on a array of them. Args: registers_array (list[dict]): An array of classical registers in dictionary format. For example:: [{"name": "cr", "size": 4}, ... ] Any other key in the dictionary will be ignored. If "name" is not defined (or None) a random name wil be assigned. Returns: list(ClassicalRegister): Array of classical registers objects Destroy an existing Classical Register. Args: name (str): the name of the classical register Raises: QISKitError: if the register does not exist in the program. Destroy a set of Classical Registers based on a array of them. Args: registers_array (list[dict]): An array of classical registers in dictionary format. For example:: [{"name": "cr"}, ... ] Any other key in the dictionary will be ignored. Create a empty Quantum Circuit in the Quantum Program. Args: name (str or None): the name of the circuit. If None, an automatically generated identifier will be assigned. qregisters (list(QuantumRegister)): is an Array of Quantum Registers by object reference cregisters (list(ClassicalRegister)): is an Array of Classical Registers by object reference Returns: QuantumCircuit: A quantum circuit is created and added to the Quantum Program Destroy a Quantum Circuit in the Quantum Program. This will not destroy any registers associated with the circuit. Args: name (str): the name of the circuit Raises: QISKitError: if the register does not exist in the program. Add a new circuit based on an Object representation. Args: name (str or None): the name of the circuit to add. If None, an automatically generated identifier will be assigned to the circuit. quantum_circuit (QuantumCircuit): a quantum circuit to add to the program-name Raises: QISKitError: if `quantum_circuit` is None, as the attribute is optional only for not breaking backwards compatibility (as it is placed after an optional argument). Load qasm file into the quantum program. Args: qasm_file (str): a string for the filename including its location. name (str or None): the name of the quantum circuit after loading qasm text into it. If no name is give the name is of the text file. basis_gates (str): basis gates for the quantum circuit. Returns: str: Adds a quantum circuit with the gates given in the qasm file to the quantum program and returns the name to be used to get this circuit Raises: QISKitError: if the file cannot be read. Load qasm string in the quantum program. Args: qasm_string (str): a string for the file name. name (str or None): the name of the quantum circuit after loading qasm text into it. If no name is give the name is of the text file. basis_gates (str): basis gates for the quantum circuit. Returns: str: Adds a quantum circuit with the gates given in the qasm string to the quantum program. Save Quantum Program in a Json file. Args: file_name (str): file name and path. beauty (boolean): save the text with indent 4 to make it readable. Returns: dict: The dictionary with the status and result of the operation Raises: LookupError: if the file_name is not correct, or writing to the file resulted in an error. Load Quantum Program Json file into the Quantum Program object. Args: file_name (str): file name and path. Returns: dict: The dictionary with the status and result of the operation Raises: LookupError: if the file_name is not correct, or reading from the file resulted in an error. ############################################################### # methods to get elements from a QuantumProgram ############################################################### Return a Quantum Register by name. Args: name (str or None): the name of the quantum register. If None and there is only one quantum register available, returns that one. Returns: QuantumRegister: The quantum register with this name. Raises: KeyError: if the quantum register is not on the quantum program. QISKitError: if the register does not exist in the program. Return a Classical Register by name. Args: name (str or None): the name of the classical register. If None and there is only one classical register available, returns that one. Returns: ClassicalRegister: The classical register with this name. Raises: KeyError: if the classical register is not on the quantum program. QISKitError: if the register does not exist in the program. Return all the names of the quantum Registers. Return all the names of the classical Registers. Return a Circuit Object by name. Args: name (str or None): the name of the quantum circuit. If None and there is only one circuit available, returns that one. Returns: QuantumCircuit: The quantum circuit with this name Raises: KeyError: if the circuit is not on the quantum program. QISKitError: if the register does not exist in the program. Return all the names of the quantum circuits. Get qasm format of circuit by name. Args: name (str or None): name of the circuit. If None and only one circuit is available, that one is selected. Returns: str: The quantum circuit in qasm format Raises: QISKitError: if the register does not exist in the program. Get qasm format of circuit by list of names. Args: list_circuit_name (list[str] or None): names of the circuit. If None, it gets all the circuits in the program. Returns: list(QuantumCircuit): List of quantum circuit in qasm format Raises: QISKitError: if the register does not exist in the program. Return the initialization Circuit. ############################################################### # methods for working with backends ############################################################### Setup the API. Fills the __api, and __api_config variables. Does not catch exceptions from IBMQuantumExperience. Args: token (str): The token used to register on the online backend such as the quantum experience. url (str): The url used for online backend such as the quantum experience. hub (str): The hub used for online backend. group (str): The group used for online backend. project (str): The project used for online backend. proxies (dict): Proxy configuration for the API, as a dict with 'urls' and credential keys. verify (bool): If False, ignores SSL certificates errors. Raises: ConnectionError: if the API instantiation failed. QISKitError: if no hub, group or project were specified. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the API object instead is recommended. # TODO: remove the tests as well when the deprecation is completed # TODO: the setting of self._api and self.__api_config is left for # backwards-compatibility. # pylint: disable=no-member # Only append hub/group/project if they are different than None. Update the API hubs configuration, replacing the previous one. hub (str): The hub used for online backend. group (str): The group used for online backend. project (str): The project used for online backend. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the API object instead is recommended. Return the program specs. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the API object instead is recommended. Returns a function handle to the API. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the API object instead is recommended. All the backends that are seen by QISKIT. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the qiskit.backends family of functions instead is recommended. Get the online backends. Queries network API if it exists and gets the backends that are online. Returns: list(str): List of online backends names if the online api has been set or an empty list if it has not been set. Raises: ConnectionError: if the API call failed. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the qiskit.backends family of functions instead is recommended. Gets online simulators via QX API calls. Returns: list(str): List of online simulator names. Raises: ConnectionError: if the API call failed. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the qiskit.backends family of functions instead is recommended. Gets online devices via QX API calls. Returns: list(str): List of online devices names. Raises: ConnectionError: if the API call failed. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the qiskit.backends family of functions instead is recommended. Return the online backend status. It uses QX API call or by local backend is the name of the local or online simulator or experiment. Args: backend (str): The backend to check Returns: dict: {'available': True} Raises: ConnectionError: if the API call failed. ValueError: if the backend is not available. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the qiskit.backends family of functions instead is recommended. Return the configuration of the backend. The return is via QX API call. Args: backend (str): Name of the backend. Returns: dict: The configuration of the named backend. Raises: ConnectionError: if the API call failed. LookupError: if a configuration for the named backend can't be found. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the qiskit.backends family of functions instead is recommended. Return the online backend calibrations. The return is via QX API call. Args: backend (str): Name of the backend. Returns: dict: The calibration of the named backend. Raises: ConnectionError: if the API call failed. LookupError: If a configuration for the named backend can't be found. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the qiskit.backends family of functions instead is recommended. Return the online backend parameters. The return is via QX API call. Args: backend (str): Name of the backend. Returns: dict: The configuration of the named backend. Raises: ConnectionError: if the API call failed. LookupError: If a configuration for the named backend can't be found. .. deprecated:: 0.5 This method will be deprecated in upcoming versions. Using the qiskit.backends family of functions instead is recommended. ############################################################### # methods to compile quantum programs into qobj ############################################################### Compile the circuits into the execution list. .. deprecated:: 0.5 The `coupling_map` parameter as a dictionary will be deprecated in upcoming versions. Using the coupling_map as a list is recommended. # pylint: disable=missing-param-doc, missing-type-doc Change configuration parameters for a compile qobj. Only parameters which don't affect the circuit compilation can change, e.g., the coupling_map cannot be changed here! Notes: If the inputs are left as None then the qobj is not updated Args: qobj (dict): already compile qobj backend (str): see .compile config (dict): see .compile shots (int): see .compile max_credits (int): see .compile seed (int): see .compile Returns: qobj: updated qobj Print the compiled circuits that are ready to run. Note: This method is intended to be used during interactive sessions, and prints directly to stdout instead of using the logger by default. If you set print_func with a log function (eg. log.info) it will be used instead of the stdout. Returns: list(str): names of the circuits in `qobj` Get the compiled layout for the named circuit and backend. Args: name (str): the circuit name qobj (dict): the qobj Returns: dict: the config of the circuit. Raises: QISKitError: if the circuit has no configurations Return the compiled circuit in qasm format. Args: qobj (dict): the qobj name (str): name of the quantum circuit Returns: str: the QASM of the compiled circuit. Raises: QISKitError: if the circuit has no configurations ############################################################### # methods to run quantum programs ############################################################### Run a program (a pre-compiled quantum program). This function will block until the Job is processed. The program to run is extracted from the qobj parameter. Args: qobj (dict): the dictionary of the quantum object to run. timeout (int): Total time to wait until the execution stops Returns: Result: A Result (class). Run various programs (a list of pre-compiled quantum programs). This function will block until all programs are processed. The programs to run are extracted from qobj elements of the list. Args: qobj_list (list(dict)): The list of quantum objects to run. timeout (int): Total time to wait until the execution stops Returns: list(Result): A list of Result (class). The list will contain one Result object per qobj in the input list. Execute, compile, and run an array of quantum circuits). This builds the internal "to execute" list which is list of quantum circuits to run on different backends. Args: name_of_circuits (list[str] or str or None): circuit names to be executed. If None, all the circuits will be executed. backend (str): a string representing the backend to compile to. config (dict): a dictionary of configurations parameters for the compiler. timeout (int): Total time to wait until the execution stops basis_gates (str): a comma separated string and are the base gates, which by default are: u1,u2,u3,cx,id. coupling_map (list): A graph of coupling:: [ [control0(int), target0(int)], [control1(int), target1(int)], ] eg. [[0, 2], [1, 2], [3, 2]] initial_layout (dict): A mapping of qubit to qubit { ("q", start(int)): ("q", final(int)), ... } eg. { ("q", 0): ("q", 0), ("q", 1): ("q", 1), ("q", 2): ("q", 2), ("q", 3): ("q", 3) } shots (int): the number of shots max_credits (int): the max credits to use 3, or 5 seed (int): the initial seed the simulators use hpc (dict): This will setup some parameter for ibmq_qasm_simulator, using a JSON-like format like:: { 'multi_shot_optimization': Boolean, 'omp_num_threads': Numeric } skip_transpiler (bool): If True, bypass most of the compilation process and creates a qobj with minimal check nor translation Returns: Result: status done and populates the internal __quantum_program with the data. .. deprecated:: 0.5 The `coupling_map` parameter as a dictionary will be deprecated in upcoming versions. Using the coupling_map as a list is recommended. # pylint: disable=missing-param-doc, missing-type-doc # TODO: Jay: currently basis_gates, coupling_map, initial_layout, shots, # max_credits, and seed are extra inputs but I would like them to go # into the config ############################################################### # utility methods ############################################################### Return the first and only element of `items`, raising an error otherwise. Args: items (list): list of items. item_description (string): text description of the item type. Returns: object: the first and only element of `items`. Raises: QISKitError: if the list does not have exactly one item. Return an automatically generated identifier, increased sequentially based on the internal `_counter` generator, with the form "[prefix][numeric_id]" (ie. "q2", where the prefix is "q"). Args: prefix (str): string to be prepended to the numeric id. existing_ids (iterable): list of ids that should be checked for duplicates. Returns: str: the new identifier. Raises: QISKitError: if the identifier is already in `existing_ids`.
| 2.10785
| 2
|
setup.py
|
zfghterb721/nxbt
| 257
|
6626306
|
<gh_stars>100-1000
from setuptools import setup
setup(
name="nxbt",
include_package_data=True,
long_description_content_type="text/markdown",
install_requires=[
"dbus-python==1.2.16",
"Flask==1.1.2",
"Flask-SocketIO==5.0.1",
"eventlet==0.31.0",
"blessed==1.17.10",
"pynput==1.7.1",
"psutil==5.6.6",
"cryptography==3.3.2",
],
extra_require={
"dev": [
"pytest"
]
}
)
|
from setuptools import setup
setup(
name="nxbt",
include_package_data=True,
long_description_content_type="text/markdown",
install_requires=[
"dbus-python==1.2.16",
"Flask==1.1.2",
"Flask-SocketIO==5.0.1",
"eventlet==0.31.0",
"blessed==1.17.10",
"pynput==1.7.1",
"psutil==5.6.6",
"cryptography==3.3.2",
],
extra_require={
"dev": [
"pytest"
]
}
)
|
none
| 1
| 1.152702
| 1
|
|
pygeotoolbox/sharedtools/fonts/fonts.py
|
raugustyn/doctest
| 0
|
6626307
|
# -*- coding: utf-8 -*-
__author__ = "<EMAIL>"
from base import getFontTableName
class Fonts:
FONTS_SCHEMA_CREATED = False
SQL_COMMANDS = None
def __init__(self):
pass
@property
def fonts(self):
if not hasattr(self, "__fonts"):
from font import Font
self.__fonts = {}
for row in self.sql.getFontInfos():
self.__fonts[row[0]] = Font(row[0])
return self.__fonts
def __iter__(self):
return self.fonts.values().__iter__()
def font(self, name):
return self.fonts.get(name, None)
@property
def names(self):
return self.fonts.keys()
@property
def sql(self):
if not Fonts.SQL_COMMANDS:
from database import SQLCommands
Fonts.SQL_COMMANDS = SQLCommands(sqlFileName="fonts.sql", file=__file__)
return Fonts.SQL_COMMANDS
def schemaNeeded(self):
"""
>>> f.schemaNeeded()
"""
if not Fonts.FONTS_SCHEMA_CREATED:
self.sql.prepareFontSchema()
Fonts.FONTS_SCHEMA_CREATED = True
def getFontInfo(self, fontName):
row = self.sql.getFontInfo(fontName).fetchone()
if row:
return row
else:
self.sql.registerFont(fontName, getFontTableName(fontName))
return self.getFontInfo(fontName)
def registerFont(self, name):
pass
def loadFromSVG(self, svgFileName, charsToBeAdded=None):
from font import Font
font = Font(svgFileName, charsToBeAdded)
font.saveToDatabase()
fonts = Fonts()
if __name__ == "__main__":
if False:
fonts.schemaNeeded()
id, tableName = fonts.getFontInfo('ArialMT.svg')
print id, tableName
if True:
for font in fonts:
print "%s - %d glyphs" % (font.name, len(font.glyphs))
|
# -*- coding: utf-8 -*-
__author__ = "<EMAIL>"
from base import getFontTableName
class Fonts:
FONTS_SCHEMA_CREATED = False
SQL_COMMANDS = None
def __init__(self):
pass
@property
def fonts(self):
if not hasattr(self, "__fonts"):
from font import Font
self.__fonts = {}
for row in self.sql.getFontInfos():
self.__fonts[row[0]] = Font(row[0])
return self.__fonts
def __iter__(self):
return self.fonts.values().__iter__()
def font(self, name):
return self.fonts.get(name, None)
@property
def names(self):
return self.fonts.keys()
@property
def sql(self):
if not Fonts.SQL_COMMANDS:
from database import SQLCommands
Fonts.SQL_COMMANDS = SQLCommands(sqlFileName="fonts.sql", file=__file__)
return Fonts.SQL_COMMANDS
def schemaNeeded(self):
"""
>>> f.schemaNeeded()
"""
if not Fonts.FONTS_SCHEMA_CREATED:
self.sql.prepareFontSchema()
Fonts.FONTS_SCHEMA_CREATED = True
def getFontInfo(self, fontName):
row = self.sql.getFontInfo(fontName).fetchone()
if row:
return row
else:
self.sql.registerFont(fontName, getFontTableName(fontName))
return self.getFontInfo(fontName)
def registerFont(self, name):
pass
def loadFromSVG(self, svgFileName, charsToBeAdded=None):
from font import Font
font = Font(svgFileName, charsToBeAdded)
font.saveToDatabase()
fonts = Fonts()
if __name__ == "__main__":
if False:
fonts.schemaNeeded()
id, tableName = fonts.getFontInfo('ArialMT.svg')
print id, tableName
if True:
for font in fonts:
print "%s - %d glyphs" % (font.name, len(font.glyphs))
|
en
| 0.567462
|
# -*- coding: utf-8 -*- >>> f.schemaNeeded()
| 2.713771
| 3
|
hard-gists/8b1502a49d8b20a6ae70/snippet.py
|
jjhenkel/dockerizeme
| 21
|
6626308
|
<reponame>jjhenkel/dockerizeme
#!/usr/bin/env python
#coding=utf-8
import apt
import apt_pkg
from time import strftime
import os
import subprocess
import sys
"""
Following functions are used to return package info of available updates.
See: /usr/lib/update-notifier/apt_check.py
"""
SYNAPTIC_PINFILE = "/var/lib/synaptic/preferences"
DISTRO = subprocess.check_output(["lsb_release", "-c", "-s"],
universal_newlines=True).strip()
def clean(cache,depcache):
""" unmark (clean) all changes from the given depcache """
# mvo: looping is too inefficient with the new auto-mark code
# for pkg in cache.Packages:
# depcache.MarkKeep(pkg)
depcache.init()
def saveDistUpgrade(cache,depcache):
""" this functions mimics a upgrade but will never remove anything """
depcache.upgrade(True)
if depcache.del_count > 0:
clean(cache,depcache)
depcache.upgrade()
def get_update_packages():
"""
Return a list of dict about package updates
"""
pkgs = []
apt_pkg.init()
# force apt to build its caches in memory for now to make sure
# that there is no race when the pkgcache file gets re-generated
apt_pkg.config.set("Dir::Cache::pkgcache","")
try:
cache = apt_pkg.Cache(apt.progress.base.OpProgress())
except SystemError as e:
sys.stderr.write("Error: Opening the cache (%s)" % e)
sys.exit(-1)
depcache = apt_pkg.DepCache(cache)
# read the pin files
depcache.read_pinfile()
# read the synaptic pins too
if os.path.exists(SYNAPTIC_PINFILE):
depcache.read_pinfile(SYNAPTIC_PINFILE)
# init the depcache
depcache.init()
try:
saveDistUpgrade(cache,depcache)
except SystemError as e:
sys.stderr.write("Error: Marking the upgrade (%s)" % e)
sys.exit(-1)
# use assignment here since apt.Cache() doesn't provide a __exit__ method
# on Ubuntu 12.04 it looks like
# aptcache = apt.Cache()
for pkg in cache.packages:
if not (depcache.marked_install(pkg) or depcache.marked_upgrade(pkg)):
continue
inst_ver = pkg.current_ver
cand_ver = depcache.get_candidate_ver(pkg)
if cand_ver == inst_ver:
continue
record = {"name": pkg.name,
"security": isSecurityUpgrade(pkg, depcache),
"section": pkg.section,
"current_version": inst_ver.ver_str if inst_ver else '-',
"candidate_version": cand_ver.ver_str if cand_ver else '-',
"priority": cand_ver.priority_str}
pkgs.append(record)
return pkgs
def isSecurityUpgrade(pkg, depcache):
def isSecurityUpgrade_helper(ver):
""" check if the given version is a security update (or masks one) """
security_pockets = [("Ubuntu", "%s-security" % DISTRO),
("gNewSense", "%s-security" % DISTRO),
("Debian", "%s-updates" % DISTRO)]
for (file, index) in ver.file_list:
for origin, archive in security_pockets:
if (file.archive == archive and file.origin == origin):
return True
return False
inst_ver = pkg.current_ver
cand_ver = depcache.get_candidate_ver(pkg)
if isSecurityUpgrade_helper(cand_ver):
return True
# now check for security updates that are masked by a
# canidate version from another repo (-proposed or -updates)
for ver in pkg.version_list:
if (inst_ver and
apt_pkg.version_compare(ver.ver_str, inst_ver.ver_str) <= 0):
#print "skipping '%s' " % ver.VerStr
continue
if isSecurityUpgrade_helper(ver):
return True
return False
def print_result(pkgs):
"""
Print package updates in a table
"""
security_updates = filter(lambda x: x.get('security'), pkgs)
text = list()
text.append('Check Time: %s' % strftime('%m/%d/%Y %H:%M:%S'))
if not pkgs:
text.append('No available updates on this machine.')
else:
# Updates are available, build a table
text.append('%d packages can be updated.' % len(pkgs))
text.append('%d updates are security updates.' % len(security_updates))
text.append('-' * 100)
# List available security updates
text.append('Package Name'.ljust(30) +
'Current Version'.ljust(30) +
'Latest Version'.ljust(30) +
'Security'.ljust(10))
text.append('-' * 100)
for pkg in pkgs:
text.append('{:<30}{:<30}{:<30}{:<10}'.format(pkg.get('name'),
pkg.get('current_version'),
pkg.get('candidate_version'),
'*' if pkg.get('security') else ''))
text.append('=' * 100)
return '\n'.join(text)
if __name__ == '__main__':
pkgs = get_update_packages()
print print_result(pkgs)
|
#!/usr/bin/env python
#coding=utf-8
import apt
import apt_pkg
from time import strftime
import os
import subprocess
import sys
"""
Following functions are used to return package info of available updates.
See: /usr/lib/update-notifier/apt_check.py
"""
SYNAPTIC_PINFILE = "/var/lib/synaptic/preferences"
DISTRO = subprocess.check_output(["lsb_release", "-c", "-s"],
universal_newlines=True).strip()
def clean(cache,depcache):
""" unmark (clean) all changes from the given depcache """
# mvo: looping is too inefficient with the new auto-mark code
# for pkg in cache.Packages:
# depcache.MarkKeep(pkg)
depcache.init()
def saveDistUpgrade(cache,depcache):
""" this functions mimics a upgrade but will never remove anything """
depcache.upgrade(True)
if depcache.del_count > 0:
clean(cache,depcache)
depcache.upgrade()
def get_update_packages():
"""
Return a list of dict about package updates
"""
pkgs = []
apt_pkg.init()
# force apt to build its caches in memory for now to make sure
# that there is no race when the pkgcache file gets re-generated
apt_pkg.config.set("Dir::Cache::pkgcache","")
try:
cache = apt_pkg.Cache(apt.progress.base.OpProgress())
except SystemError as e:
sys.stderr.write("Error: Opening the cache (%s)" % e)
sys.exit(-1)
depcache = apt_pkg.DepCache(cache)
# read the pin files
depcache.read_pinfile()
# read the synaptic pins too
if os.path.exists(SYNAPTIC_PINFILE):
depcache.read_pinfile(SYNAPTIC_PINFILE)
# init the depcache
depcache.init()
try:
saveDistUpgrade(cache,depcache)
except SystemError as e:
sys.stderr.write("Error: Marking the upgrade (%s)" % e)
sys.exit(-1)
# use assignment here since apt.Cache() doesn't provide a __exit__ method
# on Ubuntu 12.04 it looks like
# aptcache = apt.Cache()
for pkg in cache.packages:
if not (depcache.marked_install(pkg) or depcache.marked_upgrade(pkg)):
continue
inst_ver = pkg.current_ver
cand_ver = depcache.get_candidate_ver(pkg)
if cand_ver == inst_ver:
continue
record = {"name": pkg.name,
"security": isSecurityUpgrade(pkg, depcache),
"section": pkg.section,
"current_version": inst_ver.ver_str if inst_ver else '-',
"candidate_version": cand_ver.ver_str if cand_ver else '-',
"priority": cand_ver.priority_str}
pkgs.append(record)
return pkgs
def isSecurityUpgrade(pkg, depcache):
def isSecurityUpgrade_helper(ver):
""" check if the given version is a security update (or masks one) """
security_pockets = [("Ubuntu", "%s-security" % DISTRO),
("gNewSense", "%s-security" % DISTRO),
("Debian", "%s-updates" % DISTRO)]
for (file, index) in ver.file_list:
for origin, archive in security_pockets:
if (file.archive == archive and file.origin == origin):
return True
return False
inst_ver = pkg.current_ver
cand_ver = depcache.get_candidate_ver(pkg)
if isSecurityUpgrade_helper(cand_ver):
return True
# now check for security updates that are masked by a
# canidate version from another repo (-proposed or -updates)
for ver in pkg.version_list:
if (inst_ver and
apt_pkg.version_compare(ver.ver_str, inst_ver.ver_str) <= 0):
#print "skipping '%s' " % ver.VerStr
continue
if isSecurityUpgrade_helper(ver):
return True
return False
def print_result(pkgs):
"""
Print package updates in a table
"""
security_updates = filter(lambda x: x.get('security'), pkgs)
text = list()
text.append('Check Time: %s' % strftime('%m/%d/%Y %H:%M:%S'))
if not pkgs:
text.append('No available updates on this machine.')
else:
# Updates are available, build a table
text.append('%d packages can be updated.' % len(pkgs))
text.append('%d updates are security updates.' % len(security_updates))
text.append('-' * 100)
# List available security updates
text.append('Package Name'.ljust(30) +
'Current Version'.ljust(30) +
'Latest Version'.ljust(30) +
'Security'.ljust(10))
text.append('-' * 100)
for pkg in pkgs:
text.append('{:<30}{:<30}{:<30}{:<10}'.format(pkg.get('name'),
pkg.get('current_version'),
pkg.get('candidate_version'),
'*' if pkg.get('security') else ''))
text.append('=' * 100)
return '\n'.join(text)
if __name__ == '__main__':
pkgs = get_update_packages()
print print_result(pkgs)
|
en
| 0.782981
|
#!/usr/bin/env python #coding=utf-8 Following functions are used to return package info of available updates. See: /usr/lib/update-notifier/apt_check.py unmark (clean) all changes from the given depcache # mvo: looping is too inefficient with the new auto-mark code # for pkg in cache.Packages: # depcache.MarkKeep(pkg) this functions mimics a upgrade but will never remove anything Return a list of dict about package updates # force apt to build its caches in memory for now to make sure # that there is no race when the pkgcache file gets re-generated # read the pin files # read the synaptic pins too # init the depcache # use assignment here since apt.Cache() doesn't provide a __exit__ method # on Ubuntu 12.04 it looks like # aptcache = apt.Cache() check if the given version is a security update (or masks one) # now check for security updates that are masked by a # canidate version from another repo (-proposed or -updates) #print "skipping '%s' " % ver.VerStr Print package updates in a table # Updates are available, build a table # List available security updates
| 2.622167
| 3
|
other/day21b.py
|
p88h/aoc2021
| 15
|
6626309
|
<gh_stars>10-100
from collections import defaultdict
import time
lines = open("input/day21.txt").readlines()
p1 = int(lines[0].split(": ")[1])
p2 = int(lines[1].split(": ")[1])
def run1(p1, p2):
s1 = s2 = ofs = cnt = 0
while True:
p1 = (p1+(ofs % 100)+((ofs+1) % 100)+((ofs+2) % 100)+2) % 10+1
ofs = (ofs+3) % 100
cnt = cnt + 3
s1 = s1 + p1
if s1 >= 1000:
return s2*cnt
(p1, p2, s1, s2) = (p2, p1, s2, s1)
def produce3(multiverse, p, s, c, w):
for (d, f) in [(6, 7), (5, 6), (7, 6), (4, 3), (8, 3), (3, 1), (9, 1)]:
np = ((p + d - 1) % 10) + 1
ns = s + np
if ns < 21:
multiverse[(np, ns)] += c*f
else:
w[-1] += c*f
def run2(p):
multiverse = defaultdict(int)
multiverse[(p, 0)] = 1
wins = []
while multiverse:
wins.append(0)
temp = defaultdict(int)
for (p, s) in multiverse:
produce3(temp, p, s, multiverse[(p, s)], wins)
multiverse = temp
return wins
def run3(p1, p2):
wins1 = run2(p1)
wins2 = run2(p2)
size1 = size2 = 1
w1 = w2 = 0
for step in range(len(wins1)):
size1 = size1 * 27 - wins1[step]
w1 += wins1[step]*size2
size2 = size2 * 27 - wins2[step]
w2 += wins2[step]*size1
return max(w1, w2)
start = time.time()
ret1 = run1(p1, p2)
end = time.time()
print(ret1, end-start)
start = time.time()
ret2 = run3(p1, p2)
end = time.time()
print(ret2, end-start)
|
from collections import defaultdict
import time
lines = open("input/day21.txt").readlines()
p1 = int(lines[0].split(": ")[1])
p2 = int(lines[1].split(": ")[1])
def run1(p1, p2):
s1 = s2 = ofs = cnt = 0
while True:
p1 = (p1+(ofs % 100)+((ofs+1) % 100)+((ofs+2) % 100)+2) % 10+1
ofs = (ofs+3) % 100
cnt = cnt + 3
s1 = s1 + p1
if s1 >= 1000:
return s2*cnt
(p1, p2, s1, s2) = (p2, p1, s2, s1)
def produce3(multiverse, p, s, c, w):
for (d, f) in [(6, 7), (5, 6), (7, 6), (4, 3), (8, 3), (3, 1), (9, 1)]:
np = ((p + d - 1) % 10) + 1
ns = s + np
if ns < 21:
multiverse[(np, ns)] += c*f
else:
w[-1] += c*f
def run2(p):
multiverse = defaultdict(int)
multiverse[(p, 0)] = 1
wins = []
while multiverse:
wins.append(0)
temp = defaultdict(int)
for (p, s) in multiverse:
produce3(temp, p, s, multiverse[(p, s)], wins)
multiverse = temp
return wins
def run3(p1, p2):
wins1 = run2(p1)
wins2 = run2(p2)
size1 = size2 = 1
w1 = w2 = 0
for step in range(len(wins1)):
size1 = size1 * 27 - wins1[step]
w1 += wins1[step]*size2
size2 = size2 * 27 - wins2[step]
w2 += wins2[step]*size1
return max(w1, w2)
start = time.time()
ret1 = run1(p1, p2)
end = time.time()
print(ret1, end-start)
start = time.time()
ret2 = run3(p1, p2)
end = time.time()
print(ret2, end-start)
|
none
| 1
| 2.976866
| 3
|
|
tournaments/checkFactorial/checkFactorial.py
|
gurfinkel/codeSignal
| 5
|
6626310
|
<gh_stars>1-10
def checkFactorial(n):
k = 1
while 1 != n:
if (0 == n % k):
n /= k
k += 1
else:
return False
return True
|
def checkFactorial(n):
k = 1
while 1 != n:
if (0 == n % k):
n /= k
k += 1
else:
return False
return True
|
none
| 1
| 3.540925
| 4
|
|
ot/lp/cvx.py
|
kguerda-idris/POT
| 830
|
6626311
|
# -*- coding: utf-8 -*-
"""
LP solvers for optimal transport using cvxopt
"""
# Author: <NAME> <<EMAIL>>
#
# License: MIT License
import numpy as np
import scipy as sp
import scipy.sparse as sps
try:
import cvxopt
from cvxopt import solvers, matrix, spmatrix
except ImportError:
cvxopt = False
def scipy_sparse_to_spmatrix(A):
"""Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
coo = A.tocoo()
SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
return SP
def barycenter(A, M, weights=None, verbose=False, log=False, solver='interior-point'):
r"""Compute the Wasserstein barycenter of distributions A
The function solves the following optimization problem [16]:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{1}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_1(\cdot,\cdot)` is the Wasserstein distance (see ot.emd.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
The linear program is solved using the interior point solver from scipy.optimize.
If cvxopt solver if installed it can use cvxopt
Note that this problem do not scale well (both in memory and computational time).
Parameters
----------
A : np.ndarray (d,n)
n training distributions a_i of size d
M : np.ndarray (d,d)
loss matrix for OT
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each histogram a_i on the simplex (barycentric coodinates)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
solver : string, optional
the solver used, default 'interior-point' use the lp solver from
scipy.optimize. None, or 'glpk' or 'mosek' use the solver from cvxopt.
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [16] <NAME>., & <NAME>. (2011). Barycenters in the Wasserstein space. SIAM Journal on Mathematical Analysis, 43(2), 904-924.
"""
if weights is None:
weights = np.ones(A.shape[1]) / A.shape[1]
else:
assert(len(weights) == A.shape[1])
n_distributions = A.shape[1]
n = A.shape[0]
n2 = n * n
c = np.zeros((0))
b_eq1 = np.zeros((0))
for i in range(n_distributions):
c = np.concatenate((c, M.ravel() * weights[i]))
b_eq1 = np.concatenate((b_eq1, A[:, i]))
c = np.concatenate((c, np.zeros(n)))
lst_idiag1 = [sps.kron(sps.eye(n), np.ones((1, n))) for i in range(n_distributions)]
# row constraints
A_eq1 = sps.hstack((sps.block_diag(lst_idiag1), sps.coo_matrix((n_distributions * n, n))))
# columns constraints
lst_idiag2 = []
lst_eye = []
for i in range(n_distributions):
if i == 0:
lst_idiag2.append(sps.kron(np.ones((1, n)), sps.eye(n)))
lst_eye.append(-sps.eye(n))
else:
lst_idiag2.append(sps.kron(np.ones((1, n)), sps.eye(n - 1, n)))
lst_eye.append(-sps.eye(n - 1, n))
A_eq2 = sps.hstack((sps.block_diag(lst_idiag2), sps.vstack(lst_eye)))
b_eq2 = np.zeros((A_eq2.shape[0]))
# full problem
A_eq = sps.vstack((A_eq1, A_eq2))
b_eq = np.concatenate((b_eq1, b_eq2))
if not cvxopt or solver in ['interior-point']:
# cvxopt not installed or interior point
if solver is None:
solver = 'interior-point'
options = {'sparse': True, 'disp': verbose}
sol = sp.optimize.linprog(c, A_eq=A_eq, b_eq=b_eq, method=solver,
options=options)
x = sol.x
b = x[-n:]
else:
h = np.zeros((n_distributions * n2 + n))
G = -sps.eye(n_distributions * n2 + n)
sol = solvers.lp(matrix(c), scipy_sparse_to_spmatrix(G), matrix(h),
A=scipy_sparse_to_spmatrix(A_eq), b=matrix(b_eq),
solver=solver)
x = np.array(sol['x'])
b = x[-n:].ravel()
if log:
return b, sol
else:
return b
|
# -*- coding: utf-8 -*-
"""
LP solvers for optimal transport using cvxopt
"""
# Author: <NAME> <<EMAIL>>
#
# License: MIT License
import numpy as np
import scipy as sp
import scipy.sparse as sps
try:
import cvxopt
from cvxopt import solvers, matrix, spmatrix
except ImportError:
cvxopt = False
def scipy_sparse_to_spmatrix(A):
"""Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
coo = A.tocoo()
SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
return SP
def barycenter(A, M, weights=None, verbose=False, log=False, solver='interior-point'):
r"""Compute the Wasserstein barycenter of distributions A
The function solves the following optimization problem [16]:
.. math::
\mathbf{a} = arg\min_\mathbf{a} \sum_i W_{1}(\mathbf{a},\mathbf{a}_i)
where :
- :math:`W_1(\cdot,\cdot)` is the Wasserstein distance (see ot.emd.sinkhorn)
- :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
The linear program is solved using the interior point solver from scipy.optimize.
If cvxopt solver if installed it can use cvxopt
Note that this problem do not scale well (both in memory and computational time).
Parameters
----------
A : np.ndarray (d,n)
n training distributions a_i of size d
M : np.ndarray (d,d)
loss matrix for OT
reg : float
Regularization term >0
weights : np.ndarray (n,)
Weights of each histogram a_i on the simplex (barycentric coodinates)
verbose : bool, optional
Print information along iterations
log : bool, optional
record log if True
solver : string, optional
the solver used, default 'interior-point' use the lp solver from
scipy.optimize. None, or 'glpk' or 'mosek' use the solver from cvxopt.
Returns
-------
a : (d,) ndarray
Wasserstein barycenter
log : dict
log dictionary return only if log==True in parameters
References
----------
.. [16] <NAME>., & <NAME>. (2011). Barycenters in the Wasserstein space. SIAM Journal on Mathematical Analysis, 43(2), 904-924.
"""
if weights is None:
weights = np.ones(A.shape[1]) / A.shape[1]
else:
assert(len(weights) == A.shape[1])
n_distributions = A.shape[1]
n = A.shape[0]
n2 = n * n
c = np.zeros((0))
b_eq1 = np.zeros((0))
for i in range(n_distributions):
c = np.concatenate((c, M.ravel() * weights[i]))
b_eq1 = np.concatenate((b_eq1, A[:, i]))
c = np.concatenate((c, np.zeros(n)))
lst_idiag1 = [sps.kron(sps.eye(n), np.ones((1, n))) for i in range(n_distributions)]
# row constraints
A_eq1 = sps.hstack((sps.block_diag(lst_idiag1), sps.coo_matrix((n_distributions * n, n))))
# columns constraints
lst_idiag2 = []
lst_eye = []
for i in range(n_distributions):
if i == 0:
lst_idiag2.append(sps.kron(np.ones((1, n)), sps.eye(n)))
lst_eye.append(-sps.eye(n))
else:
lst_idiag2.append(sps.kron(np.ones((1, n)), sps.eye(n - 1, n)))
lst_eye.append(-sps.eye(n - 1, n))
A_eq2 = sps.hstack((sps.block_diag(lst_idiag2), sps.vstack(lst_eye)))
b_eq2 = np.zeros((A_eq2.shape[0]))
# full problem
A_eq = sps.vstack((A_eq1, A_eq2))
b_eq = np.concatenate((b_eq1, b_eq2))
if not cvxopt or solver in ['interior-point']:
# cvxopt not installed or interior point
if solver is None:
solver = 'interior-point'
options = {'sparse': True, 'disp': verbose}
sol = sp.optimize.linprog(c, A_eq=A_eq, b_eq=b_eq, method=solver,
options=options)
x = sol.x
b = x[-n:]
else:
h = np.zeros((n_distributions * n2 + n))
G = -sps.eye(n_distributions * n2 + n)
sol = solvers.lp(matrix(c), scipy_sparse_to_spmatrix(G), matrix(h),
A=scipy_sparse_to_spmatrix(A_eq), b=matrix(b_eq),
solver=solver)
x = np.array(sol['x'])
b = x[-n:].ravel()
if log:
return b, sol
else:
return b
|
en
| 0.565765
|
# -*- coding: utf-8 -*- LP solvers for optimal transport using cvxopt # Author: <NAME> <<EMAIL>> # # License: MIT License Efficient conversion from scipy sparse matrix to cvxopt sparse matrix Compute the Wasserstein barycenter of distributions A The function solves the following optimization problem [16]: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{1}(\mathbf{a},\mathbf{a}_i) where : - :math:`W_1(\cdot,\cdot)` is the Wasserstein distance (see ot.emd.sinkhorn) - :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}` The linear program is solved using the interior point solver from scipy.optimize. If cvxopt solver if installed it can use cvxopt Note that this problem do not scale well (both in memory and computational time). Parameters ---------- A : np.ndarray (d,n) n training distributions a_i of size d M : np.ndarray (d,d) loss matrix for OT reg : float Regularization term >0 weights : np.ndarray (n,) Weights of each histogram a_i on the simplex (barycentric coodinates) verbose : bool, optional Print information along iterations log : bool, optional record log if True solver : string, optional the solver used, default 'interior-point' use the lp solver from scipy.optimize. None, or 'glpk' or 'mosek' use the solver from cvxopt. Returns ------- a : (d,) ndarray Wasserstein barycenter log : dict log dictionary return only if log==True in parameters References ---------- .. [16] <NAME>., & <NAME>. (2011). Barycenters in the Wasserstein space. SIAM Journal on Mathematical Analysis, 43(2), 904-924. # row constraints # columns constraints # full problem # cvxopt not installed or interior point
| 2.265184
| 2
|
iac_electricals/iac_electricals/custom_scripts/item/item.py
|
indictranstech/iac_electricals_v13
| 1
|
6626312
|
# Copyright (c) 2021, IAC Electricals and contributors
# For license information, please see license.txt
import frappe
from frappe import _
import gzip
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
def before_insert(self,method=None):
self.flags.name_set = 1
current = frappe.db.sql("""select MAX(current) AS current from `tabSeries` where name = '{0}'""".format(self.custom_naming_series),as_dict=1)
for row in current:
current = row.current
last_doc = frappe.get_last_doc('File')
if last_doc.file_name.endswith('.csv'):
file = open(frappe.utils.get_site_path("private")+"/files/"+last_doc.file_name, "rt")
csv= file.readlines()
id_list = []
variable = None
if variable:
frappe.db.sql("""update tabSeries set current = {0} where name = '{1}'""".format(variable, self.custom_naming_series), debug = 1)
series = self.custom_naming_series + str(variable).zfill(3)
self.name = series
# for row in csv[1:]:
# li = list(row.split(","))
# if li:
# id_list.append(li[7])
# if li[7] == self.item_name:
# variable = int(li[0][6:])
# break
if current is None:
current = 1
series = str(self.real_item_code)
self.name = series
first_series_to_store = self.custom_naming_series
frappe.db.sql("insert into tabSeries (name, current) values (%s, 1)", (first_series_to_store))
else:
current = current + 1
current = current
series = str(self.real_item_code)
self.name = series
frappe.db.sql("""update tabSeries set current = {0} where name = '{1}'""".format(current, self.custom_naming_series))
pass
if current is None:
current = 1
if self.real_item_code is None:
series = self.custom_naming_series + str(current).zfill(3)
self.name = series
first_series_to_store = self.custom_naming_series
frappe.db.sql("insert into tabSeries (name, current) values (%s, 1)", (series))
else:
current = current + 1
current = current
if self.real_item_code is None:
series = self.custom_naming_series + str(current).zfill(3)
self.name = series
first_series_to_store = self.custom_naming_series
frappe.db.sql("insert into tabSeries (name, current) values (%s, 1)", (series))
@frappe.whitelist()
def update_old_item_custom_naming_series_for_one_time():
all_item = frappe.get_all('Item')
cnt = 0
for item in all_item:
cnt = cnt + 1
sql = """ UPDATE `tabItem` SET custom_naming_series = "" where name IN ('{0}')""".format(item.name)
benificiary_purchase_count = frappe.db.sql(sql,debug=1)
error_log = frappe.log_error(frappe.get_traceback(), _("All item Updated item count: '{0}' ").format(cnt))
@frappe.whitelist()
def update_the_series_item_updation(prefix_level_for_item,count1):
item_updation = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count1, prefix_level_for_item), debug = 1)
return "Success"
@frappe.whitelist()
def update_the_series_prefix2_updation(prefix_level_3, count2):
item_updation = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count2, prefix_level_3), debug = 1)
return "Success"
@frappe.whitelist()
def update_the_series_prefix3_updation(prefix_level_2, count3):
series_3_updation = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count3, prefix_level_2), debug = 1)
return "Success"
@frappe.whitelist()
def all_reset_series(level, count4):
#item series level 1 counter reset
item_updation = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,level), debug = 1)
#item series level 2 counter reset
level2_name = frappe.db.sql("""SELECT l2.name from `tabItem Series lavel 2` l2 join `tabItem Series lavel 1` l1 on l1.name = l2.lavel_2_item_code where l1.name = '{0}' """.format(level), debug = 1, as_dict = 1)
level_2_name_list = [item.name for item in level2_name]
if len(level_2_name_list)> 1:
item_updation2 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1} """.format(count4,tuple(level_2_name_list)), debug = 1)
level3_name = frappe.db.sql("""SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name in {0} """.format(tuple(level_2_name_list)), debug = 1, as_dict = 1)
level_3_name_list = [item.name for item in level3_name]
if len(level_3_name_list) > 1:
item_updation3 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(level_3_name_list)), debug = 1)
item_name = frappe.db.sql("""SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name in {0} """.format(tuple(level_3_name_list)), debug = 1, as_dict = 1)
item_name_list = tuple([item.name for item in item_name])
if len(item_name_list) > 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(item_name_list)), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name in {0}""".format(tuple(item_name_list)), debug = 1)
elif len(item_name_list) == 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,item_name_list[0]), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name = '{0}' """.format(item_name_list[0]), debug = 1)
else:
pass
if len(level_2_name_list)> 1:
item_updation2 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1} """.format(count4,tuple(level_2_name_list)), debug = 1)
level3_name = frappe.db.sql("""SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name in {0} """.format(tuple(level_2_name_list)), debug = 1, as_dict = 1)
level_3_name_list = [item.name for item in level3_name]
if len(level_3_name_list) == 1:
item_updation3 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,level_3_name_list[0]), debug = 1)
item_name = frappe.db.sql("""SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name = '{0}' """.format(level_3_name_list[0]), debug = 1, as_dict = 1)
item_name_list = tuple([item.name for item in item_name])
if len(item_name_list) > 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(item_name_list)), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name in {0}""".format(tuple(item_name_list)), debug = 1)
elif len(item_name_list) == 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,item_name_list[0]), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name = '{0}' """.format(item_name_list[0]), debug = 1)
else:
pass
if len(level_2_name_list) == 1:
item_updation2 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,level_2_name_list[0]), debug = 1)
level3_name = frappe.db.sql("""SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name = '{0}' """.format(level_2_name_list[0]), debug = 1, as_dict = 1)
level_3_name_list = [item.name for item in level3_name]
if len(level_3_name_list) > 1:
item_updation3 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(level_3_name_list)), debug = 1)
item_name = frappe.db.sql("""SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name in {0} """.format(tuple(level_3_name_list)), debug = 1, as_dict = 1)
item_name_list = tuple([item.name for item in item_name])
if len(item_name_list) > 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(item_name_list)), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name in {0}""".format(tuple(item_name_list)), debug = 1)
elif len(item_name_list) == 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,item_name_list[0]), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name = '{0}' """.format(item_name_list[0]), debug = 1)
else:
pass
if len(level_2_name_list) == 1:
item_updation2 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,level_2_name_list[0]), debug = 1)
level3_name = frappe.db.sql("""SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name = '{0}' """.format(level_2_name_list[0]), debug = 1, as_dict = 1)
level_3_name_list = [item.name for item in level3_name]
if len(level_3_name_list) == 1:
item_updation3 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,level_3_name_list[0]), debug = 1)
item_name = frappe.db.sql("""SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name = '{0}' """.format(level_3_name_list[0]), debug = 1, as_dict = 1)
item_name_list = tuple([item.name for item in item_name])
if len(item_name_list) > 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(item_name_list)), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name in {0}""".format(tuple(item_name_list)), debug = 1)
elif len(item_name_list) == 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,item_name_list[0]), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name = '{0}' """.format(item_name_list[0]), debug = 1)
else:
pass
return "Success"
|
# Copyright (c) 2021, IAC Electricals and contributors
# For license information, please see license.txt
import frappe
from frappe import _
import gzip
from frappe.model.document import Document
from frappe.model.mapper import get_mapped_doc
def before_insert(self,method=None):
self.flags.name_set = 1
current = frappe.db.sql("""select MAX(current) AS current from `tabSeries` where name = '{0}'""".format(self.custom_naming_series),as_dict=1)
for row in current:
current = row.current
last_doc = frappe.get_last_doc('File')
if last_doc.file_name.endswith('.csv'):
file = open(frappe.utils.get_site_path("private")+"/files/"+last_doc.file_name, "rt")
csv= file.readlines()
id_list = []
variable = None
if variable:
frappe.db.sql("""update tabSeries set current = {0} where name = '{1}'""".format(variable, self.custom_naming_series), debug = 1)
series = self.custom_naming_series + str(variable).zfill(3)
self.name = series
# for row in csv[1:]:
# li = list(row.split(","))
# if li:
# id_list.append(li[7])
# if li[7] == self.item_name:
# variable = int(li[0][6:])
# break
if current is None:
current = 1
series = str(self.real_item_code)
self.name = series
first_series_to_store = self.custom_naming_series
frappe.db.sql("insert into tabSeries (name, current) values (%s, 1)", (first_series_to_store))
else:
current = current + 1
current = current
series = str(self.real_item_code)
self.name = series
frappe.db.sql("""update tabSeries set current = {0} where name = '{1}'""".format(current, self.custom_naming_series))
pass
if current is None:
current = 1
if self.real_item_code is None:
series = self.custom_naming_series + str(current).zfill(3)
self.name = series
first_series_to_store = self.custom_naming_series
frappe.db.sql("insert into tabSeries (name, current) values (%s, 1)", (series))
else:
current = current + 1
current = current
if self.real_item_code is None:
series = self.custom_naming_series + str(current).zfill(3)
self.name = series
first_series_to_store = self.custom_naming_series
frappe.db.sql("insert into tabSeries (name, current) values (%s, 1)", (series))
@frappe.whitelist()
def update_old_item_custom_naming_series_for_one_time():
all_item = frappe.get_all('Item')
cnt = 0
for item in all_item:
cnt = cnt + 1
sql = """ UPDATE `tabItem` SET custom_naming_series = "" where name IN ('{0}')""".format(item.name)
benificiary_purchase_count = frappe.db.sql(sql,debug=1)
error_log = frappe.log_error(frappe.get_traceback(), _("All item Updated item count: '{0}' ").format(cnt))
@frappe.whitelist()
def update_the_series_item_updation(prefix_level_for_item,count1):
item_updation = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count1, prefix_level_for_item), debug = 1)
return "Success"
@frappe.whitelist()
def update_the_series_prefix2_updation(prefix_level_3, count2):
item_updation = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count2, prefix_level_3), debug = 1)
return "Success"
@frappe.whitelist()
def update_the_series_prefix3_updation(prefix_level_2, count3):
series_3_updation = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count3, prefix_level_2), debug = 1)
return "Success"
@frappe.whitelist()
def all_reset_series(level, count4):
#item series level 1 counter reset
item_updation = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,level), debug = 1)
#item series level 2 counter reset
level2_name = frappe.db.sql("""SELECT l2.name from `tabItem Series lavel 2` l2 join `tabItem Series lavel 1` l1 on l1.name = l2.lavel_2_item_code where l1.name = '{0}' """.format(level), debug = 1, as_dict = 1)
level_2_name_list = [item.name for item in level2_name]
if len(level_2_name_list)> 1:
item_updation2 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1} """.format(count4,tuple(level_2_name_list)), debug = 1)
level3_name = frappe.db.sql("""SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name in {0} """.format(tuple(level_2_name_list)), debug = 1, as_dict = 1)
level_3_name_list = [item.name for item in level3_name]
if len(level_3_name_list) > 1:
item_updation3 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(level_3_name_list)), debug = 1)
item_name = frappe.db.sql("""SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name in {0} """.format(tuple(level_3_name_list)), debug = 1, as_dict = 1)
item_name_list = tuple([item.name for item in item_name])
if len(item_name_list) > 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(item_name_list)), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name in {0}""".format(tuple(item_name_list)), debug = 1)
elif len(item_name_list) == 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,item_name_list[0]), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name = '{0}' """.format(item_name_list[0]), debug = 1)
else:
pass
if len(level_2_name_list)> 1:
item_updation2 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1} """.format(count4,tuple(level_2_name_list)), debug = 1)
level3_name = frappe.db.sql("""SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name in {0} """.format(tuple(level_2_name_list)), debug = 1, as_dict = 1)
level_3_name_list = [item.name for item in level3_name]
if len(level_3_name_list) == 1:
item_updation3 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,level_3_name_list[0]), debug = 1)
item_name = frappe.db.sql("""SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name = '{0}' """.format(level_3_name_list[0]), debug = 1, as_dict = 1)
item_name_list = tuple([item.name for item in item_name])
if len(item_name_list) > 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(item_name_list)), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name in {0}""".format(tuple(item_name_list)), debug = 1)
elif len(item_name_list) == 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,item_name_list[0]), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name = '{0}' """.format(item_name_list[0]), debug = 1)
else:
pass
if len(level_2_name_list) == 1:
item_updation2 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,level_2_name_list[0]), debug = 1)
level3_name = frappe.db.sql("""SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name = '{0}' """.format(level_2_name_list[0]), debug = 1, as_dict = 1)
level_3_name_list = [item.name for item in level3_name]
if len(level_3_name_list) > 1:
item_updation3 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(level_3_name_list)), debug = 1)
item_name = frappe.db.sql("""SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name in {0} """.format(tuple(level_3_name_list)), debug = 1, as_dict = 1)
item_name_list = tuple([item.name for item in item_name])
if len(item_name_list) > 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(item_name_list)), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name in {0}""".format(tuple(item_name_list)), debug = 1)
elif len(item_name_list) == 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,item_name_list[0]), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name = '{0}' """.format(item_name_list[0]), debug = 1)
else:
pass
if len(level_2_name_list) == 1:
item_updation2 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,level_2_name_list[0]), debug = 1)
level3_name = frappe.db.sql("""SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name = '{0}' """.format(level_2_name_list[0]), debug = 1, as_dict = 1)
level_3_name_list = [item.name for item in level3_name]
if len(level_3_name_list) == 1:
item_updation3 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,level_3_name_list[0]), debug = 1)
item_name = frappe.db.sql("""SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name = '{0}' """.format(level_3_name_list[0]), debug = 1, as_dict = 1)
item_name_list = tuple([item.name for item in item_name])
if len(item_name_list) > 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name in {1}""".format(count4,tuple(item_name_list)), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name in {0}""".format(tuple(item_name_list)), debug = 1)
elif len(item_name_list) == 1:
item_updation4 = frappe.db.sql("""UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' """.format(count4,item_name_list[0]), debug = 1)
item_deletion = frappe.db.sql("""DELETE from `tabItem` where name = '{0}' """.format(item_name_list[0]), debug = 1)
else:
pass
return "Success"
|
en
| 0.540875
|
# Copyright (c) 2021, IAC Electricals and contributors # For license information, please see license.txt select MAX(current) AS current from `tabSeries` where name = '{0}' update tabSeries set current = {0} where name = '{1}' # for row in csv[1:]: # li = list(row.split(",")) # if li: # id_list.append(li[7]) # if li[7] == self.item_name: # variable = int(li[0][6:]) # break update tabSeries set current = {0} where name = '{1}' UPDATE `tabItem` SET custom_naming_series = "" where name IN ('{0}') UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' #item series level 1 counter reset UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' #item series level 2 counter reset SELECT l2.name from `tabItem Series lavel 2` l2 join `tabItem Series lavel 1` l1 on l1.name = l2.lavel_2_item_code where l1.name = '{0}' UPDATE `tabSeries` SET current = {0} WHERE name in {1} SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name in {0} UPDATE `tabSeries` SET current = {0} WHERE name in {1} SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name in {0} UPDATE `tabSeries` SET current = {0} WHERE name in {1} DELETE from `tabItem` where name in {0} UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' DELETE from `tabItem` where name = '{0}' UPDATE `tabSeries` SET current = {0} WHERE name in {1} SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name in {0} UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name = '{0}' UPDATE `tabSeries` SET current = {0} WHERE name in {1} DELETE from `tabItem` where name in {0} UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' DELETE from `tabItem` where name = '{0}' UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name = '{0}' UPDATE `tabSeries` SET current = {0} WHERE name in {1} SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name in {0} UPDATE `tabSeries` SET current = {0} WHERE name in {1} DELETE from `tabItem` where name in {0} UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' DELETE from `tabItem` where name = '{0}' UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' SELECT l3.name from `tabItem Series lavel 3` l3 join `tabItem Series lavel 2` l2 on l2.name = l3.level_3_item_code where l2.name = '{0}' UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' SELECT item.name from `tabItem` item join `tabItem Series lavel 3` l3 on l3.name = item.item_name where l3.name = '{0}' UPDATE `tabSeries` SET current = {0} WHERE name in {1} DELETE from `tabItem` where name in {0} UPDATE `tabSeries` SET current = {0} WHERE name = '{1}' DELETE from `tabItem` where name = '{0}'
| 2.112231
| 2
|
main.py
|
VimanyuAgg/Have_a_seat
| 0
|
6626313
|
<gh_stars>0
import pymongo
from pymongo import MongoClient
import flask
from flask import Flask,url_for , redirect, session ,flash,request
from flask import request
from flask import render_template
import bson.objectid
from bson.objectid import ObjectId
#import flask_login
import json
from functools import wraps
#from flask_login import LoginManager
import tweepy
from random import randint
import bcrypt
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import datetime
from time import gmtime, strftime
from twilio.rest import TwilioRestClient
# import sentimentalAnalysis
# from sentimentalAnalysis import analyseSentiments
import datetime
app= Flask(__name__)
con = MongoClient("mongodb://abcd:qwerty@ds111798.mlab.com:11798/have_a_seat")
db = con.have_a_seat
#list=[]
#dic={}
#login_manager=LoginManager()
#login_manager.init_app(app)
'''
r1= "This restaurant gives huge discounts at 9:00 pm...Love it!"
r2= "Awesome food, great service ! Book the seats when you find one..because you may not find it later"
r3= "I wish I could find more seats here... good good:("
r4= "Love the ambience inside !! Worth the money bad"
r5= "Quick and fast service--just go for it bad bad bad!"
r6= "Service is not good"
u1= "<NAME>"
u2= "<NAME>"
u3= "<NAME>"
u4= "<NAME>"
u5= "<NAME>"
u6= "<NAME>"
'''
# review_list=[r1,r2,r3,r4,r5,r6]
# user_list=[u1,u2,u3,u4,u5]
def get_api(cfg):
auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
return tweepy.API(auth)
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'email' in session:
return f(*args, **kwargs)
else:
flash("You need to login first")
return redirect(url_for('login'))
return wrap
@app.route('/', methods=['GET', 'POST'])
def Homepage():
if (request.method == "POST"):
restaurant_searched = request.form['search']
print restaurant_searched
restaurantList = db.Restaurants.find({"restName": restaurant_searched})
for restaurant in restaurantList:
list = str(restaurant['restName'])
link = "/" + restaurant_searched + "/checkSeats"
global dic
dic = {"Restaurant": [[list, link]]}
print dic
#return redirect(url_for('restaurantList'))
return render_template("index.html")
# @app.route('/hello/', methods=['POST'])
# def index():
# restaurant_searched = request.form['search']
# print restaurant_searched
#
@app.route('/getSeats', methods=['POST'])
def getSeats():
print " Hello I am in"
reqObj = request.get_json()
rid=int(reqObj['restaurantId'])
rObj = db.Restaurants.find_one({"_id": rid})
#'templateSeats':pizzaHutLayout - pizzaHutLayout
#'templateSeats':mcDonaldsLayout - mcDonaldsLayout
#'templateSeats':subwayLayout - subwayLayout
#'templateSeats':starbucksLayout - starbucksLayout
s_list = []
sObj = db.Tables.find({"Restid":rid})
for seat in sObj:
s_list.append({'sid':seat["TableNo"], 'status': seat['isAvailable']})
print s_list
layout=str(rObj["restName"] +'Layout')
print layout
return json.dumps({'id': rid, 'name': rObj["restName"], 'templateSeats': layout,'seats':s_list})
# return json.dumps({'id': 456, 'name': rObj["restName"], 'templateSeats':'subwayLayout','seats':[
# {'sid':101,'status':'available'},
# {'sid': 102, 'status': 'available'},
# {'sid': 103, 'status': 'booked'},
# {'sid': 104, 'status': 'available'},
# {'sid': 105, 'status': 'unavailable'},
# {'sid': 106, 'status': 'unavailable'},
# {'sid': 107, 'status': 'booked'},
# {'sid': 108, 'status': 'available'},
# {'sid': 109, 'status': 'booked'},
# {'sid': 110, 'status': 'unavailable'},
# {'sid': 111, 'status': 'unavailable'},
# {'sid': 112, 'status': 'available'},
# {'sid': 113, 'status': 'available'},
# {'sid': 114, 'status': 'unavailable'},
# {'sid': 115, 'status': 'available'},
# {'sid': 116, 'status': 'available'},
# ]})
# @app.route('/seatBooked', methods=['POST'])
# def SeatBooked():
# print "hellooooooo"
# seatSelected= request.get_json()
# print "hellooooooo"
# print seatSelected;
@app.route('/restaurants', methods=['POST'])
def restaurants():
#counter=0
print " Hello I am in Restaurents"
restaurant_searched = request.get_json()
restname=str(restaurant_searched['search'])
print restname
restname=restname.lower().replace(" ", "")
dic=[]
counter=0
listOfRestaurants= db.Restaurants.find({"restName":restname})
if listOfRestaurants.count()==0:
listOfRestaurants=db.Restaurants.find({"City": restname})
#global user_list
#global review_list
quotes = []
print listOfRestaurants.count()
for i in listOfRestaurants:
sObj = db.Tables.find({"Restid": i['_id']})
counter=0
for seat in sObj:
print seat['isAvailable']
if(seat['isAvailable']==0):
counter+=1
#quotes.append({"rname": user_list[randint(0, len(user_list) - 1)],
# "review": review_list[randint(0, len(review_list) - 1)]})
# for i in range(listOfRestaurants.count()):
# quotes_dict[user_list[randint(0,len(user_list)-1)]] = review_list[randint(0,len(review_list)-1)]
dic.append({"quotes": quotes,"Availability":counter, "name":str(i["restName"]), "address":str(i['Street']),"id":i['_id']})
#dic.append({"name": "Peanuts", "Street":"abc", "City": "nhb", "State":"CA"})
print dic
return json.dumps(dic)
#return render_template("index.html")
#restaurant_searched = request.get_json()
# print restaurant_searched
# restaurantList = db.Restaurants.find({"restName": str(restaurant_searched['search'])})
# for restaurant in restaurantList:
# list = str(restaurant['restName'])
# link = "/" + restaurant_searched + "/checkSeats"
# global dic
# dic = {"Restaurant": [[list, link]]}
#print restaurantList
# return json.dumps([{'id':123,'name':'aaa'},{'id':456,'name':'bbb'},{'id':789,'name':'ccc'}])
#
#
# @app.route('/searchRestaurants', methods=['POST'])
# def searchRestaurants():
# print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx'
# # print request.form['search']
# return json.dumps([{'id':123,'name':'aaa'},{'id':456,'name':'bbb'},{'id':789,'name':'ccc'}])
#
#
# # this is the home page which loads first
# @app.route('/', methods=['GET', 'POST'])
# def Homepage():
# if (request.method == "POST"):
# restaurant_searched = request.form['search']
# print restaurant_searched
# restaurantList = db.Restaurants.find({"restName":restaurant_searched})
# for restaurant in restaurantList:
# list = str(restaurant['restName'])
# link = "/" + restaurant_searched + "/checkSeats"
# global dic
# dic = {"Restaurant": [[list, link]]}
#
# #print dic
# return redirect(url_for('restaurantList'))
#
# return render_template("index.html")
#
#
#
# @app.route('/hello')
# def hello():
# return json.dumps({id:123,'name':'aaa','name':'bbb','name':'ccc'})
#
#
# # when user searches for restaurent this page gets loaded
# @app.route('/restaurantList/')
# def restaurantList():
# # restaurantList = Restaurants.find({"restName": restaurant_seached})
# # for restaurant in restaurantList:
# # list= str(restaurant['restName'])
# # link="/" + restaurant_seached + "/checkSeats"
# # dic={"Restaurant" : [[list, link]]}
# global dic
# #print dic
# # return render_template("restaurantList.html", dic = dic)
# return json.dump(dic)
#
# """
# @app.route('/dashboard/')
# def dashboard():
# return render_template('dashboard.html')"""
#
#
# @app.route('/<string:restaurant_name>/checkSeats')
# def checkSeats(restaurant_name):
# """user reaches here after selecting the restaurant name
# """
# #totalRestaurants = mongo.db.Restaurants
#
# #rest_cursor = mongo.db.Restaurants.find({"restName": "subway"})
#
# restID = db.Restaurants.find({"restName": restaurant_name},{"_id":1})
# print restID
# myrestID =0
# for i in restID:
# myrestID = i["_id"]
# print myrestID
# totaltables = db.Tables.find({"Restid": myrestID})
# tup = []
# for i in totaltables:
# if i["isAvailable"] == 0:
# i["isAvailable"] = "available"
#
# if i["isAvailable"] == 1:
# i["isAvailable"] = "booked"
#
# if i["isAvailable"] == 2:
# i["isAvailable"] = "unavailable"
# tup.append((i["isAvailable"]))
#
# #tup = tuple(tup)
# #print tup
# #total_counter = 0
# #Customer_booked_counter =0
# #Available_counter =0
# #Owner_booked_counter =0
# #availableTableNo = []
# #CustomerbookedTableNo = []
# #OwnerBookedTableNo = []
#
#
# #for i in totaltables:
# # if(i["isAvailable"]==0):
# # #Available_counter +=1
# # #availableTableNo.append(i["TableNo"])
# # elif(i["isAvailable"]==1):
# # Customer_booked_counter +=1
# # elif (i["isAvailable"] == 2):
# # Owner_booked_counter += 1
# # total_counter +=1
#
# """seat_details= "This Restaurant has "+ str(total_counter) + " seats of which "\
# + str(Available_counter)+" Available , " \
# + str(Customer_booked_counter) + " customer booked , " \
# + str(Owner_booked_counter) + " owner booked ."
# """
# #return 'Hello'
# return render_template("restaurant.html", seat_details=tup, restaurant_name=restaurant_name)
#
# @app.route('/seatBooked', methods = ['GET','POST'])
# def success():
# if (request.method == "POST"):
# table_updated = request.form['seatId']
# print table_updated
# return table_updated
#
# # this is the authenticate route
# @app.route('/register', methods=['GET','POST'])
# def Register():
# # print 'u have readched login'
# # print request.form.get('email')
# # print request.form.get('password')
# return render_template('register.html'), 200
#
# @app.route('/registerUser', methods=['POST'])
# def registerUser():
# print 'u have readched regitserter user'
# print request.form.get('email')
# print request.form.get('password')
# email = request.form.get('email')
# password = request.form.get('password')
#
# # restID = db.Users.insert_one({'email':email,'password':password})
# restID = db.Customers.update_one({'email':email},{'$set':{'password':password}},upsert=True)
# print restID
# print 'inserted'
# #print("you're logged in as:"+session['email'])
# return render_template("index.html")
#
@app.route('/signup', methods=['GET', 'POST'])
def signup():
print "I am inside"
if (request.method == "POST"):
cred = request.get_json()
print cred
obj = cred['cred']
print obj
firstname = obj['firstName']
lastName = obj['lastName']
emailid = obj['emailid']
password = obj['password']
checkIfExist=db.Customers.find_one({'Email':emailid})
if checkIfExist:
result= "Email already used"
return json.dumps({'result':result})
try:
hashpass=bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
print hashpass
db.Customers.insert_one({'customerName':firstname+" "+lastName,'Email': emailid, 'Password': <PASSWORD>})
print ("Inserted")
print "done"
except pymongo.errors.DuplicateKeyError:
print "In Except"
return "User Already Exists!!"
print({'customerName': firstname + " " + lastName, 'email': emailid, 'password': password})
return json.dumps({'customerName': firstname+" "+lastName, 'email': emailid, 'password': password})
@app.route('/login', methods=['GET','POST'])
def login():
error= None
if request.method == 'POST':
cred = request.get_json()
print cred
obj = cred['cred']
# print obj
username = obj['username']
password = obj['password']
print username
print password
login_user = db.Customers.find_one({'Email': username})
login_owner=db.Owners.find_one({'owner_email': username})
if login_user:
print (login_user['Password'])
print("user is here")
print login_user['Password']
#if(password == login_user['Password']):
if bcrypt.hashpw(password.encode('utf-8'),
login_user['Password'].encode('utf-8')) == login_user['Password'].encode('utf-8'):
print("password found")
session['Email'] = username
#return redirect(url_for('checkSeats', restaurant_name="subway"))
print ("I am here")
#return ("HII")
return json.dumps({'templateSeats':'pizzaHutLayout','login_type':'user','email': login_user['Email'], 'name': login_user['customerName']})
print("password NOT found")
error = "Invalid Passowrd. Please try again."
# return json.dumps({'email': username, 'name': login_user['customerName']})
#return render_template("LogIn.html", error=error)
elif login_owner:
print("owner is here")
print password.encode('utf-8')
# if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password'].encode('utf-8')) ==
# login_user['password'].encode('utf-8'):
#if bcrypt.hashpw(password.encode('utf-8'),
# login_owner['owner_password'].encode('utf-8')) == login_owner['owner_password'].encode('utf-8'):
#if(password == login_owner['owner_password']):
if (password == login_owner['owner_password']):
print "Owner has signed in"
ownerDetails = db.Owners.find_one({"owner_email": username})
session['Email'] = username
restaurantDetails=db.Restaurants.find_one({"_id": ownerDetails['Restid']})
restaurantName=restaurantDetails['restName']
return json.dumps({'templateSeats':'pizzaHutLayout','restid':ownerDetails['Restid'], 'login_type':'owner','email': login_owner['owner_email'], 'name': login_owner['owner_name']})
error = "Invalid Passowrd. Please try again."
#return redirect(url_for('checkOwnerSeats', restaurant_name=restaurantName))
else:
error="Invalid Username"
print ("Invalid user")
return json.dumps({'error': error})
@app.route('/isValidAdmin', methods=['POST'])
def isValidAdmin():
res = request.get_json() #request object is of form {'Restid': 123, 'tables': [{"sid": 1, "status":0},{"sid":2,"status":2}]}
print res
return json.dumps({'isValidAdmin':'true'})
@app.route('/seatsBooked', methods=['POST'])
def seatsBooked():
res = request.get_json() #request object is of form {'Restid': 123, 'tables': [{"sid": 1, "status":0},{"sid":2,"status":2}]}
restID = int(res['Restid'])
CustomerEmail = session['Email']
CustomerBooking = "No"
CustomerName = ""
CustomerPhone = ""
custObj = db.Customers.find_one({'Email':CustomerEmail})
if custObj:
CustomerBooking = "Yes"
if(CustomerBooking == 'Yes'):
CustomerName = custObj['customerName']
CustomerEmail = custObj['Email']
try:
CustomerPhone = custObj['customerPhone']
except:
print "No phone number"
print res
tables = (res['tables'])
print tables
session['Tables'] = tables
counter=0
slot = 0
bookedRest = db.Restaurants.find_one({"_id": restID})
dateTime = strftime("%Y-%m-%d %H:%M:%S")
date, time = dateTime.split(" ")
if time[0:time.index(':')] < 13:
slot = 0
elif time[0:time.index(':')] < 17:
slot = 1
elif time[0:time.index(':')] < 20:
slot = 2
else:
slot = 3
if(CustomerBooking == 'Yes'):
db.Bookings.insert({'customerName':CustomerName, 'customerEmail': CustomerEmail, 'customerPhone': CustomerPhone, 'Slot': slot})
for table in tables:
print int(table["sid"])
print "hello----->",int(table["status"])
db.Tables.update({"Restid": restID, "TableNo": int(table["sid"])},{'$set': {"isAvailable":int(table["status"])}}, upsert=False)
print "updated", table["sid"]
counter=counter+1
currentUser=db.Customers.find_one({'Email':session['Email']})
if counter>0 and currentUser:
emailCustomer(counter,bookedRest['restName'], bookedRest['City'], currentUser['Email'])
dict = {}
dict['status'] = "success" #just for returning something
return json.dumps(dict)
@app.route('/seatsBookedAdmin', methods=['POST'])
def seatsBookedAdmin():
res = request.get_json() #request object is of form {'Restid': 123, 'tables': [{"sid": 1, "status":0},{"sid":2,"status":2}]}
restID = int(res['Restid'])
print res
tables = (res['tables'])
print tables
session['Tables'] = tables
db.Tables.update({"Restid": restID, "TableNo": int(tables["sid"])},{'$set': {"isAvailable":int(tables["status"])}}, upsert=False)
# print "updated", table["sid"]
dict = {}
dict['status'] = "success" #just for returning something
return json.dumps(dict)
@app.route("/timerout")
def revertseats():
res = request.get_json() # request object is of form {'restid': 123} ---May or may not give the table numbers
tables = session['Tables'] # if table ids not given in request object
for table in tables:
db.Tables.update({"Restid": restID, "TableNo": table["sid"]}, {'$set': {"isAvailable": 0}},upsert=False)
print "reverted back", table["sid"]
dict = {}
dict['status'] = "success" #just for returning something
return json.dumps(dict)
@app.route('/<string:restaurant_name>/checkOwnerSeats')
@login_required
def checkOwnerSeats(restaurant_name):
print("you're logged in as:" + session['email'])
"""user reaches here after selecting the restaurant name
"""
#totalRestaurants = mongo.db.Restaurants
# #rest_cursor = mongo.db.Restaurants.find({"restName": "subway"})
restID = db.Restaurants.find({"restName": restaurant_name},{"_id":1})
print restID
myrestID =0
for i in restID:
myrestID = i["_id"]
print myrestID
totaltables = db.Tables.find({"Restid": myrestID})
tup = []
for i in totaltables:
if i["isAvailable"] == 0:
i["isAvailable"] = "available"
if i["isAvailable"] == 1:
i["isAvailable"] = "booked"
if i["isAvailable"] == 2:
i["isAvailable"] = "unavailable"
tup.append((i["isAvailable"]))
return render_template("restaurantOwner.html", seat_details=tup, restaurant_name=restaurant_name)
#
# # restaurantList = Restaurants.find({"restName": restaurant_seached})
# # for restaurant in restaurantList:
# # list= str(restaurant['restName'])
# # link="/" + restaurant_seached + "/checkSeats"
# # dic={"Restaurant" : [[list, link]]}
# #return render_template("Login.html", dic = dic)
#
# @app.route('/<string:restaurant_name>/checkOwnerSeats')
# def checkOwnerSeats(restaurant_name):
# print("you're logged in as:" + session['email'])
# """user reaches here after selecting the restaurant name
# """
# #totalRestaurants = mongo.db.Restaurants
# #rest_cursor = mongo.db.Restaurants.find({"restName": "subway"})
#
# restID = db.Restaurants.find({"restName": restaurant_name},{"_id":1})
# print restID
# myrestID =0
# for i in restID:
# myrestID = i["_id"]
# print myrestID
# totaltables = db.Tables.find({"Restid": myrestID})
# tup = []
# for i in totaltables:
# if i["isAvailable"] == 0:
# i["isAvailable"] = "available"
#
# if i["isAvailable"] == 1:
# i["isAvailable"] = "booked"
#
# if i["isAvailable"] == 2:
# i["isAvailable"] = "unavailable"
# tup.append((i["isAvailable"]))
# return render_template("restaurantOwner.html", seat_details=tup, restaurant_name=restaurant_name)
#
@app.route('/bookSeat',methods=['POST'])
@login_required
def bookseat_user():
print "Booking seats"
seats = request.get_json()
#Need RestaurantID/Name, seatsID,
#I will update the DB
@app.route('/loggedinUser', methods=['GET'])
def loggedinUser():
if 'Email' in session:
currentUserEmail=session['Email']
login_user = db.Customers.find_one({'Email': currentUserEmail})
login_owner = db.Owners.find_one({'owner_email': currentUserEmail})
if login_user:
return json.dumps({"Role":"Customer", "isValidAdmin":'False', "Email":login_user['Email'], "Name":login_user['customerName']})
if login_owner:
ownerDetails = db.Owners.find_one({"owner_email": currentUserEmail})
restaurantDetails = db.Restaurants.find_one({"_id": ownerDetails['Restid']})
restaurantName = restaurantDetails['restName']
return json.dumps({"Role":"Owner", "Restid":ownerDetails['Restid'], "isValidAdmin":'True', "Email":ownerDetails['owner_email'], "Name":ownerDetails["owner_name"]})
return json.dumps({"error":"no user loggedin"})
@app.route('/tweet', methods=['POST'])
def tweet():
# Fill in the values noted in previous step here
cfg = {
"consumer_key" : "<KEY>",
"consumer_secret" : "<KEY>",
"access_token" : "<KEY>",
"access_token_secret" : "<KEY>"
}
print("HI")
res = request.get_json()
restID = res["restid"]
restTweet = res["tweetmessage"]
print restTweet
print restID
restObj = db.Restaurants.find_one({'_id':int(restID)})
api = get_api(cfg)
tweet = "#"+restObj['restName'] + "says: "+restTweet
status = api.update_status(status=tweet)
dict = {"status":"success"}
return json.dumps(dict)
@app.route('/logout', methods=['GET', 'POST'])
#@login_required
def logout():
if 'Email' in session:
session.clear()
#print("you're logged in as:" + session['email'])
return 'Logged out'
return "noone is logged in"
def emailCustomer(counter, name, city, email):
sender ="<EMAIL>"
receiver = email
message = MIMEMultipart()
message['From'] = sender
message['To'] = receiver
message['Subject'] = "Seats Booked, Happy Dining!"
print("Please reach the restaurant within the next 15 minutes!")
body = "You have booked "+str(counter)+" seats(s) at " + " "+ name + ". Please reach the restaurant within the next 15 minutes"
message.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, "haveaseat")
server.sendmail(sender, receiver, message.as_string())
server.quit()
@app.route('/exploration',methods=['POST'])
def exploration():
print "Hello from Exploration"
data=request.get_json()
slot=data['Slot']
print slot
winner=db.Exploration.find_one({"Slot":slot})
currentOwner=db.Owners.find_one({"owner_email": session['Email']})
currentRestaurant=currentOwner['Restid']
print "1st" ,currentRestaurant
# print "2nd " ,currentRestaurant['restName']
emailWinner(winner['customerEmail'], "subway")
# return json.dumps({'Name':winner['customerEmail'], 'Email': winner['customerName']})
return json.dumps({'Name': winner['customerName'], 'Email': winner['customerEmail'],'PhoneNumber': "6692655123"})
@app.route('/exploitation', methods=['POST'])
def exploitation():
print "Hello from Exploitaion"
data=request.get_json()
slot=data['Slot']
winner= db.Exploitation.find_one({"Slot":slot})
currentOwner = db.Owners.find_one({"owner_email": session['Email']})
currentRestaurant = currentOwner['Restid']
emailWinner(winner['customerEmail'], "subway")
return json.dumps({'Name': winner['customerName'],'Email':winner['customerEmail'],'PhoneNumber': "6692657685"})
def emailWinner(email, restname):
sender ="<EMAIL>"
receiver = email
message = MIMEMultipart()
message['From'] = sender
message['To'] = email
message['Subject'] = "Exclusive Discounts For You at "+restname
print("Please reach the restaurant within the next 15 minutes!")
body = "Dine and get 25% discount at "+ restname +"! Offer valid for today"
message.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, "haveaseat")
server.sendmail(sender, receiver, message.as_string())
server.quit()
@app.route('/sendOffer', methods=['POST'])
def sendOffer():
print "I am in phone function"
data = request.get_json()
print data
print data['phoneNumber']
account_sid = "AC42a81cddc97b00c9f7e086deae7201e7"
auth_token = "<PASSWORD>"
client = TwilioRestClient(account_sid, auth_token)
client.messages.create(to="+1"+data['phoneNumber'],
from_="+14093163978",
body="Hello , you have been given 30% discount on your next visit to restaurant!")
print "success"
return json.dumps({'Message': "Offer Successfully Sent"})
@app.route('/setReview', methods=['POST'])
def setReview():
#datetime.datetime.now().strftime("%d/%m/%Y")
resp=request.get_json()
currentReview=resp['Review']
print currentReview
dateTime = strftime("%d/%m/%Y %H:%M:%S")
date = dateTime.split(" ")[0]
if 'Email' in session:
db.Reviews.insert({'customerEmail':session['Email'], 'restID':resp['restID'], 'customerReview':currentReview, "Date":date})
return json.dumps({'Message': "Your review was successfully posted"})
return json.dumps({'Message': "Please login to post review"})
@app.route('/getReviewAnalysis', methods=['POST'])
def getReviewAnalysis():
resp = request.get_json()
restID= resp['Restaurant']
#OwnerObj = db.Owners.find_one({'owner_email': session['Email']})
# restID = OwnerObj['Restid']
# print restID
reviewObj = db.Reviews.find({'restID': restID})
review_list = []
for r in reviewObj:
review_list.append(r['customerReview'])
print review_list
positive = 0
positivereview = []
negativereview = []
negative = 0
positive,positivereview, negative, negativereview = analyseSentiments(review_list)
dict = {}
dict['positive'] = int(positive)
dict['negative'] = int(negative)
dict['negativeReviewList'] = negativereview
dict['positiveReviewList'] = positivereview
print dict
return json.dumps(dict)
# resp=request.get_json()
# currentReview=resp['Review']
# db.Reviews.insert({'customerEmail':session['Email'], 'restID':resp['restID'], 'customerReview':currentReview})
@app.route('/emailHaveASeat',methods=['POST'])
def emailHaveASeat():
res = request.get_json()
restID = res["restid"]
restMessage = res["emailmessage"]
restDetails=db.Restaurants.find_one({"_id":int(restID)})
ownerDetails=db.Owners.find_one({'Restid':int(restID)})
ownerEmail=ownerDetails['owner_email']
#sender="<EMAIL>"
sender=ownerEmail
receiver = "<EMAIL>"
message = MIMEMultipart()
message['From'] = sender
message['To'] = receiver
message['Subject'] = "Email From "+restDetails['restName']
body=restMessage
print(body)
#body = "Dine and get 25% discount at "+ restname +"! Offer valid for today"
message.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, "testowner")
server.sendmail(sender, receiver, message.as_string())
server.quit()
dict={'message':"success"}
return json.dumps(dict)
if __name__ == "__main__": #main source running
app.secret_key= '<KEY>'
app.run(host="0.0.0.0", port=5017, debug=True)
|
import pymongo
from pymongo import MongoClient
import flask
from flask import Flask,url_for , redirect, session ,flash,request
from flask import request
from flask import render_template
import bson.objectid
from bson.objectid import ObjectId
#import flask_login
import json
from functools import wraps
#from flask_login import LoginManager
import tweepy
from random import randint
import bcrypt
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import datetime
from time import gmtime, strftime
from twilio.rest import TwilioRestClient
# import sentimentalAnalysis
# from sentimentalAnalysis import analyseSentiments
import datetime
app= Flask(__name__)
con = MongoClient("mongodb://abcd:qwerty@ds111798.mlab.com:11798/have_a_seat")
db = con.have_a_seat
#list=[]
#dic={}
#login_manager=LoginManager()
#login_manager.init_app(app)
'''
r1= "This restaurant gives huge discounts at 9:00 pm...Love it!"
r2= "Awesome food, great service ! Book the seats when you find one..because you may not find it later"
r3= "I wish I could find more seats here... good good:("
r4= "Love the ambience inside !! Worth the money bad"
r5= "Quick and fast service--just go for it bad bad bad!"
r6= "Service is not good"
u1= "<NAME>"
u2= "<NAME>"
u3= "<NAME>"
u4= "<NAME>"
u5= "<NAME>"
u6= "<NAME>"
'''
# review_list=[r1,r2,r3,r4,r5,r6]
# user_list=[u1,u2,u3,u4,u5]
def get_api(cfg):
auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
return tweepy.API(auth)
def login_required(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'email' in session:
return f(*args, **kwargs)
else:
flash("You need to login first")
return redirect(url_for('login'))
return wrap
@app.route('/', methods=['GET', 'POST'])
def Homepage():
if (request.method == "POST"):
restaurant_searched = request.form['search']
print restaurant_searched
restaurantList = db.Restaurants.find({"restName": restaurant_searched})
for restaurant in restaurantList:
list = str(restaurant['restName'])
link = "/" + restaurant_searched + "/checkSeats"
global dic
dic = {"Restaurant": [[list, link]]}
print dic
#return redirect(url_for('restaurantList'))
return render_template("index.html")
# @app.route('/hello/', methods=['POST'])
# def index():
# restaurant_searched = request.form['search']
# print restaurant_searched
#
@app.route('/getSeats', methods=['POST'])
def getSeats():
print " Hello I am in"
reqObj = request.get_json()
rid=int(reqObj['restaurantId'])
rObj = db.Restaurants.find_one({"_id": rid})
#'templateSeats':pizzaHutLayout - pizzaHutLayout
#'templateSeats':mcDonaldsLayout - mcDonaldsLayout
#'templateSeats':subwayLayout - subwayLayout
#'templateSeats':starbucksLayout - starbucksLayout
s_list = []
sObj = db.Tables.find({"Restid":rid})
for seat in sObj:
s_list.append({'sid':seat["TableNo"], 'status': seat['isAvailable']})
print s_list
layout=str(rObj["restName"] +'Layout')
print layout
return json.dumps({'id': rid, 'name': rObj["restName"], 'templateSeats': layout,'seats':s_list})
# return json.dumps({'id': 456, 'name': rObj["restName"], 'templateSeats':'subwayLayout','seats':[
# {'sid':101,'status':'available'},
# {'sid': 102, 'status': 'available'},
# {'sid': 103, 'status': 'booked'},
# {'sid': 104, 'status': 'available'},
# {'sid': 105, 'status': 'unavailable'},
# {'sid': 106, 'status': 'unavailable'},
# {'sid': 107, 'status': 'booked'},
# {'sid': 108, 'status': 'available'},
# {'sid': 109, 'status': 'booked'},
# {'sid': 110, 'status': 'unavailable'},
# {'sid': 111, 'status': 'unavailable'},
# {'sid': 112, 'status': 'available'},
# {'sid': 113, 'status': 'available'},
# {'sid': 114, 'status': 'unavailable'},
# {'sid': 115, 'status': 'available'},
# {'sid': 116, 'status': 'available'},
# ]})
# @app.route('/seatBooked', methods=['POST'])
# def SeatBooked():
# print "hellooooooo"
# seatSelected= request.get_json()
# print "hellooooooo"
# print seatSelected;
@app.route('/restaurants', methods=['POST'])
def restaurants():
#counter=0
print " Hello I am in Restaurents"
restaurant_searched = request.get_json()
restname=str(restaurant_searched['search'])
print restname
restname=restname.lower().replace(" ", "")
dic=[]
counter=0
listOfRestaurants= db.Restaurants.find({"restName":restname})
if listOfRestaurants.count()==0:
listOfRestaurants=db.Restaurants.find({"City": restname})
#global user_list
#global review_list
quotes = []
print listOfRestaurants.count()
for i in listOfRestaurants:
sObj = db.Tables.find({"Restid": i['_id']})
counter=0
for seat in sObj:
print seat['isAvailable']
if(seat['isAvailable']==0):
counter+=1
#quotes.append({"rname": user_list[randint(0, len(user_list) - 1)],
# "review": review_list[randint(0, len(review_list) - 1)]})
# for i in range(listOfRestaurants.count()):
# quotes_dict[user_list[randint(0,len(user_list)-1)]] = review_list[randint(0,len(review_list)-1)]
dic.append({"quotes": quotes,"Availability":counter, "name":str(i["restName"]), "address":str(i['Street']),"id":i['_id']})
#dic.append({"name": "Peanuts", "Street":"abc", "City": "nhb", "State":"CA"})
print dic
return json.dumps(dic)
#return render_template("index.html")
#restaurant_searched = request.get_json()
# print restaurant_searched
# restaurantList = db.Restaurants.find({"restName": str(restaurant_searched['search'])})
# for restaurant in restaurantList:
# list = str(restaurant['restName'])
# link = "/" + restaurant_searched + "/checkSeats"
# global dic
# dic = {"Restaurant": [[list, link]]}
#print restaurantList
# return json.dumps([{'id':123,'name':'aaa'},{'id':456,'name':'bbb'},{'id':789,'name':'ccc'}])
#
#
# @app.route('/searchRestaurants', methods=['POST'])
# def searchRestaurants():
# print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx'
# # print request.form['search']
# return json.dumps([{'id':123,'name':'aaa'},{'id':456,'name':'bbb'},{'id':789,'name':'ccc'}])
#
#
# # this is the home page which loads first
# @app.route('/', methods=['GET', 'POST'])
# def Homepage():
# if (request.method == "POST"):
# restaurant_searched = request.form['search']
# print restaurant_searched
# restaurantList = db.Restaurants.find({"restName":restaurant_searched})
# for restaurant in restaurantList:
# list = str(restaurant['restName'])
# link = "/" + restaurant_searched + "/checkSeats"
# global dic
# dic = {"Restaurant": [[list, link]]}
#
# #print dic
# return redirect(url_for('restaurantList'))
#
# return render_template("index.html")
#
#
#
# @app.route('/hello')
# def hello():
# return json.dumps({id:123,'name':'aaa','name':'bbb','name':'ccc'})
#
#
# # when user searches for restaurent this page gets loaded
# @app.route('/restaurantList/')
# def restaurantList():
# # restaurantList = Restaurants.find({"restName": restaurant_seached})
# # for restaurant in restaurantList:
# # list= str(restaurant['restName'])
# # link="/" + restaurant_seached + "/checkSeats"
# # dic={"Restaurant" : [[list, link]]}
# global dic
# #print dic
# # return render_template("restaurantList.html", dic = dic)
# return json.dump(dic)
#
# """
# @app.route('/dashboard/')
# def dashboard():
# return render_template('dashboard.html')"""
#
#
# @app.route('/<string:restaurant_name>/checkSeats')
# def checkSeats(restaurant_name):
# """user reaches here after selecting the restaurant name
# """
# #totalRestaurants = mongo.db.Restaurants
#
# #rest_cursor = mongo.db.Restaurants.find({"restName": "subway"})
#
# restID = db.Restaurants.find({"restName": restaurant_name},{"_id":1})
# print restID
# myrestID =0
# for i in restID:
# myrestID = i["_id"]
# print myrestID
# totaltables = db.Tables.find({"Restid": myrestID})
# tup = []
# for i in totaltables:
# if i["isAvailable"] == 0:
# i["isAvailable"] = "available"
#
# if i["isAvailable"] == 1:
# i["isAvailable"] = "booked"
#
# if i["isAvailable"] == 2:
# i["isAvailable"] = "unavailable"
# tup.append((i["isAvailable"]))
#
# #tup = tuple(tup)
# #print tup
# #total_counter = 0
# #Customer_booked_counter =0
# #Available_counter =0
# #Owner_booked_counter =0
# #availableTableNo = []
# #CustomerbookedTableNo = []
# #OwnerBookedTableNo = []
#
#
# #for i in totaltables:
# # if(i["isAvailable"]==0):
# # #Available_counter +=1
# # #availableTableNo.append(i["TableNo"])
# # elif(i["isAvailable"]==1):
# # Customer_booked_counter +=1
# # elif (i["isAvailable"] == 2):
# # Owner_booked_counter += 1
# # total_counter +=1
#
# """seat_details= "This Restaurant has "+ str(total_counter) + " seats of which "\
# + str(Available_counter)+" Available , " \
# + str(Customer_booked_counter) + " customer booked , " \
# + str(Owner_booked_counter) + " owner booked ."
# """
# #return 'Hello'
# return render_template("restaurant.html", seat_details=tup, restaurant_name=restaurant_name)
#
# @app.route('/seatBooked', methods = ['GET','POST'])
# def success():
# if (request.method == "POST"):
# table_updated = request.form['seatId']
# print table_updated
# return table_updated
#
# # this is the authenticate route
# @app.route('/register', methods=['GET','POST'])
# def Register():
# # print 'u have readched login'
# # print request.form.get('email')
# # print request.form.get('password')
# return render_template('register.html'), 200
#
# @app.route('/registerUser', methods=['POST'])
# def registerUser():
# print 'u have readched regitserter user'
# print request.form.get('email')
# print request.form.get('password')
# email = request.form.get('email')
# password = request.form.get('password')
#
# # restID = db.Users.insert_one({'email':email,'password':password})
# restID = db.Customers.update_one({'email':email},{'$set':{'password':password}},upsert=True)
# print restID
# print 'inserted'
# #print("you're logged in as:"+session['email'])
# return render_template("index.html")
#
@app.route('/signup', methods=['GET', 'POST'])
def signup():
print "I am inside"
if (request.method == "POST"):
cred = request.get_json()
print cred
obj = cred['cred']
print obj
firstname = obj['firstName']
lastName = obj['lastName']
emailid = obj['emailid']
password = obj['password']
checkIfExist=db.Customers.find_one({'Email':emailid})
if checkIfExist:
result= "Email already used"
return json.dumps({'result':result})
try:
hashpass=bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
print hashpass
db.Customers.insert_one({'customerName':firstname+" "+lastName,'Email': emailid, 'Password': <PASSWORD>})
print ("Inserted")
print "done"
except pymongo.errors.DuplicateKeyError:
print "In Except"
return "User Already Exists!!"
print({'customerName': firstname + " " + lastName, 'email': emailid, 'password': password})
return json.dumps({'customerName': firstname+" "+lastName, 'email': emailid, 'password': password})
@app.route('/login', methods=['GET','POST'])
def login():
error= None
if request.method == 'POST':
cred = request.get_json()
print cred
obj = cred['cred']
# print obj
username = obj['username']
password = obj['password']
print username
print password
login_user = db.Customers.find_one({'Email': username})
login_owner=db.Owners.find_one({'owner_email': username})
if login_user:
print (login_user['Password'])
print("user is here")
print login_user['Password']
#if(password == login_user['Password']):
if bcrypt.hashpw(password.encode('utf-8'),
login_user['Password'].encode('utf-8')) == login_user['Password'].encode('utf-8'):
print("password found")
session['Email'] = username
#return redirect(url_for('checkSeats', restaurant_name="subway"))
print ("I am here")
#return ("HII")
return json.dumps({'templateSeats':'pizzaHutLayout','login_type':'user','email': login_user['Email'], 'name': login_user['customerName']})
print("password NOT found")
error = "Invalid Passowrd. Please try again."
# return json.dumps({'email': username, 'name': login_user['customerName']})
#return render_template("LogIn.html", error=error)
elif login_owner:
print("owner is here")
print password.encode('utf-8')
# if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password'].encode('utf-8')) ==
# login_user['password'].encode('utf-8'):
#if bcrypt.hashpw(password.encode('utf-8'),
# login_owner['owner_password'].encode('utf-8')) == login_owner['owner_password'].encode('utf-8'):
#if(password == login_owner['owner_password']):
if (password == login_owner['owner_password']):
print "Owner has signed in"
ownerDetails = db.Owners.find_one({"owner_email": username})
session['Email'] = username
restaurantDetails=db.Restaurants.find_one({"_id": ownerDetails['Restid']})
restaurantName=restaurantDetails['restName']
return json.dumps({'templateSeats':'pizzaHutLayout','restid':ownerDetails['Restid'], 'login_type':'owner','email': login_owner['owner_email'], 'name': login_owner['owner_name']})
error = "Invalid Passowrd. Please try again."
#return redirect(url_for('checkOwnerSeats', restaurant_name=restaurantName))
else:
error="Invalid Username"
print ("Invalid user")
return json.dumps({'error': error})
@app.route('/isValidAdmin', methods=['POST'])
def isValidAdmin():
res = request.get_json() #request object is of form {'Restid': 123, 'tables': [{"sid": 1, "status":0},{"sid":2,"status":2}]}
print res
return json.dumps({'isValidAdmin':'true'})
@app.route('/seatsBooked', methods=['POST'])
def seatsBooked():
res = request.get_json() #request object is of form {'Restid': 123, 'tables': [{"sid": 1, "status":0},{"sid":2,"status":2}]}
restID = int(res['Restid'])
CustomerEmail = session['Email']
CustomerBooking = "No"
CustomerName = ""
CustomerPhone = ""
custObj = db.Customers.find_one({'Email':CustomerEmail})
if custObj:
CustomerBooking = "Yes"
if(CustomerBooking == 'Yes'):
CustomerName = custObj['customerName']
CustomerEmail = custObj['Email']
try:
CustomerPhone = custObj['customerPhone']
except:
print "No phone number"
print res
tables = (res['tables'])
print tables
session['Tables'] = tables
counter=0
slot = 0
bookedRest = db.Restaurants.find_one({"_id": restID})
dateTime = strftime("%Y-%m-%d %H:%M:%S")
date, time = dateTime.split(" ")
if time[0:time.index(':')] < 13:
slot = 0
elif time[0:time.index(':')] < 17:
slot = 1
elif time[0:time.index(':')] < 20:
slot = 2
else:
slot = 3
if(CustomerBooking == 'Yes'):
db.Bookings.insert({'customerName':CustomerName, 'customerEmail': CustomerEmail, 'customerPhone': CustomerPhone, 'Slot': slot})
for table in tables:
print int(table["sid"])
print "hello----->",int(table["status"])
db.Tables.update({"Restid": restID, "TableNo": int(table["sid"])},{'$set': {"isAvailable":int(table["status"])}}, upsert=False)
print "updated", table["sid"]
counter=counter+1
currentUser=db.Customers.find_one({'Email':session['Email']})
if counter>0 and currentUser:
emailCustomer(counter,bookedRest['restName'], bookedRest['City'], currentUser['Email'])
dict = {}
dict['status'] = "success" #just for returning something
return json.dumps(dict)
@app.route('/seatsBookedAdmin', methods=['POST'])
def seatsBookedAdmin():
res = request.get_json() #request object is of form {'Restid': 123, 'tables': [{"sid": 1, "status":0},{"sid":2,"status":2}]}
restID = int(res['Restid'])
print res
tables = (res['tables'])
print tables
session['Tables'] = tables
db.Tables.update({"Restid": restID, "TableNo": int(tables["sid"])},{'$set': {"isAvailable":int(tables["status"])}}, upsert=False)
# print "updated", table["sid"]
dict = {}
dict['status'] = "success" #just for returning something
return json.dumps(dict)
@app.route("/timerout")
def revertseats():
res = request.get_json() # request object is of form {'restid': 123} ---May or may not give the table numbers
tables = session['Tables'] # if table ids not given in request object
for table in tables:
db.Tables.update({"Restid": restID, "TableNo": table["sid"]}, {'$set': {"isAvailable": 0}},upsert=False)
print "reverted back", table["sid"]
dict = {}
dict['status'] = "success" #just for returning something
return json.dumps(dict)
@app.route('/<string:restaurant_name>/checkOwnerSeats')
@login_required
def checkOwnerSeats(restaurant_name):
print("you're logged in as:" + session['email'])
"""user reaches here after selecting the restaurant name
"""
#totalRestaurants = mongo.db.Restaurants
# #rest_cursor = mongo.db.Restaurants.find({"restName": "subway"})
restID = db.Restaurants.find({"restName": restaurant_name},{"_id":1})
print restID
myrestID =0
for i in restID:
myrestID = i["_id"]
print myrestID
totaltables = db.Tables.find({"Restid": myrestID})
tup = []
for i in totaltables:
if i["isAvailable"] == 0:
i["isAvailable"] = "available"
if i["isAvailable"] == 1:
i["isAvailable"] = "booked"
if i["isAvailable"] == 2:
i["isAvailable"] = "unavailable"
tup.append((i["isAvailable"]))
return render_template("restaurantOwner.html", seat_details=tup, restaurant_name=restaurant_name)
#
# # restaurantList = Restaurants.find({"restName": restaurant_seached})
# # for restaurant in restaurantList:
# # list= str(restaurant['restName'])
# # link="/" + restaurant_seached + "/checkSeats"
# # dic={"Restaurant" : [[list, link]]}
# #return render_template("Login.html", dic = dic)
#
# @app.route('/<string:restaurant_name>/checkOwnerSeats')
# def checkOwnerSeats(restaurant_name):
# print("you're logged in as:" + session['email'])
# """user reaches here after selecting the restaurant name
# """
# #totalRestaurants = mongo.db.Restaurants
# #rest_cursor = mongo.db.Restaurants.find({"restName": "subway"})
#
# restID = db.Restaurants.find({"restName": restaurant_name},{"_id":1})
# print restID
# myrestID =0
# for i in restID:
# myrestID = i["_id"]
# print myrestID
# totaltables = db.Tables.find({"Restid": myrestID})
# tup = []
# for i in totaltables:
# if i["isAvailable"] == 0:
# i["isAvailable"] = "available"
#
# if i["isAvailable"] == 1:
# i["isAvailable"] = "booked"
#
# if i["isAvailable"] == 2:
# i["isAvailable"] = "unavailable"
# tup.append((i["isAvailable"]))
# return render_template("restaurantOwner.html", seat_details=tup, restaurant_name=restaurant_name)
#
@app.route('/bookSeat',methods=['POST'])
@login_required
def bookseat_user():
print "Booking seats"
seats = request.get_json()
#Need RestaurantID/Name, seatsID,
#I will update the DB
@app.route('/loggedinUser', methods=['GET'])
def loggedinUser():
if 'Email' in session:
currentUserEmail=session['Email']
login_user = db.Customers.find_one({'Email': currentUserEmail})
login_owner = db.Owners.find_one({'owner_email': currentUserEmail})
if login_user:
return json.dumps({"Role":"Customer", "isValidAdmin":'False', "Email":login_user['Email'], "Name":login_user['customerName']})
if login_owner:
ownerDetails = db.Owners.find_one({"owner_email": currentUserEmail})
restaurantDetails = db.Restaurants.find_one({"_id": ownerDetails['Restid']})
restaurantName = restaurantDetails['restName']
return json.dumps({"Role":"Owner", "Restid":ownerDetails['Restid'], "isValidAdmin":'True', "Email":ownerDetails['owner_email'], "Name":ownerDetails["owner_name"]})
return json.dumps({"error":"no user loggedin"})
@app.route('/tweet', methods=['POST'])
def tweet():
# Fill in the values noted in previous step here
cfg = {
"consumer_key" : "<KEY>",
"consumer_secret" : "<KEY>",
"access_token" : "<KEY>",
"access_token_secret" : "<KEY>"
}
print("HI")
res = request.get_json()
restID = res["restid"]
restTweet = res["tweetmessage"]
print restTweet
print restID
restObj = db.Restaurants.find_one({'_id':int(restID)})
api = get_api(cfg)
tweet = "#"+restObj['restName'] + "says: "+restTweet
status = api.update_status(status=tweet)
dict = {"status":"success"}
return json.dumps(dict)
@app.route('/logout', methods=['GET', 'POST'])
#@login_required
def logout():
if 'Email' in session:
session.clear()
#print("you're logged in as:" + session['email'])
return 'Logged out'
return "noone is logged in"
def emailCustomer(counter, name, city, email):
sender ="<EMAIL>"
receiver = email
message = MIMEMultipart()
message['From'] = sender
message['To'] = receiver
message['Subject'] = "Seats Booked, Happy Dining!"
print("Please reach the restaurant within the next 15 minutes!")
body = "You have booked "+str(counter)+" seats(s) at " + " "+ name + ". Please reach the restaurant within the next 15 minutes"
message.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, "haveaseat")
server.sendmail(sender, receiver, message.as_string())
server.quit()
@app.route('/exploration',methods=['POST'])
def exploration():
print "Hello from Exploration"
data=request.get_json()
slot=data['Slot']
print slot
winner=db.Exploration.find_one({"Slot":slot})
currentOwner=db.Owners.find_one({"owner_email": session['Email']})
currentRestaurant=currentOwner['Restid']
print "1st" ,currentRestaurant
# print "2nd " ,currentRestaurant['restName']
emailWinner(winner['customerEmail'], "subway")
# return json.dumps({'Name':winner['customerEmail'], 'Email': winner['customerName']})
return json.dumps({'Name': winner['customerName'], 'Email': winner['customerEmail'],'PhoneNumber': "6692655123"})
@app.route('/exploitation', methods=['POST'])
def exploitation():
print "Hello from Exploitaion"
data=request.get_json()
slot=data['Slot']
winner= db.Exploitation.find_one({"Slot":slot})
currentOwner = db.Owners.find_one({"owner_email": session['Email']})
currentRestaurant = currentOwner['Restid']
emailWinner(winner['customerEmail'], "subway")
return json.dumps({'Name': winner['customerName'],'Email':winner['customerEmail'],'PhoneNumber': "6692657685"})
def emailWinner(email, restname):
sender ="<EMAIL>"
receiver = email
message = MIMEMultipart()
message['From'] = sender
message['To'] = email
message['Subject'] = "Exclusive Discounts For You at "+restname
print("Please reach the restaurant within the next 15 minutes!")
body = "Dine and get 25% discount at "+ restname +"! Offer valid for today"
message.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, "haveaseat")
server.sendmail(sender, receiver, message.as_string())
server.quit()
@app.route('/sendOffer', methods=['POST'])
def sendOffer():
print "I am in phone function"
data = request.get_json()
print data
print data['phoneNumber']
account_sid = "AC42a81cddc97b00c9f7e086deae7201e7"
auth_token = "<PASSWORD>"
client = TwilioRestClient(account_sid, auth_token)
client.messages.create(to="+1"+data['phoneNumber'],
from_="+14093163978",
body="Hello , you have been given 30% discount on your next visit to restaurant!")
print "success"
return json.dumps({'Message': "Offer Successfully Sent"})
@app.route('/setReview', methods=['POST'])
def setReview():
#datetime.datetime.now().strftime("%d/%m/%Y")
resp=request.get_json()
currentReview=resp['Review']
print currentReview
dateTime = strftime("%d/%m/%Y %H:%M:%S")
date = dateTime.split(" ")[0]
if 'Email' in session:
db.Reviews.insert({'customerEmail':session['Email'], 'restID':resp['restID'], 'customerReview':currentReview, "Date":date})
return json.dumps({'Message': "Your review was successfully posted"})
return json.dumps({'Message': "Please login to post review"})
@app.route('/getReviewAnalysis', methods=['POST'])
def getReviewAnalysis():
resp = request.get_json()
restID= resp['Restaurant']
#OwnerObj = db.Owners.find_one({'owner_email': session['Email']})
# restID = OwnerObj['Restid']
# print restID
reviewObj = db.Reviews.find({'restID': restID})
review_list = []
for r in reviewObj:
review_list.append(r['customerReview'])
print review_list
positive = 0
positivereview = []
negativereview = []
negative = 0
positive,positivereview, negative, negativereview = analyseSentiments(review_list)
dict = {}
dict['positive'] = int(positive)
dict['negative'] = int(negative)
dict['negativeReviewList'] = negativereview
dict['positiveReviewList'] = positivereview
print dict
return json.dumps(dict)
# resp=request.get_json()
# currentReview=resp['Review']
# db.Reviews.insert({'customerEmail':session['Email'], 'restID':resp['restID'], 'customerReview':currentReview})
@app.route('/emailHaveASeat',methods=['POST'])
def emailHaveASeat():
res = request.get_json()
restID = res["restid"]
restMessage = res["emailmessage"]
restDetails=db.Restaurants.find_one({"_id":int(restID)})
ownerDetails=db.Owners.find_one({'Restid':int(restID)})
ownerEmail=ownerDetails['owner_email']
#sender="<EMAIL>"
sender=ownerEmail
receiver = "<EMAIL>"
message = MIMEMultipart()
message['From'] = sender
message['To'] = receiver
message['Subject'] = "Email From "+restDetails['restName']
body=restMessage
print(body)
#body = "Dine and get 25% discount at "+ restname +"! Offer valid for today"
message.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(sender, "testowner")
server.sendmail(sender, receiver, message.as_string())
server.quit()
dict={'message':"success"}
return json.dumps(dict)
if __name__ == "__main__": #main source running
app.secret_key= '<KEY>'
app.run(host="0.0.0.0", port=5017, debug=True)
|
en
| 0.416178
|
#import flask_login #from flask_login import LoginManager # import sentimentalAnalysis # from sentimentalAnalysis import analyseSentiments #list=[] #dic={} #login_manager=LoginManager() #login_manager.init_app(app) r1= "This restaurant gives huge discounts at 9:00 pm...Love it!" r2= "Awesome food, great service ! Book the seats when you find one..because you may not find it later" r3= "I wish I could find more seats here... good good:(" r4= "Love the ambience inside !! Worth the money bad" r5= "Quick and fast service--just go for it bad bad bad!" r6= "Service is not good" u1= "<NAME>" u2= "<NAME>" u3= "<NAME>" u4= "<NAME>" u5= "<NAME>" u6= "<NAME>" # review_list=[r1,r2,r3,r4,r5,r6] # user_list=[u1,u2,u3,u4,u5] #return redirect(url_for('restaurantList')) # @app.route('/hello/', methods=['POST']) # def index(): # restaurant_searched = request.form['search'] # print restaurant_searched # #'templateSeats':pizzaHutLayout - pizzaHutLayout #'templateSeats':mcDonaldsLayout - mcDonaldsLayout #'templateSeats':subwayLayout - subwayLayout #'templateSeats':starbucksLayout - starbucksLayout # return json.dumps({'id': 456, 'name': rObj["restName"], 'templateSeats':'subwayLayout','seats':[ # {'sid':101,'status':'available'}, # {'sid': 102, 'status': 'available'}, # {'sid': 103, 'status': 'booked'}, # {'sid': 104, 'status': 'available'}, # {'sid': 105, 'status': 'unavailable'}, # {'sid': 106, 'status': 'unavailable'}, # {'sid': 107, 'status': 'booked'}, # {'sid': 108, 'status': 'available'}, # {'sid': 109, 'status': 'booked'}, # {'sid': 110, 'status': 'unavailable'}, # {'sid': 111, 'status': 'unavailable'}, # {'sid': 112, 'status': 'available'}, # {'sid': 113, 'status': 'available'}, # {'sid': 114, 'status': 'unavailable'}, # {'sid': 115, 'status': 'available'}, # {'sid': 116, 'status': 'available'}, # ]}) # @app.route('/seatBooked', methods=['POST']) # def SeatBooked(): # print "hellooooooo" # seatSelected= request.get_json() # print "hellooooooo" # print seatSelected; #counter=0 #global user_list #global review_list #quotes.append({"rname": user_list[randint(0, len(user_list) - 1)], # "review": review_list[randint(0, len(review_list) - 1)]}) # for i in range(listOfRestaurants.count()): # quotes_dict[user_list[randint(0,len(user_list)-1)]] = review_list[randint(0,len(review_list)-1)] #dic.append({"name": "Peanuts", "Street":"abc", "City": "nhb", "State":"CA"}) #return render_template("index.html") #restaurant_searched = request.get_json() # print restaurant_searched # restaurantList = db.Restaurants.find({"restName": str(restaurant_searched['search'])}) # for restaurant in restaurantList: # list = str(restaurant['restName']) # link = "/" + restaurant_searched + "/checkSeats" # global dic # dic = {"Restaurant": [[list, link]]} #print restaurantList # return json.dumps([{'id':123,'name':'aaa'},{'id':456,'name':'bbb'},{'id':789,'name':'ccc'}]) # # # @app.route('/searchRestaurants', methods=['POST']) # def searchRestaurants(): # print 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx' # # print request.form['search'] # return json.dumps([{'id':123,'name':'aaa'},{'id':456,'name':'bbb'},{'id':789,'name':'ccc'}]) # # # # this is the home page which loads first # @app.route('/', methods=['GET', 'POST']) # def Homepage(): # if (request.method == "POST"): # restaurant_searched = request.form['search'] # print restaurant_searched # restaurantList = db.Restaurants.find({"restName":restaurant_searched}) # for restaurant in restaurantList: # list = str(restaurant['restName']) # link = "/" + restaurant_searched + "/checkSeats" # global dic # dic = {"Restaurant": [[list, link]]} # # #print dic # return redirect(url_for('restaurantList')) # # return render_template("index.html") # # # # @app.route('/hello') # def hello(): # return json.dumps({id:123,'name':'aaa','name':'bbb','name':'ccc'}) # # # # when user searches for restaurent this page gets loaded # @app.route('/restaurantList/') # def restaurantList(): # # restaurantList = Restaurants.find({"restName": restaurant_seached}) # # for restaurant in restaurantList: # # list= str(restaurant['restName']) # # link="/" + restaurant_seached + "/checkSeats" # # dic={"Restaurant" : [[list, link]]} # global dic # #print dic # # return render_template("restaurantList.html", dic = dic) # return json.dump(dic) # # """ # @app.route('/dashboard/') # def dashboard(): # return render_template('dashboard.html')""" # # # @app.route('/<string:restaurant_name>/checkSeats') # def checkSeats(restaurant_name): # """user reaches here after selecting the restaurant name # """ # #totalRestaurants = mongo.db.Restaurants # # #rest_cursor = mongo.db.Restaurants.find({"restName": "subway"}) # # restID = db.Restaurants.find({"restName": restaurant_name},{"_id":1}) # print restID # myrestID =0 # for i in restID: # myrestID = i["_id"] # print myrestID # totaltables = db.Tables.find({"Restid": myrestID}) # tup = [] # for i in totaltables: # if i["isAvailable"] == 0: # i["isAvailable"] = "available" # # if i["isAvailable"] == 1: # i["isAvailable"] = "booked" # # if i["isAvailable"] == 2: # i["isAvailable"] = "unavailable" # tup.append((i["isAvailable"])) # # #tup = tuple(tup) # #print tup # #total_counter = 0 # #Customer_booked_counter =0 # #Available_counter =0 # #Owner_booked_counter =0 # #availableTableNo = [] # #CustomerbookedTableNo = [] # #OwnerBookedTableNo = [] # # # #for i in totaltables: # # if(i["isAvailable"]==0): # # #Available_counter +=1 # # #availableTableNo.append(i["TableNo"]) # # elif(i["isAvailable"]==1): # # Customer_booked_counter +=1 # # elif (i["isAvailable"] == 2): # # Owner_booked_counter += 1 # # total_counter +=1 # # """seat_details= "This Restaurant has "+ str(total_counter) + " seats of which "\ # + str(Available_counter)+" Available , " \ # + str(Customer_booked_counter) + " customer booked , " \ # + str(Owner_booked_counter) + " owner booked ." # """ # #return 'Hello' # return render_template("restaurant.html", seat_details=tup, restaurant_name=restaurant_name) # # @app.route('/seatBooked', methods = ['GET','POST']) # def success(): # if (request.method == "POST"): # table_updated = request.form['seatId'] # print table_updated # return table_updated # # # this is the authenticate route # @app.route('/register', methods=['GET','POST']) # def Register(): # # print 'u have readched login' # # print request.form.get('email') # # print request.form.get('password') # return render_template('register.html'), 200 # # @app.route('/registerUser', methods=['POST']) # def registerUser(): # print 'u have readched regitserter user' # print request.form.get('email') # print request.form.get('password') # email = request.form.get('email') # password = request.form.get('password') # # # restID = db.Users.insert_one({'email':email,'password':password}) # restID = db.Customers.update_one({'email':email},{'$set':{'password':password}},upsert=True) # print restID # print 'inserted' # #print("you're logged in as:"+session['email']) # return render_template("index.html") # # print obj #if(password == login_user['Password']): #return redirect(url_for('checkSeats', restaurant_name="subway")) #return ("HII") # return json.dumps({'email': username, 'name': login_user['customerName']}) #return render_template("LogIn.html", error=error) # if bcrypt.hashpw(request.form['pass'].encode('utf-8'), login_user['password'].encode('utf-8')) == # login_user['password'].encode('utf-8'): #if bcrypt.hashpw(password.encode('utf-8'), # login_owner['owner_password'].encode('utf-8')) == login_owner['owner_password'].encode('utf-8'): #if(password == login_owner['owner_password']): #return redirect(url_for('checkOwnerSeats', restaurant_name=restaurantName)) #request object is of form {'Restid': 123, 'tables': [{"sid": 1, "status":0},{"sid":2,"status":2}]} #request object is of form {'Restid': 123, 'tables': [{"sid": 1, "status":0},{"sid":2,"status":2}]} #just for returning something #request object is of form {'Restid': 123, 'tables': [{"sid": 1, "status":0},{"sid":2,"status":2}]} # print "updated", table["sid"] #just for returning something # request object is of form {'restid': 123} ---May or may not give the table numbers # if table ids not given in request object #just for returning something user reaches here after selecting the restaurant name #totalRestaurants = mongo.db.Restaurants # #rest_cursor = mongo.db.Restaurants.find({"restName": "subway"}) # # # restaurantList = Restaurants.find({"restName": restaurant_seached}) # # for restaurant in restaurantList: # # list= str(restaurant['restName']) # # link="/" + restaurant_seached + "/checkSeats" # # dic={"Restaurant" : [[list, link]]} # #return render_template("Login.html", dic = dic) # # @app.route('/<string:restaurant_name>/checkOwnerSeats') # def checkOwnerSeats(restaurant_name): # print("you're logged in as:" + session['email']) # """user reaches here after selecting the restaurant name # """ # #totalRestaurants = mongo.db.Restaurants # #rest_cursor = mongo.db.Restaurants.find({"restName": "subway"}) # # restID = db.Restaurants.find({"restName": restaurant_name},{"_id":1}) # print restID # myrestID =0 # for i in restID: # myrestID = i["_id"] # print myrestID # totaltables = db.Tables.find({"Restid": myrestID}) # tup = [] # for i in totaltables: # if i["isAvailable"] == 0: # i["isAvailable"] = "available" # # if i["isAvailable"] == 1: # i["isAvailable"] = "booked" # # if i["isAvailable"] == 2: # i["isAvailable"] = "unavailable" # tup.append((i["isAvailable"])) # return render_template("restaurantOwner.html", seat_details=tup, restaurant_name=restaurant_name) # #Need RestaurantID/Name, seatsID, #I will update the DB # Fill in the values noted in previous step here #@login_required #print("you're logged in as:" + session['email']) # print "2nd " ,currentRestaurant['restName'] # return json.dumps({'Name':winner['customerEmail'], 'Email': winner['customerName']}) #datetime.datetime.now().strftime("%d/%m/%Y") #OwnerObj = db.Owners.find_one({'owner_email': session['Email']}) # restID = OwnerObj['Restid'] # print restID # resp=request.get_json() # currentReview=resp['Review'] # db.Reviews.insert({'customerEmail':session['Email'], 'restID':resp['restID'], 'customerReview':currentReview}) #sender="<EMAIL>" #body = "Dine and get 25% discount at "+ restname +"! Offer valid for today" #main source running
| 2.470136
| 2
|
Cats and Dogs with Image Augmentation Parameters.py
|
seanjudelyons/TensorFLow_Certificate
| 4
|
6626314
|
<reponame>seanjudelyons/TensorFLow_Certificate<filename>Cats and Dogs with Image Augmentation Parameters.py<gh_stars>1-10
#We will also try image augmentation in this
import os
import zipfile
import random
import tensorflow as tf
import shutil
import numpy as np
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from shutil import copyfile
from os import getcwd
CAT_SOURCE_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/PetImages/Cat/')
TRAINING_CATS_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/cats-v-dogs/training/dogs/')
TESTING_CATS_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/cats-v-dogs/testing/dogs/')
DOG_SOURCE_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/PetImages/Dog/')
TRAINING_DOGS_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/cats-v-dogs/training/dogs/')
TESTING_DOGS_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/cats-v-dogs/testing/dogs/')
def split_data(SOURCE, TRAINING, TESTING, SPLIT_SIZE):
files = []
for filename in os.listdir(SOURCE):
file = SOURCE + filename
if os.path.getsize(file) > 0:
files.append(filename)
else:
print(filename + " is zero length, so ignoring.")
training_length = int(len(files) * SPLIT_SIZE)
testing_length = int(len(files) - training_length)
shuffled_data = random.sample(files, len(files))
training_data = shuffled_data[0:training_length]
testing_data = shuffled_data[-testing_length:]
for fn in training_data:
datasource = SOURCE + fn
destination = os.path.join(TRAINING + fn)
copyfile(datasource, destination)
for fn1 in testing_data:
datasourece1 = SOURCE + fn1
destination1 = os.path.join(TESTING + fn1)
copyfile(datasourece1, destination1)
split_size = .9
split_data(CAT_SOURCE_DIR, TRAINING_CATS_DIR, TESTING_CATS_DIR, split_size)
split_data(DOG_SOURCE_DIR, TRAINING_DOGS_DIR, TESTING_DOGS_DIR, split_size)
print(len(os.listdir(TRAINING_CATS_DIR)))
print(len(os.listdir(TRAINING_DOGS_DIR)))
print(len(os.listdir(TESTING_CATS_DIR)))
print(len(os.listdir(TESTING_DOGS_DIR)))
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
model = tf.keras.models.Sequential([
Conv2D(16, (3,3), activation='relu', input_shape=(150,150,3)),
MaxPooling2D(2,2),
Conv2D(32, (3,3), activation='relu'),
MaxPooling2D(2,2),
Conv2D(64, (3,3), activation='relu'),
MaxPooling2D(2,2),
Conv2D(128, (3,3), activation='relu'),
MaxPooling2D(2,2),
Flatten(),
Dense(128, activation='relu'),
Dense(1, activation='sigmoid')
])
model.compile(optimizer=RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['acc'])
TRAINING_DIR = "/Users/seanjudelyons/Downloads/Find/cats-v-dogs/training/"
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
# NOTE: YOU MUST USE A BATCH SIZE OF 10 (batch_size=10) FOR THE
# TRAIN GENERATOR.
train_generator = train_datagen.flow_from_directory(TRAINING_DIR, target_size=(150, 150), batch_size=10, class_mode='binary')
VALIDATION_DIR = "/Users/seanjudelyons/Downloads/Find/cats-v-dogs/testing/"
validation_datagen = ImageDataGenerator(rescale=1/255.)
# NOTE: YOU MUST USE A BACTH SIZE OF 10 (batch_size=10) FOR THE
# VALIDATION GENERATOR.
validation_generator = validation_datagen.flow_from_directory(VALIDATION_DIR, target_size=(150, 150), batch_size=10,class_mode='binary')
# Expected Output:
# Found 2700 images belonging to 2 classes.
# Found 300 images belonging to 2 classes.
history = model.fit_generator(train_generator,
epochs=2,
verbose=1,
validation_data=validation_generator)
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
#-----------------------------------------------------------
# Retrieve a list of list results on training and test data
# sets for each training epoch
#-----------------------------------------------------------
acc=history.history['acc']
val_acc=history.history['val_acc']
loss=history.history['loss']
val_loss=history.history['val_loss']
epochs=range(len(acc)) # Get number of epochs
#------------------------------------------------
# Plot training and validation accuracy per epoch
#------------------------------------------------
plt.plot(epochs, acc, 'r', "Training Accuracy")
plt.plot(epochs, val_acc, 'b', "Validation Accuracy")
plt.title('Training and validation accuracy')
plt.figure()
#------------------------------------------------
# Plot training and validation loss per epoch
#------------------------------------------------
plt.plot(epochs, loss, 'r', "Training Loss")
plt.plot(epochs, val_loss, 'b', "Validation Loss")
plt.title('Training and validation loss')
# Desired output. Charts with training and validation metrics. No crash :)
|
and Dogs with Image Augmentation Parameters.py<gh_stars>1-10
#We will also try image augmentation in this
import os
import zipfile
import random
import tensorflow as tf
import shutil
import numpy as np
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from shutil import copyfile
from os import getcwd
CAT_SOURCE_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/PetImages/Cat/')
TRAINING_CATS_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/cats-v-dogs/training/dogs/')
TESTING_CATS_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/cats-v-dogs/testing/dogs/')
DOG_SOURCE_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/PetImages/Dog/')
TRAINING_DOGS_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/cats-v-dogs/training/dogs/')
TESTING_DOGS_DIR = os.path.join('/Users/seanjudelyons/Downloads/Find/cats-v-dogs/testing/dogs/')
def split_data(SOURCE, TRAINING, TESTING, SPLIT_SIZE):
files = []
for filename in os.listdir(SOURCE):
file = SOURCE + filename
if os.path.getsize(file) > 0:
files.append(filename)
else:
print(filename + " is zero length, so ignoring.")
training_length = int(len(files) * SPLIT_SIZE)
testing_length = int(len(files) - training_length)
shuffled_data = random.sample(files, len(files))
training_data = shuffled_data[0:training_length]
testing_data = shuffled_data[-testing_length:]
for fn in training_data:
datasource = SOURCE + fn
destination = os.path.join(TRAINING + fn)
copyfile(datasource, destination)
for fn1 in testing_data:
datasourece1 = SOURCE + fn1
destination1 = os.path.join(TESTING + fn1)
copyfile(datasourece1, destination1)
split_size = .9
split_data(CAT_SOURCE_DIR, TRAINING_CATS_DIR, TESTING_CATS_DIR, split_size)
split_data(DOG_SOURCE_DIR, TRAINING_DOGS_DIR, TESTING_DOGS_DIR, split_size)
print(len(os.listdir(TRAINING_CATS_DIR)))
print(len(os.listdir(TRAINING_DOGS_DIR)))
print(len(os.listdir(TESTING_CATS_DIR)))
print(len(os.listdir(TESTING_DOGS_DIR)))
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
model = tf.keras.models.Sequential([
Conv2D(16, (3,3), activation='relu', input_shape=(150,150,3)),
MaxPooling2D(2,2),
Conv2D(32, (3,3), activation='relu'),
MaxPooling2D(2,2),
Conv2D(64, (3,3), activation='relu'),
MaxPooling2D(2,2),
Conv2D(128, (3,3), activation='relu'),
MaxPooling2D(2,2),
Flatten(),
Dense(128, activation='relu'),
Dense(1, activation='sigmoid')
])
model.compile(optimizer=RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['acc'])
TRAINING_DIR = "/Users/seanjudelyons/Downloads/Find/cats-v-dogs/training/"
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest')
# NOTE: YOU MUST USE A BATCH SIZE OF 10 (batch_size=10) FOR THE
# TRAIN GENERATOR.
train_generator = train_datagen.flow_from_directory(TRAINING_DIR, target_size=(150, 150), batch_size=10, class_mode='binary')
VALIDATION_DIR = "/Users/seanjudelyons/Downloads/Find/cats-v-dogs/testing/"
validation_datagen = ImageDataGenerator(rescale=1/255.)
# NOTE: YOU MUST USE A BACTH SIZE OF 10 (batch_size=10) FOR THE
# VALIDATION GENERATOR.
validation_generator = validation_datagen.flow_from_directory(VALIDATION_DIR, target_size=(150, 150), batch_size=10,class_mode='binary')
# Expected Output:
# Found 2700 images belonging to 2 classes.
# Found 300 images belonging to 2 classes.
history = model.fit_generator(train_generator,
epochs=2,
verbose=1,
validation_data=validation_generator)
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
#-----------------------------------------------------------
# Retrieve a list of list results on training and test data
# sets for each training epoch
#-----------------------------------------------------------
acc=history.history['acc']
val_acc=history.history['val_acc']
loss=history.history['loss']
val_loss=history.history['val_loss']
epochs=range(len(acc)) # Get number of epochs
#------------------------------------------------
# Plot training and validation accuracy per epoch
#------------------------------------------------
plt.plot(epochs, acc, 'r', "Training Accuracy")
plt.plot(epochs, val_acc, 'b', "Validation Accuracy")
plt.title('Training and validation accuracy')
plt.figure()
#------------------------------------------------
# Plot training and validation loss per epoch
#------------------------------------------------
plt.plot(epochs, loss, 'r', "Training Loss")
plt.plot(epochs, val_loss, 'b', "Validation Loss")
plt.title('Training and validation loss')
# Desired output. Charts with training and validation metrics. No crash :)
|
en
| 0.434898
|
#We will also try image augmentation in this # NOTE: YOU MUST USE A BATCH SIZE OF 10 (batch_size=10) FOR THE # TRAIN GENERATOR. # NOTE: YOU MUST USE A BACTH SIZE OF 10 (batch_size=10) FOR THE # VALIDATION GENERATOR. # Expected Output: # Found 2700 images belonging to 2 classes. # Found 300 images belonging to 2 classes. #----------------------------------------------------------- # Retrieve a list of list results on training and test data # sets for each training epoch #----------------------------------------------------------- # Get number of epochs #------------------------------------------------ # Plot training and validation accuracy per epoch #------------------------------------------------ #------------------------------------------------ # Plot training and validation loss per epoch #------------------------------------------------ # Desired output. Charts with training and validation metrics. No crash :)
| 2.700967
| 3
|
tennisApp/forms.py
|
ncvescera/tasso_tennis
| 0
|
6626315
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField, TimeField, FloatField
from wtforms.validators import DataRequired, Length, EqualTo
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=30)])
name = StringField('Name', validators=[DataRequired(), Length(min=2, max=30)])
surname = StringField('Surname', validators=[DataRequired(), Length(min=2, max=40)])
email = StringField('Email', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired(), Length(min=3, max=40)])
confirm_password = PasswordField('<PASSWORD>', validators=[DataRequired()])
landowner = BooleanField('Landowner?')
submit = SubmitField('Sign Up')
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired(), Length(min=3, max=40)])
submit = SubmitField('Login')
class AddFieldForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), Length(min=2, max=30)])
description = TextAreaField()
address = StringField('Address', validators=[DataRequired(), Length(min=2, max=60)])
available_from = TimeField('Apertura', validators=[DataRequired()])
available_to = TimeField('Chiusura', validators=[DataRequired()])
price_h = FloatField('Prezzo orario', validators=[DataRequired()])
submit = SubmitField('Add Field')
def as_dict(self):
res = {
'name': str(self.name.data),
'description': str(self.description.data),
'address': str(self.address.data),
'available_from': str(self.available_from.data),
'available_to': str(self.available_to.data),
'price_h': str(self.price_h.data)
}
return res
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField, TextAreaField, TimeField, FloatField
from wtforms.validators import DataRequired, Length, EqualTo
class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(), Length(min=2, max=30)])
name = StringField('Name', validators=[DataRequired(), Length(min=2, max=30)])
surname = StringField('Surname', validators=[DataRequired(), Length(min=2, max=40)])
email = StringField('Email', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired(), Length(min=3, max=40)])
confirm_password = PasswordField('<PASSWORD>', validators=[DataRequired()])
landowner = BooleanField('Landowner?')
submit = SubmitField('Sign Up')
class LoginForm(FlaskForm):
email = StringField('Email', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired(), Length(min=3, max=40)])
submit = SubmitField('Login')
class AddFieldForm(FlaskForm):
name = StringField('Name', validators=[DataRequired(), Length(min=2, max=30)])
description = TextAreaField()
address = StringField('Address', validators=[DataRequired(), Length(min=2, max=60)])
available_from = TimeField('Apertura', validators=[DataRequired()])
available_to = TimeField('Chiusura', validators=[DataRequired()])
price_h = FloatField('Prezzo orario', validators=[DataRequired()])
submit = SubmitField('Add Field')
def as_dict(self):
res = {
'name': str(self.name.data),
'description': str(self.description.data),
'address': str(self.address.data),
'available_from': str(self.available_from.data),
'available_to': str(self.available_to.data),
'price_h': str(self.price_h.data)
}
return res
|
none
| 1
| 2.812235
| 3
|
|
lib/exabgp/bgp/message/__init__.py
|
lochiiconnectivity/exabgp
| 0
|
6626316
|
<filename>lib/exabgp/bgp/message/__init__.py
# encoding: utf-8
"""
update/__init__.py
Created by <NAME> on 2010-01-15.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
from struct import pack
# =================================================================== BGP States
#
class State (object):
IDLE = 0x01
CONNECT = 0x02
ACTIVE = 0x03
OPENSENT = 0x04
OPENCONFIRM = 0x05
ESTABLISHED = 0x06
# ==================================================================== Direction
#
from exabgp.util.enumeration import Enumeration
OUT = Enumeration ('announce','withdraw')
IN = Enumeration ('announced','withdrawn')
# ================================================================== BGP Message
#
# 0 1 2 3
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | |
# + +
# | |
# + +
# | Marker |
# + +
# | |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | Length | Type |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
class Message (Exception):
# we need to define TYPE inside __init__ of the subclasses
# otherwise we can not dynamically create different UnknownMessage
# TYPE = None
MARKER = chr(0xff)*16
HEADER_LEN = 19
MAX_LEN = 4096
registered_message = {}
klass_notify = None
class ID (int):
__slots__ = []
NOP = 0x00 # . 0 - internal
OPEN = 0x01 # . 1
UPDATE = 0x02 # . 2
NOTIFICATION = 0x03 # . 3
KEEPALIVE = 0x04 # . 4
ROUTE_REFRESH = 0x05 # . 5
OPERATIONAL = 0x06 # . 6 # Not IANA assigned yet
#LIST = 0x20 # . 32
#HEADER = 0x40 # . 64
#GENERAL = 0x80 # . 128
#LOCALRIB = 0x100 # . 256
names = {
NOP : 'NOP',
OPEN : 'OPEN',
UPDATE : 'UPDATE',
NOTIFICATION : 'NOTIFICATION',
KEEPALIVE : 'KEEPALIVE',
ROUTE_REFRESH : 'ROUTE_REFRESH',
OPERATIONAL : 'OPERATIONAL',
}
def __str__ (self):
return self.names.get(self,'UNKNOWN MESSAGE %s' % hex(self))
def __repr__ (self):
return str(self)
@classmethod
def name (cls,message_id):
return cls.names.get(message_id,'UNKNOWN MESSAGE %s' % hex(message_id))
class Name:
NOP = 'NOP'
OPEN = 'OPEN'
UPDATE = 'UPDATE'
NOTIFICATION = 'NOTIFICATION'
KEEPALIVE = 'KEEPALIVE'
ROUTE_REFRESH = 'ROUTE_REFRESH'
OPERATIONAL = 'OPERATIONAL'
Length = {
ID.OPEN : lambda _ : _ >= 29,
ID.UPDATE : lambda _ : _ >= 23,
ID.NOTIFICATION : lambda _ : _ >= 21,
ID.KEEPALIVE : lambda _ : _ == 19,
ID.ROUTE_REFRESH : lambda _ : _ == 23,
}
def __init__ (self):
self._name = None
@staticmethod
def string (code):
if code is None:
return 'invalid'
if code == Message.ID.OPEN:
return 'open'
if code == Message.ID.UPDATE:
return 'update'
if code == Message.ID.NOTIFICATION:
return 'notification'
if code == Message.ID.KEEPALIVE:
return 'keepalive'
if code == Message.ID.ROUTE_REFRESH:
return 'route refresh'
if code == Message.ID.OPERATIONAL:
return 'operational'
return 'unknown'
def _message (self,message):
message_len = pack('!H',19+len(message))
return "%s%s%s%s" % (self.MARKER,message_len,self.TYPE,message)
def message (self):
raise RuntimeError('message not implemented in subclasses')
@classmethod
def register_message (cls,message=None):
what = cls.TYPE if message is None else message
if what in cls.registered_message:
raise RuntimeError('only one class can be registered per message')
cls.registered_message[ord(what)] = cls
@classmethod
def klass (cls,what):
if what in cls.registered_message:
return cls.registered_message[what]
raise cls.klass_notify(2,4,'can not handle message %s' % what)
@classmethod
def unpack_message (cls,message,data,negotiated):
if message in cls.registered_message:
return cls.klass(message).unpack_message(data,negotiated)
return cls.klass(message).unpack_message(data,negotiated)
|
<filename>lib/exabgp/bgp/message/__init__.py
# encoding: utf-8
"""
update/__init__.py
Created by <NAME> on 2010-01-15.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
from struct import pack
# =================================================================== BGP States
#
class State (object):
IDLE = 0x01
CONNECT = 0x02
ACTIVE = 0x03
OPENSENT = 0x04
OPENCONFIRM = 0x05
ESTABLISHED = 0x06
# ==================================================================== Direction
#
from exabgp.util.enumeration import Enumeration
OUT = Enumeration ('announce','withdraw')
IN = Enumeration ('announced','withdrawn')
# ================================================================== BGP Message
#
# 0 1 2 3
# 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | |
# + +
# | |
# + +
# | Marker |
# + +
# | |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
# | Length | Type |
# +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
class Message (Exception):
# we need to define TYPE inside __init__ of the subclasses
# otherwise we can not dynamically create different UnknownMessage
# TYPE = None
MARKER = chr(0xff)*16
HEADER_LEN = 19
MAX_LEN = 4096
registered_message = {}
klass_notify = None
class ID (int):
__slots__ = []
NOP = 0x00 # . 0 - internal
OPEN = 0x01 # . 1
UPDATE = 0x02 # . 2
NOTIFICATION = 0x03 # . 3
KEEPALIVE = 0x04 # . 4
ROUTE_REFRESH = 0x05 # . 5
OPERATIONAL = 0x06 # . 6 # Not IANA assigned yet
#LIST = 0x20 # . 32
#HEADER = 0x40 # . 64
#GENERAL = 0x80 # . 128
#LOCALRIB = 0x100 # . 256
names = {
NOP : 'NOP',
OPEN : 'OPEN',
UPDATE : 'UPDATE',
NOTIFICATION : 'NOTIFICATION',
KEEPALIVE : 'KEEPALIVE',
ROUTE_REFRESH : 'ROUTE_REFRESH',
OPERATIONAL : 'OPERATIONAL',
}
def __str__ (self):
return self.names.get(self,'UNKNOWN MESSAGE %s' % hex(self))
def __repr__ (self):
return str(self)
@classmethod
def name (cls,message_id):
return cls.names.get(message_id,'UNKNOWN MESSAGE %s' % hex(message_id))
class Name:
NOP = 'NOP'
OPEN = 'OPEN'
UPDATE = 'UPDATE'
NOTIFICATION = 'NOTIFICATION'
KEEPALIVE = 'KEEPALIVE'
ROUTE_REFRESH = 'ROUTE_REFRESH'
OPERATIONAL = 'OPERATIONAL'
Length = {
ID.OPEN : lambda _ : _ >= 29,
ID.UPDATE : lambda _ : _ >= 23,
ID.NOTIFICATION : lambda _ : _ >= 21,
ID.KEEPALIVE : lambda _ : _ == 19,
ID.ROUTE_REFRESH : lambda _ : _ == 23,
}
def __init__ (self):
self._name = None
@staticmethod
def string (code):
if code is None:
return 'invalid'
if code == Message.ID.OPEN:
return 'open'
if code == Message.ID.UPDATE:
return 'update'
if code == Message.ID.NOTIFICATION:
return 'notification'
if code == Message.ID.KEEPALIVE:
return 'keepalive'
if code == Message.ID.ROUTE_REFRESH:
return 'route refresh'
if code == Message.ID.OPERATIONAL:
return 'operational'
return 'unknown'
def _message (self,message):
message_len = pack('!H',19+len(message))
return "%s%s%s%s" % (self.MARKER,message_len,self.TYPE,message)
def message (self):
raise RuntimeError('message not implemented in subclasses')
@classmethod
def register_message (cls,message=None):
what = cls.TYPE if message is None else message
if what in cls.registered_message:
raise RuntimeError('only one class can be registered per message')
cls.registered_message[ord(what)] = cls
@classmethod
def klass (cls,what):
if what in cls.registered_message:
return cls.registered_message[what]
raise cls.klass_notify(2,4,'can not handle message %s' % what)
@classmethod
def unpack_message (cls,message,data,negotiated):
if message in cls.registered_message:
return cls.klass(message).unpack_message(data,negotiated)
return cls.klass(message).unpack_message(data,negotiated)
|
en
| 0.243725
|
# encoding: utf-8 update/__init__.py Created by <NAME> on 2010-01-15. Copyright (c) 2009-2015 Exa Networks. All rights reserved. # =================================================================== BGP States # # ==================================================================== Direction # # ================================================================== BGP Message # # 0 1 2 3 # 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | | # + + # | | # + + # | Marker | # + + # | | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # | Length | Type | # +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ # we need to define TYPE inside __init__ of the subclasses # otherwise we can not dynamically create different UnknownMessage # TYPE = None # . 0 - internal # . 1 # . 2 # . 3 # . 4 # . 5 # . 6 # Not IANA assigned yet #LIST = 0x20 # . 32 #HEADER = 0x40 # . 64 #GENERAL = 0x80 # . 128 #LOCALRIB = 0x100 # . 256
| 2.124516
| 2
|
src/kestrel/config.py
|
raymundl/kestrel-lang
| 1
|
6626317
|
import os
import yaml
import pathlib
import pkgutil
import logging
from kestrel.utils import update_nested_dict
CONFIG_DIR_DEFAULT = pathlib.Path.home() / ".config" / "kestrel"
CONFIG_PATH_DEFAULT = CONFIG_DIR_DEFAULT / "kestrel.yaml"
CONFIG_PATH_ENV_VAR = "KESTREL_CONFIG" # override CONFIG_PATH_DEFAULT if provided
_logger = logging.getLogger(__name__)
def load_default_config():
_logger.debug(f"Loading default config file...")
return yaml.safe_load(pkgutil.get_data(__name__, "config.yaml"))
def load_user_config(config_path_env_var, config_path_default):
config_path = os.getenv(config_path_env_var, config_path_default)
config = {}
if config_path:
try:
with open(config_path, "r") as fp:
_logger.debug(f"User configuration file found: {config_path}")
config = yaml.safe_load(fp)
except FileNotFoundError:
_logger.debug(f"User configuration file not exist.")
return config
def load_config():
config_default = load_default_config()
config_user = load_user_config(CONFIG_PATH_ENV_VAR, CONFIG_PATH_DEFAULT)
_logger.debug(f"User configuration loaded: {config_user}")
_logger.debug(f"Updating default config with user config...")
return update_nested_dict(config_default, config_user)
|
import os
import yaml
import pathlib
import pkgutil
import logging
from kestrel.utils import update_nested_dict
CONFIG_DIR_DEFAULT = pathlib.Path.home() / ".config" / "kestrel"
CONFIG_PATH_DEFAULT = CONFIG_DIR_DEFAULT / "kestrel.yaml"
CONFIG_PATH_ENV_VAR = "KESTREL_CONFIG" # override CONFIG_PATH_DEFAULT if provided
_logger = logging.getLogger(__name__)
def load_default_config():
_logger.debug(f"Loading default config file...")
return yaml.safe_load(pkgutil.get_data(__name__, "config.yaml"))
def load_user_config(config_path_env_var, config_path_default):
config_path = os.getenv(config_path_env_var, config_path_default)
config = {}
if config_path:
try:
with open(config_path, "r") as fp:
_logger.debug(f"User configuration file found: {config_path}")
config = yaml.safe_load(fp)
except FileNotFoundError:
_logger.debug(f"User configuration file not exist.")
return config
def load_config():
config_default = load_default_config()
config_user = load_user_config(CONFIG_PATH_ENV_VAR, CONFIG_PATH_DEFAULT)
_logger.debug(f"User configuration loaded: {config_user}")
_logger.debug(f"Updating default config with user config...")
return update_nested_dict(config_default, config_user)
|
en
| 0.348871
|
# override CONFIG_PATH_DEFAULT if provided
| 2.148145
| 2
|
Python/Cracking the Coding Interview/Chapter 4_Trees and Graphs/Graph.py
|
honghaoz/Interview-Algorithm-in-Swift
| 1
|
6626318
|
<reponame>honghaoz/Interview-Algorithm-in-Swift
# Graph implementation
# Reference http://stackoverflow.com/questions/19472530/representing-graphs-data-structure-in-python
# Reference http://interactivepython.org/courselib/static/pythonds/Graphs/graphintro.html
# from enum import Enum
class GraphNode:
def __init__(self, key):
self.key = key
self.adjacents = []
def addNeighbor(self, neighbor):
if not isinstance(neighbor, GraphNode):
return False
self.adjacents.append(neighbor)
return True
def __str__(self):
return str(self.key) + ": " + str([x.key for x in self.adjacents])
class Graph:
def __init__(self):
self.nodes = []
self.isDirected = False
def addNode(self, keyOrNode):
if self.contain(keyOrNode):
return self.getNodeByKey(keyOrNode.key if isinstance(keyOrNode, GraphNode) else keyOrNode)
newNode = keyOrNode if isinstance(keyOrNode, GraphNode) else GraphNode(keyOrNode)
self.nodes.append(newNode)
return newNode
def getNodeByKey(self, key):
if not isinstance(key, int):
return None
else:
resultNodes = filter(lambda node: node.key == key, self.nodes)
length = len(resultNodes)
if length == 0:
return None
elif length == 1:
return resultNodes[0]
else:
assert(False)
def contain(self, keyOrNode):
key = keyOrNode.key if isinstance(keyOrNode, GraphNode) else keyOrNode
return len(filter(lambda node: node.key == key, self.nodes)) >= 1
def addEdge(self, fromKeyOrNode, toKeyOrNode):
fromNode = None
toNode = None
if not self.contain(fromKeyOrNode):
fromNode = self.addNode(fromKeyOrNode)
else:
fromNode = fromKeyOrNode if isinstance(fromKeyOrNode, GraphNode) else self.getNodeByKey(fromKeyOrNode)
if not self.contain(toKeyOrNode):
toNode = self.addNode(toKeyOrNode)
else:
toNode = toKeyOrNode if isinstance(toKeyOrNode, GraphNode) else self.getNodeByKey(toKeyOrNode)
fromNode.addNeighbor(toNode)
if not self.isDirected:
toNode.addNeighbor(fromNode)
def getNodeKeys(self):
return map(lambda node: node.key, self.nodes)
def __iter__(self):
return iter(self.nodes)
def __str__(self):
printBuffer = ""
for eachNode in self.nodes:
printBuffer += str(eachNode) + "\n"
printBuffer = printBuffer[:len(printBuffer) - 1]
return printBuffer
# def test():
# print "Node"
# node = GraphNode(1)
# node.addNeighbor(GraphNode(2))
# print node
# print "\nGraph"
# g = Graph()
# g.addNode(1)
# g.addNode(2)
# g.addEdge(1, 2)
# g.addEdge(4, 5)
# g.addEdge(4, 2)
# print g
# print g.nodes
# print g.getNodeKeys()
# print g.contain(node)
# g.addNode(node)
# print g
# test()
|
# Graph implementation
# Reference http://stackoverflow.com/questions/19472530/representing-graphs-data-structure-in-python
# Reference http://interactivepython.org/courselib/static/pythonds/Graphs/graphintro.html
# from enum import Enum
class GraphNode:
def __init__(self, key):
self.key = key
self.adjacents = []
def addNeighbor(self, neighbor):
if not isinstance(neighbor, GraphNode):
return False
self.adjacents.append(neighbor)
return True
def __str__(self):
return str(self.key) + ": " + str([x.key for x in self.adjacents])
class Graph:
def __init__(self):
self.nodes = []
self.isDirected = False
def addNode(self, keyOrNode):
if self.contain(keyOrNode):
return self.getNodeByKey(keyOrNode.key if isinstance(keyOrNode, GraphNode) else keyOrNode)
newNode = keyOrNode if isinstance(keyOrNode, GraphNode) else GraphNode(keyOrNode)
self.nodes.append(newNode)
return newNode
def getNodeByKey(self, key):
if not isinstance(key, int):
return None
else:
resultNodes = filter(lambda node: node.key == key, self.nodes)
length = len(resultNodes)
if length == 0:
return None
elif length == 1:
return resultNodes[0]
else:
assert(False)
def contain(self, keyOrNode):
key = keyOrNode.key if isinstance(keyOrNode, GraphNode) else keyOrNode
return len(filter(lambda node: node.key == key, self.nodes)) >= 1
def addEdge(self, fromKeyOrNode, toKeyOrNode):
fromNode = None
toNode = None
if not self.contain(fromKeyOrNode):
fromNode = self.addNode(fromKeyOrNode)
else:
fromNode = fromKeyOrNode if isinstance(fromKeyOrNode, GraphNode) else self.getNodeByKey(fromKeyOrNode)
if not self.contain(toKeyOrNode):
toNode = self.addNode(toKeyOrNode)
else:
toNode = toKeyOrNode if isinstance(toKeyOrNode, GraphNode) else self.getNodeByKey(toKeyOrNode)
fromNode.addNeighbor(toNode)
if not self.isDirected:
toNode.addNeighbor(fromNode)
def getNodeKeys(self):
return map(lambda node: node.key, self.nodes)
def __iter__(self):
return iter(self.nodes)
def __str__(self):
printBuffer = ""
for eachNode in self.nodes:
printBuffer += str(eachNode) + "\n"
printBuffer = printBuffer[:len(printBuffer) - 1]
return printBuffer
# def test():
# print "Node"
# node = GraphNode(1)
# node.addNeighbor(GraphNode(2))
# print node
# print "\nGraph"
# g = Graph()
# g.addNode(1)
# g.addNode(2)
# g.addEdge(1, 2)
# g.addEdge(4, 5)
# g.addEdge(4, 2)
# print g
# print g.nodes
# print g.getNodeKeys()
# print g.contain(node)
# g.addNode(node)
# print g
# test()
|
en
| 0.396404
|
# Graph implementation # Reference http://stackoverflow.com/questions/19472530/representing-graphs-data-structure-in-python # Reference http://interactivepython.org/courselib/static/pythonds/Graphs/graphintro.html # from enum import Enum # def test(): # print "Node" # node = GraphNode(1) # node.addNeighbor(GraphNode(2)) # print node # print "\nGraph" # g = Graph() # g.addNode(1) # g.addNode(2) # g.addEdge(1, 2) # g.addEdge(4, 5) # g.addEdge(4, 2) # print g # print g.nodes # print g.getNodeKeys() # print g.contain(node) # g.addNode(node) # print g # test()
| 3.748945
| 4
|
scripts/format.py
|
tektronix/syphon
| 3
|
6626319
|
import os
os.environ["PIPENV_IGNORE_VIRTUALENVS"] = "1"
cmds = ["isort", "black syphon tests setup.py"]
for cmd in cmds:
print(cmd)
os.system(f"pipenv run {cmd}")
print()
|
import os
os.environ["PIPENV_IGNORE_VIRTUALENVS"] = "1"
cmds = ["isort", "black syphon tests setup.py"]
for cmd in cmds:
print(cmd)
os.system(f"pipenv run {cmd}")
print()
|
none
| 1
| 1.579497
| 2
|
|
var/spack/repos/builtin/packages/libsodium/package.py
|
antonl/spack
| 0
|
6626320
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libsodium(AutotoolsPackage):
"""Sodium is a modern, easy-to-use software library for encryption,
decryption, signatures, password hashing and more."""
homepage = "https://download.libsodium.org/doc/"
url = "https://download.libsodium.org/libsodium/releases/libsodium-1.0.13.tar.gz"
list_url = "https://download.libsodium.org/libsodium/releases/old"
version('1.0.18', sha256='6f504490b342a4f8a4c4a02fc9b866cbef8622d5df4e5452b46be121e46636c1')
version('1.0.17', sha256='0cc3dae33e642cc187b5ceb467e0ad0e1b51dcba577de1190e9ffa17766ac2b1')
version('1.0.16', sha256='eeadc7e1e1bcef09680fb4837d448fbdf57224978f865ac1c16745868fbd0533')
version('1.0.15', sha256='fb6a9e879a2f674592e4328c5d9f79f082405ee4bb05cb6e679b90afe9e178f4')
version('1.0.13', sha256='9c13accb1a9e59ab3affde0e60ef9a2149ed4d6e8f99c93c7a5b97499ee323fd')
version('1.0.3', sha256='cbcfc63cc90c05d18a20f229a62c7e7054a73731d0aa858c0517152c549b1288')
version('1.0.2', sha256='961d8f10047f545ae658bcc73b8ab0bf2c312ac945968dd579d87c768e5baa19')
version('1.0.1', sha256='c3090887a4ef9e2d63af1c1e77f5d5a0656fadb5105ebb9fb66a302210cb3af5')
version('1.0.0', sha256='ced1fe3d2066953fea94f307a92f8ae41bf0643739a44309cbe43aa881dbc9a5')
version('0.7.1', sha256='ef46bbb5bac263ef6d3fc00ccc11d4690aea83643412919fe15369b9870280a7')
def url_for_version(self, version):
url = 'https://download.libsodium.org/libsodium/releases/'
if version < Version('1.0.16'):
url += 'old/unsupported/'
elif version < Version('1.0.17'):
url += 'old/'
return url + 'libsodium-{0}.tar.gz'.format(version)
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Libsodium(AutotoolsPackage):
"""Sodium is a modern, easy-to-use software library for encryption,
decryption, signatures, password hashing and more."""
homepage = "https://download.libsodium.org/doc/"
url = "https://download.libsodium.org/libsodium/releases/libsodium-1.0.13.tar.gz"
list_url = "https://download.libsodium.org/libsodium/releases/old"
version('1.0.18', sha256='6f504490b342a4f8a4c4a02fc9b866cbef8622d5df4e5452b46be121e46636c1')
version('1.0.17', sha256='0cc3dae33e642cc187b5ceb467e0ad0e1b51dcba577de1190e9ffa17766ac2b1')
version('1.0.16', sha256='eeadc7e1e1bcef09680fb4837d448fbdf57224978f865ac1c16745868fbd0533')
version('1.0.15', sha256='fb6a9e879a2f674592e4328c5d9f79f082405ee4bb05cb6e679b90afe9e178f4')
version('1.0.13', sha256='9c13accb1a9e59ab3affde0e60ef9a2149ed4d6e8f99c93c7a5b97499ee323fd')
version('1.0.3', sha256='cbcfc63cc90c05d18a20f229a62c7e7054a73731d0aa858c0517152c549b1288')
version('1.0.2', sha256='961d8f10047f545ae658bcc73b8ab0bf2c312ac945968dd579d87c768e5baa19')
version('1.0.1', sha256='c3090887a4ef9e2d63af1c1e77f5d5a0656fadb5105ebb9fb66a302210cb3af5')
version('1.0.0', sha256='ced1fe3d2066953fea94f307a92f8ae41bf0643739a44309cbe43aa881dbc9a5')
version('0.7.1', sha256='ef46bbb5bac263ef6d3fc00ccc11d4690aea83643412919fe15369b9870280a7')
def url_for_version(self, version):
url = 'https://download.libsodium.org/libsodium/releases/'
if version < Version('1.0.16'):
url += 'old/unsupported/'
elif version < Version('1.0.17'):
url += 'old/'
return url + 'libsodium-{0}.tar.gz'.format(version)
|
en
| 0.734503
|
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) Sodium is a modern, easy-to-use software library for encryption, decryption, signatures, password hashing and more.
| 1.462005
| 1
|
example/calcuator.py
|
ViterbiDevelopment/LearingPython
| 0
|
6626321
|
<filename>example/calcuator.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
for i in range(1,85):
if 168 % i == 0:
j = 168 / i;
if i > j and (i + j) % 2 == 0 and (i - j) % 2 == 0 :
m = (i + j) / 2
n = (i - j) / 2
x = n * n - 100
print(x)
|
<filename>example/calcuator.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
for i in range(1,85):
if 168 % i == 0:
j = 168 / i;
if i > j and (i + j) % 2 == 0 and (i - j) % 2 == 0 :
m = (i + j) / 2
n = (i - j) / 2
x = n * n - 100
print(x)
|
zh
| 0.947506
|
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #一个整数,它加上100后是一个完全平方数,再加上168又是一个完全平方数,请问该数是多少?
| 3.398289
| 3
|
benchexec/tablegenerator/__init__.py
|
blizzard4591/benchexec
| 0
|
6626322
|
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 <NAME> <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import argparse
import bz2
import collections
import copy
import functools
import gzip
import io
import itertools
import logging
import os.path
import signal
import subprocess
import sys
import time
import types
import urllib.parse
import urllib.request
from xml.etree import ElementTree
from benchexec import __version__, BenchExecException
import benchexec.model as model
import benchexec.result as result
import benchexec.tooladapter as tooladapter
import benchexec.util
from benchexec.tablegenerator import htmltable, statistics, util
from benchexec.tablegenerator.columns import Column
from benchexec.tablegenerator.util import TaskId
import zipfile
# Process pool for parallel work.
# Some of our loops are CPU-bound (e.g., statistics calculations), thus we use
# processes, not threads.
# Fully initialized only in main() because we cannot do so in the worker processes.
parallel = util.DummyExecutor()
# Most important columns that should be shown first in tables (in the given order)
MAIN_COLUMNS = [
Column("status"),
Column("category"),
Column("cputime"),
Column("walltime"),
Column("memory", unit="MB", source_unit="B"),
Column(
"memUsage", display_title="memory", unit="MB", source_unit="B"
), # if old results are given
Column("cpuenergy"),
]
NAME_START = "results" # first part of filename of table
DEFAULT_OUTPUT_PATH = "results/"
TEMPLATE_FORMATS = ["html", "csv"]
_BYTE_FACTOR = 1000 # bytes in a kilobyte
UNIT_CONVERSION = {
"s": {"ms": 1000, "min": 1.0 / 60, "h": 1.0 / 3600},
"B": {"kB": 1.0 / 10 ** 3, "MB": 1.0 / 10 ** 6, "GB": 1.0 / 10 ** 9},
"J": {
"kJ": 1.0 / 10 ** 3,
"Ws": 1,
"kWs": 1.0 / 1000,
"Wh": 1.0 / 3600,
"kWh": 1.0 / (1000 * 3600),
"mWh": 1.0 / (1000 * 1000 * 3600),
},
}
def handle_error(message, *args):
"""Log error message and terminate program."""
logging.error(message, *args)
exit(1)
def parse_table_definition_file(file):
"""
Read an parse the XML of a table-definition file.
@return: an ElementTree object for the table definition
"""
logging.info("Reading table definition from '%s'...", file)
if not os.path.isfile(file):
handle_error("File '%s' does not exist.", file)
try:
tableGenFile = ElementTree.ElementTree().parse(file)
except OSError as e:
handle_error("Could not read result file %s: %s", file, e)
except ElementTree.ParseError as e:
handle_error("Table file %s is invalid: %s", file, e)
if "table" != tableGenFile.tag:
handle_error(
"Table file %s is invalid: It's root element is not named 'table'.", file
)
return tableGenFile
def table_definition_lists_result_files(table_definition):
return any(tag.tag in ["result", "union"] for tag in table_definition)
def load_results_from_table_definition(
table_definition, table_definition_file, options
):
"""
Load all results in files that are listed in the given table-definition file.
@return: a list of RunSetResult objects
"""
default_columns = extract_columns_from_table_definition_file(
table_definition, table_definition_file
)
columns_relevant_for_diff = _get_columns_relevant_for_diff(default_columns)
results = []
for tag in table_definition:
if tag.tag == "result":
columns = (
extract_columns_from_table_definition_file(tag, table_definition_file)
or default_columns
)
run_set_id = tag.get("id")
for resultsFile in get_file_list_from_result_tag(
tag, table_definition_file
):
results.append(
parallel.submit(
load_result,
resultsFile,
options,
run_set_id,
columns,
columns_relevant_for_diff,
)
)
elif tag.tag == "union":
results.append(
parallel.submit(
handle_union_tag,
tag,
table_definition_file,
options,
default_columns,
columns_relevant_for_diff,
)
)
return [future.result() for future in results]
def handle_union_tag(
tag, table_definition_file, options, default_columns, columns_relevant_for_diff
):
columns = (
extract_columns_from_table_definition_file(tag, table_definition_file)
or default_columns
)
result = RunSetResult([], collections.defaultdict(list), columns)
all_result_files = set()
for resultTag in tag.findall("result"):
if extract_columns_from_table_definition_file(resultTag, table_definition_file):
logging.warning(
"<result> tags within <union> tags may not contain <column> tags, "
"these column declarations will be ignored. Please move them to the <union> tag."
)
run_set_id = resultTag.get("id")
for resultsFile in get_file_list_from_result_tag(
resultTag, table_definition_file
):
if resultsFile in all_result_files:
handle_error("File '%s' included twice in <union> tag", resultsFile)
all_result_files.add(resultsFile)
result_xml = parse_results_file(resultsFile, run_set_id)
if result_xml is not None:
result.append(resultsFile, result_xml, options.all_columns)
if not result._xml_results:
return None
name = tag.get("name")
if name:
logging.warning(
"Attribute 'name' for <union> tags is deprecated, use 'title' instead."
)
name = tag.get("title", name)
if name:
result.attributes["name"] = [name]
result.collect_data(options.correct_only)
return result
def get_file_list_from_result_tag(result_tag, table_definition_file):
if "filename" not in result_tag.attrib:
logging.warning(
"Result tag without filename attribute in file '%s'.", table_definition_file
)
return []
# expand wildcards
return util.get_file_list(
os.path.join(os.path.dirname(table_definition_file), result_tag.get("filename"))
)
def load_results_with_table_definition(
result_files, table_definition, table_definition_file, options
):
"""
Load results from given files with column definitions taken from a table-definition file.
@return: a list of RunSetResult objects
"""
columns = extract_columns_from_table_definition_file(
table_definition, table_definition_file
)
columns_relevant_for_diff = _get_columns_relevant_for_diff(columns)
return load_results(
result_files,
options=options,
columns=columns,
columns_relevant_for_diff=columns_relevant_for_diff,
)
def extract_columns_from_table_definition_file(xmltag, table_definition_file):
"""
Extract all columns mentioned in the result tag of a table definition file.
"""
def handle_path(path):
"""Convert path from a path relative to table-definition file."""
if not path or path.startswith("http://") or path.startswith("https://"):
return path
return os.path.join(os.path.dirname(table_definition_file), path)
columns = []
for c in xmltag.findall("column"):
scale_factor = c.get("scaleFactor")
display_unit = c.get("displayUnit")
source_unit = c.get("sourceUnit")
new_column = Column(
c.get("title"),
c.text,
c.get("numberOfDigits"),
handle_path(c.get("href")),
None,
display_unit,
source_unit,
scale_factor,
c.get("relevantForDiff"),
c.get("displayTitle"),
)
columns.append(new_column)
return columns
def _get_columns_relevant_for_diff(columns_to_show):
"""
Extract columns that are relevant for the diff table.
@param columns_to_show: (list) A list of columns that should be shown
@return: (set) Set of columns that are relevant for the diff table. If
none is marked relevant, the column named "status" will be
returned in the set.
"""
cols = {col.title for col in columns_to_show if col.relevant_for_diff}
if len(cols) == 0:
return {col.title for col in columns_to_show if col.title == "status"}
else:
return cols
def normalize_path(path, base_path_or_url):
"""Returns a normalized form of path, interpreted relative to base_path_or_url"""
if util.is_url(base_path_or_url):
return urllib.parse.urljoin(base_path_or_url, path)
else:
return os.path.normpath(os.path.join(os.path.dirname(base_path_or_url), path))
loaded_tools = {}
def load_tool(result):
"""
Load the module with the tool-specific code.
"""
def load_tool_module(tool_module):
if not tool_module:
logging.warning(
"Cannot extract values from log files for benchmark results %s "
'(missing attribute "toolmodule" on tag "result").',
util.prettylist(result.attributes["name"]),
)
return None
try:
logging.debug("Loading %s", tool_module)
tool = __import__(tool_module, fromlist=["Tool"]).Tool()
return tooladapter.adapt_to_current_version(tool)
except ImportError as ie:
logging.warning(
'Missing module "%s", cannot extract values from log files (ImportError: %s).',
tool_module,
ie,
)
except AttributeError:
logging.warning(
'The module "%s" does not define the necessary class Tool, '
"cannot extract values from log files.",
tool_module,
)
except TypeError as te:
logging.warning(
'Unsupported module "%s", cannot extract values from log files '
"(TypeError: %s).",
tool_module,
te,
)
return None
tool_module = (
result.attributes["toolmodule"][0]
if "toolmodule" in result.attributes
else None
)
if tool_module in loaded_tools:
return loaded_tools[tool_module]
else:
result = load_tool_module(tool_module)
loaded_tools[tool_module] = result
return result
class RunSetResult(object):
"""
The Class RunSetResult contains all the results of one execution of a run set:
the sourcefiles tags (with sourcefiles + values), the columns to show
and the benchmark attributes.
"""
def __init__(
self,
xml_results,
attributes,
columns,
summary={},
columns_relevant_for_diff=set(),
):
self._xml_results = xml_results
self.attributes = attributes
# Copy the columns since they may be modified
self.columns = copy.deepcopy(columns)
self.summary = summary
self.columns_relevant_for_diff = columns_relevant_for_diff
def get_tasks(self):
"""
Return the list of task ids for these results.
May be called only after collect_data()
"""
return [r.task_id for r in self.results]
def append(self, resultFile, resultElem, all_columns=False):
"""
Append the result for one run. Needs to be called before collect_data().
"""
self._xml_results += [
(result, resultFile) for result in _get_run_tags_from_xml(resultElem)
]
for attrib, values in RunSetResult._extract_attributes_from_result(
resultFile, resultElem
).items():
self.attributes[attrib].extend(values)
if not self.columns:
self.columns = RunSetResult._extract_existing_columns_from_result(
resultFile, resultElem, all_columns
)
def collect_data(self, correct_only):
"""
Load the actual result values from the XML file and the log files.
This may take some time if many log files have to be opened and parsed.
"""
self.results = []
def get_value_from_logfile(lines, identifier):
"""
This method searches for values in lines of the content.
It uses a tool-specific method to so.
"""
output = tooladapter.CURRENT_BASETOOL.RunOutput(lines)
return load_tool(self).get_value_from_output(output, identifier)
# Opening the ZIP archive with the logs for every run is too slow, we cache it.
log_zip_cache = {}
try:
for xml_result, result_file in self._xml_results:
self.results.append(
RunResult.create_from_xml(
xml_result,
get_value_from_logfile,
self.columns,
correct_only,
log_zip_cache,
self.columns_relevant_for_diff,
result_file,
)
)
finally:
for file in log_zip_cache.values():
file.close()
for column in self.columns:
column_values = (
run_result.values[run_result.columns.index(column)]
for run_result in self.results
)
column.set_column_type_from(column_values)
del self._xml_results
def __str__(self):
return util.prettylist(self.attributes["filename"])
@staticmethod
def create_from_xml(
resultFile,
resultElem,
columns=None,
all_columns=False,
columns_relevant_for_diff=set(),
):
"""
This function extracts everything necessary for creating a RunSetResult object
from the "result" XML tag of a benchmark result file.
It returns a RunSetResult object, which is not yet fully initialized.
To finish initializing the object, call collect_data()
before using it for anything else
(this is to separate the possibly costly collect_data() call from object instantiation).
"""
attributes = RunSetResult._extract_attributes_from_result(
resultFile, resultElem
)
if not columns:
columns = RunSetResult._extract_existing_columns_from_result(
resultFile, resultElem, all_columns
)
summary = RunSetResult._extract_summary_from_result(resultElem, columns)
return RunSetResult(
[(result, resultFile) for result in _get_run_tags_from_xml(resultElem)],
attributes,
columns,
summary,
columns_relevant_for_diff,
)
@staticmethod
def _extract_existing_columns_from_result(resultFile, resultElem, all_columns):
run_results = _get_run_tags_from_xml(resultElem)
if not run_results:
logging.warning("Result file '%s' is empty.", resultFile)
return []
else: # show all available columns
column_names = {
c.get("title")
for s in run_results
for c in s.findall("column")
if all_columns or c.get("hidden") != "true"
}
if not column_names:
# completely empty results break stuff, add at least status column
return [MAIN_COLUMNS[0]]
# Put main columns first, then rest sorted alphabetically
custom_columns = column_names.difference(
column.title for column in MAIN_COLUMNS
)
return [
column for column in MAIN_COLUMNS if column.title in column_names
] + [Column(title) for title in sorted(custom_columns)]
@staticmethod
def _extract_attributes_from_result(resultFile, resultTag):
attributes = collections.defaultdict(list)
# Defaults
attributes["filename"] = [resultFile]
attributes["branch"] = [
os.path.basename(resultFile).split("#")[0] if "#" in resultFile else ""
]
attributes["timelimit"] = ["-"]
attributes["memlimit"] = ["-"]
attributes["cpuCores"] = ["-"]
attributes["displayName"] = []
# Update with real values
for attrib, value in resultTag.attrib.items():
attributes[attrib] = [value]
# Add system information if present
for systemTag in sorted(
resultTag.findall("systeminfo"),
key=lambda systemTag: systemTag.get("hostname", "unknown"),
):
cpuTag = systemTag.find("cpu")
attributes["os"].append(systemTag.find("os").get("name"))
attributes["cpu"].append(cpuTag.get("model"))
attributes["cores"].append(cpuTag.get("cores"))
attributes["freq"].append(cpuTag.get("frequency"))
attributes["turbo"].append(cpuTag.get("turboboostActive"))
attributes["ram"].append(systemTag.find("ram").get("size"))
attributes["host"].append(systemTag.get("hostname", "unknown"))
return attributes
@staticmethod
def _extract_summary_from_result(resultTag, columns):
summary = collections.defaultdict(list)
# Add summary for columns if present
for column in resultTag.findall("column"):
title = column.get("title")
if title in (c.title for c in columns):
summary[title] = column.get("value")
return summary
def _get_run_tags_from_xml(result_elem):
# Here we keep support for <sourcefile> in order to be able to read old benchmark
# results (no reason to forbid this).
return result_elem.findall("run") + result_elem.findall("sourcefile")
def load_results(
result_files,
options,
run_set_id=None,
columns=None,
columns_relevant_for_diff=set(),
):
"""Version of load_result for multiple input files that will be loaded concurrently."""
return parallel.map(
load_result,
result_files,
itertools.repeat(options),
itertools.repeat(run_set_id),
itertools.repeat(columns),
itertools.repeat(columns_relevant_for_diff),
)
def load_result(
result_file, options, run_set_id=None, columns=None, columns_relevant_for_diff=set()
):
"""
Completely handle loading a single result file.
@param result_file the file to parse
@param options additional options
@param run_set_id the identifier of the run set
@param columns the list of columns
@param columns_relevant_for_diff a set of columns that is relevant for
the diff table
@return a fully ready RunSetResult instance or None
"""
xml = parse_results_file(
result_file, run_set_id=run_set_id, ignore_errors=options.ignore_errors
)
if xml is None:
return None
result = RunSetResult.create_from_xml(
result_file,
xml,
columns=columns,
all_columns=options.all_columns,
columns_relevant_for_diff=columns_relevant_for_diff,
)
result.collect_data(options.correct_only)
return result
def parse_results_file(resultFile, run_set_id=None, ignore_errors=False):
"""
This function parses an XML file that contains the results of the execution of a run set.
It returns the "result" XML tag.
@param resultFile: The file name of the XML file that contains the results.
@param run_set_id: An optional identifier of this set of results.
"""
logging.info(" %s", resultFile)
url = util.make_url(resultFile)
parse = ElementTree.ElementTree().parse
try:
with util.open_url_seekable(url, mode="rb") as f:
try:
try:
resultElem = parse(gzip.GzipFile(fileobj=f))
except OSError:
f.seek(0)
resultElem = parse(bz2.BZ2File(f))
except OSError:
f.seek(0)
resultElem = parse(f)
except OSError as e:
handle_error("Could not read result file %s: %s", resultFile, e)
except ElementTree.ParseError as e:
handle_error("Result file %s is invalid: %s", resultFile, e)
if resultElem.tag not in ["result", "test"]:
handle_error(
"XML file with benchmark results seems to be invalid.\n"
"The root element of the file is not named 'result' or 'test'.\n"
"If you want to run a table-definition file,\n"
"you should use the option '-x' or '--xml'."
)
if ignore_errors and "error" in resultElem.attrib:
logging.warning(
'Ignoring file "%s" because of error: %s',
resultFile,
resultElem.attrib["error"],
)
return None
if run_set_id is not None:
for sourcefile in _get_run_tags_from_xml(resultElem):
sourcefile.set("runset", run_set_id)
insert_logfile_names(resultFile, resultElem)
return resultElem
def insert_logfile_names(resultFile, resultElem):
# get folder of logfiles (truncate end of XML file name and append .logfiles instead)
log_folder = resultFile[0 : resultFile.rfind(".results.")] + ".logfiles/"
# append begin of filename
runSetName = resultElem.get("name")
if runSetName is not None:
blockname = resultElem.get("block")
if blockname is None:
log_folder += runSetName + "."
elif blockname == runSetName:
pass # real runSetName is empty
else:
assert runSetName.endswith("." + blockname)
runSetName = runSetName[: -(1 + len(blockname))] # remove last chars
log_folder += runSetName + "."
# for each file: append original filename and insert log_file_name into sourcefileElement
for sourcefile in _get_run_tags_from_xml(resultElem):
if "logfile" in sourcefile.attrib:
log_file = urllib.parse.urljoin(resultFile, sourcefile.get("logfile"))
else:
log_file = log_folder + os.path.basename(sourcefile.get("name")) + ".log"
sourcefile.set("logfile", log_file)
def merge_tasks(runset_results):
"""
This function merges the results of all RunSetResult objects.
If necessary, it can merge lists of names: [A,C] + [A,B] --> [A,B,C]
and add dummy elements to the results.
It also ensures the same order of tasks.
"""
task_list = []
task_set = set()
for runset in runset_results:
index = -1
currentresult_taskset = set()
for task in runset.get_tasks():
if task in currentresult_taskset:
logging.warning(
"Task %s is present twice in '%s', skipping it.", task, runset
)
else:
currentresult_taskset.add(task)
if task not in task_set:
task_list.insert(index + 1, task)
task_set.add(task)
index += 1
else:
index = task_list.index(task)
merge_task_lists(runset_results, task_list)
def merge_task_lists(runset_results, tasks):
"""
Set the filelists of all RunSetResult elements so that they contain the same files
in the same order. For missing files a dummy element is inserted.
"""
for runset in runset_results:
# create mapping from id to RunResult object
# Use reversed list such that the first instance of equal tasks end up in dic
dic = {
run_result.task_id: run_result for run_result in reversed(runset.results)
}
runset.results = [] # clear and repopulate results
for task in tasks:
run_result = dic.get(task)
if run_result is None:
logging.info(" No result for task %s in '%s'.", task, runset)
# create an empty dummy element
run_result = RunResult(
task,
None,
"empty", # special category for tables
None,
None,
runset.columns,
[None] * len(runset.columns),
)
runset.results.append(run_result)
def find_common_tasks(runset_results):
tasks_in_first_runset = runset_results[0].get_tasks()
task_set = set(tasks_in_first_runset)
for runset_result in runset_results:
task_set = task_set & set(runset_result.get_tasks())
task_list = []
if not task_set:
logging.warning("No tasks are present in all benchmark results.")
else:
task_list = [task for task in tasks_in_first_runset if task in task_set]
merge_task_lists(runset_results, task_list)
class RunResult(object):
"""
The class RunResult contains the results of a single verification run.
"""
def __init__(
self,
task_id,
status,
category,
score,
log_file,
columns,
values,
columns_relevant_for_diff=set(),
sourcefiles_exist=True,
):
assert len(columns) == len(values)
self.task_id = task_id
self.sourcefiles_exist = sourcefiles_exist
self.status = status
self.log_file = log_file
self.columns = columns
self.values = values
self.category = category
self.score = score
self.columns_relevant_for_diff = columns_relevant_for_diff
@staticmethod
def create_from_xml(
sourcefileTag,
get_value_from_logfile,
listOfColumns,
correct_only,
log_zip_cache,
columns_relevant_for_diff,
result_file_or_url,
):
"""
This function collects the values from one run.
Only columns that should be part of the table are collected.
"""
def read_logfile_lines(log_file):
if not log_file:
return []
log_file_url = util.make_url(log_file)
url_parts = urllib.parse.urlparse(log_file_url, allow_fragments=False)
log_zip_path = os.path.dirname(url_parts.path) + ".zip"
log_zip_url = urllib.parse.urlunparse(
(
url_parts.scheme,
url_parts.netloc,
log_zip_path,
url_parts.params,
url_parts.query,
url_parts.fragment,
)
)
path_in_zip = urllib.parse.unquote(
# os.path.relpath creates os-dependant paths, but windows separators can produce errors with zipfile lib
util.fix_path_if_on_windows(
os.path.relpath(url_parts.path, os.path.dirname(log_zip_path))
)
)
if log_zip_url.startswith("file:///") and not log_zip_path.startswith("/"):
# Replace file:/// with file: for relative paths,
# otherwise opening fails.
log_zip_url = "file:" + log_zip_url[8:]
try:
with util.open_url_seekable(log_file_url, "rt") as logfile:
return logfile.readlines()
except OSError:
try:
if log_zip_url not in log_zip_cache:
log_zip_cache[log_zip_url] = zipfile.ZipFile(
util.open_url_seekable(log_zip_url, "rb")
)
log_zip = log_zip_cache[log_zip_url]
try:
with io.TextIOWrapper(log_zip.open(path_in_zip)) as logfile:
return logfile.readlines()
except KeyError:
logging.warning(
"Could not find logfile '%s' in archive '%s'.",
log_file,
log_zip_url,
)
return []
except OSError:
logging.warning(
"Could not find logfile '%s' nor log archive '%s'.",
log_file,
log_zip_url,
)
return []
sourcefiles = sourcefileTag.get("files")
if sourcefiles:
if not sourcefiles.startswith("["):
raise AssertionError("Unknown format for files tag:")
sourcefiles_exist = any(s.strip() for s in sourcefiles[1:-1].split(","))
else:
sourcefiles_exist = False
task_name = sourcefileTag.get("name")
if sourcefiles_exist:
# task_name is a path
task_name = normalize_path(task_name, result_file_or_url)
prop, expected_result = get_property_of_task(
task_name,
result_file_or_url,
sourcefileTag.get("properties"),
sourcefileTag.get("propertyFile"),
sourcefileTag.get("expectedVerdict"),
)
task_id = TaskId(task_name, prop, expected_result, sourcefileTag.get("runset"))
status = util.get_column_value(sourcefileTag, "status", "")
category = util.get_column_value(sourcefileTag, "category")
if not category:
if status: # only category missing
category = result.CATEGORY_MISSING
else: # probably everything is missing, special category for tables
category = "aborted"
score = None
if prop:
score = prop.compute_score(category, status)
logfileLines = None
values = []
for column in listOfColumns: # for all columns that should be shown
value = None # default value
if column.title.lower() == "status":
value = status
elif not correct_only or category == result.CATEGORY_CORRECT:
if not column.pattern or column.href:
# collect values from XML
value = util.get_column_value(sourcefileTag, column.title)
else: # collect values from logfile
if logfileLines is None: # cache content
logfileLines = read_logfile_lines(sourcefileTag.get("logfile"))
value = get_value_from_logfile(logfileLines, column.pattern)
if column.title.lower() == "score" and value is None and score is not None:
# If no score column exists in the xml, take the internally computed score,
# if available
value = str(score)
values.append(value)
return RunResult(
task_id,
status,
category,
score,
sourcefileTag.get("logfile"),
listOfColumns,
values,
columns_relevant_for_diff,
sourcefiles_exist=sourcefiles_exist,
)
class Row(object):
"""
The class Row contains all the results for one sourcefile (a list of RunResult instances).
It is identified by the name of the source file and optional additional data
(such as the property).
It corresponds to one complete row in the final tables.
"""
def __init__(self, results):
assert results
self.results = results
self.id = results[0].task_id
self.has_sourcefile = results[0].sourcefiles_exist
assert (
len({r.task_id for r in results}) == 1
), "not all results are for same task"
def set_relative_path(self, common_prefix, base_dir):
"""
generate output representation of rows
"""
self.short_filename = self.id.name.replace(common_prefix, "", 1)
def get_property_of_task(
task_name, base_path, property_string, property_file, expected_result
):
if property_string is None:
return (None, None)
if property_file:
property_file = normalize_path(property_file, base_path)
try:
prop = result.Property.create(property_file)
except OSError as e:
logging.debug("Cannot read property file %s: %s", property_file, e)
prop = result.Property(property_file, False, property_string)
if expected_result is not None:
expected_result = result.ExpectedResult.from_str(expected_result)
return (prop, expected_result)
if task_name.endswith(".yml"):
# try to find property file of task and create Property object
try:
task_template = model.load_task_definition_file(task_name)
for prop_dict in task_template.get("properties", []):
if "property_file" in prop_dict:
expanded = benchexec.util.expand_filename_pattern(
prop_dict["property_file"], os.path.dirname(task_name)
)
if len(expanded) == 1:
prop = result.Property.create(expanded[0])
if prop.name == property_string:
expected_result = prop_dict.get("expected_verdict")
if isinstance(expected_result, bool):
expected_result = result.ExpectedResult(
expected_result, prop_dict.get("subproperty")
)
else:
expected_result = None
return (prop, expected_result)
except BenchExecException as e:
logging.debug("Could not load task-template file %s: %s", task_name, e)
return (result.Property(None, False, property_string), None)
def rows_to_columns(rows):
"""
Convert a list of Rows into a column-wise list of list of RunResult
"""
return zip(*[row.results for row in rows])
def get_rows(runSetResults):
"""
Create list of rows with all data. Each row consists of several RunResults.
"""
rows = []
for task_results in zip(*[runset.results for runset in runSetResults]):
rows.append(Row(task_results))
return rows
def filter_rows_with_differences(rows):
"""
Find all rows with differences in the status column.
"""
if not rows:
# empty table
return []
if len(rows[0].results) == 1:
# table with single column
return []
def get_index_of_column(name, cols):
assert cols, "Cannot look for column '{}' in empy column list".format(name)
for i in range(0, len(cols)):
if cols[i].title == name:
return i
assert False, "Column '{}' not found in columns '{}'".format(name, cols)
def all_equal_result(listOfResults):
relevant_columns = set()
for res in listOfResults:
for relevant_column in res.columns_relevant_for_diff:
relevant_columns.add(relevant_column)
if len(relevant_columns) == 0:
relevant_columns.add("status")
status = []
for col in relevant_columns:
# It's necessary to search for the index of a column every time
# because they can differ between results
status.append(
{
res.values[get_index_of_column(col, res.columns)]
for res in listOfResults
if res.values
}
)
return functools.reduce(lambda x, y: x and (len(y) <= 1), status, True)
rowsDiff = [row for row in rows if not all_equal_result(row.results)]
if len(rowsDiff) == 0:
logging.info("---> NO DIFFERENCE FOUND IN SELECTED COLUMNS")
elif len(rowsDiff) == len(rows):
logging.info(
"---> DIFFERENCES FOUND IN ALL ROWS, NO NEED TO CREATE DIFFERENCE TABLE"
)
return []
return rowsDiff
def format_run_set_attributes_nicely(runSetResults):
"""Replace the attributes of each RunSetResult with nicely formatted strings."""
for runSetResult in runSetResults:
for key in runSetResult.attributes:
values = runSetResult.attributes[key]
if key == "turbo":
turbo_values = list(set(values))
if len(turbo_values) > 1:
turbo = "mixed"
elif turbo_values[0] == "true":
turbo = "enabled"
elif turbo_values[0] == "false":
turbo = "disabled"
else:
turbo = None
runSetResult.attributes["turbo"] = (
", Turbo Boost: {}".format(turbo) if turbo else ""
)
elif key == "timelimit":
def fix_unit_display(value):
if len(value) >= 2 and value[-1] == "s" and value[-2] != " ":
return value[:-1] + " s"
return value
runSetResult.attributes[key] = util.prettylist(
map(fix_unit_display, values)
)
elif key == "memlimit" or key == "ram":
def round_to_MB(value):
number, unit = util.split_number_and_unit(value)
if unit and unit != "B":
return value
try:
return "{:.0f} MB".format(
int(number) / _BYTE_FACTOR / _BYTE_FACTOR
)
except ValueError:
return value
runSetResult.attributes[key] = util.prettylist(map(round_to_MB, values))
elif key == "freq":
def round_to_MHz(value):
number, unit = util.split_number_and_unit(value)
if unit and unit != "Hz":
return value
try:
return "{:.0f} MHz".format(int(number) / 1000 / 1000)
except ValueError:
return value
runSetResult.attributes[key] = util.prettylist(
map(round_to_MHz, values)
)
elif key == "host":
runSetResult.attributes[key] = util.prettylist(
util.merge_entries_with_common_prefixes(values)
)
else:
runSetResult.attributes[key] = util.prettylist(values)
# compute nice name of each run set for displaying
firstBenchmarkName = runSetResults[0].attributes["benchmarkname"]
allBenchmarkNamesEqual = all(
r.attributes["benchmarkname"] == firstBenchmarkName for r in runSetResults
)
for runSetResult in runSetResults:
benchmarkName = runSetResult.attributes["benchmarkname"]
name = runSetResult.attributes["name"]
if not name:
niceName = benchmarkName
elif allBenchmarkNamesEqual:
niceName = name
else:
niceName = benchmarkName + "." + name
runSetResult.attributes["niceName"] = niceName
def select_relevant_id_columns(rows):
"""
Find out which of the entries in Row.id are equal for all given rows.
@return: A list of True/False values according to whether the i-th part of the id is always equal.
"""
relevant_id_columns = [True] # first column (file name) is always relevant
if rows:
prototype_id = rows[0].id
for column in range(1, len(prototype_id)):
def id_equal_to_prototype(row):
return row.id[column] == prototype_id[column]
relevant_id_columns.append(not all(map(id_equal_to_prototype, rows)))
return relevant_id_columns
def compute_stats(rows, run_set_results, use_local_summary, correct_only):
result_cols = list(rows_to_columns(rows)) # column-wise
all_column_stats = list(
parallel.map(
statistics.get_stats_of_run_set,
result_cols,
[correct_only] * len(result_cols),
)
)
if use_local_summary:
for run_set_result, run_set_stats in zip(run_set_results, all_column_stats):
statistics.add_local_summary_statistics(run_set_result, run_set_stats)
return all_column_stats
def get_regression_count(rows, ignoreFlappingTimeouts): # for options.dump_counts
"""Count the number of regressions, i.e., differences in status of the two right-most results
where the new one is not "better" than the old one.
Any change in status between error, unknown, and wrong result is a regression.
Different kind of errors or wrong results are also a regression.
"""
def status_is(run_result, status):
# startswith is used because status can be "TIMEOUT (TRUE)" etc., which count as "TIMEOUT"
return run_result.status and run_result.status.startswith(status)
def any_status_is(run_results, status):
for run_result in run_results:
if status_is(run_result, status):
return True
return False
regressions = 0
for row in rows:
if len(row.results) < 2:
return 0 # no regressions at all with only one run
# "new" and "old" are the latest two results
new = row.results[-1]
old = row.results[-2]
if new.category == result.CATEGORY_CORRECT:
continue # no regression if result is correct
if new.status == old.status:
continue # no regression if result is the same as before
if status_is(new, "TIMEOUT") and status_is(old, "TIMEOUT"):
continue # no regression if both are some form of timeout
if status_is(new, "OUT OF MEMORY") and status_is(old, "OUT OF MEMORY"):
continue # same for OOM
if (
ignoreFlappingTimeouts
and status_is(new, "TIMEOUT")
and any_status_is(row.results[:-2], "TIMEOUT")
):
continue # flapping timeout because any of the older results is also a timeout
regressions += 1
return regressions
def get_counts(rows): # for options.dump_counts
countsList = []
for runResults in rows_to_columns(rows):
counts = collections.Counter(runResult.category for runResult in runResults)
countsList.append(
(
counts[result.CATEGORY_CORRECT],
counts[result.CATEGORY_WRONG],
counts[result.CATEGORY_UNKNOWN]
+ counts[result.CATEGORY_ERROR]
+ counts[None], # for rows without a result
)
)
return countsList
def create_tables(
name, runSetResults, rows, rowsDiff, outputPath, outputFilePattern, options
):
"""
Create tables and write them to files.
@return a list of futures to allow waiting for completion
"""
# get common folder of sourcefiles
# os.path.commonprefix can return a partial path component (does not truncate on /)
common_prefix = os.path.commonprefix([r.id.name for r in rows])
separator = "/" if "://" in common_prefix else os.sep
common_prefix = common_prefix[: common_prefix.rfind(separator) + 1]
for row in rows:
Row.set_relative_path(row, common_prefix, outputPath)
# Ugly because this overwrites the entries in the attributes of RunSetResult,
# but we don't need them anymore and this is the easiest way
format_run_set_attributes_nicely(runSetResults)
data = types.SimpleNamespace(
run_sets=runSetResults,
relevant_id_columns=select_relevant_id_columns(rows),
output_path=outputPath,
common_prefix=common_prefix,
options=options,
)
futures = []
def write_table(table_type, title, rows, use_local_summary):
local_data = types.SimpleNamespace(title=title, rows=rows)
# calculate statistics if necessary
if not options.format == ["csv"]:
local_data.stats = compute_stats(
rows, runSetResults, use_local_summary, options.correct_only
)
for template_format in options.format or TEMPLATE_FORMATS:
if outputFilePattern == "-":
outfile = None
logging.info(
"Writing %s to stdout...", template_format.upper().ljust(4)
)
else:
outfile = os.path.join(
outputPath,
outputFilePattern.format(
name=name, type=table_type, ext=template_format
),
)
logging.info(
"Writing %s into %s ...", template_format.upper().ljust(4), outfile
)
futures.append(
parallel.submit(
write_table_in_format,
template_format,
outfile,
**data.__dict__,
**local_data.__dict__,
)
)
# write normal tables
write_table(
"table",
name,
rows,
use_local_summary=(not options.correct_only and not options.common),
)
# write difference tables
if rowsDiff:
write_table("diff", name + " differences", rowsDiff, use_local_summary=False)
return futures
def write_csv_table(
out, run_sets, rows, common_prefix, relevant_id_columns, sep="\t", **kwargs
):
num_id_columns = relevant_id_columns[1:].count(True)
def write_head_line(
name, values, value_repetitions=itertools.repeat(1) # noqa: B008
):
if any(values):
# name may contain paths, so standardize the output across OSs
out.write(util.fix_path_if_on_windows(name))
for i in range(num_id_columns): # noqa: B007
out.write(sep)
for value, count in zip(values, value_repetitions):
for i in range(count): # noqa: B007
out.write(sep)
if value:
out.write(value)
out.write("\n")
write_head_line(
"tool",
["{tool} {version}".format_map(run_set.attributes) for run_set in run_sets],
[len(run_set.columns) for run_set in run_sets],
)
write_head_line(
"run set",
[run_set.attributes.get("niceName") for run_set in run_sets],
[len(run_set.columns) for run_set in run_sets],
)
write_head_line(
common_prefix,
[column.format_title() for run_set in run_sets for column in run_set.columns],
)
for row in rows:
# row.short_filename may contain paths, so standardize the output across OSs
out.write(util.fix_path_if_on_windows(row.short_filename))
for row_id, is_relevant in zip(row.id[1:], relevant_id_columns[1:]):
if is_relevant:
out.write(sep)
if row_id is not None:
out.write(str(row_id))
for run_result in row.results:
for value, column in zip(run_result.values, run_result.columns):
out.write(sep)
out.write(column.format_value(value or "", False, "csv"))
out.write("\n")
def write_table_in_format(template_format, outfile, options, **kwargs):
callback = {"csv": write_csv_table, "html": htmltable.write_html_table}[
template_format
]
if outfile:
# Force HTML file to be UTF-8 regardless of system encoding because it actually
# declares itself to be UTF-8 in a meta tag.
encoding = "utf-8" if template_format == "html" else None
with open(outfile, "w", encoding=encoding) as out:
callback(out, options=options, **kwargs)
if options.show_table and template_format == "html":
try:
subprocess.Popen(
["xdg-open", outfile],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except OSError:
pass
else:
callback(sys.stdout, options=options, **kwargs)
def basename_without_ending(file):
name = os.path.basename(file)
if name.endswith(".xml"):
name = name[:-4]
elif name.endswith(".xml.gz"):
name = name[:-7]
elif name.endswith(".xml.bz2"):
name = name[:-8]
return name
def create_argument_parser():
parser = argparse.ArgumentParser(
fromfile_prefix_chars="@",
description="""Create tables with the results of one or more benchmark executions.
Command-line parameters can additionally be read from a file if file name prefixed with '@' is given as argument.
Part of BenchExec: https://github.com/sosy-lab/benchexec/""",
)
parser.add_argument(
"tables",
metavar="RESULT",
type=str,
nargs="*",
help="XML file with the results from the benchmark script",
)
parser.add_argument(
"-x",
"--xml",
action="store",
type=str,
dest="xmltablefile",
help="XML file with the table definition.",
)
parser.add_argument(
"-o",
"--outputpath",
action="store",
type=str,
dest="outputPath",
help="Output path for the tables. If '-', the tables are written to stdout.",
)
parser.add_argument(
"-n",
"--name",
action="store",
type=str,
dest="output_name",
help="Base name of the created output files.",
)
parser.add_argument(
"--ignore-erroneous-benchmarks",
action="store_true",
dest="ignore_errors",
help="Ignore incomplete result files or results where the was an error during benchmarking.",
)
parser.add_argument(
"-d",
"--dump",
action="store_true",
dest="dump_counts",
help="Print summary statistics for regressions and the good, bad, and unknown counts.",
)
parser.add_argument(
"--ignore-flapping-timeout-regressions",
action="store_true",
dest="ignoreFlappingTimeouts",
help="For the regression-count statistics, do not count regressions to timeouts if the file already had timeouts before.",
)
parser.add_argument(
"-f",
"--format",
action="append",
choices=TEMPLATE_FORMATS,
help="Which format to generate (HTML or CSV). Can be specified multiple times. If not specified, all are generated.",
)
parser.add_argument(
"-c",
"--common",
action="store_true",
dest="common",
help="Put only rows into the table for which all benchmarks contain results.",
)
parser.add_argument(
"--no-diff",
action="store_false",
dest="write_diff_table",
help="Do not output a table with result differences between benchmarks.",
)
parser.add_argument(
"--correct-only",
action="store_true",
dest="correct_only",
help="Clear all results (e.g., time) in cases where the result was not correct.",
)
parser.add_argument(
"--all-columns",
action="store_true",
dest="all_columns",
help="Show all columns in tables, including those that are normally hidden.",
)
parser.add_argument(
"--show",
action="store_true",
dest="show_table",
help="Open the produced HTML table(s) in the default browser.",
)
parser.add_argument(
"-q",
"--quiet",
action="store_true",
help="Do not show informational messages, only warnings.",
)
parser.add_argument(
"--version", action="version", version="%(prog)s " + __version__
)
return parser
def sigint_handler(*args, **kwargs):
# Use SystemExit instead of KeyboardInterrupt to avoid ugly stack traces for each worker
sys.exit(1)
def main(args=None):
if sys.version_info < (3,):
sys.exit("table-generator needs Python 3 to run.")
signal.signal(signal.SIGINT, sigint_handler)
arg_parser = create_argument_parser()
options = arg_parser.parse_args((args or sys.argv)[1:])
benchexec.util.setup_logging(
fmt="%(levelname)s: %(message)s",
level=logging.WARNING if options.quiet else logging.INFO,
)
global parallel
import concurrent.futures
cpu_count = 1
try:
cpu_count = os.cpu_count() or 1
except AttributeError:
pass
# Use up to cpu_count*2 workers because some tasks are I/O bound.
parallel = concurrent.futures.ProcessPoolExecutor(max_workers=cpu_count * 2)
name = options.output_name
outputPath = options.outputPath
if outputPath == "-":
# write to stdout
outputFilePattern = "-"
outputPath = "."
else:
outputFilePattern = "{name}.{type}.{ext}"
if options.xmltablefile:
try:
table_definition = parse_table_definition_file(options.xmltablefile)
if table_definition_lists_result_files(table_definition):
if options.tables:
arg_parser.error(
"Invalid additional arguments '{}'.".format(
" ".join(options.tables)
)
)
runSetResults = load_results_from_table_definition(
table_definition, options.xmltablefile, options
)
else:
if not options.tables:
arg_parser.error(
"No result files given. Either list them on the command line "
"or with <result> tags in the table-definiton file."
)
result_files = util.extend_file_list(options.tables) # expand wildcards
runSetResults = load_results_with_table_definition(
result_files, table_definition, options.xmltablefile, options
)
except util.TableDefinitionError as e:
handle_error("Fault in %s: %s", options.xmltablefile, e)
if not name:
name = basename_without_ending(options.xmltablefile)
if not outputPath:
outputPath = os.path.dirname(options.xmltablefile)
else:
if options.tables:
inputFiles = options.tables
else:
searchDir = outputPath or DEFAULT_OUTPUT_PATH
logging.info("Searching result files in '%s'...", searchDir)
inputFiles = [os.path.join(searchDir, "*.results*.xml")]
inputFiles = util.extend_file_list(inputFiles) # expand wildcards
runSetResults = load_results(inputFiles, options)
if len(inputFiles) == 1:
if not name:
name = basename_without_ending(inputFiles[0])
if not outputFilePattern == "-":
outputFilePattern = "{name}.{ext}"
else:
if not name:
timestamp = time.strftime(
benchexec.util.TIMESTAMP_FILENAME_FORMAT, time.localtime()
)
name = NAME_START + "." + timestamp
if inputFiles and not outputPath:
path = os.path.dirname(inputFiles[0])
if "://" not in path and all(
path == os.path.dirname(file) for file in inputFiles
):
outputPath = path
else:
outputPath = DEFAULT_OUTPUT_PATH
if not outputPath:
outputPath = "."
runSetResults = [r for r in runSetResults if r is not None]
if not runSetResults:
handle_error("No benchmark results found.")
logging.info("Merging results...")
if options.common:
find_common_tasks(runSetResults)
else:
# merge list of run sets, so that all run sets contain the same tasks
merge_tasks(runSetResults)
rows = get_rows(runSetResults)
if not rows:
handle_error("No results found, no tables produced.")
rowsDiff = filter_rows_with_differences(rows) if options.write_diff_table else []
logging.info("Generating table...")
if not os.path.isdir(outputPath) and not outputFilePattern == "-":
os.makedirs(outputPath)
futures = create_tables(
name, runSetResults, rows, rowsDiff, outputPath, outputFilePattern, options
)
if options.dump_counts: # print some stats for Buildbot
print(
"REGRESSIONS {}".format(
get_regression_count(rows, options.ignoreFlappingTimeouts)
)
)
countsList = get_counts(rows)
print("STATS")
for counts in countsList:
print(" ".join(str(e) for e in counts))
for f in futures:
f.result() # to get any exceptions that may have occurred
logging.info("done")
parallel.shutdown(wait=True)
if __name__ == "__main__":
sys.exit(main())
|
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 <NAME> <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import argparse
import bz2
import collections
import copy
import functools
import gzip
import io
import itertools
import logging
import os.path
import signal
import subprocess
import sys
import time
import types
import urllib.parse
import urllib.request
from xml.etree import ElementTree
from benchexec import __version__, BenchExecException
import benchexec.model as model
import benchexec.result as result
import benchexec.tooladapter as tooladapter
import benchexec.util
from benchexec.tablegenerator import htmltable, statistics, util
from benchexec.tablegenerator.columns import Column
from benchexec.tablegenerator.util import TaskId
import zipfile
# Process pool for parallel work.
# Some of our loops are CPU-bound (e.g., statistics calculations), thus we use
# processes, not threads.
# Fully initialized only in main() because we cannot do so in the worker processes.
parallel = util.DummyExecutor()
# Most important columns that should be shown first in tables (in the given order)
MAIN_COLUMNS = [
Column("status"),
Column("category"),
Column("cputime"),
Column("walltime"),
Column("memory", unit="MB", source_unit="B"),
Column(
"memUsage", display_title="memory", unit="MB", source_unit="B"
), # if old results are given
Column("cpuenergy"),
]
NAME_START = "results" # first part of filename of table
DEFAULT_OUTPUT_PATH = "results/"
TEMPLATE_FORMATS = ["html", "csv"]
_BYTE_FACTOR = 1000 # bytes in a kilobyte
UNIT_CONVERSION = {
"s": {"ms": 1000, "min": 1.0 / 60, "h": 1.0 / 3600},
"B": {"kB": 1.0 / 10 ** 3, "MB": 1.0 / 10 ** 6, "GB": 1.0 / 10 ** 9},
"J": {
"kJ": 1.0 / 10 ** 3,
"Ws": 1,
"kWs": 1.0 / 1000,
"Wh": 1.0 / 3600,
"kWh": 1.0 / (1000 * 3600),
"mWh": 1.0 / (1000 * 1000 * 3600),
},
}
def handle_error(message, *args):
"""Log error message and terminate program."""
logging.error(message, *args)
exit(1)
def parse_table_definition_file(file):
"""
Read an parse the XML of a table-definition file.
@return: an ElementTree object for the table definition
"""
logging.info("Reading table definition from '%s'...", file)
if not os.path.isfile(file):
handle_error("File '%s' does not exist.", file)
try:
tableGenFile = ElementTree.ElementTree().parse(file)
except OSError as e:
handle_error("Could not read result file %s: %s", file, e)
except ElementTree.ParseError as e:
handle_error("Table file %s is invalid: %s", file, e)
if "table" != tableGenFile.tag:
handle_error(
"Table file %s is invalid: It's root element is not named 'table'.", file
)
return tableGenFile
def table_definition_lists_result_files(table_definition):
return any(tag.tag in ["result", "union"] for tag in table_definition)
def load_results_from_table_definition(
table_definition, table_definition_file, options
):
"""
Load all results in files that are listed in the given table-definition file.
@return: a list of RunSetResult objects
"""
default_columns = extract_columns_from_table_definition_file(
table_definition, table_definition_file
)
columns_relevant_for_diff = _get_columns_relevant_for_diff(default_columns)
results = []
for tag in table_definition:
if tag.tag == "result":
columns = (
extract_columns_from_table_definition_file(tag, table_definition_file)
or default_columns
)
run_set_id = tag.get("id")
for resultsFile in get_file_list_from_result_tag(
tag, table_definition_file
):
results.append(
parallel.submit(
load_result,
resultsFile,
options,
run_set_id,
columns,
columns_relevant_for_diff,
)
)
elif tag.tag == "union":
results.append(
parallel.submit(
handle_union_tag,
tag,
table_definition_file,
options,
default_columns,
columns_relevant_for_diff,
)
)
return [future.result() for future in results]
def handle_union_tag(
tag, table_definition_file, options, default_columns, columns_relevant_for_diff
):
columns = (
extract_columns_from_table_definition_file(tag, table_definition_file)
or default_columns
)
result = RunSetResult([], collections.defaultdict(list), columns)
all_result_files = set()
for resultTag in tag.findall("result"):
if extract_columns_from_table_definition_file(resultTag, table_definition_file):
logging.warning(
"<result> tags within <union> tags may not contain <column> tags, "
"these column declarations will be ignored. Please move them to the <union> tag."
)
run_set_id = resultTag.get("id")
for resultsFile in get_file_list_from_result_tag(
resultTag, table_definition_file
):
if resultsFile in all_result_files:
handle_error("File '%s' included twice in <union> tag", resultsFile)
all_result_files.add(resultsFile)
result_xml = parse_results_file(resultsFile, run_set_id)
if result_xml is not None:
result.append(resultsFile, result_xml, options.all_columns)
if not result._xml_results:
return None
name = tag.get("name")
if name:
logging.warning(
"Attribute 'name' for <union> tags is deprecated, use 'title' instead."
)
name = tag.get("title", name)
if name:
result.attributes["name"] = [name]
result.collect_data(options.correct_only)
return result
def get_file_list_from_result_tag(result_tag, table_definition_file):
if "filename" not in result_tag.attrib:
logging.warning(
"Result tag without filename attribute in file '%s'.", table_definition_file
)
return []
# expand wildcards
return util.get_file_list(
os.path.join(os.path.dirname(table_definition_file), result_tag.get("filename"))
)
def load_results_with_table_definition(
result_files, table_definition, table_definition_file, options
):
"""
Load results from given files with column definitions taken from a table-definition file.
@return: a list of RunSetResult objects
"""
columns = extract_columns_from_table_definition_file(
table_definition, table_definition_file
)
columns_relevant_for_diff = _get_columns_relevant_for_diff(columns)
return load_results(
result_files,
options=options,
columns=columns,
columns_relevant_for_diff=columns_relevant_for_diff,
)
def extract_columns_from_table_definition_file(xmltag, table_definition_file):
"""
Extract all columns mentioned in the result tag of a table definition file.
"""
def handle_path(path):
"""Convert path from a path relative to table-definition file."""
if not path or path.startswith("http://") or path.startswith("https://"):
return path
return os.path.join(os.path.dirname(table_definition_file), path)
columns = []
for c in xmltag.findall("column"):
scale_factor = c.get("scaleFactor")
display_unit = c.get("displayUnit")
source_unit = c.get("sourceUnit")
new_column = Column(
c.get("title"),
c.text,
c.get("numberOfDigits"),
handle_path(c.get("href")),
None,
display_unit,
source_unit,
scale_factor,
c.get("relevantForDiff"),
c.get("displayTitle"),
)
columns.append(new_column)
return columns
def _get_columns_relevant_for_diff(columns_to_show):
"""
Extract columns that are relevant for the diff table.
@param columns_to_show: (list) A list of columns that should be shown
@return: (set) Set of columns that are relevant for the diff table. If
none is marked relevant, the column named "status" will be
returned in the set.
"""
cols = {col.title for col in columns_to_show if col.relevant_for_diff}
if len(cols) == 0:
return {col.title for col in columns_to_show if col.title == "status"}
else:
return cols
def normalize_path(path, base_path_or_url):
"""Returns a normalized form of path, interpreted relative to base_path_or_url"""
if util.is_url(base_path_or_url):
return urllib.parse.urljoin(base_path_or_url, path)
else:
return os.path.normpath(os.path.join(os.path.dirname(base_path_or_url), path))
loaded_tools = {}
def load_tool(result):
"""
Load the module with the tool-specific code.
"""
def load_tool_module(tool_module):
if not tool_module:
logging.warning(
"Cannot extract values from log files for benchmark results %s "
'(missing attribute "toolmodule" on tag "result").',
util.prettylist(result.attributes["name"]),
)
return None
try:
logging.debug("Loading %s", tool_module)
tool = __import__(tool_module, fromlist=["Tool"]).Tool()
return tooladapter.adapt_to_current_version(tool)
except ImportError as ie:
logging.warning(
'Missing module "%s", cannot extract values from log files (ImportError: %s).',
tool_module,
ie,
)
except AttributeError:
logging.warning(
'The module "%s" does not define the necessary class Tool, '
"cannot extract values from log files.",
tool_module,
)
except TypeError as te:
logging.warning(
'Unsupported module "%s", cannot extract values from log files '
"(TypeError: %s).",
tool_module,
te,
)
return None
tool_module = (
result.attributes["toolmodule"][0]
if "toolmodule" in result.attributes
else None
)
if tool_module in loaded_tools:
return loaded_tools[tool_module]
else:
result = load_tool_module(tool_module)
loaded_tools[tool_module] = result
return result
class RunSetResult(object):
"""
The Class RunSetResult contains all the results of one execution of a run set:
the sourcefiles tags (with sourcefiles + values), the columns to show
and the benchmark attributes.
"""
def __init__(
self,
xml_results,
attributes,
columns,
summary={},
columns_relevant_for_diff=set(),
):
self._xml_results = xml_results
self.attributes = attributes
# Copy the columns since they may be modified
self.columns = copy.deepcopy(columns)
self.summary = summary
self.columns_relevant_for_diff = columns_relevant_for_diff
def get_tasks(self):
"""
Return the list of task ids for these results.
May be called only after collect_data()
"""
return [r.task_id for r in self.results]
def append(self, resultFile, resultElem, all_columns=False):
"""
Append the result for one run. Needs to be called before collect_data().
"""
self._xml_results += [
(result, resultFile) for result in _get_run_tags_from_xml(resultElem)
]
for attrib, values in RunSetResult._extract_attributes_from_result(
resultFile, resultElem
).items():
self.attributes[attrib].extend(values)
if not self.columns:
self.columns = RunSetResult._extract_existing_columns_from_result(
resultFile, resultElem, all_columns
)
def collect_data(self, correct_only):
"""
Load the actual result values from the XML file and the log files.
This may take some time if many log files have to be opened and parsed.
"""
self.results = []
def get_value_from_logfile(lines, identifier):
"""
This method searches for values in lines of the content.
It uses a tool-specific method to so.
"""
output = tooladapter.CURRENT_BASETOOL.RunOutput(lines)
return load_tool(self).get_value_from_output(output, identifier)
# Opening the ZIP archive with the logs for every run is too slow, we cache it.
log_zip_cache = {}
try:
for xml_result, result_file in self._xml_results:
self.results.append(
RunResult.create_from_xml(
xml_result,
get_value_from_logfile,
self.columns,
correct_only,
log_zip_cache,
self.columns_relevant_for_diff,
result_file,
)
)
finally:
for file in log_zip_cache.values():
file.close()
for column in self.columns:
column_values = (
run_result.values[run_result.columns.index(column)]
for run_result in self.results
)
column.set_column_type_from(column_values)
del self._xml_results
def __str__(self):
return util.prettylist(self.attributes["filename"])
@staticmethod
def create_from_xml(
resultFile,
resultElem,
columns=None,
all_columns=False,
columns_relevant_for_diff=set(),
):
"""
This function extracts everything necessary for creating a RunSetResult object
from the "result" XML tag of a benchmark result file.
It returns a RunSetResult object, which is not yet fully initialized.
To finish initializing the object, call collect_data()
before using it for anything else
(this is to separate the possibly costly collect_data() call from object instantiation).
"""
attributes = RunSetResult._extract_attributes_from_result(
resultFile, resultElem
)
if not columns:
columns = RunSetResult._extract_existing_columns_from_result(
resultFile, resultElem, all_columns
)
summary = RunSetResult._extract_summary_from_result(resultElem, columns)
return RunSetResult(
[(result, resultFile) for result in _get_run_tags_from_xml(resultElem)],
attributes,
columns,
summary,
columns_relevant_for_diff,
)
@staticmethod
def _extract_existing_columns_from_result(resultFile, resultElem, all_columns):
run_results = _get_run_tags_from_xml(resultElem)
if not run_results:
logging.warning("Result file '%s' is empty.", resultFile)
return []
else: # show all available columns
column_names = {
c.get("title")
for s in run_results
for c in s.findall("column")
if all_columns or c.get("hidden") != "true"
}
if not column_names:
# completely empty results break stuff, add at least status column
return [MAIN_COLUMNS[0]]
# Put main columns first, then rest sorted alphabetically
custom_columns = column_names.difference(
column.title for column in MAIN_COLUMNS
)
return [
column for column in MAIN_COLUMNS if column.title in column_names
] + [Column(title) for title in sorted(custom_columns)]
@staticmethod
def _extract_attributes_from_result(resultFile, resultTag):
attributes = collections.defaultdict(list)
# Defaults
attributes["filename"] = [resultFile]
attributes["branch"] = [
os.path.basename(resultFile).split("#")[0] if "#" in resultFile else ""
]
attributes["timelimit"] = ["-"]
attributes["memlimit"] = ["-"]
attributes["cpuCores"] = ["-"]
attributes["displayName"] = []
# Update with real values
for attrib, value in resultTag.attrib.items():
attributes[attrib] = [value]
# Add system information if present
for systemTag in sorted(
resultTag.findall("systeminfo"),
key=lambda systemTag: systemTag.get("hostname", "unknown"),
):
cpuTag = systemTag.find("cpu")
attributes["os"].append(systemTag.find("os").get("name"))
attributes["cpu"].append(cpuTag.get("model"))
attributes["cores"].append(cpuTag.get("cores"))
attributes["freq"].append(cpuTag.get("frequency"))
attributes["turbo"].append(cpuTag.get("turboboostActive"))
attributes["ram"].append(systemTag.find("ram").get("size"))
attributes["host"].append(systemTag.get("hostname", "unknown"))
return attributes
@staticmethod
def _extract_summary_from_result(resultTag, columns):
summary = collections.defaultdict(list)
# Add summary for columns if present
for column in resultTag.findall("column"):
title = column.get("title")
if title in (c.title for c in columns):
summary[title] = column.get("value")
return summary
def _get_run_tags_from_xml(result_elem):
# Here we keep support for <sourcefile> in order to be able to read old benchmark
# results (no reason to forbid this).
return result_elem.findall("run") + result_elem.findall("sourcefile")
def load_results(
result_files,
options,
run_set_id=None,
columns=None,
columns_relevant_for_diff=set(),
):
"""Version of load_result for multiple input files that will be loaded concurrently."""
return parallel.map(
load_result,
result_files,
itertools.repeat(options),
itertools.repeat(run_set_id),
itertools.repeat(columns),
itertools.repeat(columns_relevant_for_diff),
)
def load_result(
result_file, options, run_set_id=None, columns=None, columns_relevant_for_diff=set()
):
"""
Completely handle loading a single result file.
@param result_file the file to parse
@param options additional options
@param run_set_id the identifier of the run set
@param columns the list of columns
@param columns_relevant_for_diff a set of columns that is relevant for
the diff table
@return a fully ready RunSetResult instance or None
"""
xml = parse_results_file(
result_file, run_set_id=run_set_id, ignore_errors=options.ignore_errors
)
if xml is None:
return None
result = RunSetResult.create_from_xml(
result_file,
xml,
columns=columns,
all_columns=options.all_columns,
columns_relevant_for_diff=columns_relevant_for_diff,
)
result.collect_data(options.correct_only)
return result
def parse_results_file(resultFile, run_set_id=None, ignore_errors=False):
"""
This function parses an XML file that contains the results of the execution of a run set.
It returns the "result" XML tag.
@param resultFile: The file name of the XML file that contains the results.
@param run_set_id: An optional identifier of this set of results.
"""
logging.info(" %s", resultFile)
url = util.make_url(resultFile)
parse = ElementTree.ElementTree().parse
try:
with util.open_url_seekable(url, mode="rb") as f:
try:
try:
resultElem = parse(gzip.GzipFile(fileobj=f))
except OSError:
f.seek(0)
resultElem = parse(bz2.BZ2File(f))
except OSError:
f.seek(0)
resultElem = parse(f)
except OSError as e:
handle_error("Could not read result file %s: %s", resultFile, e)
except ElementTree.ParseError as e:
handle_error("Result file %s is invalid: %s", resultFile, e)
if resultElem.tag not in ["result", "test"]:
handle_error(
"XML file with benchmark results seems to be invalid.\n"
"The root element of the file is not named 'result' or 'test'.\n"
"If you want to run a table-definition file,\n"
"you should use the option '-x' or '--xml'."
)
if ignore_errors and "error" in resultElem.attrib:
logging.warning(
'Ignoring file "%s" because of error: %s',
resultFile,
resultElem.attrib["error"],
)
return None
if run_set_id is not None:
for sourcefile in _get_run_tags_from_xml(resultElem):
sourcefile.set("runset", run_set_id)
insert_logfile_names(resultFile, resultElem)
return resultElem
def insert_logfile_names(resultFile, resultElem):
# get folder of logfiles (truncate end of XML file name and append .logfiles instead)
log_folder = resultFile[0 : resultFile.rfind(".results.")] + ".logfiles/"
# append begin of filename
runSetName = resultElem.get("name")
if runSetName is not None:
blockname = resultElem.get("block")
if blockname is None:
log_folder += runSetName + "."
elif blockname == runSetName:
pass # real runSetName is empty
else:
assert runSetName.endswith("." + blockname)
runSetName = runSetName[: -(1 + len(blockname))] # remove last chars
log_folder += runSetName + "."
# for each file: append original filename and insert log_file_name into sourcefileElement
for sourcefile in _get_run_tags_from_xml(resultElem):
if "logfile" in sourcefile.attrib:
log_file = urllib.parse.urljoin(resultFile, sourcefile.get("logfile"))
else:
log_file = log_folder + os.path.basename(sourcefile.get("name")) + ".log"
sourcefile.set("logfile", log_file)
def merge_tasks(runset_results):
"""
This function merges the results of all RunSetResult objects.
If necessary, it can merge lists of names: [A,C] + [A,B] --> [A,B,C]
and add dummy elements to the results.
It also ensures the same order of tasks.
"""
task_list = []
task_set = set()
for runset in runset_results:
index = -1
currentresult_taskset = set()
for task in runset.get_tasks():
if task in currentresult_taskset:
logging.warning(
"Task %s is present twice in '%s', skipping it.", task, runset
)
else:
currentresult_taskset.add(task)
if task not in task_set:
task_list.insert(index + 1, task)
task_set.add(task)
index += 1
else:
index = task_list.index(task)
merge_task_lists(runset_results, task_list)
def merge_task_lists(runset_results, tasks):
"""
Set the filelists of all RunSetResult elements so that they contain the same files
in the same order. For missing files a dummy element is inserted.
"""
for runset in runset_results:
# create mapping from id to RunResult object
# Use reversed list such that the first instance of equal tasks end up in dic
dic = {
run_result.task_id: run_result for run_result in reversed(runset.results)
}
runset.results = [] # clear and repopulate results
for task in tasks:
run_result = dic.get(task)
if run_result is None:
logging.info(" No result for task %s in '%s'.", task, runset)
# create an empty dummy element
run_result = RunResult(
task,
None,
"empty", # special category for tables
None,
None,
runset.columns,
[None] * len(runset.columns),
)
runset.results.append(run_result)
def find_common_tasks(runset_results):
tasks_in_first_runset = runset_results[0].get_tasks()
task_set = set(tasks_in_first_runset)
for runset_result in runset_results:
task_set = task_set & set(runset_result.get_tasks())
task_list = []
if not task_set:
logging.warning("No tasks are present in all benchmark results.")
else:
task_list = [task for task in tasks_in_first_runset if task in task_set]
merge_task_lists(runset_results, task_list)
class RunResult(object):
"""
The class RunResult contains the results of a single verification run.
"""
def __init__(
self,
task_id,
status,
category,
score,
log_file,
columns,
values,
columns_relevant_for_diff=set(),
sourcefiles_exist=True,
):
assert len(columns) == len(values)
self.task_id = task_id
self.sourcefiles_exist = sourcefiles_exist
self.status = status
self.log_file = log_file
self.columns = columns
self.values = values
self.category = category
self.score = score
self.columns_relevant_for_diff = columns_relevant_for_diff
@staticmethod
def create_from_xml(
sourcefileTag,
get_value_from_logfile,
listOfColumns,
correct_only,
log_zip_cache,
columns_relevant_for_diff,
result_file_or_url,
):
"""
This function collects the values from one run.
Only columns that should be part of the table are collected.
"""
def read_logfile_lines(log_file):
if not log_file:
return []
log_file_url = util.make_url(log_file)
url_parts = urllib.parse.urlparse(log_file_url, allow_fragments=False)
log_zip_path = os.path.dirname(url_parts.path) + ".zip"
log_zip_url = urllib.parse.urlunparse(
(
url_parts.scheme,
url_parts.netloc,
log_zip_path,
url_parts.params,
url_parts.query,
url_parts.fragment,
)
)
path_in_zip = urllib.parse.unquote(
# os.path.relpath creates os-dependant paths, but windows separators can produce errors with zipfile lib
util.fix_path_if_on_windows(
os.path.relpath(url_parts.path, os.path.dirname(log_zip_path))
)
)
if log_zip_url.startswith("file:///") and not log_zip_path.startswith("/"):
# Replace file:/// with file: for relative paths,
# otherwise opening fails.
log_zip_url = "file:" + log_zip_url[8:]
try:
with util.open_url_seekable(log_file_url, "rt") as logfile:
return logfile.readlines()
except OSError:
try:
if log_zip_url not in log_zip_cache:
log_zip_cache[log_zip_url] = zipfile.ZipFile(
util.open_url_seekable(log_zip_url, "rb")
)
log_zip = log_zip_cache[log_zip_url]
try:
with io.TextIOWrapper(log_zip.open(path_in_zip)) as logfile:
return logfile.readlines()
except KeyError:
logging.warning(
"Could not find logfile '%s' in archive '%s'.",
log_file,
log_zip_url,
)
return []
except OSError:
logging.warning(
"Could not find logfile '%s' nor log archive '%s'.",
log_file,
log_zip_url,
)
return []
sourcefiles = sourcefileTag.get("files")
if sourcefiles:
if not sourcefiles.startswith("["):
raise AssertionError("Unknown format for files tag:")
sourcefiles_exist = any(s.strip() for s in sourcefiles[1:-1].split(","))
else:
sourcefiles_exist = False
task_name = sourcefileTag.get("name")
if sourcefiles_exist:
# task_name is a path
task_name = normalize_path(task_name, result_file_or_url)
prop, expected_result = get_property_of_task(
task_name,
result_file_or_url,
sourcefileTag.get("properties"),
sourcefileTag.get("propertyFile"),
sourcefileTag.get("expectedVerdict"),
)
task_id = TaskId(task_name, prop, expected_result, sourcefileTag.get("runset"))
status = util.get_column_value(sourcefileTag, "status", "")
category = util.get_column_value(sourcefileTag, "category")
if not category:
if status: # only category missing
category = result.CATEGORY_MISSING
else: # probably everything is missing, special category for tables
category = "aborted"
score = None
if prop:
score = prop.compute_score(category, status)
logfileLines = None
values = []
for column in listOfColumns: # for all columns that should be shown
value = None # default value
if column.title.lower() == "status":
value = status
elif not correct_only or category == result.CATEGORY_CORRECT:
if not column.pattern or column.href:
# collect values from XML
value = util.get_column_value(sourcefileTag, column.title)
else: # collect values from logfile
if logfileLines is None: # cache content
logfileLines = read_logfile_lines(sourcefileTag.get("logfile"))
value = get_value_from_logfile(logfileLines, column.pattern)
if column.title.lower() == "score" and value is None and score is not None:
# If no score column exists in the xml, take the internally computed score,
# if available
value = str(score)
values.append(value)
return RunResult(
task_id,
status,
category,
score,
sourcefileTag.get("logfile"),
listOfColumns,
values,
columns_relevant_for_diff,
sourcefiles_exist=sourcefiles_exist,
)
class Row(object):
"""
The class Row contains all the results for one sourcefile (a list of RunResult instances).
It is identified by the name of the source file and optional additional data
(such as the property).
It corresponds to one complete row in the final tables.
"""
def __init__(self, results):
assert results
self.results = results
self.id = results[0].task_id
self.has_sourcefile = results[0].sourcefiles_exist
assert (
len({r.task_id for r in results}) == 1
), "not all results are for same task"
def set_relative_path(self, common_prefix, base_dir):
"""
generate output representation of rows
"""
self.short_filename = self.id.name.replace(common_prefix, "", 1)
def get_property_of_task(
task_name, base_path, property_string, property_file, expected_result
):
if property_string is None:
return (None, None)
if property_file:
property_file = normalize_path(property_file, base_path)
try:
prop = result.Property.create(property_file)
except OSError as e:
logging.debug("Cannot read property file %s: %s", property_file, e)
prop = result.Property(property_file, False, property_string)
if expected_result is not None:
expected_result = result.ExpectedResult.from_str(expected_result)
return (prop, expected_result)
if task_name.endswith(".yml"):
# try to find property file of task and create Property object
try:
task_template = model.load_task_definition_file(task_name)
for prop_dict in task_template.get("properties", []):
if "property_file" in prop_dict:
expanded = benchexec.util.expand_filename_pattern(
prop_dict["property_file"], os.path.dirname(task_name)
)
if len(expanded) == 1:
prop = result.Property.create(expanded[0])
if prop.name == property_string:
expected_result = prop_dict.get("expected_verdict")
if isinstance(expected_result, bool):
expected_result = result.ExpectedResult(
expected_result, prop_dict.get("subproperty")
)
else:
expected_result = None
return (prop, expected_result)
except BenchExecException as e:
logging.debug("Could not load task-template file %s: %s", task_name, e)
return (result.Property(None, False, property_string), None)
def rows_to_columns(rows):
"""
Convert a list of Rows into a column-wise list of list of RunResult
"""
return zip(*[row.results for row in rows])
def get_rows(runSetResults):
"""
Create list of rows with all data. Each row consists of several RunResults.
"""
rows = []
for task_results in zip(*[runset.results for runset in runSetResults]):
rows.append(Row(task_results))
return rows
def filter_rows_with_differences(rows):
"""
Find all rows with differences in the status column.
"""
if not rows:
# empty table
return []
if len(rows[0].results) == 1:
# table with single column
return []
def get_index_of_column(name, cols):
assert cols, "Cannot look for column '{}' in empy column list".format(name)
for i in range(0, len(cols)):
if cols[i].title == name:
return i
assert False, "Column '{}' not found in columns '{}'".format(name, cols)
def all_equal_result(listOfResults):
relevant_columns = set()
for res in listOfResults:
for relevant_column in res.columns_relevant_for_diff:
relevant_columns.add(relevant_column)
if len(relevant_columns) == 0:
relevant_columns.add("status")
status = []
for col in relevant_columns:
# It's necessary to search for the index of a column every time
# because they can differ between results
status.append(
{
res.values[get_index_of_column(col, res.columns)]
for res in listOfResults
if res.values
}
)
return functools.reduce(lambda x, y: x and (len(y) <= 1), status, True)
rowsDiff = [row for row in rows if not all_equal_result(row.results)]
if len(rowsDiff) == 0:
logging.info("---> NO DIFFERENCE FOUND IN SELECTED COLUMNS")
elif len(rowsDiff) == len(rows):
logging.info(
"---> DIFFERENCES FOUND IN ALL ROWS, NO NEED TO CREATE DIFFERENCE TABLE"
)
return []
return rowsDiff
def format_run_set_attributes_nicely(runSetResults):
"""Replace the attributes of each RunSetResult with nicely formatted strings."""
for runSetResult in runSetResults:
for key in runSetResult.attributes:
values = runSetResult.attributes[key]
if key == "turbo":
turbo_values = list(set(values))
if len(turbo_values) > 1:
turbo = "mixed"
elif turbo_values[0] == "true":
turbo = "enabled"
elif turbo_values[0] == "false":
turbo = "disabled"
else:
turbo = None
runSetResult.attributes["turbo"] = (
", Turbo Boost: {}".format(turbo) if turbo else ""
)
elif key == "timelimit":
def fix_unit_display(value):
if len(value) >= 2 and value[-1] == "s" and value[-2] != " ":
return value[:-1] + " s"
return value
runSetResult.attributes[key] = util.prettylist(
map(fix_unit_display, values)
)
elif key == "memlimit" or key == "ram":
def round_to_MB(value):
number, unit = util.split_number_and_unit(value)
if unit and unit != "B":
return value
try:
return "{:.0f} MB".format(
int(number) / _BYTE_FACTOR / _BYTE_FACTOR
)
except ValueError:
return value
runSetResult.attributes[key] = util.prettylist(map(round_to_MB, values))
elif key == "freq":
def round_to_MHz(value):
number, unit = util.split_number_and_unit(value)
if unit and unit != "Hz":
return value
try:
return "{:.0f} MHz".format(int(number) / 1000 / 1000)
except ValueError:
return value
runSetResult.attributes[key] = util.prettylist(
map(round_to_MHz, values)
)
elif key == "host":
runSetResult.attributes[key] = util.prettylist(
util.merge_entries_with_common_prefixes(values)
)
else:
runSetResult.attributes[key] = util.prettylist(values)
# compute nice name of each run set for displaying
firstBenchmarkName = runSetResults[0].attributes["benchmarkname"]
allBenchmarkNamesEqual = all(
r.attributes["benchmarkname"] == firstBenchmarkName for r in runSetResults
)
for runSetResult in runSetResults:
benchmarkName = runSetResult.attributes["benchmarkname"]
name = runSetResult.attributes["name"]
if not name:
niceName = benchmarkName
elif allBenchmarkNamesEqual:
niceName = name
else:
niceName = benchmarkName + "." + name
runSetResult.attributes["niceName"] = niceName
def select_relevant_id_columns(rows):
"""
Find out which of the entries in Row.id are equal for all given rows.
@return: A list of True/False values according to whether the i-th part of the id is always equal.
"""
relevant_id_columns = [True] # first column (file name) is always relevant
if rows:
prototype_id = rows[0].id
for column in range(1, len(prototype_id)):
def id_equal_to_prototype(row):
return row.id[column] == prototype_id[column]
relevant_id_columns.append(not all(map(id_equal_to_prototype, rows)))
return relevant_id_columns
def compute_stats(rows, run_set_results, use_local_summary, correct_only):
result_cols = list(rows_to_columns(rows)) # column-wise
all_column_stats = list(
parallel.map(
statistics.get_stats_of_run_set,
result_cols,
[correct_only] * len(result_cols),
)
)
if use_local_summary:
for run_set_result, run_set_stats in zip(run_set_results, all_column_stats):
statistics.add_local_summary_statistics(run_set_result, run_set_stats)
return all_column_stats
def get_regression_count(rows, ignoreFlappingTimeouts): # for options.dump_counts
"""Count the number of regressions, i.e., differences in status of the two right-most results
where the new one is not "better" than the old one.
Any change in status between error, unknown, and wrong result is a regression.
Different kind of errors or wrong results are also a regression.
"""
def status_is(run_result, status):
# startswith is used because status can be "TIMEOUT (TRUE)" etc., which count as "TIMEOUT"
return run_result.status and run_result.status.startswith(status)
def any_status_is(run_results, status):
for run_result in run_results:
if status_is(run_result, status):
return True
return False
regressions = 0
for row in rows:
if len(row.results) < 2:
return 0 # no regressions at all with only one run
# "new" and "old" are the latest two results
new = row.results[-1]
old = row.results[-2]
if new.category == result.CATEGORY_CORRECT:
continue # no regression if result is correct
if new.status == old.status:
continue # no regression if result is the same as before
if status_is(new, "TIMEOUT") and status_is(old, "TIMEOUT"):
continue # no regression if both are some form of timeout
if status_is(new, "OUT OF MEMORY") and status_is(old, "OUT OF MEMORY"):
continue # same for OOM
if (
ignoreFlappingTimeouts
and status_is(new, "TIMEOUT")
and any_status_is(row.results[:-2], "TIMEOUT")
):
continue # flapping timeout because any of the older results is also a timeout
regressions += 1
return regressions
def get_counts(rows): # for options.dump_counts
countsList = []
for runResults in rows_to_columns(rows):
counts = collections.Counter(runResult.category for runResult in runResults)
countsList.append(
(
counts[result.CATEGORY_CORRECT],
counts[result.CATEGORY_WRONG],
counts[result.CATEGORY_UNKNOWN]
+ counts[result.CATEGORY_ERROR]
+ counts[None], # for rows without a result
)
)
return countsList
def create_tables(
name, runSetResults, rows, rowsDiff, outputPath, outputFilePattern, options
):
"""
Create tables and write them to files.
@return a list of futures to allow waiting for completion
"""
# get common folder of sourcefiles
# os.path.commonprefix can return a partial path component (does not truncate on /)
common_prefix = os.path.commonprefix([r.id.name for r in rows])
separator = "/" if "://" in common_prefix else os.sep
common_prefix = common_prefix[: common_prefix.rfind(separator) + 1]
for row in rows:
Row.set_relative_path(row, common_prefix, outputPath)
# Ugly because this overwrites the entries in the attributes of RunSetResult,
# but we don't need them anymore and this is the easiest way
format_run_set_attributes_nicely(runSetResults)
data = types.SimpleNamespace(
run_sets=runSetResults,
relevant_id_columns=select_relevant_id_columns(rows),
output_path=outputPath,
common_prefix=common_prefix,
options=options,
)
futures = []
def write_table(table_type, title, rows, use_local_summary):
local_data = types.SimpleNamespace(title=title, rows=rows)
# calculate statistics if necessary
if not options.format == ["csv"]:
local_data.stats = compute_stats(
rows, runSetResults, use_local_summary, options.correct_only
)
for template_format in options.format or TEMPLATE_FORMATS:
if outputFilePattern == "-":
outfile = None
logging.info(
"Writing %s to stdout...", template_format.upper().ljust(4)
)
else:
outfile = os.path.join(
outputPath,
outputFilePattern.format(
name=name, type=table_type, ext=template_format
),
)
logging.info(
"Writing %s into %s ...", template_format.upper().ljust(4), outfile
)
futures.append(
parallel.submit(
write_table_in_format,
template_format,
outfile,
**data.__dict__,
**local_data.__dict__,
)
)
# write normal tables
write_table(
"table",
name,
rows,
use_local_summary=(not options.correct_only and not options.common),
)
# write difference tables
if rowsDiff:
write_table("diff", name + " differences", rowsDiff, use_local_summary=False)
return futures
def write_csv_table(
out, run_sets, rows, common_prefix, relevant_id_columns, sep="\t", **kwargs
):
num_id_columns = relevant_id_columns[1:].count(True)
def write_head_line(
name, values, value_repetitions=itertools.repeat(1) # noqa: B008
):
if any(values):
# name may contain paths, so standardize the output across OSs
out.write(util.fix_path_if_on_windows(name))
for i in range(num_id_columns): # noqa: B007
out.write(sep)
for value, count in zip(values, value_repetitions):
for i in range(count): # noqa: B007
out.write(sep)
if value:
out.write(value)
out.write("\n")
write_head_line(
"tool",
["{tool} {version}".format_map(run_set.attributes) for run_set in run_sets],
[len(run_set.columns) for run_set in run_sets],
)
write_head_line(
"run set",
[run_set.attributes.get("niceName") for run_set in run_sets],
[len(run_set.columns) for run_set in run_sets],
)
write_head_line(
common_prefix,
[column.format_title() for run_set in run_sets for column in run_set.columns],
)
for row in rows:
# row.short_filename may contain paths, so standardize the output across OSs
out.write(util.fix_path_if_on_windows(row.short_filename))
for row_id, is_relevant in zip(row.id[1:], relevant_id_columns[1:]):
if is_relevant:
out.write(sep)
if row_id is not None:
out.write(str(row_id))
for run_result in row.results:
for value, column in zip(run_result.values, run_result.columns):
out.write(sep)
out.write(column.format_value(value or "", False, "csv"))
out.write("\n")
def write_table_in_format(template_format, outfile, options, **kwargs):
callback = {"csv": write_csv_table, "html": htmltable.write_html_table}[
template_format
]
if outfile:
# Force HTML file to be UTF-8 regardless of system encoding because it actually
# declares itself to be UTF-8 in a meta tag.
encoding = "utf-8" if template_format == "html" else None
with open(outfile, "w", encoding=encoding) as out:
callback(out, options=options, **kwargs)
if options.show_table and template_format == "html":
try:
subprocess.Popen(
["xdg-open", outfile],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
except OSError:
pass
else:
callback(sys.stdout, options=options, **kwargs)
def basename_without_ending(file):
name = os.path.basename(file)
if name.endswith(".xml"):
name = name[:-4]
elif name.endswith(".xml.gz"):
name = name[:-7]
elif name.endswith(".xml.bz2"):
name = name[:-8]
return name
def create_argument_parser():
parser = argparse.ArgumentParser(
fromfile_prefix_chars="@",
description="""Create tables with the results of one or more benchmark executions.
Command-line parameters can additionally be read from a file if file name prefixed with '@' is given as argument.
Part of BenchExec: https://github.com/sosy-lab/benchexec/""",
)
parser.add_argument(
"tables",
metavar="RESULT",
type=str,
nargs="*",
help="XML file with the results from the benchmark script",
)
parser.add_argument(
"-x",
"--xml",
action="store",
type=str,
dest="xmltablefile",
help="XML file with the table definition.",
)
parser.add_argument(
"-o",
"--outputpath",
action="store",
type=str,
dest="outputPath",
help="Output path for the tables. If '-', the tables are written to stdout.",
)
parser.add_argument(
"-n",
"--name",
action="store",
type=str,
dest="output_name",
help="Base name of the created output files.",
)
parser.add_argument(
"--ignore-erroneous-benchmarks",
action="store_true",
dest="ignore_errors",
help="Ignore incomplete result files or results where the was an error during benchmarking.",
)
parser.add_argument(
"-d",
"--dump",
action="store_true",
dest="dump_counts",
help="Print summary statistics for regressions and the good, bad, and unknown counts.",
)
parser.add_argument(
"--ignore-flapping-timeout-regressions",
action="store_true",
dest="ignoreFlappingTimeouts",
help="For the regression-count statistics, do not count regressions to timeouts if the file already had timeouts before.",
)
parser.add_argument(
"-f",
"--format",
action="append",
choices=TEMPLATE_FORMATS,
help="Which format to generate (HTML or CSV). Can be specified multiple times. If not specified, all are generated.",
)
parser.add_argument(
"-c",
"--common",
action="store_true",
dest="common",
help="Put only rows into the table for which all benchmarks contain results.",
)
parser.add_argument(
"--no-diff",
action="store_false",
dest="write_diff_table",
help="Do not output a table with result differences between benchmarks.",
)
parser.add_argument(
"--correct-only",
action="store_true",
dest="correct_only",
help="Clear all results (e.g., time) in cases where the result was not correct.",
)
parser.add_argument(
"--all-columns",
action="store_true",
dest="all_columns",
help="Show all columns in tables, including those that are normally hidden.",
)
parser.add_argument(
"--show",
action="store_true",
dest="show_table",
help="Open the produced HTML table(s) in the default browser.",
)
parser.add_argument(
"-q",
"--quiet",
action="store_true",
help="Do not show informational messages, only warnings.",
)
parser.add_argument(
"--version", action="version", version="%(prog)s " + __version__
)
return parser
def sigint_handler(*args, **kwargs):
# Use SystemExit instead of KeyboardInterrupt to avoid ugly stack traces for each worker
sys.exit(1)
def main(args=None):
if sys.version_info < (3,):
sys.exit("table-generator needs Python 3 to run.")
signal.signal(signal.SIGINT, sigint_handler)
arg_parser = create_argument_parser()
options = arg_parser.parse_args((args or sys.argv)[1:])
benchexec.util.setup_logging(
fmt="%(levelname)s: %(message)s",
level=logging.WARNING if options.quiet else logging.INFO,
)
global parallel
import concurrent.futures
cpu_count = 1
try:
cpu_count = os.cpu_count() or 1
except AttributeError:
pass
# Use up to cpu_count*2 workers because some tasks are I/O bound.
parallel = concurrent.futures.ProcessPoolExecutor(max_workers=cpu_count * 2)
name = options.output_name
outputPath = options.outputPath
if outputPath == "-":
# write to stdout
outputFilePattern = "-"
outputPath = "."
else:
outputFilePattern = "{name}.{type}.{ext}"
if options.xmltablefile:
try:
table_definition = parse_table_definition_file(options.xmltablefile)
if table_definition_lists_result_files(table_definition):
if options.tables:
arg_parser.error(
"Invalid additional arguments '{}'.".format(
" ".join(options.tables)
)
)
runSetResults = load_results_from_table_definition(
table_definition, options.xmltablefile, options
)
else:
if not options.tables:
arg_parser.error(
"No result files given. Either list them on the command line "
"or with <result> tags in the table-definiton file."
)
result_files = util.extend_file_list(options.tables) # expand wildcards
runSetResults = load_results_with_table_definition(
result_files, table_definition, options.xmltablefile, options
)
except util.TableDefinitionError as e:
handle_error("Fault in %s: %s", options.xmltablefile, e)
if not name:
name = basename_without_ending(options.xmltablefile)
if not outputPath:
outputPath = os.path.dirname(options.xmltablefile)
else:
if options.tables:
inputFiles = options.tables
else:
searchDir = outputPath or DEFAULT_OUTPUT_PATH
logging.info("Searching result files in '%s'...", searchDir)
inputFiles = [os.path.join(searchDir, "*.results*.xml")]
inputFiles = util.extend_file_list(inputFiles) # expand wildcards
runSetResults = load_results(inputFiles, options)
if len(inputFiles) == 1:
if not name:
name = basename_without_ending(inputFiles[0])
if not outputFilePattern == "-":
outputFilePattern = "{name}.{ext}"
else:
if not name:
timestamp = time.strftime(
benchexec.util.TIMESTAMP_FILENAME_FORMAT, time.localtime()
)
name = NAME_START + "." + timestamp
if inputFiles and not outputPath:
path = os.path.dirname(inputFiles[0])
if "://" not in path and all(
path == os.path.dirname(file) for file in inputFiles
):
outputPath = path
else:
outputPath = DEFAULT_OUTPUT_PATH
if not outputPath:
outputPath = "."
runSetResults = [r for r in runSetResults if r is not None]
if not runSetResults:
handle_error("No benchmark results found.")
logging.info("Merging results...")
if options.common:
find_common_tasks(runSetResults)
else:
# merge list of run sets, so that all run sets contain the same tasks
merge_tasks(runSetResults)
rows = get_rows(runSetResults)
if not rows:
handle_error("No results found, no tables produced.")
rowsDiff = filter_rows_with_differences(rows) if options.write_diff_table else []
logging.info("Generating table...")
if not os.path.isdir(outputPath) and not outputFilePattern == "-":
os.makedirs(outputPath)
futures = create_tables(
name, runSetResults, rows, rowsDiff, outputPath, outputFilePattern, options
)
if options.dump_counts: # print some stats for Buildbot
print(
"REGRESSIONS {}".format(
get_regression_count(rows, options.ignoreFlappingTimeouts)
)
)
countsList = get_counts(rows)
print("STATS")
for counts in countsList:
print(" ".join(str(e) for e in counts))
for f in futures:
f.result() # to get any exceptions that may have occurred
logging.info("done")
parallel.shutdown(wait=True)
if __name__ == "__main__":
sys.exit(main())
|
en
| 0.812222
|
# This file is part of BenchExec, a framework for reliable benchmarking: # https://github.com/sosy-lab/benchexec # # SPDX-FileCopyrightText: 2007-2020 <NAME> <https://www.sosy-lab.org> # # SPDX-License-Identifier: Apache-2.0 # Process pool for parallel work. # Some of our loops are CPU-bound (e.g., statistics calculations), thus we use # processes, not threads. # Fully initialized only in main() because we cannot do so in the worker processes. # Most important columns that should be shown first in tables (in the given order) # if old results are given # first part of filename of table # bytes in a kilobyte Log error message and terminate program. Read an parse the XML of a table-definition file. @return: an ElementTree object for the table definition Load all results in files that are listed in the given table-definition file. @return: a list of RunSetResult objects # expand wildcards Load results from given files with column definitions taken from a table-definition file. @return: a list of RunSetResult objects Extract all columns mentioned in the result tag of a table definition file. Convert path from a path relative to table-definition file. Extract columns that are relevant for the diff table. @param columns_to_show: (list) A list of columns that should be shown @return: (set) Set of columns that are relevant for the diff table. If none is marked relevant, the column named "status" will be returned in the set. Returns a normalized form of path, interpreted relative to base_path_or_url Load the module with the tool-specific code. The Class RunSetResult contains all the results of one execution of a run set: the sourcefiles tags (with sourcefiles + values), the columns to show and the benchmark attributes. # Copy the columns since they may be modified Return the list of task ids for these results. May be called only after collect_data() Append the result for one run. Needs to be called before collect_data(). Load the actual result values from the XML file and the log files. This may take some time if many log files have to be opened and parsed. This method searches for values in lines of the content. It uses a tool-specific method to so. # Opening the ZIP archive with the logs for every run is too slow, we cache it. This function extracts everything necessary for creating a RunSetResult object from the "result" XML tag of a benchmark result file. It returns a RunSetResult object, which is not yet fully initialized. To finish initializing the object, call collect_data() before using it for anything else (this is to separate the possibly costly collect_data() call from object instantiation). # show all available columns # completely empty results break stuff, add at least status column # Put main columns first, then rest sorted alphabetically # Defaults # Update with real values # Add system information if present # Add summary for columns if present # Here we keep support for <sourcefile> in order to be able to read old benchmark # results (no reason to forbid this). Version of load_result for multiple input files that will be loaded concurrently. Completely handle loading a single result file. @param result_file the file to parse @param options additional options @param run_set_id the identifier of the run set @param columns the list of columns @param columns_relevant_for_diff a set of columns that is relevant for the diff table @return a fully ready RunSetResult instance or None This function parses an XML file that contains the results of the execution of a run set. It returns the "result" XML tag. @param resultFile: The file name of the XML file that contains the results. @param run_set_id: An optional identifier of this set of results. # get folder of logfiles (truncate end of XML file name and append .logfiles instead) # append begin of filename # real runSetName is empty # remove last chars # for each file: append original filename and insert log_file_name into sourcefileElement This function merges the results of all RunSetResult objects. If necessary, it can merge lists of names: [A,C] + [A,B] --> [A,B,C] and add dummy elements to the results. It also ensures the same order of tasks. Set the filelists of all RunSetResult elements so that they contain the same files in the same order. For missing files a dummy element is inserted. # create mapping from id to RunResult object # Use reversed list such that the first instance of equal tasks end up in dic # clear and repopulate results # create an empty dummy element # special category for tables The class RunResult contains the results of a single verification run. This function collects the values from one run. Only columns that should be part of the table are collected. # os.path.relpath creates os-dependant paths, but windows separators can produce errors with zipfile lib # Replace file:/// with file: for relative paths, # otherwise opening fails. # task_name is a path # only category missing # probably everything is missing, special category for tables # for all columns that should be shown # default value # collect values from XML # collect values from logfile # cache content # If no score column exists in the xml, take the internally computed score, # if available The class Row contains all the results for one sourcefile (a list of RunResult instances). It is identified by the name of the source file and optional additional data (such as the property). It corresponds to one complete row in the final tables. generate output representation of rows # try to find property file of task and create Property object Convert a list of Rows into a column-wise list of list of RunResult Create list of rows with all data. Each row consists of several RunResults. Find all rows with differences in the status column. # empty table # table with single column # It's necessary to search for the index of a column every time # because they can differ between results Replace the attributes of each RunSetResult with nicely formatted strings. # compute nice name of each run set for displaying Find out which of the entries in Row.id are equal for all given rows. @return: A list of True/False values according to whether the i-th part of the id is always equal. # first column (file name) is always relevant # column-wise # for options.dump_counts Count the number of regressions, i.e., differences in status of the two right-most results where the new one is not "better" than the old one. Any change in status between error, unknown, and wrong result is a regression. Different kind of errors or wrong results are also a regression. # startswith is used because status can be "TIMEOUT (TRUE)" etc., which count as "TIMEOUT" # no regressions at all with only one run # "new" and "old" are the latest two results # no regression if result is correct # no regression if result is the same as before # no regression if both are some form of timeout # same for OOM # flapping timeout because any of the older results is also a timeout # for options.dump_counts # for rows without a result Create tables and write them to files. @return a list of futures to allow waiting for completion # get common folder of sourcefiles # os.path.commonprefix can return a partial path component (does not truncate on /) # Ugly because this overwrites the entries in the attributes of RunSetResult, # but we don't need them anymore and this is the easiest way # calculate statistics if necessary # write normal tables # write difference tables # noqa: B008 # name may contain paths, so standardize the output across OSs # noqa: B007 # noqa: B007 # row.short_filename may contain paths, so standardize the output across OSs # Force HTML file to be UTF-8 regardless of system encoding because it actually # declares itself to be UTF-8 in a meta tag. Create tables with the results of one or more benchmark executions. Command-line parameters can additionally be read from a file if file name prefixed with '@' is given as argument. Part of BenchExec: https://github.com/sosy-lab/benchexec/ # Use SystemExit instead of KeyboardInterrupt to avoid ugly stack traces for each worker # Use up to cpu_count*2 workers because some tasks are I/O bound. # write to stdout # expand wildcards # expand wildcards # merge list of run sets, so that all run sets contain the same tasks # print some stats for Buildbot # to get any exceptions that may have occurred
| 2.359123
| 2
|
A2OJ-11/009_A_Nearly_Lucky_Number.py
|
vendyv/A2OJ-Ladders
| 0
|
6626323
|
"""
9 Nearly Lucky Number - https://codeforces.com/problemset/problem/110/A
"""
n= input()
count=0
for i in n:
if i=='4' or i=='7':
count+=1
if(count==4 or count==7):
print("YES")
else:
print("NO")
|
"""
9 Nearly Lucky Number - https://codeforces.com/problemset/problem/110/A
"""
n= input()
count=0
for i in n:
if i=='4' or i=='7':
count+=1
if(count==4 or count==7):
print("YES")
else:
print("NO")
|
en
| 0.602628
|
9 Nearly Lucky Number - https://codeforces.com/problemset/problem/110/A
| 3.352246
| 3
|
server.py
|
hbph/gRPCDateTimePython
| 0
|
6626324
|
<reponame>hbph/gRPCDateTimePython
import grpc
from concurrent import futures
from datetime import datetime
import time
import dateTime_pb2_grpc
import dateTime_pb2
class DateTimeServicer(dateTime_pb2_grpc.DateTimeServicer):
def getCurrentDateTime(self, request, context):
response = dateTime_pb2.DateTimeMsg()
response.value = str(datetime.now())
return response
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
dateTime_pb2_grpc.add_DateTimeServicer_to_server(DateTimeServicer(),server)
print('Starting server, Listening on port 50051.')
server.add_insecure_port('[::]:50051')
server.start()
try:
while True:
time.sleep(90000)
except KeyboardInterrupt:
server.stop(0)
|
import grpc
from concurrent import futures
from datetime import datetime
import time
import dateTime_pb2_grpc
import dateTime_pb2
class DateTimeServicer(dateTime_pb2_grpc.DateTimeServicer):
def getCurrentDateTime(self, request, context):
response = dateTime_pb2.DateTimeMsg()
response.value = str(datetime.now())
return response
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
dateTime_pb2_grpc.add_DateTimeServicer_to_server(DateTimeServicer(),server)
print('Starting server, Listening on port 50051.')
server.add_insecure_port('[::]:50051')
server.start()
try:
while True:
time.sleep(90000)
except KeyboardInterrupt:
server.stop(0)
|
none
| 1
| 2.774782
| 3
|
|
tests/GeneratorRmdir_test.py
|
hanniballar/mazikeen
| 0
|
6626325
|
<reponame>hanniballar/mazikeen
import unittest
import yaml
from mazikeen.GeneratorLooper import generateSerialBlock
from mazikeen.ScriptDataProcessor import SafeLineLoader
from mazikeen.RmdirBlock import RmdirBlock
from mazikeen.GeneratorException import GeneratorException
class GeneratorRmdirBlock_test(unittest.TestCase):
def test_basic(self):
with open('TestFiles/GeneratorRmdirBlock_test/test_basic/script.yaml') as f:
data = yaml.load(f, Loader=SafeLineLoader)
block = generateSerialBlock(data)
self.assertTrue(isinstance(block.steps[0], RmdirBlock))
self.assertEqual(block.steps[0].dir, 'Output/GeneratorRmdirBlock_test/TestDir1')
if __name__ == '__main__':
unittest.main()
|
import unittest
import yaml
from mazikeen.GeneratorLooper import generateSerialBlock
from mazikeen.ScriptDataProcessor import SafeLineLoader
from mazikeen.RmdirBlock import RmdirBlock
from mazikeen.GeneratorException import GeneratorException
class GeneratorRmdirBlock_test(unittest.TestCase):
def test_basic(self):
with open('TestFiles/GeneratorRmdirBlock_test/test_basic/script.yaml') as f:
data = yaml.load(f, Loader=SafeLineLoader)
block = generateSerialBlock(data)
self.assertTrue(isinstance(block.steps[0], RmdirBlock))
self.assertEqual(block.steps[0].dir, 'Output/GeneratorRmdirBlock_test/TestDir1')
if __name__ == '__main__':
unittest.main()
|
none
| 1
| 2.335001
| 2
|
|
tests/datatypes/test_frozenset.py
|
HelloMelanieC/batavia
| 0
|
6626326
|
<filename>tests/datatypes/test_frozenset.py<gh_stars>0
from .. utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperationTestCase, InplaceOperationTestCase
import unittest
class FrozensetTests(TranspileTestCase):
def test_creation(self):
self.assertCodeExecution("""
x = frozenset([1, 1, '1', '1'])
print(x)
""", substitutions={"{1, '1'}": ["{'1', 1}"]})
class UnaryFrozensetOperationTests(UnaryOperationTestCase, TranspileTestCase):
data_type = 'frozenset'
class BinaryFrozensetOperationTests(BinaryOperationTestCase, TranspileTestCase):
data_type = 'frozenset'
|
<filename>tests/datatypes/test_frozenset.py<gh_stars>0
from .. utils import TranspileTestCase, UnaryOperationTestCase, BinaryOperationTestCase, InplaceOperationTestCase
import unittest
class FrozensetTests(TranspileTestCase):
def test_creation(self):
self.assertCodeExecution("""
x = frozenset([1, 1, '1', '1'])
print(x)
""", substitutions={"{1, '1'}": ["{'1', 1}"]})
class UnaryFrozensetOperationTests(UnaryOperationTestCase, TranspileTestCase):
data_type = 'frozenset'
class BinaryFrozensetOperationTests(BinaryOperationTestCase, TranspileTestCase):
data_type = 'frozenset'
|
en
| 0.270452
|
x = frozenset([1, 1, '1', '1']) print(x)
| 2.600436
| 3
|
workflow/scripts/script1.py
|
kopardev/CCBR_ATACseq
| 3
|
6626327
|
<gh_stars>1-10
#!/usr/bin/env python
# some python script
|
#!/usr/bin/env python
# some python script
|
en
| 0.275763
|
#!/usr/bin/env python # some python script
| 1.147081
| 1
|
software/tests/test_europi_script.py
|
mjaskula/EuroPi
| 7
|
6626328
|
import pytest
from europi_script import EuroPiScript
from collections import namedtuple
from struct import pack, unpack
class ScriptForTesting(EuroPiScript):
pass
@pytest.fixture
def script_for_testing():
s = ScriptForTesting()
yield s
s.remove_state()
def test_save_state(script_for_testing):
script_for_testing._save_state("test state")
assert script_for_testing._load_state() == "test state"
def test_state_file_name(script_for_testing):
assert script_for_testing._state_filename == "saved_state_ScriptForTesting.txt"
def test_save_load_state_json(script_for_testing):
state = {"one": 1, "two": ["a", "bb"], "three": True}
script_for_testing.save_state_json(state)
with open(script_for_testing._state_filename, 'r') as f:
assert f.read() == '{"one": 1, "two": ["a", "bb"], "three": true}'
assert script_for_testing.load_state_json() == state
def test_save_load_state_bytes(script_for_testing):
State = namedtuple("State", "one two three")
format_string = "b2s?" # https://docs.python.org/3/library/struct.html#format-characters
state = pack(format_string, 1, bytes([8, 16]), True)
script_for_testing.save_state_bytes(state)
with open(script_for_testing._state_filename, 'rb') as f:
assert f.read() == b'\x01\x08\x10\x01'
got_bytes = script_for_testing.load_state_bytes()
assert got_bytes == state
got_struct = State(*unpack(format_string, got_bytes))
assert got_struct.one == 1
assert list(got_struct.two) == [8, 16]
assert got_struct.three == True
|
import pytest
from europi_script import EuroPiScript
from collections import namedtuple
from struct import pack, unpack
class ScriptForTesting(EuroPiScript):
pass
@pytest.fixture
def script_for_testing():
s = ScriptForTesting()
yield s
s.remove_state()
def test_save_state(script_for_testing):
script_for_testing._save_state("test state")
assert script_for_testing._load_state() == "test state"
def test_state_file_name(script_for_testing):
assert script_for_testing._state_filename == "saved_state_ScriptForTesting.txt"
def test_save_load_state_json(script_for_testing):
state = {"one": 1, "two": ["a", "bb"], "three": True}
script_for_testing.save_state_json(state)
with open(script_for_testing._state_filename, 'r') as f:
assert f.read() == '{"one": 1, "two": ["a", "bb"], "three": true}'
assert script_for_testing.load_state_json() == state
def test_save_load_state_bytes(script_for_testing):
State = namedtuple("State", "one two three")
format_string = "b2s?" # https://docs.python.org/3/library/struct.html#format-characters
state = pack(format_string, 1, bytes([8, 16]), True)
script_for_testing.save_state_bytes(state)
with open(script_for_testing._state_filename, 'rb') as f:
assert f.read() == b'\x01\x08\x10\x01'
got_bytes = script_for_testing.load_state_bytes()
assert got_bytes == state
got_struct = State(*unpack(format_string, got_bytes))
assert got_struct.one == 1
assert list(got_struct.two) == [8, 16]
assert got_struct.three == True
|
en
| 0.588878
|
# https://docs.python.org/3/library/struct.html#format-characters
| 2.408641
| 2
|
beetles/scripts/train_merged_data_runner.py
|
ESA-PhiLab/hypernet
| 34
|
6626329
|
"""
Run experiments given set of hyperparameters.
"""
import os
import clize
import tensorflow as tf
from clize.parameters import multi
from scripts import prepare_data, train_model
import ml_intuition.data.utils as utils
import ml_intuition.enums as enums
from ml_intuition.data import noise
def run_experiments(*,
data_file_paths: ('d', multi(min=1)),
ground_truth_path: str,
train_size: float = 0.8,
val_size: float = 0.1,
stratified: bool = True,
background_label: int = 0,
channels_idx: int = 0,
save_data: bool = False,
n_runs: int,
model_name: str,
kernel_size: int = 3,
n_kernels: int = 16,
n_layers: int = 1,
dest_path: str,
sample_size: int,
n_classes: int,
lr: float = 0.005,
batch_size: int = 150,
epochs: int = 10,
verbose: int = 2,
shuffle: bool = True,
patience: int = 3,
pre_noise: ('pre', multi(min=0)),
pre_noise_sets: ('spre', multi(min=0)),
post_noise: ('post', multi(min=0)),
post_noise_sets: ('spost', multi(min=0)),
noise_params: str = None):
"""
Function for running experiments given a set of hyperparameters.
:param data_file_paths: Paths to the data files. Supported types are:
.npy and .h5
:param ground_truth_path: Path to the ground-truth data file.
:param train_size: If float, should be between 0.0 and 1.0,
if stratified = True, it represents percentage of each
class to be extracted,
If float and stratified = False, it represents percentage of the
whole dataset to be extracted with samples drawn randomly,
regardless of their class.
If int and stratified = True, it represents number of samples
to be drawn from each class.
If int and stratified = False, it represents overall number of
samples to be drawn regardless of their class, randomly.
Defaults to 0.8
:param val_size: Should be between 0.0 and 1.0. Represents the percentage of
each class from the training set to be extracted as a
validation set, defaults to 0.1
:param stratified: Indicated whether the extracted training set should be
stratified, defaults to True
:param background_label: Label indicating the background in GT file
:param channels_idx: Index specifying the channels position in the provided
data
:param save_data: Whether to save the prepared dataset
:param n_runs: Number of total experiment runs.
:param model_name: Name of the model, it serves as a key in the
dictionary holding all functions returning models.
:param kernel_size: Size of ech kernel in each layer.
:param n_kernels: Number of kernels in each layer.
:param n_layers: Number of layers in the model.
:param dest_path: Path to where all experiment runs will be saved as subfolders
in this directory.
:param sample_size: Size of the input sample.
:param n_classes: Number of classes.
:param lr: Learning rate for the model, i.e., regulates the size of the step
in the gradient descent process.
:param batch_size: Size of the batch used in training phase,
it is the size of samples per gradient step.
:param epochs: Number of epochs for model to train.
:param verbose: Verbosity mode used in training, (0, 1 or 2).
:param shuffle: Boolean indicating whether to shuffle dataset
dataset_key each epoch.
:param patience: Number of epochs without improvement in order to
stop the training phase.
:param pre_noise: The list of names of noise injection methods before
the normalization transformations. Examplary names are "gaussian"
or "impulsive".
:param pre_noise_sets: The list of sets to which the noise will be
injected. One element can either be "train", "val" or "test".
:param post_noise: The list of names of noise injection metods after
the normalization transformations.
:param post_noise_sets: The list of sets to which the noise will be injected.
:param noise_params: JSON containing the parameter setting of injection methods.
Examplary value for this parameter: "{"mean": 0, "std": 1, "pa": 0.1}".
This JSON should include all parameters for noise injection
functions that are specified in pre_noise and post_noise arguments.
For the accurate description of each parameter, please
refer to the ml_intuition/data/noise.py module.
"""
for experiment_id in range(n_runs):
experiment_dest_path = os.path.join(
dest_path, 'experiment_' + str(experiment_id))
if save_data:
data_source = os.path.join(experiment_dest_path, 'data.h5')
else:
data_source = None
os.makedirs(experiment_dest_path, exist_ok=True)
data_to_merge = []
for data_file_path in data_file_paths:
data = prepare_data.main(data_file_path=data_file_path,
ground_truth_path=ground_truth_path,
output_path=data_source,
train_size=train_size,
val_size=val_size,
stratified=stratified,
background_label=background_label,
channels_idx=channels_idx,
save_data=save_data,
seed=experiment_id)
del data[enums.Dataset.TEST]
data_to_merge.append(data)
data = utils.merge_datasets(data_to_merge)
del data_to_merge
if not save_data:
data_source = data
if len(pre_noise) > 0:
noise.inject_noise(data_source=data_source,
affected_subsets=pre_noise_sets,
noise_injectors=pre_noise,
noise_params=noise_params)
train_model.train(model_name=model_name,
kernel_size=kernel_size,
n_kernels=n_kernels,
n_layers=n_layers,
dest_path=experiment_dest_path,
data=data_source,
sample_size=sample_size,
n_classes=n_classes,
lr=lr,
batch_size=batch_size,
epochs=epochs,
verbose=verbose,
shuffle=shuffle,
patience=patience,
noise=post_noise,
noise_sets=pre_noise_sets,
noise_params=noise_params)
tf.keras.backend.clear_session()
if __name__ == '__main__':
clize.run(run_experiments)
|
"""
Run experiments given set of hyperparameters.
"""
import os
import clize
import tensorflow as tf
from clize.parameters import multi
from scripts import prepare_data, train_model
import ml_intuition.data.utils as utils
import ml_intuition.enums as enums
from ml_intuition.data import noise
def run_experiments(*,
data_file_paths: ('d', multi(min=1)),
ground_truth_path: str,
train_size: float = 0.8,
val_size: float = 0.1,
stratified: bool = True,
background_label: int = 0,
channels_idx: int = 0,
save_data: bool = False,
n_runs: int,
model_name: str,
kernel_size: int = 3,
n_kernels: int = 16,
n_layers: int = 1,
dest_path: str,
sample_size: int,
n_classes: int,
lr: float = 0.005,
batch_size: int = 150,
epochs: int = 10,
verbose: int = 2,
shuffle: bool = True,
patience: int = 3,
pre_noise: ('pre', multi(min=0)),
pre_noise_sets: ('spre', multi(min=0)),
post_noise: ('post', multi(min=0)),
post_noise_sets: ('spost', multi(min=0)),
noise_params: str = None):
"""
Function for running experiments given a set of hyperparameters.
:param data_file_paths: Paths to the data files. Supported types are:
.npy and .h5
:param ground_truth_path: Path to the ground-truth data file.
:param train_size: If float, should be between 0.0 and 1.0,
if stratified = True, it represents percentage of each
class to be extracted,
If float and stratified = False, it represents percentage of the
whole dataset to be extracted with samples drawn randomly,
regardless of their class.
If int and stratified = True, it represents number of samples
to be drawn from each class.
If int and stratified = False, it represents overall number of
samples to be drawn regardless of their class, randomly.
Defaults to 0.8
:param val_size: Should be between 0.0 and 1.0. Represents the percentage of
each class from the training set to be extracted as a
validation set, defaults to 0.1
:param stratified: Indicated whether the extracted training set should be
stratified, defaults to True
:param background_label: Label indicating the background in GT file
:param channels_idx: Index specifying the channels position in the provided
data
:param save_data: Whether to save the prepared dataset
:param n_runs: Number of total experiment runs.
:param model_name: Name of the model, it serves as a key in the
dictionary holding all functions returning models.
:param kernel_size: Size of ech kernel in each layer.
:param n_kernels: Number of kernels in each layer.
:param n_layers: Number of layers in the model.
:param dest_path: Path to where all experiment runs will be saved as subfolders
in this directory.
:param sample_size: Size of the input sample.
:param n_classes: Number of classes.
:param lr: Learning rate for the model, i.e., regulates the size of the step
in the gradient descent process.
:param batch_size: Size of the batch used in training phase,
it is the size of samples per gradient step.
:param epochs: Number of epochs for model to train.
:param verbose: Verbosity mode used in training, (0, 1 or 2).
:param shuffle: Boolean indicating whether to shuffle dataset
dataset_key each epoch.
:param patience: Number of epochs without improvement in order to
stop the training phase.
:param pre_noise: The list of names of noise injection methods before
the normalization transformations. Examplary names are "gaussian"
or "impulsive".
:param pre_noise_sets: The list of sets to which the noise will be
injected. One element can either be "train", "val" or "test".
:param post_noise: The list of names of noise injection metods after
the normalization transformations.
:param post_noise_sets: The list of sets to which the noise will be injected.
:param noise_params: JSON containing the parameter setting of injection methods.
Examplary value for this parameter: "{"mean": 0, "std": 1, "pa": 0.1}".
This JSON should include all parameters for noise injection
functions that are specified in pre_noise and post_noise arguments.
For the accurate description of each parameter, please
refer to the ml_intuition/data/noise.py module.
"""
for experiment_id in range(n_runs):
experiment_dest_path = os.path.join(
dest_path, 'experiment_' + str(experiment_id))
if save_data:
data_source = os.path.join(experiment_dest_path, 'data.h5')
else:
data_source = None
os.makedirs(experiment_dest_path, exist_ok=True)
data_to_merge = []
for data_file_path in data_file_paths:
data = prepare_data.main(data_file_path=data_file_path,
ground_truth_path=ground_truth_path,
output_path=data_source,
train_size=train_size,
val_size=val_size,
stratified=stratified,
background_label=background_label,
channels_idx=channels_idx,
save_data=save_data,
seed=experiment_id)
del data[enums.Dataset.TEST]
data_to_merge.append(data)
data = utils.merge_datasets(data_to_merge)
del data_to_merge
if not save_data:
data_source = data
if len(pre_noise) > 0:
noise.inject_noise(data_source=data_source,
affected_subsets=pre_noise_sets,
noise_injectors=pre_noise,
noise_params=noise_params)
train_model.train(model_name=model_name,
kernel_size=kernel_size,
n_kernels=n_kernels,
n_layers=n_layers,
dest_path=experiment_dest_path,
data=data_source,
sample_size=sample_size,
n_classes=n_classes,
lr=lr,
batch_size=batch_size,
epochs=epochs,
verbose=verbose,
shuffle=shuffle,
patience=patience,
noise=post_noise,
noise_sets=pre_noise_sets,
noise_params=noise_params)
tf.keras.backend.clear_session()
if __name__ == '__main__':
clize.run(run_experiments)
|
en
| 0.813366
|
Run experiments given set of hyperparameters. Function for running experiments given a set of hyperparameters. :param data_file_paths: Paths to the data files. Supported types are: .npy and .h5 :param ground_truth_path: Path to the ground-truth data file. :param train_size: If float, should be between 0.0 and 1.0, if stratified = True, it represents percentage of each class to be extracted, If float and stratified = False, it represents percentage of the whole dataset to be extracted with samples drawn randomly, regardless of their class. If int and stratified = True, it represents number of samples to be drawn from each class. If int and stratified = False, it represents overall number of samples to be drawn regardless of their class, randomly. Defaults to 0.8 :param val_size: Should be between 0.0 and 1.0. Represents the percentage of each class from the training set to be extracted as a validation set, defaults to 0.1 :param stratified: Indicated whether the extracted training set should be stratified, defaults to True :param background_label: Label indicating the background in GT file :param channels_idx: Index specifying the channels position in the provided data :param save_data: Whether to save the prepared dataset :param n_runs: Number of total experiment runs. :param model_name: Name of the model, it serves as a key in the dictionary holding all functions returning models. :param kernel_size: Size of ech kernel in each layer. :param n_kernels: Number of kernels in each layer. :param n_layers: Number of layers in the model. :param dest_path: Path to where all experiment runs will be saved as subfolders in this directory. :param sample_size: Size of the input sample. :param n_classes: Number of classes. :param lr: Learning rate for the model, i.e., regulates the size of the step in the gradient descent process. :param batch_size: Size of the batch used in training phase, it is the size of samples per gradient step. :param epochs: Number of epochs for model to train. :param verbose: Verbosity mode used in training, (0, 1 or 2). :param shuffle: Boolean indicating whether to shuffle dataset dataset_key each epoch. :param patience: Number of epochs without improvement in order to stop the training phase. :param pre_noise: The list of names of noise injection methods before the normalization transformations. Examplary names are "gaussian" or "impulsive". :param pre_noise_sets: The list of sets to which the noise will be injected. One element can either be "train", "val" or "test". :param post_noise: The list of names of noise injection metods after the normalization transformations. :param post_noise_sets: The list of sets to which the noise will be injected. :param noise_params: JSON containing the parameter setting of injection methods. Examplary value for this parameter: "{"mean": 0, "std": 1, "pa": 0.1}". This JSON should include all parameters for noise injection functions that are specified in pre_noise and post_noise arguments. For the accurate description of each parameter, please refer to the ml_intuition/data/noise.py module.
| 2.851476
| 3
|
test/test_insert.py
|
bfolkens/siridb-server
| 0
|
6626330
|
import asyncio
import functools
import random
import time
from testing import Client
from testing import default_test_setup
from testing import gen_data
from testing import gen_points
from testing import gen_series
from testing import InsertError
from testing import PoolError
from testing import QueryError
from testing import run_test
from testing import Series
from testing import Server
from testing import ServerError
from testing import SiriDB
from testing import TestBase
from testing import UserAuthError
TIME_PRECISION = 'ns'
class TestInsert(TestBase):
title = 'Test inserts and response'
GEN_POINTS = functools.partial(gen_points, n=1, time_precision=TIME_PRECISION)
async def _test_series(self, client):
result = await client.query('select * from "series float"')
self.assertEqual(result['series float'], self.series_float)
result = await client.query('select * from "series int"')
self.assertEqual(result['series int'], self.series_int)
result = await client.query('list series name, length, type, start, end')
result['series'].sort()
self.assertEqual(
result,
{ 'columns': ['name', 'length', 'type', 'start', 'end'],
'series': [
['series float', 10000, 'float', self.series_float[0][0], self.series_float[-1][0]],
['series int', 10000, 'integer', self.series_int[0][0], self.series_int[-1][0]],
]
})
async def insert(self, client, series, n, timeout=1):
for _ in range(n):
await client.insert_some_series(series, timeout=timeout, points=self.GEN_POINTS)
await asyncio.sleep(1.0)
@default_test_setup(2, time_precision=TIME_PRECISION, compression=True)
async def run(self):
await self.client0.connect()
self.assertEqual(
await self.client0.insert({}),
{'success_msg': 'Successfully inserted 0 point(s).'})
self.assertEqual(
await self.client0.insert([]),
{'success_msg': 'Successfully inserted 0 point(s).'})
self.series_float = gen_points(tp=float, n=10000, time_precision=TIME_PRECISION, ts_gap='5m')
random.shuffle(self.series_float)
self.series_int = gen_points(tp=int, n=10000, time_precision=TIME_PRECISION, ts_gap='5m')
random.shuffle(self.series_int)
self.assertEqual(
await self.client0.insert({
'series float': self.series_float,
'series int': self.series_int
}), {'success_msg': 'Successfully inserted 20000 point(s).'})
self.series_float.sort()
self.series_int.sort()
await self._test_series(self.client0)
with self.assertRaises(InsertError):
await self.client0.insert('[]')
with self.assertRaises(InsertError):
await self.client0.insert('[]')
with self.assertRaises(InsertError):
await self.client0.insert([{}])
with self.assertRaises(InsertError):
await self.client0.insert({'log': [[1, "1"]]})
with self.assertRaises(InsertError):
await self.client0.insert({'no points': []})
with self.assertRaises(InsertError):
await self.client0.insert({'no points': [[]]})
with self.assertRaises(InsertError):
await self.client0.insert([{'name': 'no points', 'points': []}])
# timestamps should be interger values
with self.assertRaises(InsertError):
await self.client0.insert({'invalid ts': [[0.5, 6]]})
# empty series name is not allowed
with self.assertRaises(InsertError):
await self.client0.insert({'': [[1, 0]]})
# empty series name is not allowed
with self.assertRaises(InsertError):
await self.client0.insert([{'name': '', 'points': [[1, 0]]}])
await self.db.add_replica(self.server1, 0, sleep=30)
# await self.db.add_pool(self.server1, sleep=3)
await self.assertIsRunning(self.db, self.client0, timeout=3)
await self.client1.connect()
await self._test_series(self.client1)
# Create some random series and start 25 insert task parallel
series = gen_series(n=10000)
tasks = [
asyncio.ensure_future(
self.client0.insert_some_series(
series,
timeout=0,
points=self.GEN_POINTS))
for i in range(25)]
await asyncio.gather(*tasks)
await asyncio.sleep(2)
# Check the result
await self.assertSeries(self.client0, series)
await self.assertSeries(self.client1, series)
tasks = [
asyncio.ensure_future(self.client0.query(
'drop series /.*/ set ignore_threshold true'))
for i in range(5)]
await asyncio.gather(*tasks)
tasks = [
asyncio.ensure_future(self.client0.query(
'drop shards set ignore_threshold true'))
for i in range(5)]
await asyncio.gather(*tasks)
await asyncio.sleep(2)
self.client0.close()
self.client1.close()
return False
if __name__ == '__main__':
random.seed(1)
SiriDB.LOG_LEVEL = 'CRITICAL'
Server.HOLD_TERM = True
Server.MEM_CHECK = True
Server.BUILDTYPE = 'Debug'
run_test(TestInsert())
|
import asyncio
import functools
import random
import time
from testing import Client
from testing import default_test_setup
from testing import gen_data
from testing import gen_points
from testing import gen_series
from testing import InsertError
from testing import PoolError
from testing import QueryError
from testing import run_test
from testing import Series
from testing import Server
from testing import ServerError
from testing import SiriDB
from testing import TestBase
from testing import UserAuthError
TIME_PRECISION = 'ns'
class TestInsert(TestBase):
title = 'Test inserts and response'
GEN_POINTS = functools.partial(gen_points, n=1, time_precision=TIME_PRECISION)
async def _test_series(self, client):
result = await client.query('select * from "series float"')
self.assertEqual(result['series float'], self.series_float)
result = await client.query('select * from "series int"')
self.assertEqual(result['series int'], self.series_int)
result = await client.query('list series name, length, type, start, end')
result['series'].sort()
self.assertEqual(
result,
{ 'columns': ['name', 'length', 'type', 'start', 'end'],
'series': [
['series float', 10000, 'float', self.series_float[0][0], self.series_float[-1][0]],
['series int', 10000, 'integer', self.series_int[0][0], self.series_int[-1][0]],
]
})
async def insert(self, client, series, n, timeout=1):
for _ in range(n):
await client.insert_some_series(series, timeout=timeout, points=self.GEN_POINTS)
await asyncio.sleep(1.0)
@default_test_setup(2, time_precision=TIME_PRECISION, compression=True)
async def run(self):
await self.client0.connect()
self.assertEqual(
await self.client0.insert({}),
{'success_msg': 'Successfully inserted 0 point(s).'})
self.assertEqual(
await self.client0.insert([]),
{'success_msg': 'Successfully inserted 0 point(s).'})
self.series_float = gen_points(tp=float, n=10000, time_precision=TIME_PRECISION, ts_gap='5m')
random.shuffle(self.series_float)
self.series_int = gen_points(tp=int, n=10000, time_precision=TIME_PRECISION, ts_gap='5m')
random.shuffle(self.series_int)
self.assertEqual(
await self.client0.insert({
'series float': self.series_float,
'series int': self.series_int
}), {'success_msg': 'Successfully inserted 20000 point(s).'})
self.series_float.sort()
self.series_int.sort()
await self._test_series(self.client0)
with self.assertRaises(InsertError):
await self.client0.insert('[]')
with self.assertRaises(InsertError):
await self.client0.insert('[]')
with self.assertRaises(InsertError):
await self.client0.insert([{}])
with self.assertRaises(InsertError):
await self.client0.insert({'log': [[1, "1"]]})
with self.assertRaises(InsertError):
await self.client0.insert({'no points': []})
with self.assertRaises(InsertError):
await self.client0.insert({'no points': [[]]})
with self.assertRaises(InsertError):
await self.client0.insert([{'name': 'no points', 'points': []}])
# timestamps should be interger values
with self.assertRaises(InsertError):
await self.client0.insert({'invalid ts': [[0.5, 6]]})
# empty series name is not allowed
with self.assertRaises(InsertError):
await self.client0.insert({'': [[1, 0]]})
# empty series name is not allowed
with self.assertRaises(InsertError):
await self.client0.insert([{'name': '', 'points': [[1, 0]]}])
await self.db.add_replica(self.server1, 0, sleep=30)
# await self.db.add_pool(self.server1, sleep=3)
await self.assertIsRunning(self.db, self.client0, timeout=3)
await self.client1.connect()
await self._test_series(self.client1)
# Create some random series and start 25 insert task parallel
series = gen_series(n=10000)
tasks = [
asyncio.ensure_future(
self.client0.insert_some_series(
series,
timeout=0,
points=self.GEN_POINTS))
for i in range(25)]
await asyncio.gather(*tasks)
await asyncio.sleep(2)
# Check the result
await self.assertSeries(self.client0, series)
await self.assertSeries(self.client1, series)
tasks = [
asyncio.ensure_future(self.client0.query(
'drop series /.*/ set ignore_threshold true'))
for i in range(5)]
await asyncio.gather(*tasks)
tasks = [
asyncio.ensure_future(self.client0.query(
'drop shards set ignore_threshold true'))
for i in range(5)]
await asyncio.gather(*tasks)
await asyncio.sleep(2)
self.client0.close()
self.client1.close()
return False
if __name__ == '__main__':
random.seed(1)
SiriDB.LOG_LEVEL = 'CRITICAL'
Server.HOLD_TERM = True
Server.MEM_CHECK = True
Server.BUILDTYPE = 'Debug'
run_test(TestInsert())
|
en
| 0.662785
|
# timestamps should be interger values # empty series name is not allowed # empty series name is not allowed # await self.db.add_pool(self.server1, sleep=3) # Create some random series and start 25 insert task parallel # Check the result
| 2.486384
| 2
|
linear_regression/linear_regression.py
|
anjanik807/ml-from-scratch
| 1
|
6626331
|
<reponame>anjanik807/ml-from-scratch<filename>linear_regression/linear_regression.py
"""
Author: <NAME>
Email: <EMAIL>
Docs: https://giangtranml.github.io/ml/linear-regression.html
"""
import sys
sys.path.append("..")
import numpy as np
from sklearn.model_selection import train_test_split
from optimizations_algorithms.optimizers import SGD
class LinearRegression:
def __init__(self, optimizer, epochs=1000, lambda_=0.1):
self.epochs = epochs
self.lambda_ = lambda_
self.optimizer = optimizer
def _hypothesis(self, X):
return np.dot(X, self.w) + self.b
def _mse_loss(self, X, y_hat, y):
m = y.shape[0]
return np.sum((y_hat - y)**2)/(2*m) + self.lambda_*np.linalg.norm(self.w, 2)**2 / (2*m)
def _gradient(self, X, y_hat, y):
m = X.shape[0]
return 1/m * np.dot(X.T, y_hat - y) + (self.lambda_/m*self.w)
def _gradient_bias(self, y_hat, y):
m = y.shape[0]
return 1/m * np.sum(y_hat - y)
def _train(self, X_train, y_train):
for e in range(self.epochs):
y_hat = self._hypothesis(X_train)
print("Loss at epoch %s: %f" % (e, self._mse_loss(X_train, y_hat, y_train)))
w_grad = self._gradient(X_train, y_hat, y_train)
b_grad = self._gradient_bias(y_hat, y_train)
self._update_params(w_grad, b_grad)
if np.linalg.norm(w_grad, 2) < 1e-6:
break
def _update_params(self, w_grad, b_grad):
self.w -= self.optimizer.minimize(w_grad)
self.b -= self.optimizer.minimize(b_grad)
def train(self, X_train, y_train):
self.w = np.random.normal(size=(X_train.shape[1], 1))
self.b = np.mean(y_train)
self._train(X_train, y_train)
def predict(self, X_test):
assert X_test.shape[1] == self.w.shape[0], "Incorrect shape."
return self._hypothesis(X_test)
def r2_score(self, y_hat, y_test):
total_sum_squares = np.sum((y_test - np.mean(y_test))**2)
residual_sum_squares = np.sum((y_test - y_hat)**2)
return 1 - residual_sum_squares/total_sum_squares
def standardize_regression(X, y):
x_mean = np.mean(X, axis=0)
x_std = np.std(X, axis=0)
y_mean = np.mean(y)
y_std = np.std(y)
return ((X - x_mean)/x_std, x_mean, x_std), ((y - y_mean) / y_std, y_mean, y_std)
def main():
X = np.loadtxt('prostate.data.txt', skiprows=1)
columns = ['lcavol', 'lweight', 'age', 'lbph', 'svi', 'lcp', 'gleason', 'pgg45']
y = X[:, -1]
X = X[:, :-1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
(X_train, _, _), (y_train, _, _) = standardize_regression(X_train, y_train)
y_train = y_train.reshape((-1, 1))
alpha = 0.01
epochs = 500
lambda_ = 0
optimizer = SGD(alpha=alpha)
linear_regression = LinearRegression(optimizer, epochs, lambda_)
linear_regression.train(X_train, y_train)
(X_test, x_mean, x_std), (y_test, y_mean, y_std) = standardize_regression(X_test, y_test)
pred = linear_regression.predict(X_test)
y_test = y_test.reshape((-1, 1))
print("Test score: %f" % linear_regression.r2_score(pred, y_test))
if __name__ == '__main__':
main()
|
"""
Author: <NAME>
Email: <EMAIL>
Docs: https://giangtranml.github.io/ml/linear-regression.html
"""
import sys
sys.path.append("..")
import numpy as np
from sklearn.model_selection import train_test_split
from optimizations_algorithms.optimizers import SGD
class LinearRegression:
def __init__(self, optimizer, epochs=1000, lambda_=0.1):
self.epochs = epochs
self.lambda_ = lambda_
self.optimizer = optimizer
def _hypothesis(self, X):
return np.dot(X, self.w) + self.b
def _mse_loss(self, X, y_hat, y):
m = y.shape[0]
return np.sum((y_hat - y)**2)/(2*m) + self.lambda_*np.linalg.norm(self.w, 2)**2 / (2*m)
def _gradient(self, X, y_hat, y):
m = X.shape[0]
return 1/m * np.dot(X.T, y_hat - y) + (self.lambda_/m*self.w)
def _gradient_bias(self, y_hat, y):
m = y.shape[0]
return 1/m * np.sum(y_hat - y)
def _train(self, X_train, y_train):
for e in range(self.epochs):
y_hat = self._hypothesis(X_train)
print("Loss at epoch %s: %f" % (e, self._mse_loss(X_train, y_hat, y_train)))
w_grad = self._gradient(X_train, y_hat, y_train)
b_grad = self._gradient_bias(y_hat, y_train)
self._update_params(w_grad, b_grad)
if np.linalg.norm(w_grad, 2) < 1e-6:
break
def _update_params(self, w_grad, b_grad):
self.w -= self.optimizer.minimize(w_grad)
self.b -= self.optimizer.minimize(b_grad)
def train(self, X_train, y_train):
self.w = np.random.normal(size=(X_train.shape[1], 1))
self.b = np.mean(y_train)
self._train(X_train, y_train)
def predict(self, X_test):
assert X_test.shape[1] == self.w.shape[0], "Incorrect shape."
return self._hypothesis(X_test)
def r2_score(self, y_hat, y_test):
total_sum_squares = np.sum((y_test - np.mean(y_test))**2)
residual_sum_squares = np.sum((y_test - y_hat)**2)
return 1 - residual_sum_squares/total_sum_squares
def standardize_regression(X, y):
x_mean = np.mean(X, axis=0)
x_std = np.std(X, axis=0)
y_mean = np.mean(y)
y_std = np.std(y)
return ((X - x_mean)/x_std, x_mean, x_std), ((y - y_mean) / y_std, y_mean, y_std)
def main():
X = np.loadtxt('prostate.data.txt', skiprows=1)
columns = ['lcavol', 'lweight', 'age', 'lbph', 'svi', 'lcp', 'gleason', 'pgg45']
y = X[:, -1]
X = X[:, :-1]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
(X_train, _, _), (y_train, _, _) = standardize_regression(X_train, y_train)
y_train = y_train.reshape((-1, 1))
alpha = 0.01
epochs = 500
lambda_ = 0
optimizer = SGD(alpha=alpha)
linear_regression = LinearRegression(optimizer, epochs, lambda_)
linear_regression.train(X_train, y_train)
(X_test, x_mean, x_std), (y_test, y_mean, y_std) = standardize_regression(X_test, y_test)
pred = linear_regression.predict(X_test)
y_test = y_test.reshape((-1, 1))
print("Test score: %f" % linear_regression.r2_score(pred, y_test))
if __name__ == '__main__':
main()
|
en
| 0.438561
|
Author: <NAME> Email: <EMAIL> Docs: https://giangtranml.github.io/ml/linear-regression.html
| 3.266165
| 3
|
pytrait/__init__.py
|
tushar-deepsource/pytrait
| 115
|
6626332
|
from abc import abstractmethod
from pytrait.errors import *
from pytrait.trait import Trait
from pytrait.impl import Impl
from pytrait.struct import Struct
|
from abc import abstractmethod
from pytrait.errors import *
from pytrait.trait import Trait
from pytrait.impl import Impl
from pytrait.struct import Struct
|
none
| 1
| 1.740602
| 2
|
|
parser/team29/analizer/test.py
|
Cristian-HP23/tytus
| 0
|
6626333
|
<filename>parser/team29/analizer/test.py
from sys import path
from os.path import dirname as dir
path.append(dir(path[0]))
from analizer import grammar
s = """
USE db1;
SELECT de1.id, caca.name FROM demo1 de1, (SELECT de2.name FROM demo1 de2 WHERE de1.id = de2.id) AS caca;
"""
result = grammar.parse(s)
print(result)
|
<filename>parser/team29/analizer/test.py
from sys import path
from os.path import dirname as dir
path.append(dir(path[0]))
from analizer import grammar
s = """
USE db1;
SELECT de1.id, caca.name FROM demo1 de1, (SELECT de2.name FROM demo1 de2 WHERE de1.id = de2.id) AS caca;
"""
result = grammar.parse(s)
print(result)
|
en
| 0.101108
|
USE db1; SELECT de1.id, caca.name FROM demo1 de1, (SELECT de2.name FROM demo1 de2 WHERE de1.id = de2.id) AS caca;
| 2.498967
| 2
|
python/setup.py
|
PedroSPSantos/hintsvm
| 0
|
6626334
|
<filename>python/setup.py
import sys, os
from os import path
from shutil import copyfile, rmtree
from glob import glob
from setuptools import setup, Extension
from distutils.command.clean import clean as clean_cmd
# a technique to build a shared library on windows
from distutils.command.build_ext import build_ext
build_ext.get_export_symbols = lambda x, y: []
PACKAGE_DIR = "hsvm"
PACKAGE_NAME = "hintsvm"
VERSION = "3.1.0"
cpp_dir = "cpp-source"
# should be consistent with dynamic_lib_name in libsvm/svm.py
dynamic_lib_name = "clib"
# sources to be included to build the shared library
source_codes = [
"svm.cpp",
]
headers = [
"svm.h",
"svm.def",
]
kwargs_for_extension = {
"sources": [path.join(cpp_dir, f) for f in source_codes],
"depends": [path.join(cpp_dir, f) for f in headers],
"include_dirs": [cpp_dir],
"language": "c++",
}
# see ../Makefile.win
if sys.platform == "win32":
kwargs_for_extension.update(
{
"define_macros": [("_WIN64", ""), ("_CRT_SECURE_NO_DEPRECATE", "")],
"extra_link_args": ["-DEF:{}\svm.def".format(cpp_dir)],
}
)
def create_cpp_source():
for f in source_codes + headers:
src_file = path.join("..", f)
tgt_file = path.join(cpp_dir, f)
# ensure blas directory is created
os.makedirs(path.dirname(tgt_file), exist_ok=True)
copyfile(src_file, tgt_file)
class CleanCommand(clean_cmd):
def run(self):
clean_cmd.run(self)
to_be_removed = ["build/", "dist/", "MANIFEST", cpp_dir, "{}.egg-info".format(PACKAGE_NAME)]
to_be_removed += glob("./{}/{}.*".format(PACKAGE_DIR, dynamic_lib_name))
for root, dirs, files in os.walk(os.curdir, topdown=False):
if "__pycache__" in dirs:
to_be_removed.append(path.join(root, "__pycache__"))
to_be_removed += [f for f in files if f.endswith(".pyc")]
for f in to_be_removed:
print("remove {}".format(f))
if f == ".":
continue
elif path.isfile(f):
os.remove(f)
elif path.isdir(f):
rmtree(f)
def main():
if not path.exists(cpp_dir):
create_cpp_source()
with open("README") as f:
long_description = f.read()
setup(
name=PACKAGE_NAME,
packages=[PACKAGE_DIR],
version=VERSION,
description="Python binding of HSVM",
long_description=long_description,
long_description_content_type="text/plain",
author="ML group @ National Taiwan University",
author_email="<EMAIL>",
url="https://www.csie.ntu.edu.tw/~cjlin/libsvm",
install_requires=["scipy"],
ext_modules=[
Extension(
"{}.{}".format(PACKAGE_DIR, dynamic_lib_name), **kwargs_for_extension
)
],
cmdclass={"clean": CleanCommand},
)
main()
|
<filename>python/setup.py
import sys, os
from os import path
from shutil import copyfile, rmtree
from glob import glob
from setuptools import setup, Extension
from distutils.command.clean import clean as clean_cmd
# a technique to build a shared library on windows
from distutils.command.build_ext import build_ext
build_ext.get_export_symbols = lambda x, y: []
PACKAGE_DIR = "hsvm"
PACKAGE_NAME = "hintsvm"
VERSION = "3.1.0"
cpp_dir = "cpp-source"
# should be consistent with dynamic_lib_name in libsvm/svm.py
dynamic_lib_name = "clib"
# sources to be included to build the shared library
source_codes = [
"svm.cpp",
]
headers = [
"svm.h",
"svm.def",
]
kwargs_for_extension = {
"sources": [path.join(cpp_dir, f) for f in source_codes],
"depends": [path.join(cpp_dir, f) for f in headers],
"include_dirs": [cpp_dir],
"language": "c++",
}
# see ../Makefile.win
if sys.platform == "win32":
kwargs_for_extension.update(
{
"define_macros": [("_WIN64", ""), ("_CRT_SECURE_NO_DEPRECATE", "")],
"extra_link_args": ["-DEF:{}\svm.def".format(cpp_dir)],
}
)
def create_cpp_source():
for f in source_codes + headers:
src_file = path.join("..", f)
tgt_file = path.join(cpp_dir, f)
# ensure blas directory is created
os.makedirs(path.dirname(tgt_file), exist_ok=True)
copyfile(src_file, tgt_file)
class CleanCommand(clean_cmd):
def run(self):
clean_cmd.run(self)
to_be_removed = ["build/", "dist/", "MANIFEST", cpp_dir, "{}.egg-info".format(PACKAGE_NAME)]
to_be_removed += glob("./{}/{}.*".format(PACKAGE_DIR, dynamic_lib_name))
for root, dirs, files in os.walk(os.curdir, topdown=False):
if "__pycache__" in dirs:
to_be_removed.append(path.join(root, "__pycache__"))
to_be_removed += [f for f in files if f.endswith(".pyc")]
for f in to_be_removed:
print("remove {}".format(f))
if f == ".":
continue
elif path.isfile(f):
os.remove(f)
elif path.isdir(f):
rmtree(f)
def main():
if not path.exists(cpp_dir):
create_cpp_source()
with open("README") as f:
long_description = f.read()
setup(
name=PACKAGE_NAME,
packages=[PACKAGE_DIR],
version=VERSION,
description="Python binding of HSVM",
long_description=long_description,
long_description_content_type="text/plain",
author="ML group @ National Taiwan University",
author_email="<EMAIL>",
url="https://www.csie.ntu.edu.tw/~cjlin/libsvm",
install_requires=["scipy"],
ext_modules=[
Extension(
"{}.{}".format(PACKAGE_DIR, dynamic_lib_name), **kwargs_for_extension
)
],
cmdclass={"clean": CleanCommand},
)
main()
|
en
| 0.901841
|
# a technique to build a shared library on windows # should be consistent with dynamic_lib_name in libsvm/svm.py # sources to be included to build the shared library # see ../Makefile.win # ensure blas directory is created
| 2.002538
| 2
|
pypop/simulation/wold.py
|
trouleau/pypop
| 0
|
6626335
|
<filename>pypop/simulation/wold.py
import random as rd
import numpy as np
import numba
<EMAIL>
def _total_intensity(mu, adj, beta, delta, t):
return mu + np.sum(adj / (beta + 1 + delta), axis=0)
<EMAIL>
def _simulate(mu, adj, beta, last, delta, start_t, start_n, max_t, max_n, seed=None):
dim = len(mu)
# FIXME: Add fake 0.0 events to avoid numba complaining of unknown type
events = [[0.0] for i in range(dim)]
if seed:
rd.seed(seed)
# Init time
t = float(start_t)
max_time = t + max_t
# Init number of jumps
n_jumps = int(start_n)
max_jumps = n_jumps + max_n
while (t < max_time) and (n_jumps < max_jumps):
# Compute intensity at each node
lambdas_t = _total_intensity(mu, adj, beta, delta, t)
# Compute total intensity
sum_lambdas_t = lambdas_t.cumsum()
# Sample next event time
dt = rd.expovariate(sum_lambdas_t[-1])
# Increase current time
t = float(t + dt)
n_jumps += 1
if t > max_time:
break
# Sample next event dimension
u = rd.random() * sum_lambdas_t[-1]
i = np.searchsorted(sum_lambdas_t, u)
# Add event to the history
events[i].append(t)
# Update cache for intensity computation
delta[:, i] = t - last
last[i] = t
# FIXME: Reove fake 0.0 events
events = [ev[1:] for ev in events]
return events, last, delta, t, n_jumps
class MultivariateWoldSimulator(object):
def __init__(self, mu_a, alpha_ba, beta_ba):
self.mu_a = np.asanyarray(mu_a)
assert len(self.mu_a.shape) == 1
self.dim = len(self.mu_a)
self.alpha_ba = np.asanyarray(alpha_ba)
assert self.alpha_ba.shape == (self.dim, self.dim)
self.beta_ba = np.asanyarray(beta_ba)
assert self.beta_ba.shape == (self.dim, self.dim)
self.last = 0.0 * np.ones(self.dim) # Time of previous event in each dim
self.delta = 0.0 * np.ones((self.dim, self.dim)) # Last inter-event dim
self.events = [[] for i in range(self.dim)] # List of events
self.t = 0.0
self.n_jumps = 0
def simulate(self, *, max_time=np.inf, max_jumps=np.inf, seed=None):
if seed is None:
seed = rd.randint(0, 2 ** 32 - 1)
if not ((max_time < np.inf) ^ (max_jumps < np.inf)):
raise ValueError('Either `max_time` or `max_jumps` must be set, but not both.')
new_events, last, delta, new_time, new_jumps = _simulate(
mu=self.mu_a, adj=self.alpha_ba, beta=self.beta_ba,
last=self.last, delta=self.delta, start_t=self.t,
start_n=self.n_jumps, max_t=max_time, max_n=max_jumps, seed=seed)
self.last = last.copy()
self.delta = delta.copy()
for i in range(self.dim):
self.events[i].extend(new_events[i])
self.t = new_time
self.n_jumps = new_jumps
return list(map(np.array, self.events))
@property
def end_time(self):
return self.t
def spectral_radius(self):
eigs = np.linalg.eigvals(self.alpha_ba / (self.beta_ba + 1))
return eigs.max() - eigs.min()
|
<filename>pypop/simulation/wold.py
import random as rd
import numpy as np
import numba
<EMAIL>
def _total_intensity(mu, adj, beta, delta, t):
return mu + np.sum(adj / (beta + 1 + delta), axis=0)
<EMAIL>
def _simulate(mu, adj, beta, last, delta, start_t, start_n, max_t, max_n, seed=None):
dim = len(mu)
# FIXME: Add fake 0.0 events to avoid numba complaining of unknown type
events = [[0.0] for i in range(dim)]
if seed:
rd.seed(seed)
# Init time
t = float(start_t)
max_time = t + max_t
# Init number of jumps
n_jumps = int(start_n)
max_jumps = n_jumps + max_n
while (t < max_time) and (n_jumps < max_jumps):
# Compute intensity at each node
lambdas_t = _total_intensity(mu, adj, beta, delta, t)
# Compute total intensity
sum_lambdas_t = lambdas_t.cumsum()
# Sample next event time
dt = rd.expovariate(sum_lambdas_t[-1])
# Increase current time
t = float(t + dt)
n_jumps += 1
if t > max_time:
break
# Sample next event dimension
u = rd.random() * sum_lambdas_t[-1]
i = np.searchsorted(sum_lambdas_t, u)
# Add event to the history
events[i].append(t)
# Update cache for intensity computation
delta[:, i] = t - last
last[i] = t
# FIXME: Reove fake 0.0 events
events = [ev[1:] for ev in events]
return events, last, delta, t, n_jumps
class MultivariateWoldSimulator(object):
def __init__(self, mu_a, alpha_ba, beta_ba):
self.mu_a = np.asanyarray(mu_a)
assert len(self.mu_a.shape) == 1
self.dim = len(self.mu_a)
self.alpha_ba = np.asanyarray(alpha_ba)
assert self.alpha_ba.shape == (self.dim, self.dim)
self.beta_ba = np.asanyarray(beta_ba)
assert self.beta_ba.shape == (self.dim, self.dim)
self.last = 0.0 * np.ones(self.dim) # Time of previous event in each dim
self.delta = 0.0 * np.ones((self.dim, self.dim)) # Last inter-event dim
self.events = [[] for i in range(self.dim)] # List of events
self.t = 0.0
self.n_jumps = 0
def simulate(self, *, max_time=np.inf, max_jumps=np.inf, seed=None):
if seed is None:
seed = rd.randint(0, 2 ** 32 - 1)
if not ((max_time < np.inf) ^ (max_jumps < np.inf)):
raise ValueError('Either `max_time` or `max_jumps` must be set, but not both.')
new_events, last, delta, new_time, new_jumps = _simulate(
mu=self.mu_a, adj=self.alpha_ba, beta=self.beta_ba,
last=self.last, delta=self.delta, start_t=self.t,
start_n=self.n_jumps, max_t=max_time, max_n=max_jumps, seed=seed)
self.last = last.copy()
self.delta = delta.copy()
for i in range(self.dim):
self.events[i].extend(new_events[i])
self.t = new_time
self.n_jumps = new_jumps
return list(map(np.array, self.events))
@property
def end_time(self):
return self.t
def spectral_radius(self):
eigs = np.linalg.eigvals(self.alpha_ba / (self.beta_ba + 1))
return eigs.max() - eigs.min()
|
en
| 0.81204
|
# FIXME: Add fake 0.0 events to avoid numba complaining of unknown type # Init time # Init number of jumps # Compute intensity at each node # Compute total intensity # Sample next event time # Increase current time # Sample next event dimension # Add event to the history # Update cache for intensity computation # FIXME: Reove fake 0.0 events # Time of previous event in each dim # Last inter-event dim # List of events
| 2.383261
| 2
|
lale/lib/sklearn/ada_boost_regressor.py
|
ariffyasri/lale
| 1
|
6626336
|
# Copyright 2019 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from sklearn.ensemble.weight_boosting import AdaBoostRegressor as SKLModel
import lale.docstrings
import lale.operators
class AdaBoostRegressorImpl():
def __init__(self, base_estimator=None, n_estimators=50, learning_rate=1.0, loss='linear', random_state=None):
if isinstance(base_estimator, lale.operators.Operator):
if isinstance(base_estimator, lale.operators.IndividualOp):
base_estimator = base_estimator._impl_instance()._wrapped_model
else:
raise ValueError("If base_estimator is a Lale operator, it needs to be an individual operator. ")
self._hyperparams = {
'base_estimator': base_estimator,
'n_estimators': n_estimators,
'learning_rate': learning_rate,
'loss': loss,
'random_state': random_state}
self._wrapped_model = SKLModel(**self._hyperparams)
def fit(self, X, y=None):
if (y is not None):
self._wrapped_model.fit(X, y)
else:
self._wrapped_model.fit(X)
return self
def predict(self, X):
return self._wrapped_model.predict(X)
_hyperparams_schema = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': 'inherited docstring for AdaBoostRegressor An AdaBoost regressor.',
'allOf': [{
'type': 'object',
'required': ['base_estimator', 'n_estimators', 'learning_rate', 'loss', 'random_state'],
'relevantToOptimizer': ['n_estimators', 'learning_rate', 'loss'],
'additionalProperties': False,
'properties': {
'base_estimator': {
'anyOf': [{
'laleType' : 'operator'}, {
'enum': [None]}],
'default': None,
'description': 'The base estimator from which the boosted ensemble is built.'},
'n_estimators': {
'type': 'integer',
'minimumForOptimizer': 50,
'maximumForOptimizer': 500,
'distribution': 'uniform',
'default': 50,
'description': 'The maximum number of estimators at which boosting is terminated.'},
'learning_rate': {
'type': 'number',
'minimumForOptimizer': 0.01,
'maximumForOptimizer': 1.0,
'distribution': 'loguniform',
'default': 1.0,
'description': 'Learning rate shrinks the contribution of each regressor by'},
'loss': {
'enum': ['linear', 'square', 'exponential'],
'default': 'linear',
'description': 'The loss function to use when updating the weights after each'},
'random_state': {
'anyOf': [{
'type': 'integer'}, {
'type': 'object'}, {
'enum': [None]}],
'default': None,
'description': 'If int, random_state is the seed used by the random number generator;'},
}}],
}
_input_fit_schema = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': 'Build a boosted regressor from the training set (X, y).',
'required': ['X', 'y'],
'type': 'object',
'properties': {
'X': {
'type': 'array',
'items': {
'type': 'array',
'items': {
'type': 'number'},
},
'description': 'The training input samples. Sparse matrix can be CSC, CSR, COO,'},
'y': {
'type': 'array',
'items': {
'type': 'number'},
'description': 'The target values (real numbers).'},
'sample_weight': {
'anyOf': [{
'type': 'array',
'items': {
'type': 'number'},
}, {
'enum': [None]}],
'default': None,
'description': 'Sample weights. If None, the sample weights are initialized to'},
},
}
_input_predict_schema = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': 'Predict regression value for X.',
'type': 'object',
'properties': {
'X': {
'type': 'array',
'items': {
'type': 'array',
'items': {
'type': 'number'},
},
'description': 'The training input samples. Sparse matrix can be CSC, CSR, COO,'},
},
}
_output_predict_schema = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': 'The predicted regression values.',
'type': 'array',
'items': {
'type': 'number'},
}
_combined_schemas = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': """`AdaBoost regressor`_ from scikit-learn for boosting ensemble.
.. _`AdaBoost regressor`: https://scikit-learn.org/0.20/modules/generated/sklearn.ensemble.AdaBoostRegressor.html#sklearn-ensemble-adaboostregressor
""",
'documentation_url': 'https://lale.readthedocs.io/en/latest/modules/lale.lib.sklearn.ada_boost_regressor.html',
'type': 'object',
'tags': {
'pre': [],
'op': ['estimator', 'regressor'],
'post': []},
'properties': {
'hyperparams': _hyperparams_schema,
'input_fit': _input_fit_schema,
'input_predict': _input_predict_schema,
'output_predict': _output_predict_schema}}
lale.docstrings.set_docstrings(AdaBoostRegressorImpl, _combined_schemas)
AdaBoostRegressor = lale.operators.make_operator(AdaBoostRegressorImpl, _combined_schemas)
|
# Copyright 2019 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from sklearn.ensemble.weight_boosting import AdaBoostRegressor as SKLModel
import lale.docstrings
import lale.operators
class AdaBoostRegressorImpl():
def __init__(self, base_estimator=None, n_estimators=50, learning_rate=1.0, loss='linear', random_state=None):
if isinstance(base_estimator, lale.operators.Operator):
if isinstance(base_estimator, lale.operators.IndividualOp):
base_estimator = base_estimator._impl_instance()._wrapped_model
else:
raise ValueError("If base_estimator is a Lale operator, it needs to be an individual operator. ")
self._hyperparams = {
'base_estimator': base_estimator,
'n_estimators': n_estimators,
'learning_rate': learning_rate,
'loss': loss,
'random_state': random_state}
self._wrapped_model = SKLModel(**self._hyperparams)
def fit(self, X, y=None):
if (y is not None):
self._wrapped_model.fit(X, y)
else:
self._wrapped_model.fit(X)
return self
def predict(self, X):
return self._wrapped_model.predict(X)
_hyperparams_schema = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': 'inherited docstring for AdaBoostRegressor An AdaBoost regressor.',
'allOf': [{
'type': 'object',
'required': ['base_estimator', 'n_estimators', 'learning_rate', 'loss', 'random_state'],
'relevantToOptimizer': ['n_estimators', 'learning_rate', 'loss'],
'additionalProperties': False,
'properties': {
'base_estimator': {
'anyOf': [{
'laleType' : 'operator'}, {
'enum': [None]}],
'default': None,
'description': 'The base estimator from which the boosted ensemble is built.'},
'n_estimators': {
'type': 'integer',
'minimumForOptimizer': 50,
'maximumForOptimizer': 500,
'distribution': 'uniform',
'default': 50,
'description': 'The maximum number of estimators at which boosting is terminated.'},
'learning_rate': {
'type': 'number',
'minimumForOptimizer': 0.01,
'maximumForOptimizer': 1.0,
'distribution': 'loguniform',
'default': 1.0,
'description': 'Learning rate shrinks the contribution of each regressor by'},
'loss': {
'enum': ['linear', 'square', 'exponential'],
'default': 'linear',
'description': 'The loss function to use when updating the weights after each'},
'random_state': {
'anyOf': [{
'type': 'integer'}, {
'type': 'object'}, {
'enum': [None]}],
'default': None,
'description': 'If int, random_state is the seed used by the random number generator;'},
}}],
}
_input_fit_schema = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': 'Build a boosted regressor from the training set (X, y).',
'required': ['X', 'y'],
'type': 'object',
'properties': {
'X': {
'type': 'array',
'items': {
'type': 'array',
'items': {
'type': 'number'},
},
'description': 'The training input samples. Sparse matrix can be CSC, CSR, COO,'},
'y': {
'type': 'array',
'items': {
'type': 'number'},
'description': 'The target values (real numbers).'},
'sample_weight': {
'anyOf': [{
'type': 'array',
'items': {
'type': 'number'},
}, {
'enum': [None]}],
'default': None,
'description': 'Sample weights. If None, the sample weights are initialized to'},
},
}
_input_predict_schema = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': 'Predict regression value for X.',
'type': 'object',
'properties': {
'X': {
'type': 'array',
'items': {
'type': 'array',
'items': {
'type': 'number'},
},
'description': 'The training input samples. Sparse matrix can be CSC, CSR, COO,'},
},
}
_output_predict_schema = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': 'The predicted regression values.',
'type': 'array',
'items': {
'type': 'number'},
}
_combined_schemas = {
'$schema': 'http://json-schema.org/draft-04/schema#',
'description': """`AdaBoost regressor`_ from scikit-learn for boosting ensemble.
.. _`AdaBoost regressor`: https://scikit-learn.org/0.20/modules/generated/sklearn.ensemble.AdaBoostRegressor.html#sklearn-ensemble-adaboostregressor
""",
'documentation_url': 'https://lale.readthedocs.io/en/latest/modules/lale.lib.sklearn.ada_boost_regressor.html',
'type': 'object',
'tags': {
'pre': [],
'op': ['estimator', 'regressor'],
'post': []},
'properties': {
'hyperparams': _hyperparams_schema,
'input_fit': _input_fit_schema,
'input_predict': _input_predict_schema,
'output_predict': _output_predict_schema}}
lale.docstrings.set_docstrings(AdaBoostRegressorImpl, _combined_schemas)
AdaBoostRegressor = lale.operators.make_operator(AdaBoostRegressorImpl, _combined_schemas)
|
en
| 0.73066
|
# Copyright 2019 IBM Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #', #', #', #', #', `AdaBoost regressor`_ from scikit-learn for boosting ensemble. .. _`AdaBoost regressor`: https://scikit-learn.org/0.20/modules/generated/sklearn.ensemble.AdaBoostRegressor.html#sklearn-ensemble-adaboostregressor
| 1.969881
| 2
|
hw2/pymoo/util/reference_direction.py
|
yyb1995/software_technology_project
| 0
|
6626337
|
<filename>hw2/pymoo/util/reference_direction.py
import numpy as np
from scipy import special
from pymoo.util.misc import unique_rows
from pymoo.util.plotting import plot_3d
class ReferenceDirectionFactory:
def __init__(self, n_dim, scaling=None) -> None:
super().__init__()
self.n_dim = n_dim
self.scaling = scaling
def do(self):
if self.n_dim == 1:
return np.array([[1.0]])
else:
ref_dirs = self._do()
if self.scaling is not None:
ref_dirs = ref_dirs * self.scaling + ((1 - self.scaling) / self.n_dim)
return ref_dirs
def _do(self):
return None
class UniformReferenceDirectionFactory(ReferenceDirectionFactory):
def __init__(self, n_dim, scaling=None, n_points=None, n_partitions=None) -> None:
super().__init__(n_dim, scaling=scaling)
if n_points is not None:
self.n_partitions = UniformReferenceDirectionFactory.get_partition_closest_to_points(n_points, n_dim)
else:
if n_partitions is None:
raise Exception("Either provide number of partitions or number of points.")
else:
self.n_partitions = n_partitions
def _do(self):
return self.uniform_reference_directions(self.n_partitions, self.n_dim)
@staticmethod
def get_partition_closest_to_points(n_points, n_dim):
# in this case the do method will always return one values anyway
if n_dim == 1:
return 0
n_partitions = 1
_n_points = UniformReferenceDirectionFactory.get_n_points(n_partitions, n_dim)
while _n_points <= n_points:
n_partitions += 1
_n_points = UniformReferenceDirectionFactory.get_n_points(n_partitions, n_dim)
return n_partitions - 1
@staticmethod
def get_n_points(n_partitions, n_dim):
return int(special.binom(n_dim + n_partitions - 1, n_partitions))
def uniform_reference_directions(self, n_partitions, n_dim):
ref_dirs = []
ref_dir = np.full(n_dim, np.inf)
self.__uniform_reference_directions(ref_dirs, ref_dir, n_partitions, n_partitions, 0)
return np.concatenate(ref_dirs, axis=0)
def __uniform_reference_directions(self, ref_dirs, ref_dir, n_partitions, beta, depth):
if depth == len(ref_dir) - 1:
ref_dir[depth] = beta / (1.0 * n_partitions)
ref_dirs.append(ref_dir[None, :])
else:
for i in range(beta + 1):
ref_dir[depth] = 1.0 * i / (1.0 * n_partitions)
self.__uniform_reference_directions(ref_dirs, np.copy(ref_dir), n_partitions, beta - i,
depth + 1)
class MultiLayerReferenceDirectionFactory:
def __init__(self, layers=[]) -> None:
self.layers = layers
def add_layer(self, factory):
self.layers.append(factory)
def do(self):
ref_dirs = []
for factory in self.layers:
ref_dirs.append(factory.do())
ref_dirs = np.concatenate(ref_dirs, axis=0)
return unique_rows(ref_dirs)
if __name__ == '__main__':
ref_dirs = UniformReferenceDirectionFactory(2, n_points=100).do()
print(np.sum(ref_dirs, axis=1))
n_dim = 9
ref_dirs = MultiLayerReferenceDirectionFactory([
UniformReferenceDirectionFactory(n_dim, n_partitions=3, scaling=1.0),
UniformReferenceDirectionFactory(n_dim, n_partitions=4, scaling=0.9),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.8),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.7),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.6),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.5),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.4),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.3),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.2),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.1),
]).do()
# ref_dirs = UniformReferenceDirectionFactory(3, n_points=100).do()
#np.savetxt('ref_dirs_9.csv', ref_dirs)
print(ref_dirs.shape)
multi_layer = MultiLayerReferenceDirectionFactory()
multi_layer.add_layer(UniformReferenceDirectionFactory(10, n_partitions=2, scaling=0.5))
multi_layer.add_layer(UniformReferenceDirectionFactory(10, n_partitions=3, scaling=1.0))
# multi_layer.add_layer(0.5, UniformReferenceDirectionFactory(3, n_partitions=10))
ref_dirs = multi_layer.do()
print(UniformReferenceDirectionFactory.get_partition_closest_to_points(100, 3))
print(ref_dirs.shape)
plot_3d(ref_dirs)
|
<filename>hw2/pymoo/util/reference_direction.py
import numpy as np
from scipy import special
from pymoo.util.misc import unique_rows
from pymoo.util.plotting import plot_3d
class ReferenceDirectionFactory:
def __init__(self, n_dim, scaling=None) -> None:
super().__init__()
self.n_dim = n_dim
self.scaling = scaling
def do(self):
if self.n_dim == 1:
return np.array([[1.0]])
else:
ref_dirs = self._do()
if self.scaling is not None:
ref_dirs = ref_dirs * self.scaling + ((1 - self.scaling) / self.n_dim)
return ref_dirs
def _do(self):
return None
class UniformReferenceDirectionFactory(ReferenceDirectionFactory):
def __init__(self, n_dim, scaling=None, n_points=None, n_partitions=None) -> None:
super().__init__(n_dim, scaling=scaling)
if n_points is not None:
self.n_partitions = UniformReferenceDirectionFactory.get_partition_closest_to_points(n_points, n_dim)
else:
if n_partitions is None:
raise Exception("Either provide number of partitions or number of points.")
else:
self.n_partitions = n_partitions
def _do(self):
return self.uniform_reference_directions(self.n_partitions, self.n_dim)
@staticmethod
def get_partition_closest_to_points(n_points, n_dim):
# in this case the do method will always return one values anyway
if n_dim == 1:
return 0
n_partitions = 1
_n_points = UniformReferenceDirectionFactory.get_n_points(n_partitions, n_dim)
while _n_points <= n_points:
n_partitions += 1
_n_points = UniformReferenceDirectionFactory.get_n_points(n_partitions, n_dim)
return n_partitions - 1
@staticmethod
def get_n_points(n_partitions, n_dim):
return int(special.binom(n_dim + n_partitions - 1, n_partitions))
def uniform_reference_directions(self, n_partitions, n_dim):
ref_dirs = []
ref_dir = np.full(n_dim, np.inf)
self.__uniform_reference_directions(ref_dirs, ref_dir, n_partitions, n_partitions, 0)
return np.concatenate(ref_dirs, axis=0)
def __uniform_reference_directions(self, ref_dirs, ref_dir, n_partitions, beta, depth):
if depth == len(ref_dir) - 1:
ref_dir[depth] = beta / (1.0 * n_partitions)
ref_dirs.append(ref_dir[None, :])
else:
for i in range(beta + 1):
ref_dir[depth] = 1.0 * i / (1.0 * n_partitions)
self.__uniform_reference_directions(ref_dirs, np.copy(ref_dir), n_partitions, beta - i,
depth + 1)
class MultiLayerReferenceDirectionFactory:
def __init__(self, layers=[]) -> None:
self.layers = layers
def add_layer(self, factory):
self.layers.append(factory)
def do(self):
ref_dirs = []
for factory in self.layers:
ref_dirs.append(factory.do())
ref_dirs = np.concatenate(ref_dirs, axis=0)
return unique_rows(ref_dirs)
if __name__ == '__main__':
ref_dirs = UniformReferenceDirectionFactory(2, n_points=100).do()
print(np.sum(ref_dirs, axis=1))
n_dim = 9
ref_dirs = MultiLayerReferenceDirectionFactory([
UniformReferenceDirectionFactory(n_dim, n_partitions=3, scaling=1.0),
UniformReferenceDirectionFactory(n_dim, n_partitions=4, scaling=0.9),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.8),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.7),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.6),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.5),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.4),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.3),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.2),
UniformReferenceDirectionFactory(n_dim, n_partitions=2, scaling=0.1),
]).do()
# ref_dirs = UniformReferenceDirectionFactory(3, n_points=100).do()
#np.savetxt('ref_dirs_9.csv', ref_dirs)
print(ref_dirs.shape)
multi_layer = MultiLayerReferenceDirectionFactory()
multi_layer.add_layer(UniformReferenceDirectionFactory(10, n_partitions=2, scaling=0.5))
multi_layer.add_layer(UniformReferenceDirectionFactory(10, n_partitions=3, scaling=1.0))
# multi_layer.add_layer(0.5, UniformReferenceDirectionFactory(3, n_partitions=10))
ref_dirs = multi_layer.do()
print(UniformReferenceDirectionFactory.get_partition_closest_to_points(100, 3))
print(ref_dirs.shape)
plot_3d(ref_dirs)
|
en
| 0.28359
|
# in this case the do method will always return one values anyway # ref_dirs = UniformReferenceDirectionFactory(3, n_points=100).do() #np.savetxt('ref_dirs_9.csv', ref_dirs) # multi_layer.add_layer(0.5, UniformReferenceDirectionFactory(3, n_partitions=10))
| 2.43757
| 2
|
sentry/utils/shortcuts.py
|
JiangHaoJoinGitHubj/dcrameri
| 3
|
6626338
|
<gh_stars>1-10
"""
sentry.utils.shortcuts
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from flask import abort
def get_object_or_404(Model, **kwargs):
try:
return Model.objects.get(**kwargs)
except Model.DoesNotExist:
abort(404)
|
"""
sentry.utils.shortcuts
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from flask import abort
def get_object_or_404(Model, **kwargs):
try:
return Model.objects.get(**kwargs)
except Model.DoesNotExist:
abort(404)
|
en
| 0.630093
|
sentry.utils.shortcuts ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details.
| 1.795791
| 2
|
tests/test_py3nvml.py
|
parthopdas/py3nvml
| 0
|
6626339
|
<reponame>parthopdas/py3nvml<gh_stars>0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from time import sleep
from py3nvml.py3nvml import *
import pytest
from py3nvml.utils import grab_gpus, get_free_gpus
import os
def test_readme1():
nvmlInit()
print("Driver Version: {}".format(nvmlSystemGetDriverVersion()))
deviceCount = nvmlDeviceGetCount()
for i in range(deviceCount):
handle = nvmlDeviceGetHandleByIndex(i)
print("Device {}: {}".format(i, nvmlDeviceGetName(handle)))
nvmlShutdown()
def test_grabgpus():
res = grab_gpus(0)
assert os.environ['CUDA_VISIBLE_DEVICES'] == ''
assert res == 0
def test_grabgpus2():
res = grab_gpus(1)
assert len(os.environ['CUDA_VISIBLE_DEVICES']) > 0
assert res == 1
def test_grabgpus3():
res = grab_gpus(100)
assert len(os.environ['CUDA_VISIBLE_DEVICES']) < len(','.join([str(x) for x in range(100)]))
assert res <= 8
def test_grabgpus4():
res = grab_gpus(5, gpu_select=range(3,8))
assert '0' not in os.environ['CUDA_VISIBLE_DEVICES']
assert '1' not in os.environ['CUDA_VISIBLE_DEVICES']
assert '2' not in os.environ['CUDA_VISIBLE_DEVICES']
def test_get_free_gpus():
pass
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from time import sleep
from py3nvml.py3nvml import *
import pytest
from py3nvml.utils import grab_gpus, get_free_gpus
import os
def test_readme1():
nvmlInit()
print("Driver Version: {}".format(nvmlSystemGetDriverVersion()))
deviceCount = nvmlDeviceGetCount()
for i in range(deviceCount):
handle = nvmlDeviceGetHandleByIndex(i)
print("Device {}: {}".format(i, nvmlDeviceGetName(handle)))
nvmlShutdown()
def test_grabgpus():
res = grab_gpus(0)
assert os.environ['CUDA_VISIBLE_DEVICES'] == ''
assert res == 0
def test_grabgpus2():
res = grab_gpus(1)
assert len(os.environ['CUDA_VISIBLE_DEVICES']) > 0
assert res == 1
def test_grabgpus3():
res = grab_gpus(100)
assert len(os.environ['CUDA_VISIBLE_DEVICES']) < len(','.join([str(x) for x in range(100)]))
assert res <= 8
def test_grabgpus4():
res = grab_gpus(5, gpu_select=range(3,8))
assert '0' not in os.environ['CUDA_VISIBLE_DEVICES']
assert '1' not in os.environ['CUDA_VISIBLE_DEVICES']
assert '2' not in os.environ['CUDA_VISIBLE_DEVICES']
def test_get_free_gpus():
pass
|
none
| 1
| 2.244083
| 2
|
|
plot_nikkei.py
|
masatana/stockstudy
| 0
|
6626340
|
<filename>plot_nikkei.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from datetime import datetime
import jsm
import pandas.compat as compat
import pandas
import numpy
if __name__ == "__main__":
start = datetime(2014, 11, 1)
f = jpmarket.DataReader(6952, "yahoojp", start)
plt.title("{} from {} to {}".format(6952, start, datetime.today()))
plt.fill_between(f.index, f["Low"], f["High"], color="b", alpha=0.2)
f["Close"].plot()
plt.savefig("./casio.png")
|
<filename>plot_nikkei.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from datetime import datetime
import jsm
import pandas.compat as compat
import pandas
import numpy
if __name__ == "__main__":
start = datetime(2014, 11, 1)
f = jpmarket.DataReader(6952, "yahoojp", start)
plt.title("{} from {} to {}".format(6952, start, datetime.today()))
plt.fill_between(f.index, f["Low"], f["High"], color="b", alpha=0.2)
f["Close"].plot()
plt.savefig("./casio.png")
|
en
| 0.352855
|
#!/usr/bin/env python # -*- coding: utf-8 -*-
| 2.939805
| 3
|
generate.py
|
dmmaus/mezzacotta-cinematique
| 1
|
6626341
|
import Tkinter
import random
import string
def randomline(filename, plural, cap):
global atword
story = ""
lines = []
rline = ""
f = open(filename + ".txt", "r")
for line in f:
if line.startswith("^") and random.randrange(0, 10) < 5:
rline = line[1:]
break;
if line.startswith("&"):
cap = True
elif len(line) == 0:
print "THERE IS A BLANK LINE"
elif not line.startswith("#"):
lines.append(line)
f.close()
if rline == "":
rline = lines[random.randrange(0, len(lines))]
#print "FROM", filename, "CHOSE:", rline
words = rline.split()
for word in words:
if word == "@":
word = atword
atword = ""
elif "@" in word:
atword = word[1:]
word = ""
if "|" in word:
pos = string.find(word, "|")
if not plural:
word = word[:pos]
else:
word = word[pos + 1:]
if "$" in word:
pos = string.find(word, "$")
if pos == 0:
chance = 10
else:
chance = int(word[:pos])
if chance > random.randrange(0, 10):
story += randomline(word[pos + 1:], False, cap)
elif word.startswith("*"):
story += randomline(word[1:], True, cap)
else:
if cap:
word = word.capitalize()
story += word + " "
return story
def process_tagline(tagline):
reps = {" ":" ", " .":".", " ,":",", " !":"!", " ?":"?", " _":"", " :":":", "- ":"-",
" a a":" an a", " a e":" an e"," a o":" an o"," a u":" an u"," a i":" an i",
" a A":" an A", " a E":" an E"," a O":" an O"," a U":" an U"," a I":" an I",
" A A":" An A", " A E":" An E"," A O":" An O"," A U":" An U"," A I":" An I",
" a the":" the", " the the":" the", " The The":" The", "?.":"?", " )":")", " +":"-", "+ ":"-",
"( ":"(", " ":" ", " '":"'", '"_ ':'"', ' _"':'"', "<br/>":"\n"
}
for key in reps.keys():
if key in tagline:
tagline = tagline.replace(key, reps[key])
tagline = tagline.lstrip()
a = tagline[0]
b = tagline[1:]
return a.capitalize() + b
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
button = Tkinter.Button(self,text=u"Generate",
command=self.OnButtonClick)
savebtn = Tkinter.Button(self, text=u"Classic!", command=self.OnSaveClick)
backbtn = Tkinter.Button(self, text=u"What was THAT?", command=self.OnBackClick)
button.grid(column=1,row=0)
savebtn.grid(column=2, row=0)
backbtn.grid(column=3, row=0)
self.labelVariable = Tkinter.StringVar()
self.titleVariable = Tkinter.StringVar()
self.ratingVariable = Tkinter.StringVar()
self.castVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,
anchor="w", height=6, wraplength=800, font=("Helvetica", 24), width=42)
rating = Tkinter.Label(self,textvariable=self.ratingVariable,
anchor="w", height=2, wraplength=800, foreground="red", font=("Helvetica", 12), width=42)
title = Tkinter.Label(self,textvariable=self.titleVariable, foreground="blue",
anchor="w", height=2, wraplength=800, font=("Helvetica", 32))
cast = Tkinter.Label(self,textvariable=self.castVariable, foreground="darkgreen",
anchor="w", height=3, wraplength=800, font=("Helvetica", 16))
label.grid(column=0,row=4,columnspan=2,sticky='EW')
cast.grid(column=0,row=3,columnspan=2,sticky='EW')
rating.grid(column=0, row=2, columnspan=2, sticky='EW')
title.grid(column=0,row=1,columnspan=2,sticky='EW')
self.labelVariable.set(u"Plot")
self.titleVariable.set(u"Title")
self.ratingVariable.set(u"Rating")
self.castVariable.set(u"Cast")
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
self.update()
self.geometry(self.geometry())
def OnButtonClick(self):
self.OldTitle = self.titleVariable.get()
self.OldPlot = self.labelVariable.get()
tagline = " " + randomline("basemovie", False, False)
processed_tagline = process_tagline(tagline)
self.labelVariable.set(processed_tagline)
movie_plot = processed_tagline
title = " " + randomline("title", False, False)
processed_title = process_tagline(title)
self.titleVariable.set(processed_title)
movie_title = processed_title
rating = " " + randomline("rating", False, False)
processed_rating = process_tagline(rating)
self.ratingVariable.set(processed_rating)
movie_rating = processed_rating
cast = " " + randomline("cast", False, False)
processed_cast = process_tagline(cast)
self.castVariable.set(processed_cast)
movie_cast = processed_cast
def OnSaveClick(self):
c = open("classic_films.txt", 'a')
c.write(self.titleVariable.get() + "\n" + self.labelVariable.get() + "\n\n")
c.close()
def OnBackClick(self):
self.titleVariable.set(self.OldTitle)
self.labelVariable.set(self.OldPlot)
if __name__ == "__main__":
global atword
global movie_plot
global movie_title
atword = ""
movie_plot = ""
movie_title = ""
app = simpleapp_tk(None)
app.title('mezzacotta cinematheque')
app.mainloop()
|
import Tkinter
import random
import string
def randomline(filename, plural, cap):
global atword
story = ""
lines = []
rline = ""
f = open(filename + ".txt", "r")
for line in f:
if line.startswith("^") and random.randrange(0, 10) < 5:
rline = line[1:]
break;
if line.startswith("&"):
cap = True
elif len(line) == 0:
print "THERE IS A BLANK LINE"
elif not line.startswith("#"):
lines.append(line)
f.close()
if rline == "":
rline = lines[random.randrange(0, len(lines))]
#print "FROM", filename, "CHOSE:", rline
words = rline.split()
for word in words:
if word == "@":
word = atword
atword = ""
elif "@" in word:
atword = word[1:]
word = ""
if "|" in word:
pos = string.find(word, "|")
if not plural:
word = word[:pos]
else:
word = word[pos + 1:]
if "$" in word:
pos = string.find(word, "$")
if pos == 0:
chance = 10
else:
chance = int(word[:pos])
if chance > random.randrange(0, 10):
story += randomline(word[pos + 1:], False, cap)
elif word.startswith("*"):
story += randomline(word[1:], True, cap)
else:
if cap:
word = word.capitalize()
story += word + " "
return story
def process_tagline(tagline):
reps = {" ":" ", " .":".", " ,":",", " !":"!", " ?":"?", " _":"", " :":":", "- ":"-",
" a a":" an a", " a e":" an e"," a o":" an o"," a u":" an u"," a i":" an i",
" a A":" an A", " a E":" an E"," a O":" an O"," a U":" an U"," a I":" an I",
" A A":" An A", " A E":" An E"," A O":" An O"," A U":" An U"," A I":" An I",
" a the":" the", " the the":" the", " The The":" The", "?.":"?", " )":")", " +":"-", "+ ":"-",
"( ":"(", " ":" ", " '":"'", '"_ ':'"', ' _"':'"', "<br/>":"\n"
}
for key in reps.keys():
if key in tagline:
tagline = tagline.replace(key, reps[key])
tagline = tagline.lstrip()
a = tagline[0]
b = tagline[1:]
return a.capitalize() + b
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid()
button = Tkinter.Button(self,text=u"Generate",
command=self.OnButtonClick)
savebtn = Tkinter.Button(self, text=u"Classic!", command=self.OnSaveClick)
backbtn = Tkinter.Button(self, text=u"What was THAT?", command=self.OnBackClick)
button.grid(column=1,row=0)
savebtn.grid(column=2, row=0)
backbtn.grid(column=3, row=0)
self.labelVariable = Tkinter.StringVar()
self.titleVariable = Tkinter.StringVar()
self.ratingVariable = Tkinter.StringVar()
self.castVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,
anchor="w", height=6, wraplength=800, font=("Helvetica", 24), width=42)
rating = Tkinter.Label(self,textvariable=self.ratingVariable,
anchor="w", height=2, wraplength=800, foreground="red", font=("Helvetica", 12), width=42)
title = Tkinter.Label(self,textvariable=self.titleVariable, foreground="blue",
anchor="w", height=2, wraplength=800, font=("Helvetica", 32))
cast = Tkinter.Label(self,textvariable=self.castVariable, foreground="darkgreen",
anchor="w", height=3, wraplength=800, font=("Helvetica", 16))
label.grid(column=0,row=4,columnspan=2,sticky='EW')
cast.grid(column=0,row=3,columnspan=2,sticky='EW')
rating.grid(column=0, row=2, columnspan=2, sticky='EW')
title.grid(column=0,row=1,columnspan=2,sticky='EW')
self.labelVariable.set(u"Plot")
self.titleVariable.set(u"Title")
self.ratingVariable.set(u"Rating")
self.castVariable.set(u"Cast")
self.grid_columnconfigure(0,weight=1)
self.resizable(True,False)
self.update()
self.geometry(self.geometry())
def OnButtonClick(self):
self.OldTitle = self.titleVariable.get()
self.OldPlot = self.labelVariable.get()
tagline = " " + randomline("basemovie", False, False)
processed_tagline = process_tagline(tagline)
self.labelVariable.set(processed_tagline)
movie_plot = processed_tagline
title = " " + randomline("title", False, False)
processed_title = process_tagline(title)
self.titleVariable.set(processed_title)
movie_title = processed_title
rating = " " + randomline("rating", False, False)
processed_rating = process_tagline(rating)
self.ratingVariable.set(processed_rating)
movie_rating = processed_rating
cast = " " + randomline("cast", False, False)
processed_cast = process_tagline(cast)
self.castVariable.set(processed_cast)
movie_cast = processed_cast
def OnSaveClick(self):
c = open("classic_films.txt", 'a')
c.write(self.titleVariable.get() + "\n" + self.labelVariable.get() + "\n\n")
c.close()
def OnBackClick(self):
self.titleVariable.set(self.OldTitle)
self.labelVariable.set(self.OldPlot)
if __name__ == "__main__":
global atword
global movie_plot
global movie_title
atword = ""
movie_plot = ""
movie_title = ""
app = simpleapp_tk(None)
app.title('mezzacotta cinematheque')
app.mainloop()
|
en
| 0.457327
|
#print "FROM", filename, "CHOSE:", rline
| 3.640821
| 4
|
software/tests/test_M00_prerequisites.py
|
adellanno/MetaXcan
| 83
|
6626342
|
<gh_stars>10-100
#!/usr/bin/env python
import unittest
import sys
import shutil
import os
import io
import re
import gzip
import numpy
if "DEBUG" in sys.argv:
sys.path.insert(0, "..")
sys.path.insert(0, "../../")
sys.path.insert(0, ".")
sys.argv.remove("DEBUG")
import metax.Formats as Formats
from M00_prerequisites import ProcessPrerequisites
class Dummy(object):
pass
def buildDummyArgs(root):
dummy = Dummy()
dummy.verbosity = 10
dummy.dosage_folder = os.path.join(root, "dosage_set_1")
dummy.snp_list = os.path.join(root, "snp.txt.gz")
dummy.output_folder = os.path.join(root, "intermediate/filtered")
dummy.file_pattern = "set_(.*)"
dummy.population_group_filters = ["HERO"]
dummy.individual_filters = ["ID.*"]
dummy.input_format = Formats.IMPUTE
dummy.output_format = Formats.PrediXcan
return dummy
def setupDataForArgs(args, root):
if os.path.exists(root):
shutil.rmtree(root)
shutil.copytree("tests/_td/dosage_set_1", os.path.join(root,"dosage_set_1"))
shutil.copy("tests/_td/snp.txt.gz", root)
def cleanUpDataForArgs(root):
shutil.rmtree(root)
class TestM00(unittest.TestCase):
def testProcessPrerequisitesnoArgConstructor(self):
with self.assertRaises(AttributeError):
dummy = Dummy()
p = ProcessPrerequisites(dummy)
def testProcessPrerequisitesConstructor(self):
dummy = buildDummyArgs("_test")
setupDataForArgs(dummy, "_test")
p = ProcessPrerequisites(dummy)
self.assertEqual(p.dosage_folder, "_test/dosage_set_1")
self.assertEqual(p.snp_list, "_test/snp.txt.gz")
self.assertEqual(p.output_folder, "_test/intermediate/filtered")
self.assertEqual(p.population_group_filters, ["HERO"])
# Previous check below looked at memory locations, which failed under
# some conditions even though the expressions were effectively identical
self.assertEqual([x.pattern for x in p.individual_filters], ["ID.*"])
self.assertEqual(p.chromosome_in_name_regex,re.compile("set_(.*)"))
self.assertEqual(p.samples_input, "_test/dosage_set_1/set.sample")
self.assertEqual(p.samples_output, "_test/intermediate/filtered/set.sample")
cleanUpDataForArgs("_test")
def testProcessPrerequisitesRun(self):
dummy = buildDummyArgs("_test")
setupDataForArgs(dummy, "_test")
p = ProcessPrerequisites(dummy)
try:
p.run()
except:
self.assertEqual(False, True, "Prerequisites should have run without error")
with open(p.samples_output) as f:
expected_lines = ["ID POP GROUP SEX",
"ID1 K HERO male",
"ID2 K HERO female",
"ID3 K HERO female"]
for i,expected_line in enumerate(expected_lines):
actual_line = f.readline().strip()
self.assertEqual(actual_line, expected_line)
path = os.path.join(p.output_folder, "set_chr1.dosage.gz")
with io.TextIOWrapper(gzip.open(path), newline="") as f:
expected_lines = ["chr1 rs2 2 G A 0.166666666667 0 1 0",
"chr1 rs3 3 G A 0.333333333333 0 1 1",
"chr1 rs4 4 G A 1.0 2 2 2"]
for i,expected_line in enumerate(expected_lines):
actual_line = f.readline().strip()
actual_comps = actual_line.split(" ")
expected_comps = expected_line.split(" ")
self.assertEqual(actual_comps[0:5], expected_comps[0:5])
numpy.testing.assert_almost_equal(float(actual_comps[6]), float(actual_comps[6]))
self.assertEqual(actual_comps[7:], expected_comps[7:])
cleanUpDataForArgs("_test")
if __name__ == "__main__":
unittest.main()
|
#!/usr/bin/env python
import unittest
import sys
import shutil
import os
import io
import re
import gzip
import numpy
if "DEBUG" in sys.argv:
sys.path.insert(0, "..")
sys.path.insert(0, "../../")
sys.path.insert(0, ".")
sys.argv.remove("DEBUG")
import metax.Formats as Formats
from M00_prerequisites import ProcessPrerequisites
class Dummy(object):
pass
def buildDummyArgs(root):
dummy = Dummy()
dummy.verbosity = 10
dummy.dosage_folder = os.path.join(root, "dosage_set_1")
dummy.snp_list = os.path.join(root, "snp.txt.gz")
dummy.output_folder = os.path.join(root, "intermediate/filtered")
dummy.file_pattern = "set_(.*)"
dummy.population_group_filters = ["HERO"]
dummy.individual_filters = ["ID.*"]
dummy.input_format = Formats.IMPUTE
dummy.output_format = Formats.PrediXcan
return dummy
def setupDataForArgs(args, root):
if os.path.exists(root):
shutil.rmtree(root)
shutil.copytree("tests/_td/dosage_set_1", os.path.join(root,"dosage_set_1"))
shutil.copy("tests/_td/snp.txt.gz", root)
def cleanUpDataForArgs(root):
shutil.rmtree(root)
class TestM00(unittest.TestCase):
def testProcessPrerequisitesnoArgConstructor(self):
with self.assertRaises(AttributeError):
dummy = Dummy()
p = ProcessPrerequisites(dummy)
def testProcessPrerequisitesConstructor(self):
dummy = buildDummyArgs("_test")
setupDataForArgs(dummy, "_test")
p = ProcessPrerequisites(dummy)
self.assertEqual(p.dosage_folder, "_test/dosage_set_1")
self.assertEqual(p.snp_list, "_test/snp.txt.gz")
self.assertEqual(p.output_folder, "_test/intermediate/filtered")
self.assertEqual(p.population_group_filters, ["HERO"])
# Previous check below looked at memory locations, which failed under
# some conditions even though the expressions were effectively identical
self.assertEqual([x.pattern for x in p.individual_filters], ["ID.*"])
self.assertEqual(p.chromosome_in_name_regex,re.compile("set_(.*)"))
self.assertEqual(p.samples_input, "_test/dosage_set_1/set.sample")
self.assertEqual(p.samples_output, "_test/intermediate/filtered/set.sample")
cleanUpDataForArgs("_test")
def testProcessPrerequisitesRun(self):
dummy = buildDummyArgs("_test")
setupDataForArgs(dummy, "_test")
p = ProcessPrerequisites(dummy)
try:
p.run()
except:
self.assertEqual(False, True, "Prerequisites should have run without error")
with open(p.samples_output) as f:
expected_lines = ["ID POP GROUP SEX",
"ID1 K HERO male",
"ID2 K HERO female",
"ID3 K HERO female"]
for i,expected_line in enumerate(expected_lines):
actual_line = f.readline().strip()
self.assertEqual(actual_line, expected_line)
path = os.path.join(p.output_folder, "set_chr1.dosage.gz")
with io.TextIOWrapper(gzip.open(path), newline="") as f:
expected_lines = ["chr1 rs2 2 G A 0.166666666667 0 1 0",
"chr1 rs3 3 G A 0.333333333333 0 1 1",
"chr1 rs4 4 G A 1.0 2 2 2"]
for i,expected_line in enumerate(expected_lines):
actual_line = f.readline().strip()
actual_comps = actual_line.split(" ")
expected_comps = expected_line.split(" ")
self.assertEqual(actual_comps[0:5], expected_comps[0:5])
numpy.testing.assert_almost_equal(float(actual_comps[6]), float(actual_comps[6]))
self.assertEqual(actual_comps[7:], expected_comps[7:])
cleanUpDataForArgs("_test")
if __name__ == "__main__":
unittest.main()
|
en
| 0.968533
|
#!/usr/bin/env python # Previous check below looked at memory locations, which failed under # some conditions even though the expressions were effectively identical
| 2.175322
| 2
|
QuestoesBeecrowd-Iniciante/1046.py
|
AtosNeves/Beecrowd
| 0
|
6626343
|
a,b = input().split(" ")
a = int(a)
b = int(b)
c = 24-a
d = c + b
if d > 24:
print(f"O JOGO DUROU",b-a,"HORA(S)")
else:
print(f"O JOGO DUROU",d,"HORA(S)")
|
a,b = input().split(" ")
a = int(a)
b = int(b)
c = 24-a
d = c + b
if d > 24:
print(f"O JOGO DUROU",b-a,"HORA(S)")
else:
print(f"O JOGO DUROU",d,"HORA(S)")
|
none
| 1
| 3.163169
| 3
|
|
pyntcloud/scalar_fields/voxelgrid.py
|
bernssolg/pyntcloud-master
| 1,142
|
6626344
|
import numpy as np
from .base import ScalarField
class VoxelgridScalarField(ScalarField):
def __init__(self, *, pyntcloud, voxelgrid_id):
super().__init__(pyntcloud=pyntcloud)
self.voxelgrid_id = voxelgrid_id
def extract_info(self):
self.voxelgrid = self.pyntcloud.structures[self.voxelgrid_id]
def compute(self):
pass
class VoxelX(VoxelgridScalarField):
"""Voxel index along x axis."""
def compute(self):
name = "{}({})".format("voxel_x", self.voxelgrid_id)
self.to_be_added[name] = self.voxelgrid.voxel_x
class VoxelY(VoxelgridScalarField):
"""Voxel index along y axis."""
def compute(self):
name = "{}({})".format("voxel_y", self.voxelgrid_id)
self.to_be_added[name] = self.voxelgrid.voxel_y
class VoxelZ(VoxelgridScalarField):
"""Voxel index along z axis."""
def compute(self):
name = "{}({})".format("voxel_z", self.voxelgrid_id)
self.to_be_added[name] = self.voxelgrid.voxel_z
class VoxelN(VoxelgridScalarField):
"""Voxel index in 3D array using 'C' order."""
def compute(self):
name = "{}({})".format("voxel_n", self.voxelgrid_id)
self.to_be_added[name] = self.voxelgrid.voxel_n
class EuclideanClusters(VoxelgridScalarField):
"""Assing corresponding cluster to each point inside each voxel."""
def compute(self):
name = "{}({})".format("clusters", self.voxelgrid_id)
to_be_processed = np.zeros(self.voxelgrid.n_voxels, dtype=bool)
to_be_processed[np.unique(self.voxelgrid.voxel_n)] = True
clusters = np.zeros(self.voxelgrid.voxel_n.shape[0])
C = 0
while np.any(to_be_processed):
Q = []
Q.append(np.random.choice(np.where(to_be_processed)[0]))
for voxel in Q:
clusters[np.where(self.voxelgrid.voxel_n == voxel)[0]] = C
to_be_processed[voxel] = False
neighbors = self.voxelgrid.get_voxel_neighbors(voxel)
for neighbor in neighbors:
if to_be_processed[neighbor]:
Q.append(neighbor)
to_be_processed[neighbor] = False
C += 1
self.to_be_added[name] = clusters
|
import numpy as np
from .base import ScalarField
class VoxelgridScalarField(ScalarField):
def __init__(self, *, pyntcloud, voxelgrid_id):
super().__init__(pyntcloud=pyntcloud)
self.voxelgrid_id = voxelgrid_id
def extract_info(self):
self.voxelgrid = self.pyntcloud.structures[self.voxelgrid_id]
def compute(self):
pass
class VoxelX(VoxelgridScalarField):
"""Voxel index along x axis."""
def compute(self):
name = "{}({})".format("voxel_x", self.voxelgrid_id)
self.to_be_added[name] = self.voxelgrid.voxel_x
class VoxelY(VoxelgridScalarField):
"""Voxel index along y axis."""
def compute(self):
name = "{}({})".format("voxel_y", self.voxelgrid_id)
self.to_be_added[name] = self.voxelgrid.voxel_y
class VoxelZ(VoxelgridScalarField):
"""Voxel index along z axis."""
def compute(self):
name = "{}({})".format("voxel_z", self.voxelgrid_id)
self.to_be_added[name] = self.voxelgrid.voxel_z
class VoxelN(VoxelgridScalarField):
"""Voxel index in 3D array using 'C' order."""
def compute(self):
name = "{}({})".format("voxel_n", self.voxelgrid_id)
self.to_be_added[name] = self.voxelgrid.voxel_n
class EuclideanClusters(VoxelgridScalarField):
"""Assing corresponding cluster to each point inside each voxel."""
def compute(self):
name = "{}({})".format("clusters", self.voxelgrid_id)
to_be_processed = np.zeros(self.voxelgrid.n_voxels, dtype=bool)
to_be_processed[np.unique(self.voxelgrid.voxel_n)] = True
clusters = np.zeros(self.voxelgrid.voxel_n.shape[0])
C = 0
while np.any(to_be_processed):
Q = []
Q.append(np.random.choice(np.where(to_be_processed)[0]))
for voxel in Q:
clusters[np.where(self.voxelgrid.voxel_n == voxel)[0]] = C
to_be_processed[voxel] = False
neighbors = self.voxelgrid.get_voxel_neighbors(voxel)
for neighbor in neighbors:
if to_be_processed[neighbor]:
Q.append(neighbor)
to_be_processed[neighbor] = False
C += 1
self.to_be_added[name] = clusters
|
en
| 0.561214
|
Voxel index along x axis. Voxel index along y axis. Voxel index along z axis. Voxel index in 3D array using 'C' order. Assing corresponding cluster to each point inside each voxel.
| 2.738687
| 3
|
IST_memory_OO.py
|
cravatsc/info_sample_task
| 1
|
6626345
|
<reponame>cravatsc/info_sample_task
#!/usr/bin/env python2
#psychopy version v1.85.2
# memory test for the information sampling using pictures
# created 01/21/2018 by AH & CC lasted edited 02/13/2018 by AH
import os
from psychopy import visual, data, logging, event, core
import random
from config_management import config_manager
import IST_objects
from utils import load_files_by_ext
config = config_manager.ConfigManager('IST_memory.config')
# input subject's information sampling data and collect old images
subj_info_sample_data = '/Users/abbyhsiung/Desktop/Python/log_data/005_01_2018_Feb_16_2116_IST_sampling.csv'
file_reader = open(subj_info_sample_data, 'r')
lines = file_reader.readlines()
all_old_images = []
for x in lines:
all_old_images.append(x.split(', ')[14]) # or whatever column paths are contained in sampling task
old_images = []
for image in all_old_images:
if image.endswith('.jpg'):
old_images.append(image)
# collect all images and separate new from old
all_indoor_imgs = load_files_by_ext(config.get('indoor_image_path'), config.get('image_file_ext'))
all_outdoor_imgs = load_files_by_ext(config.get('outdoor_image_path'), config.get('image_file_ext'))
all_living_imgs = load_files_by_ext(config.get('living_image_path'), config.get('image_file_ext'))
all_nonliving_imgs = load_files_by_ext(config.get('non_living_image_path'), config.get('image_file_ext'))
aggregate_other_images = all_indoor_imgs + all_outdoor_imgs + all_living_imgs + all_nonliving_imgs
all_new_images = [image for image in aggregate_other_images if image not in old_images]
new_images = random.sample(all_new_images, len(old_images)/3)
# create bank of new and old pictures for memory test
total_images = old_images + new_images
random.shuffle(total_images)
num_of_images = len(total_images)
def main():
# Store info about the experiment session
participant_no = raw_input('Participant Number:')
session_no = raw_input('Session Number:')
raw_input('Press enter when you are ready to start the task.')
participant = IST_objects.Participant(participant_no, session_no)
# set up logging information
globalClock = core.MonotonicClock() # if this isn't provided the log times will reflect secs since python started
trial_clock = core.Clock()
logging.setDefaultClock(globalClock)
# set up file creation
filename = config.get('log_location') + os.sep + '{}_{}_{}_IST_memory'.format(participant.id, participant.session,
data.getDateStr()) + '.csv'
file_writer = open(filename, 'a')
file_writer.write(
'participant_id, session, trial_number, global_time, picture, old/new, time_of_choice, confidence, '
'time_con_rating,\n')
endExpNow = False
# set up display
win = visual.Window(size=(1440, 900), fullscr=True, screen=0,
allowGUI=False, allowStencil=False, monitor='testMonitor',
color='black', colorSpace='rgb', blendMode='avg', useFBO=True)
# set up directions
old_new = visual.TextStim(win, text=u"Old/New", pos=(0, -0.77), bold=True)
confidence_rating = visual.TextStim(win, text=u"1 2 3", pos=(0, 0), height=0.3, bold=True)
confidence_text = visual.TextStim(win, text=u"low high", pos=(0, -0.3), height=0.1, bold=True)
ready_screen = visual.TextStim(win, text=u"Ready?", pos=(0, 0), bold=True)
ready_screen.draw()
win.flip()
event.waitKeys(maxWait=10, keyList=['space'], modifiers=False)
for x in range(num_of_images):
pic = total_images[x]
visual_select = visual.ImageStim(win, image=pic)
visual_select.draw()
old_new.draw()
win.flip()
trial_clock.reset(0)
status_in = event.waitKeys(maxWait=5, keyList=['left','right'], modifiers=False, timeStamped=trial_clock)
confidence_rating.draw()
confidence_text.draw()
win.flip()
trial_clock.reset(0)
conf_in = event.waitKeys(maxWait=5, keyList=['left','down','right'], modifiers=False, timeStamped=trial_clock)
blank_fixation = visual.TextStim(win, text='+', color=u'white')
blank_fixation.draw()
win.flip()
core.wait(1.0)
trial = IST_objects.ConfidenceTrial(x+1, globalClock.getTime(), pic, status_in, conf_in)
if pic in old_images:
trial.old_new = 'old'
else:
trial.old_new = 'new'
file_writer.write(participant.csv_format() + trial.csv_format()+'\n')
print'!!!!!!!!!!!!!!!!!!!!!!!!!'
file_writer.close()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python2
#psychopy version v1.85.2
# memory test for the information sampling using pictures
# created 01/21/2018 by AH & CC lasted edited 02/13/2018 by AH
import os
from psychopy import visual, data, logging, event, core
import random
from config_management import config_manager
import IST_objects
from utils import load_files_by_ext
config = config_manager.ConfigManager('IST_memory.config')
# input subject's information sampling data and collect old images
subj_info_sample_data = '/Users/abbyhsiung/Desktop/Python/log_data/005_01_2018_Feb_16_2116_IST_sampling.csv'
file_reader = open(subj_info_sample_data, 'r')
lines = file_reader.readlines()
all_old_images = []
for x in lines:
all_old_images.append(x.split(', ')[14]) # or whatever column paths are contained in sampling task
old_images = []
for image in all_old_images:
if image.endswith('.jpg'):
old_images.append(image)
# collect all images and separate new from old
all_indoor_imgs = load_files_by_ext(config.get('indoor_image_path'), config.get('image_file_ext'))
all_outdoor_imgs = load_files_by_ext(config.get('outdoor_image_path'), config.get('image_file_ext'))
all_living_imgs = load_files_by_ext(config.get('living_image_path'), config.get('image_file_ext'))
all_nonliving_imgs = load_files_by_ext(config.get('non_living_image_path'), config.get('image_file_ext'))
aggregate_other_images = all_indoor_imgs + all_outdoor_imgs + all_living_imgs + all_nonliving_imgs
all_new_images = [image for image in aggregate_other_images if image not in old_images]
new_images = random.sample(all_new_images, len(old_images)/3)
# create bank of new and old pictures for memory test
total_images = old_images + new_images
random.shuffle(total_images)
num_of_images = len(total_images)
def main():
# Store info about the experiment session
participant_no = raw_input('Participant Number:')
session_no = raw_input('Session Number:')
raw_input('Press enter when you are ready to start the task.')
participant = IST_objects.Participant(participant_no, session_no)
# set up logging information
globalClock = core.MonotonicClock() # if this isn't provided the log times will reflect secs since python started
trial_clock = core.Clock()
logging.setDefaultClock(globalClock)
# set up file creation
filename = config.get('log_location') + os.sep + '{}_{}_{}_IST_memory'.format(participant.id, participant.session,
data.getDateStr()) + '.csv'
file_writer = open(filename, 'a')
file_writer.write(
'participant_id, session, trial_number, global_time, picture, old/new, time_of_choice, confidence, '
'time_con_rating,\n')
endExpNow = False
# set up display
win = visual.Window(size=(1440, 900), fullscr=True, screen=0,
allowGUI=False, allowStencil=False, monitor='testMonitor',
color='black', colorSpace='rgb', blendMode='avg', useFBO=True)
# set up directions
old_new = visual.TextStim(win, text=u"Old/New", pos=(0, -0.77), bold=True)
confidence_rating = visual.TextStim(win, text=u"1 2 3", pos=(0, 0), height=0.3, bold=True)
confidence_text = visual.TextStim(win, text=u"low high", pos=(0, -0.3), height=0.1, bold=True)
ready_screen = visual.TextStim(win, text=u"Ready?", pos=(0, 0), bold=True)
ready_screen.draw()
win.flip()
event.waitKeys(maxWait=10, keyList=['space'], modifiers=False)
for x in range(num_of_images):
pic = total_images[x]
visual_select = visual.ImageStim(win, image=pic)
visual_select.draw()
old_new.draw()
win.flip()
trial_clock.reset(0)
status_in = event.waitKeys(maxWait=5, keyList=['left','right'], modifiers=False, timeStamped=trial_clock)
confidence_rating.draw()
confidence_text.draw()
win.flip()
trial_clock.reset(0)
conf_in = event.waitKeys(maxWait=5, keyList=['left','down','right'], modifiers=False, timeStamped=trial_clock)
blank_fixation = visual.TextStim(win, text='+', color=u'white')
blank_fixation.draw()
win.flip()
core.wait(1.0)
trial = IST_objects.ConfidenceTrial(x+1, globalClock.getTime(), pic, status_in, conf_in)
if pic in old_images:
trial.old_new = 'old'
else:
trial.old_new = 'new'
file_writer.write(participant.csv_format() + trial.csv_format()+'\n')
print'!!!!!!!!!!!!!!!!!!!!!!!!!'
file_writer.close()
if __name__ == '__main__':
main()
|
en
| 0.800303
|
#!/usr/bin/env python2 #psychopy version v1.85.2 # memory test for the information sampling using pictures # created 01/21/2018 by AH & CC lasted edited 02/13/2018 by AH # input subject's information sampling data and collect old images # or whatever column paths are contained in sampling task # collect all images and separate new from old # create bank of new and old pictures for memory test # Store info about the experiment session # set up logging information # if this isn't provided the log times will reflect secs since python started # set up file creation # set up display # set up directions
| 2.633945
| 3
|
ubiquiti_config_generator/messages/db.py
|
ammesonb/ubiquiti-config-generator
| 3
|
6626346
|
<reponame>ammesonb/ubiquiti-config-generator<filename>ubiquiti_config_generator/messages/db.py
"""
Log database interaction functionality
"""
from os import path
import sqlite3
from typing import Optional, List
from ubiquiti_config_generator.messages.check import Check
from ubiquiti_config_generator.messages.deployment import Deployment
from ubiquiti_config_generator.messages.log import Log
DB_PATH = "messages"
DB_FILE = DB_PATH + "/messages.db"
def initialize_db(db_file: str = DB_FILE) -> sqlite3.Cursor:
"""
Sets up the database for logging
"""
connection = sqlite3.connect(db_file)
cursor = connection.cursor()
table_creation_statements = [
"""
CREATE TABLE IF NOT EXISTS commit_check (
revision VARCHAR(40) PRIMARY KEY,
status VARCHAR(20) NOT NULL,
started_at FLOAT NOT NULL,
ended_at FLOAT NULL
)
""",
"""
CREATE TABLE IF NOT EXISTS check_log (
revision VARCHAR(40) NOT NULL,
status VARCHAR(20) NOT NULL,
timestamp FLOAT NOT NULL,
message TEXT NOT NULL,
FOREIGN KEY (revision)
REFERENCES commit_check (revision)
)
""",
"""
CREATE TABLE IF NOT EXISTS deployment (
from_revision VARCHAR(40),
to_revision VARCHAR(40),
status VARCHAR(20) NOT NULL,
started_at FLOAT NOT NULL,
ended_at FLOAT NULL,
PRIMARY KEY (from_revision, to_revision),
FOREIGN KEY (from_revision)
REFERENCES commit_check (revision),
FOREIGN KEY (to_revision)
REFERENCES commit_check (revision)
)
""",
"""
CREATE TABLE IF NOT EXISTS deployment_log (
from_revision VARCHAR(40),
to_revision VARCHAR(40),
status VARCHAR(20) NOT NULL,
timestamp FLOAT NOT NULL,
message TEXT NOT NULL,
FOREIGN KEY (from_revision)
REFERENCES deployment (from_revision),
FOREIGN KEY (to_revision)
REFERENCES deployment (to_revision)
)
""",
]
for statement in table_creation_statements:
cursor.execute(statement)
return get_cursor(db_file)
def get_cursor(db_file: str = DB_FILE) -> sqlite3.Cursor:
"""
Opens a connection the db and gets a cursor
"""
cursor = (
initialize_db(db_file)
if not path.isfile(db_file)
else sqlite3.connect(db_file, isolation_level=None).cursor()
)
cursor.row_factory = sqlite3.Row
return cursor
def get_check(revision: str, cursor: Optional[sqlite3.Cursor] = None) -> Check:
"""
Get details about a revision check
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"SELECT * FROM commit_check WHERE revision = ?", (revision,)
)
check = result.fetchone()
if not check:
return Check(revision, "nonexistent", 0, 0, [])
return Check(**check, **{"logs": get_check_logs(revision, cursor)})
def get_check_logs(revision: str, cursor: Optional[sqlite3.Cursor] = None) -> List[Log]:
"""
Get the logs for a given check revision
"""
cursor = cursor or get_cursor()
result = cursor.execute("SELECT * FROM check_log WHERE revision = ?", (revision,))
log_results = result.fetchall()
return [
Log(
revision1=log["revision"],
message=log["message"],
status=log["status"],
utc_unix_timestamp=log["timestamp"],
)
for log in log_results
]
def get_deployment(
from_revision: str, to_revision: str, cursor: Optional[sqlite3.Cursor] = None
) -> Check:
"""
Get details about a deployment
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
SELECT *
FROM deployment
WHERE from_revision = ?
AND to_revision = ?
""",
(from_revision, to_revision,),
)
deployment = result.fetchone()
if not deployment:
return Deployment(from_revision, to_revision, "nonexistent", 0, 0, [])
return Deployment(
**deployment,
**{"logs": get_deployment_logs(from_revision, to_revision, cursor)}
)
def get_deployment_logs(
from_revision: str, to_revision: str, cursor: Optional[sqlite3.Cursor] = None
) -> List[Log]:
"""
Get the logs for a given check revision
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
SELECT *
FROM deployment_log
WHERE from_revision = ?
AND to_revision = ?
""",
(from_revision, to_revision,),
)
log_results = result.fetchall()
return [
Log(
revision1=log["from_revision"],
revision2=log["to_revision"],
message=log["message"],
status=log["status"],
utc_unix_timestamp=log["timestamp"],
)
for log in log_results
]
def create_check(check: Check, cursor: Optional[sqlite3.Cursor] = None) -> bool:
"""
Creates a check in the DB
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
INSERT INTO commit_check (
revision,
status,
started_at,
ended_at
)
SELECT
?, ?, ?, ?
WHERE NOT EXISTS (
SELECT *
FROM commit_check
WHERE revision = ?
)
""",
(
check.revision,
check.status,
check.started_at,
check.ended_at,
check.revision,
),
)
return bool(result.lastrowid)
def update_check_status(log: Log, cursor: Optional[sqlite3.Cursor] = None) -> bool:
"""
Updates the status of a check, adding a log with a reason
"""
cursor = cursor or get_cursor()
ended_at = log.utc_unix_timestamp if log.status in ["success", "failure"] else None
result = cursor.execute(
"""
UPDATE commit_check
SET status = ?,
ended_at = ?
WHERE revision = ?
""",
(log.status, ended_at, log.revision1),
)
return result.rowcount and add_check_log(log, cursor)
def add_check_log(log: Log, cursor: Optional[sqlite3.Cursor] = None) -> bool:
"""
Adds a log for a check message
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
INSERT INTO check_log (
revision,
status,
timestamp,
message
) VALUES (
?, ?, ?, ?
)
""",
(log.revision1, log.status, log.utc_unix_timestamp, log.message,),
)
return bool(result.lastrowid)
def create_deployment(
deployment: Deployment, cursor: Optional[sqlite3.Cursor] = None
) -> bool:
"""
Creates a deployment in the DB
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
INSERT INTO deployment (
from_revision,
to_revision,
status,
started_at,
ended_at
)
SELECT
?, ?, ?, ?, ?
WHERE NOT EXISTS (
SELECT *
FROM deployment
WHERE from_revision = ?
AND to_revision = ?
)
""",
(
deployment.from_revision,
deployment.to_revision,
deployment.status,
deployment.started_at,
deployment.ended_at,
deployment.from_revision,
deployment.to_revision,
),
)
return bool(result.lastrowid)
def update_deployment_status(log: Log, cursor: Optional[sqlite3.Cursor] = None) -> bool:
"""
Updates the status of a deployment, adding a log with a reason
"""
cursor = cursor or get_cursor()
ended_at = log.utc_unix_timestamp if log.status in ["success", "failure"] else None
result = cursor.execute(
"""
UPDATE deployment
SET status = ?,
ended_at = ?
WHERE from_revision = ?
AND to_revision = ?
""",
(log.status, ended_at, log.revision1, log.revision2,),
)
return result.rowcount and add_deployment_log(log, cursor)
def add_deployment_log(log: Log, cursor: Optional[sqlite3.Cursor] = None) -> bool:
"""
Adds a log for a deployment message
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
INSERT INTO deployment_log (
from_revision,
to_revision,
status,
timestamp,
message
) VALUES (
?, ?, ?, ?, ?
)
""",
(
log.revision1,
log.revision2,
log.status,
log.utc_unix_timestamp,
log.message,
),
)
return bool(result.lastrowid)
|
"""
Log database interaction functionality
"""
from os import path
import sqlite3
from typing import Optional, List
from ubiquiti_config_generator.messages.check import Check
from ubiquiti_config_generator.messages.deployment import Deployment
from ubiquiti_config_generator.messages.log import Log
DB_PATH = "messages"
DB_FILE = DB_PATH + "/messages.db"
def initialize_db(db_file: str = DB_FILE) -> sqlite3.Cursor:
"""
Sets up the database for logging
"""
connection = sqlite3.connect(db_file)
cursor = connection.cursor()
table_creation_statements = [
"""
CREATE TABLE IF NOT EXISTS commit_check (
revision VARCHAR(40) PRIMARY KEY,
status VARCHAR(20) NOT NULL,
started_at FLOAT NOT NULL,
ended_at FLOAT NULL
)
""",
"""
CREATE TABLE IF NOT EXISTS check_log (
revision VARCHAR(40) NOT NULL,
status VARCHAR(20) NOT NULL,
timestamp FLOAT NOT NULL,
message TEXT NOT NULL,
FOREIGN KEY (revision)
REFERENCES commit_check (revision)
)
""",
"""
CREATE TABLE IF NOT EXISTS deployment (
from_revision VARCHAR(40),
to_revision VARCHAR(40),
status VARCHAR(20) NOT NULL,
started_at FLOAT NOT NULL,
ended_at FLOAT NULL,
PRIMARY KEY (from_revision, to_revision),
FOREIGN KEY (from_revision)
REFERENCES commit_check (revision),
FOREIGN KEY (to_revision)
REFERENCES commit_check (revision)
)
""",
"""
CREATE TABLE IF NOT EXISTS deployment_log (
from_revision VARCHAR(40),
to_revision VARCHAR(40),
status VARCHAR(20) NOT NULL,
timestamp FLOAT NOT NULL,
message TEXT NOT NULL,
FOREIGN KEY (from_revision)
REFERENCES deployment (from_revision),
FOREIGN KEY (to_revision)
REFERENCES deployment (to_revision)
)
""",
]
for statement in table_creation_statements:
cursor.execute(statement)
return get_cursor(db_file)
def get_cursor(db_file: str = DB_FILE) -> sqlite3.Cursor:
"""
Opens a connection the db and gets a cursor
"""
cursor = (
initialize_db(db_file)
if not path.isfile(db_file)
else sqlite3.connect(db_file, isolation_level=None).cursor()
)
cursor.row_factory = sqlite3.Row
return cursor
def get_check(revision: str, cursor: Optional[sqlite3.Cursor] = None) -> Check:
"""
Get details about a revision check
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"SELECT * FROM commit_check WHERE revision = ?", (revision,)
)
check = result.fetchone()
if not check:
return Check(revision, "nonexistent", 0, 0, [])
return Check(**check, **{"logs": get_check_logs(revision, cursor)})
def get_check_logs(revision: str, cursor: Optional[sqlite3.Cursor] = None) -> List[Log]:
"""
Get the logs for a given check revision
"""
cursor = cursor or get_cursor()
result = cursor.execute("SELECT * FROM check_log WHERE revision = ?", (revision,))
log_results = result.fetchall()
return [
Log(
revision1=log["revision"],
message=log["message"],
status=log["status"],
utc_unix_timestamp=log["timestamp"],
)
for log in log_results
]
def get_deployment(
from_revision: str, to_revision: str, cursor: Optional[sqlite3.Cursor] = None
) -> Check:
"""
Get details about a deployment
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
SELECT *
FROM deployment
WHERE from_revision = ?
AND to_revision = ?
""",
(from_revision, to_revision,),
)
deployment = result.fetchone()
if not deployment:
return Deployment(from_revision, to_revision, "nonexistent", 0, 0, [])
return Deployment(
**deployment,
**{"logs": get_deployment_logs(from_revision, to_revision, cursor)}
)
def get_deployment_logs(
from_revision: str, to_revision: str, cursor: Optional[sqlite3.Cursor] = None
) -> List[Log]:
"""
Get the logs for a given check revision
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
SELECT *
FROM deployment_log
WHERE from_revision = ?
AND to_revision = ?
""",
(from_revision, to_revision,),
)
log_results = result.fetchall()
return [
Log(
revision1=log["from_revision"],
revision2=log["to_revision"],
message=log["message"],
status=log["status"],
utc_unix_timestamp=log["timestamp"],
)
for log in log_results
]
def create_check(check: Check, cursor: Optional[sqlite3.Cursor] = None) -> bool:
"""
Creates a check in the DB
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
INSERT INTO commit_check (
revision,
status,
started_at,
ended_at
)
SELECT
?, ?, ?, ?
WHERE NOT EXISTS (
SELECT *
FROM commit_check
WHERE revision = ?
)
""",
(
check.revision,
check.status,
check.started_at,
check.ended_at,
check.revision,
),
)
return bool(result.lastrowid)
def update_check_status(log: Log, cursor: Optional[sqlite3.Cursor] = None) -> bool:
"""
Updates the status of a check, adding a log with a reason
"""
cursor = cursor or get_cursor()
ended_at = log.utc_unix_timestamp if log.status in ["success", "failure"] else None
result = cursor.execute(
"""
UPDATE commit_check
SET status = ?,
ended_at = ?
WHERE revision = ?
""",
(log.status, ended_at, log.revision1),
)
return result.rowcount and add_check_log(log, cursor)
def add_check_log(log: Log, cursor: Optional[sqlite3.Cursor] = None) -> bool:
"""
Adds a log for a check message
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
INSERT INTO check_log (
revision,
status,
timestamp,
message
) VALUES (
?, ?, ?, ?
)
""",
(log.revision1, log.status, log.utc_unix_timestamp, log.message,),
)
return bool(result.lastrowid)
def create_deployment(
deployment: Deployment, cursor: Optional[sqlite3.Cursor] = None
) -> bool:
"""
Creates a deployment in the DB
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
INSERT INTO deployment (
from_revision,
to_revision,
status,
started_at,
ended_at
)
SELECT
?, ?, ?, ?, ?
WHERE NOT EXISTS (
SELECT *
FROM deployment
WHERE from_revision = ?
AND to_revision = ?
)
""",
(
deployment.from_revision,
deployment.to_revision,
deployment.status,
deployment.started_at,
deployment.ended_at,
deployment.from_revision,
deployment.to_revision,
),
)
return bool(result.lastrowid)
def update_deployment_status(log: Log, cursor: Optional[sqlite3.Cursor] = None) -> bool:
"""
Updates the status of a deployment, adding a log with a reason
"""
cursor = cursor or get_cursor()
ended_at = log.utc_unix_timestamp if log.status in ["success", "failure"] else None
result = cursor.execute(
"""
UPDATE deployment
SET status = ?,
ended_at = ?
WHERE from_revision = ?
AND to_revision = ?
""",
(log.status, ended_at, log.revision1, log.revision2,),
)
return result.rowcount and add_deployment_log(log, cursor)
def add_deployment_log(log: Log, cursor: Optional[sqlite3.Cursor] = None) -> bool:
"""
Adds a log for a deployment message
"""
cursor = cursor or get_cursor()
result = cursor.execute(
"""
INSERT INTO deployment_log (
from_revision,
to_revision,
status,
timestamp,
message
) VALUES (
?, ?, ?, ?, ?
)
""",
(
log.revision1,
log.revision2,
log.status,
log.utc_unix_timestamp,
log.message,
),
)
return bool(result.lastrowid)
|
en
| 0.592649
|
Log database interaction functionality Sets up the database for logging CREATE TABLE IF NOT EXISTS commit_check ( revision VARCHAR(40) PRIMARY KEY, status VARCHAR(20) NOT NULL, started_at FLOAT NOT NULL, ended_at FLOAT NULL ) CREATE TABLE IF NOT EXISTS check_log ( revision VARCHAR(40) NOT NULL, status VARCHAR(20) NOT NULL, timestamp FLOAT NOT NULL, message TEXT NOT NULL, FOREIGN KEY (revision) REFERENCES commit_check (revision) ) CREATE TABLE IF NOT EXISTS deployment ( from_revision VARCHAR(40), to_revision VARCHAR(40), status VARCHAR(20) NOT NULL, started_at FLOAT NOT NULL, ended_at FLOAT NULL, PRIMARY KEY (from_revision, to_revision), FOREIGN KEY (from_revision) REFERENCES commit_check (revision), FOREIGN KEY (to_revision) REFERENCES commit_check (revision) ) CREATE TABLE IF NOT EXISTS deployment_log ( from_revision VARCHAR(40), to_revision VARCHAR(40), status VARCHAR(20) NOT NULL, timestamp FLOAT NOT NULL, message TEXT NOT NULL, FOREIGN KEY (from_revision) REFERENCES deployment (from_revision), FOREIGN KEY (to_revision) REFERENCES deployment (to_revision) ) Opens a connection the db and gets a cursor Get details about a revision check Get the logs for a given check revision Get details about a deployment SELECT * FROM deployment WHERE from_revision = ? AND to_revision = ? Get the logs for a given check revision SELECT * FROM deployment_log WHERE from_revision = ? AND to_revision = ? Creates a check in the DB INSERT INTO commit_check ( revision, status, started_at, ended_at ) SELECT ?, ?, ?, ? WHERE NOT EXISTS ( SELECT * FROM commit_check WHERE revision = ? ) Updates the status of a check, adding a log with a reason UPDATE commit_check SET status = ?, ended_at = ? WHERE revision = ? Adds a log for a check message INSERT INTO check_log ( revision, status, timestamp, message ) VALUES ( ?, ?, ?, ? ) Creates a deployment in the DB INSERT INTO deployment ( from_revision, to_revision, status, started_at, ended_at ) SELECT ?, ?, ?, ?, ? WHERE NOT EXISTS ( SELECT * FROM deployment WHERE from_revision = ? AND to_revision = ? ) Updates the status of a deployment, adding a log with a reason UPDATE deployment SET status = ?, ended_at = ? WHERE from_revision = ? AND to_revision = ? Adds a log for a deployment message INSERT INTO deployment_log ( from_revision, to_revision, status, timestamp, message ) VALUES ( ?, ?, ?, ?, ? )
| 2.538122
| 3
|
machine_learning/bayesian_is_devil.py
|
zmaas/scratch
| 0
|
6626347
|
<gh_stars>0
'''Naive Implementation of the Monty Hall Problem'''
import random
doors = ["goat"] * 2 + ["car"]
win = 0
loss = 0
for i in range(100000):
# Shuffle Doors
random.shuffle(doors)
# Pick a random choice
n = random.randrange(3)
sequence = list(range(3))
random.shuffle(sequence)
if doors[n] == "car":
loss += 1
else:
win += 1
## This is 2/3, showing that bayesian statistics is witchcraft
print("Switching Win Rate: ", (100*win)/(win+loss), "%")
|
'''Naive Implementation of the Monty Hall Problem'''
import random
doors = ["goat"] * 2 + ["car"]
win = 0
loss = 0
for i in range(100000):
# Shuffle Doors
random.shuffle(doors)
# Pick a random choice
n = random.randrange(3)
sequence = list(range(3))
random.shuffle(sequence)
if doors[n] == "car":
loss += 1
else:
win += 1
## This is 2/3, showing that bayesian statistics is witchcraft
print("Switching Win Rate: ", (100*win)/(win+loss), "%")
|
en
| 0.832151
|
Naive Implementation of the Monty Hall Problem # Shuffle Doors # Pick a random choice ## This is 2/3, showing that bayesian statistics is witchcraft
| 3.788029
| 4
|
chalupa/views.py
|
maxmilianstoklasa/zaverecny_projekt
| 0
|
6626348
|
<reponame>maxmilianstoklasa/zaverecny_projekt<gh_stars>0
from django.http import request, HttpResponseRedirect
from datetime import datetime, date, timedelta
from django.shortcuts import render, HttpResponse, get_object_or_404, redirect
from django.views import generic
from django.views.generic import ListView, FormView, View, DetailView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.urls import reverse, reverse_lazy
from django.utils.safestring import mark_safe
from .models import Room, Booking, Attachment, Category
from .forms import AvailabilityForm, Calendar, BookingForm
import calendar
from chalupa.booking_functions.availability import availability
# Create your views here.
# domovská stránka
def index(request):
num_visits = request.session.get('num_visits', 0)
request.session['num_visits'] = num_visits + 1
context = {
'num_visits': num_visits,
}
return render(request, 'index.html', context=context)
class RoomListView(generic.ListView):
model = Room
context_object_name = 'room_list'
template_name = 'chalupa/room_list.html'
# detail pokoje
'''class RoomDetailView(View):
def get(self, request, *args, **kwargs):
name = self.kwargs.get('name', None)
form = AvailabilityForm()
room_list = Room.objects.filter(name=name)
if len(room_list) > 0:
room = room_list[0]
room_name = dict(room.room_names).get(room.name, None)
context = {
'room_name': room_name,
'form': form
}
return render(request, 'room_detail_view.html', context)
else:
return HttpResponse('Tento pokoj neexistuje')'''
class RoomDetailView(generic.DetailView):
model = Room
context_object_name = 'room_detail'
template_name = 'chalupa/room_detail.html'
# Toto je nadbytečné
'''def post(self, request, *args, **kwargs):
name = self.kwargs.get('name', None)
room_list = Room.objects.filter(name=name)
form = AvailabilityForm(request.POST)
if availability(data['check_in'], data['check_out']):
bookings = Booking.objects.create(
user=self.request.user,
check_in=data['check_in'],
check_out=data['check_out'],
)
bookings.save()
return HttpResponse(bookings)
else:
return HttpResponse('Tenhle termín je už rezervovaný')
form.print_form()
return super().form_valid(form)'''
# rezervace termínu
class BookingView(LoginRequiredMixin, FormView, ListView):
form_class = AvailabilityForm
template_name = 'chalupa/booking_view.html'
def form_valid(self, form):
data = form.cleaned_data
if availability(data['check_in'], data['check_out']):
booking = Booking.objects.create(
user=self.request.user,
check_in=data['check_in'],
check_out=data['check_out'],
number_of_guests=data['number_of_guests'],
note=data['note'], )
booking.save()
return HttpResponse(booking)
else:
return HttpResponse('Tento termín už je rezervovaný')
# form.print_form()
# return super().form_valid(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
d = get_date(self.request.GET.get('month', None))
cal = Calendar(d.year, d.month)
html_cal = cal.formatmonth(withyear=True)
context['calendar'] = mark_safe(html_cal)
context['prev_month'] = prev_month(d)
context['next_month'] = next_month(d)
return context
def get_queryset(self, *args, **kwargs):
if self.request.user.is_staff:
booking_list = Booking.objects.all()
return booking_list
else:
booking_list = Booking.objects.filter(user=self.request.user)
return booking_list
def prev_month(d):
first = d.replace(day=1)
prev_month = first - timedelta(days=1)
month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month)
return month
def next_month(d):
days_in_month = calendar.monthrange(d.year, d.month)[1]
last = d.replace(day=days_in_month)
next_month = last + timedelta(days=1)
month = 'month=' + str(next_month.year) + '-' + str(next_month.month)
return month
def get_date(req_day):
if req_day:
year, month = (int(x) for x in req_day.split('-'))
return date(year, month, day=1)
return datetime.today()
def booking_edit(request, booking_id=None):
instance = Booking()
if booking_id:
instance = get_object_or_404(Booking, pk=booking_id)
else:
instance = Booking()
form = BookingForm(request.POST or None, instance=instance)
if request.POST and form.is_valid():
form.save()
return HttpResponseRedirect(reverse('chalupa:BookingView'))
return render(request, 'chalupa/booking_edit.html', {'form': form})
class BookingCancelView(LoginRequiredMixin, DeleteView):
model = Booking
template_name = 'chalupa/booking_cancel.html'
success_url = reverse_lazy('chalupa:BookingView')
def gallery(request):
category = request.GET.get('category')
if category == None:
images = Attachment.objects.all()
else:
images = Attachment.objects.filter(category__name=category)
categories = Category.objects.all()
context = {'categories': categories, 'images': images}
return render(request, 'chalupa/gallery.html', context)
def view_image(request, pk):
image = Attachment.objects.get(id=pk)
return render(request, 'chalupa/gallery.html', {'image': image})
def add_image(request):
categories = Category.objects.all()
if request.method == 'POST':
data = request.POST
image = request.FILES.get('image')
if data['category'] != 'none':
category = Category.objects.get(id=data['category'])
elif data['category_new'] != '':
category, created = Category.objects.get_or_create(title=data['category_new'])
else:
category = None
attachment = Attachment.objects.create(
title=data['title'],
category=category,
image=image,
)
return redirect('chalupa:Gallery')
context = {'categories': categories}
return render(request, 'chalupa/image_add.html', context)
'''class CalendarView(generic.ListView):
model = Booking
template_name = 'booking_view.html'
'''
|
from django.http import request, HttpResponseRedirect
from datetime import datetime, date, timedelta
from django.shortcuts import render, HttpResponse, get_object_or_404, redirect
from django.views import generic
from django.views.generic import ListView, FormView, View, DetailView, DeleteView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.urls import reverse, reverse_lazy
from django.utils.safestring import mark_safe
from .models import Room, Booking, Attachment, Category
from .forms import AvailabilityForm, Calendar, BookingForm
import calendar
from chalupa.booking_functions.availability import availability
# Create your views here.
# domovská stránka
def index(request):
num_visits = request.session.get('num_visits', 0)
request.session['num_visits'] = num_visits + 1
context = {
'num_visits': num_visits,
}
return render(request, 'index.html', context=context)
class RoomListView(generic.ListView):
model = Room
context_object_name = 'room_list'
template_name = 'chalupa/room_list.html'
# detail pokoje
'''class RoomDetailView(View):
def get(self, request, *args, **kwargs):
name = self.kwargs.get('name', None)
form = AvailabilityForm()
room_list = Room.objects.filter(name=name)
if len(room_list) > 0:
room = room_list[0]
room_name = dict(room.room_names).get(room.name, None)
context = {
'room_name': room_name,
'form': form
}
return render(request, 'room_detail_view.html', context)
else:
return HttpResponse('Tento pokoj neexistuje')'''
class RoomDetailView(generic.DetailView):
model = Room
context_object_name = 'room_detail'
template_name = 'chalupa/room_detail.html'
# Toto je nadbytečné
'''def post(self, request, *args, **kwargs):
name = self.kwargs.get('name', None)
room_list = Room.objects.filter(name=name)
form = AvailabilityForm(request.POST)
if availability(data['check_in'], data['check_out']):
bookings = Booking.objects.create(
user=self.request.user,
check_in=data['check_in'],
check_out=data['check_out'],
)
bookings.save()
return HttpResponse(bookings)
else:
return HttpResponse('Tenhle termín je už rezervovaný')
form.print_form()
return super().form_valid(form)'''
# rezervace termínu
class BookingView(LoginRequiredMixin, FormView, ListView):
form_class = AvailabilityForm
template_name = 'chalupa/booking_view.html'
def form_valid(self, form):
data = form.cleaned_data
if availability(data['check_in'], data['check_out']):
booking = Booking.objects.create(
user=self.request.user,
check_in=data['check_in'],
check_out=data['check_out'],
number_of_guests=data['number_of_guests'],
note=data['note'], )
booking.save()
return HttpResponse(booking)
else:
return HttpResponse('Tento termín už je rezervovaný')
# form.print_form()
# return super().form_valid(form)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
d = get_date(self.request.GET.get('month', None))
cal = Calendar(d.year, d.month)
html_cal = cal.formatmonth(withyear=True)
context['calendar'] = mark_safe(html_cal)
context['prev_month'] = prev_month(d)
context['next_month'] = next_month(d)
return context
def get_queryset(self, *args, **kwargs):
if self.request.user.is_staff:
booking_list = Booking.objects.all()
return booking_list
else:
booking_list = Booking.objects.filter(user=self.request.user)
return booking_list
def prev_month(d):
first = d.replace(day=1)
prev_month = first - timedelta(days=1)
month = 'month=' + str(prev_month.year) + '-' + str(prev_month.month)
return month
def next_month(d):
days_in_month = calendar.monthrange(d.year, d.month)[1]
last = d.replace(day=days_in_month)
next_month = last + timedelta(days=1)
month = 'month=' + str(next_month.year) + '-' + str(next_month.month)
return month
def get_date(req_day):
if req_day:
year, month = (int(x) for x in req_day.split('-'))
return date(year, month, day=1)
return datetime.today()
def booking_edit(request, booking_id=None):
instance = Booking()
if booking_id:
instance = get_object_or_404(Booking, pk=booking_id)
else:
instance = Booking()
form = BookingForm(request.POST or None, instance=instance)
if request.POST and form.is_valid():
form.save()
return HttpResponseRedirect(reverse('chalupa:BookingView'))
return render(request, 'chalupa/booking_edit.html', {'form': form})
class BookingCancelView(LoginRequiredMixin, DeleteView):
model = Booking
template_name = 'chalupa/booking_cancel.html'
success_url = reverse_lazy('chalupa:BookingView')
def gallery(request):
category = request.GET.get('category')
if category == None:
images = Attachment.objects.all()
else:
images = Attachment.objects.filter(category__name=category)
categories = Category.objects.all()
context = {'categories': categories, 'images': images}
return render(request, 'chalupa/gallery.html', context)
def view_image(request, pk):
image = Attachment.objects.get(id=pk)
return render(request, 'chalupa/gallery.html', {'image': image})
def add_image(request):
categories = Category.objects.all()
if request.method == 'POST':
data = request.POST
image = request.FILES.get('image')
if data['category'] != 'none':
category = Category.objects.get(id=data['category'])
elif data['category_new'] != '':
category, created = Category.objects.get_or_create(title=data['category_new'])
else:
category = None
attachment = Attachment.objects.create(
title=data['title'],
category=category,
image=image,
)
return redirect('chalupa:Gallery')
context = {'categories': categories}
return render(request, 'chalupa/image_add.html', context)
'''class CalendarView(generic.ListView):
model = Booking
template_name = 'booking_view.html'
'''
|
en
| 0.261646
|
# Create your views here. # domovská stránka # detail pokoje class RoomDetailView(View): def get(self, request, *args, **kwargs): name = self.kwargs.get('name', None) form = AvailabilityForm() room_list = Room.objects.filter(name=name) if len(room_list) > 0: room = room_list[0] room_name = dict(room.room_names).get(room.name, None) context = { 'room_name': room_name, 'form': form } return render(request, 'room_detail_view.html', context) else: return HttpResponse('Tento pokoj neexistuje') # Toto je nadbytečné def post(self, request, *args, **kwargs): name = self.kwargs.get('name', None) room_list = Room.objects.filter(name=name) form = AvailabilityForm(request.POST) if availability(data['check_in'], data['check_out']): bookings = Booking.objects.create( user=self.request.user, check_in=data['check_in'], check_out=data['check_out'], ) bookings.save() return HttpResponse(bookings) else: return HttpResponse('Tenhle termín je už rezervovaný') form.print_form() return super().form_valid(form) # rezervace termínu # form.print_form() # return super().form_valid(form) class CalendarView(generic.ListView): model = Booking template_name = 'booking_view.html'
| 1.985279
| 2
|
section_1/lesson6_step2b_find_element_by_id.py
|
MikePolyakov/selenium_course
| 0
|
6626349
|
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# By.ID – поиск по уникальному атрибуту id элемента;
# By.CSS_SELECTOR – поиск элементов с помощью правил на основе CSS;
# By.XPATH – поиск элементов с помощью языка запросов XPath;
# By.NAME – поиск по атрибуту name элемента;
# By.TAG_NAME – поиск по названию тега;
# By.CLASS_NAME – поиск по атрибуту class элемента;
# By.LINK_TEXT – поиск ссылки с указанным текстом. Текст ссылки должен быть точным совпадением;
# By.PARTIAL_LINK_TEXT – поиск ссылки по частичному совпадению текста.
browser = webdriver.Chrome()
browser.get("http://suninjuly.github.io/simple_form_find_task.html")
button = browser.find_element(By.ID, "submit_button")
print("button=", button)
time.sleep(5)
browser.quit()
|
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
# By.ID – поиск по уникальному атрибуту id элемента;
# By.CSS_SELECTOR – поиск элементов с помощью правил на основе CSS;
# By.XPATH – поиск элементов с помощью языка запросов XPath;
# By.NAME – поиск по атрибуту name элемента;
# By.TAG_NAME – поиск по названию тега;
# By.CLASS_NAME – поиск по атрибуту class элемента;
# By.LINK_TEXT – поиск ссылки с указанным текстом. Текст ссылки должен быть точным совпадением;
# By.PARTIAL_LINK_TEXT – поиск ссылки по частичному совпадению текста.
browser = webdriver.Chrome()
browser.get("http://suninjuly.github.io/simple_form_find_task.html")
button = browser.find_element(By.ID, "submit_button")
print("button=", button)
time.sleep(5)
browser.quit()
|
ru
| 0.966006
|
# By.ID – поиск по уникальному атрибуту id элемента; # By.CSS_SELECTOR – поиск элементов с помощью правил на основе CSS; # By.XPATH – поиск элементов с помощью языка запросов XPath; # By.NAME – поиск по атрибуту name элемента; # By.TAG_NAME – поиск по названию тега; # By.CLASS_NAME – поиск по атрибуту class элемента; # By.LINK_TEXT – поиск ссылки с указанным текстом. Текст ссылки должен быть точным совпадением; # By.PARTIAL_LINK_TEXT – поиск ссылки по частичному совпадению текста.
| 3.148125
| 3
|
export_pipelines.py
|
odin243/distil-auto-ml
| 0
|
6626350
|
import os
import sys
import copy
import json
import logging
import importlib
import hashlib
import traceback
# Make the output a bit quieter...
l = logging.getLogger()
l.addHandler(logging.NullHandler())
# Dir to save files in
META_DIR = 'pipelines'
# Map of default datasets to configure .meta files
# and metric for pipeline config
PIPE_TO_DATASET = {
'tabular': ('185_baseball', 'f1Macro', {}),
'audio': ('31_urbansound', 'accuracy', {}),
'clustering': ('1491_one_hundred_plants_margin_clust', 'normalizedMutualInformation', {
'num_clusters': 100,
'cluster_col_name': 'Class'
}),
'collaborative_filtering': ('60_jester', 'meanAbsoluteError', {}),
'community_detection': ('6_70_com_amazon', 'normalizedMutualInformation', {}),
'graph_matching': ('49_facebook', 'accuracy', {}),
'image': ('22_handgeometry', 'meanSquaredError', {}),
'object_detection': ('LL1_penn_fudan_pedestrian', 'objectDetectionAP', {}),
'link_prediction': ('59_umls', 'accuracy', {}),
'question_answer': ('32_wikiqa', 'f1', {}),
'text': ('30_personae', 'f1', {}),
'timeseries_forecasting': ('56_sunspots_monthly', 'rootMeanSquaredError', {}),
'timeseries_classification': ('LL1_50words', 'f1Macro', {}),
'timeseries_kanine': ('LL1_50words', 'f1Macro', {}),
'timeseries_var': ('56_sunspots', 'rootMeanSquaredError', {}),
'vertex_nomination': ('LL1_net_nomination_seed', 'accuracy', {}),
'vertex_classification': ('LL1_VTXC_1369_synthetic', 'f1Macro', {}),
}
# Skeleton of .meta data
META = {
"problem": "{}_problem",
"full_inputs": [
"{}_dataset"
],
"train_inputs": [
"{}_dataset_TRAIN"
],
"test_inputs": [
"{}_dataset_TEST"
],
"score_inputs": [
"{}_dataset_SCORE"
]
}
# Gotta update that meta somehow
def set_meta(dataset):
meta = copy.deepcopy(META)
for k, v in meta.items():
if type(v) == str:
meta[k] = meta[k].format(dataset)
elif type(v) == list:
meta[k][0] = meta[k][0].format(dataset)
return meta
def generate_hash(pipe_json):
# generate a hash from invariant pipeline data
pipe_json_mod = copy.deepcopy(pipe_json)
pipe_json_mod['id'] = ''
pipe_json_mod['created'] = ''
pipe_json_mod['digest'] = ''
return hashlib.md5(json.dumps(pipe_json_mod,sort_keys=True).encode('utf8')).hexdigest()
def generate_file_info():
print('Generating hashes of existing files....')
# open the existing pipeline dir and generate hashes for each
files = [f for f in os.listdir(META_DIR) if '.json' in f]
hashes = set()
pipeline_filenames = {}
for f in files:
# generate a hash for the file
with open(os.path.join(META_DIR, f)) as json_data:
hashes.add(generate_hash(json.load(json_data)))
# grab the pipeline name and map it to the file
pipeline_name, pipeline_id = f.split('__')
pipeline_filenames[pipeline_name] = os.path.join(META_DIR, f.replace('.json', ''))
return hashes, pipeline_filenames
if __name__ == '__main__':
# create a hash of the existing invariant pipeline file contents, and a map
# of pipeline names to pipeline file names
pipeline_hashes, pipeline_filenames = generate_file_info()
# List all the pipelines
PIPELINES_DIR = 'processing/pipelines'
pipelines = [f for f in os.listdir(PIPELINES_DIR) if '.py' in f]
# For each pipeline, load it and export it
for pipe in pipelines:
p = pipe.replace('.py', '')
print("Handling {}...".format(p))
lib = importlib.import_module('processing.pipelines.' + p)
try:
dataset_to_use, metric, hyperparams = PIPE_TO_DATASET[p]
pipe_json = lib.create_pipeline(metric=metric, **hyperparams).to_json_structure()
hash = generate_hash(pipe_json)
print(f'Hash for {pipe}: {hash}')
if hash in pipeline_hashes:
print(f'Skipping unchanged pipeline for {pipe}')
continue
id = pipe_json['id']
filename = p + '__' + id
# check if there are existing files asssociated with this pipeline type
# and delete
if p in pipeline_filenames:
os.remove(os.path.join(pipeline_filenames[p] + '.json'))
os.remove(os.path.join(pipeline_filenames[p] + '.meta'))
json_filename = os.path.join(META_DIR, filename + '.json')
meta_filename = os.path.join(META_DIR, filename + '.meta')
print(f'Writing {filename}')
with open(json_filename, 'w') as f:
f.write(json.dumps(pipe_json, indent=4))
f.write('\n')
# Get meta alongside pipeline
meta = set_meta(dataset_to_use)
with open(meta_filename, 'w') as f:
f.write(json.dumps(meta, indent=4))
f.write('\n')
except Exception as e:
traceback.print_exc()
sys.exit(0)
|
import os
import sys
import copy
import json
import logging
import importlib
import hashlib
import traceback
# Make the output a bit quieter...
l = logging.getLogger()
l.addHandler(logging.NullHandler())
# Dir to save files in
META_DIR = 'pipelines'
# Map of default datasets to configure .meta files
# and metric for pipeline config
PIPE_TO_DATASET = {
'tabular': ('185_baseball', 'f1Macro', {}),
'audio': ('31_urbansound', 'accuracy', {}),
'clustering': ('1491_one_hundred_plants_margin_clust', 'normalizedMutualInformation', {
'num_clusters': 100,
'cluster_col_name': 'Class'
}),
'collaborative_filtering': ('60_jester', 'meanAbsoluteError', {}),
'community_detection': ('6_70_com_amazon', 'normalizedMutualInformation', {}),
'graph_matching': ('49_facebook', 'accuracy', {}),
'image': ('22_handgeometry', 'meanSquaredError', {}),
'object_detection': ('LL1_penn_fudan_pedestrian', 'objectDetectionAP', {}),
'link_prediction': ('59_umls', 'accuracy', {}),
'question_answer': ('32_wikiqa', 'f1', {}),
'text': ('30_personae', 'f1', {}),
'timeseries_forecasting': ('56_sunspots_monthly', 'rootMeanSquaredError', {}),
'timeseries_classification': ('LL1_50words', 'f1Macro', {}),
'timeseries_kanine': ('LL1_50words', 'f1Macro', {}),
'timeseries_var': ('56_sunspots', 'rootMeanSquaredError', {}),
'vertex_nomination': ('LL1_net_nomination_seed', 'accuracy', {}),
'vertex_classification': ('LL1_VTXC_1369_synthetic', 'f1Macro', {}),
}
# Skeleton of .meta data
META = {
"problem": "{}_problem",
"full_inputs": [
"{}_dataset"
],
"train_inputs": [
"{}_dataset_TRAIN"
],
"test_inputs": [
"{}_dataset_TEST"
],
"score_inputs": [
"{}_dataset_SCORE"
]
}
# Gotta update that meta somehow
def set_meta(dataset):
meta = copy.deepcopy(META)
for k, v in meta.items():
if type(v) == str:
meta[k] = meta[k].format(dataset)
elif type(v) == list:
meta[k][0] = meta[k][0].format(dataset)
return meta
def generate_hash(pipe_json):
# generate a hash from invariant pipeline data
pipe_json_mod = copy.deepcopy(pipe_json)
pipe_json_mod['id'] = ''
pipe_json_mod['created'] = ''
pipe_json_mod['digest'] = ''
return hashlib.md5(json.dumps(pipe_json_mod,sort_keys=True).encode('utf8')).hexdigest()
def generate_file_info():
print('Generating hashes of existing files....')
# open the existing pipeline dir and generate hashes for each
files = [f for f in os.listdir(META_DIR) if '.json' in f]
hashes = set()
pipeline_filenames = {}
for f in files:
# generate a hash for the file
with open(os.path.join(META_DIR, f)) as json_data:
hashes.add(generate_hash(json.load(json_data)))
# grab the pipeline name and map it to the file
pipeline_name, pipeline_id = f.split('__')
pipeline_filenames[pipeline_name] = os.path.join(META_DIR, f.replace('.json', ''))
return hashes, pipeline_filenames
if __name__ == '__main__':
# create a hash of the existing invariant pipeline file contents, and a map
# of pipeline names to pipeline file names
pipeline_hashes, pipeline_filenames = generate_file_info()
# List all the pipelines
PIPELINES_DIR = 'processing/pipelines'
pipelines = [f for f in os.listdir(PIPELINES_DIR) if '.py' in f]
# For each pipeline, load it and export it
for pipe in pipelines:
p = pipe.replace('.py', '')
print("Handling {}...".format(p))
lib = importlib.import_module('processing.pipelines.' + p)
try:
dataset_to_use, metric, hyperparams = PIPE_TO_DATASET[p]
pipe_json = lib.create_pipeline(metric=metric, **hyperparams).to_json_structure()
hash = generate_hash(pipe_json)
print(f'Hash for {pipe}: {hash}')
if hash in pipeline_hashes:
print(f'Skipping unchanged pipeline for {pipe}')
continue
id = pipe_json['id']
filename = p + '__' + id
# check if there are existing files asssociated with this pipeline type
# and delete
if p in pipeline_filenames:
os.remove(os.path.join(pipeline_filenames[p] + '.json'))
os.remove(os.path.join(pipeline_filenames[p] + '.meta'))
json_filename = os.path.join(META_DIR, filename + '.json')
meta_filename = os.path.join(META_DIR, filename + '.meta')
print(f'Writing {filename}')
with open(json_filename, 'w') as f:
f.write(json.dumps(pipe_json, indent=4))
f.write('\n')
# Get meta alongside pipeline
meta = set_meta(dataset_to_use)
with open(meta_filename, 'w') as f:
f.write(json.dumps(meta, indent=4))
f.write('\n')
except Exception as e:
traceback.print_exc()
sys.exit(0)
|
en
| 0.759813
|
# Make the output a bit quieter... # Dir to save files in # Map of default datasets to configure .meta files # and metric for pipeline config # Skeleton of .meta data # Gotta update that meta somehow # generate a hash from invariant pipeline data # open the existing pipeline dir and generate hashes for each # generate a hash for the file # grab the pipeline name and map it to the file # create a hash of the existing invariant pipeline file contents, and a map # of pipeline names to pipeline file names # List all the pipelines # For each pipeline, load it and export it # check if there are existing files asssociated with this pipeline type # and delete # Get meta alongside pipeline
| 1.746163
| 2
|