content stringlengths 1 1.04M | input_ids listlengths 1 774k | ratio_char_token float64 0.38 22.9 | token_count int64 1 774k |
|---|---|---|---|
from dataclasses import dataclass
from typing_extensions import Final
# Constants
ID: Final = "id"
NAME: Final = "name"
URL_BACKGROUND: Final = "urlbackground"
CODE: Final = "code"
TYPE: Final = "type"
HAS_MEDALS: Final = "hasmedals"
LEVEL: Final = "level"
NAME_LEVEL: Final = "namelevel"
PROGRESSION: Final = "progression"
@dataclass(frozen=True)
| [
6738,
4818,
330,
28958,
1330,
4818,
330,
31172,
198,
198,
6738,
19720,
62,
2302,
5736,
1330,
8125,
198,
198,
2,
4757,
1187,
198,
2389,
25,
8125,
796,
366,
312,
1,
198,
20608,
25,
8125,
796,
366,
3672,
1,
198,
21886,
62,
31098,
46025... | 2.793651 | 126 |
# -*- coding: utf-8 -*-
# Copyright (C) 2014-2017 Andrey Antukh <niwi@niwi.nz>
# Copyright (C) 2014-2017 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014-2017 David Barragán <bameda@dbarragan.com>
# Copyright (C) 2014-2017 Alejandro Alonso <alejandro.alonso@kaleidos.net>
# Copyright (C) 2014-2017 Anler Hernández <hello@anler.me>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import pytest
from unittest import mock
from django.core.urlresolvers import reverse
from django.core import mail
from taiga.base.utils import json
from taiga.hooks.github import event_hooks
from taiga.hooks.github.api import GitHubViewSet
from taiga.hooks.exceptions import ActionSyntaxException
from taiga.projects import choices as project_choices
from taiga.projects.epics.models import Epic
from taiga.projects.issues.models import Issue
from taiga.projects.tasks.models import Task
from taiga.projects.userstories.models import UserStory
from taiga.projects.models import Membership
from taiga.projects.history.services import get_history_queryset_by_model_instance, take_snapshot
from taiga.projects.notifications.choices import NotifyLevel
from taiga.projects.notifications.models import NotifyPolicy
from taiga.projects import services
from .. import factories as f
pytestmark = pytest.mark.django_db
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
15069,
357,
34,
8,
1946,
12,
5539,
843,
4364,
3738,
2724,
71,
1279,
8461,
37686,
31,
8461,
37686,
13,
27305,
29,
198,
2,
15069,
357,
34,
8,
1946,
12,
5539,
4804,
... | 3.397188 | 569 |
import os
import sys
import random
import math
import re
import time
import numpy as np
import tensorflow as tf
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import shutil
import glob
import os.path as osp
# Root directory of the project
ROOT_DIR = os.path.abspath("../../")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
from mrcnn import utils
from mrcnn import visualize_edited as visualize
from mrcnn.visualize_edited import display_images
import mrcnn.model as modellib
from mrcnn.model import log
import skimage.draw
import cv2
# %matplotlib inline
# Directory to save logs and trained model
MODEL_DIR = os.path.join(ROOT_DIR, "logs")
# Local path to trained weights file
COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")
# Download COCO trained weights from Releases if needed
if not os.path.exists(COCO_MODEL_PATH):
utils.download_trained_weights(COCO_MODEL_PATH)
# Path to Shapes trained weights
SHAPES_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_shapes.h5")
from mrcnn.config import Config
class ObjectDetectionConfig(Config):
"""Configuration for training on the buildings and ground detection.
Derives from the base Config class and overrides some values.
"""
# Give the configuration a recognizable name
NAME = "objectDetection"
# We use a GPU with 12GB memory, which can fit two images.
# Adjust down if you use a smaller GPU.
IMAGES_PER_GPU = 2
# Number of classes (including background)
NUM_CLASSES = 1 + 5 # Background + building-ground classes
# Number of training steps per epoch
STEPS_PER_EPOCH = 500
# Skip detections with < 90% confidence
DETECTION_MIN_CONFIDENCE = 0.9
# my object detection config:
config = InferenceConfig()
data_DIR_images = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\images\\"
data_DIR_lables = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\labels\\"
data_DIR_thermals = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\thermals\\"
data_DIR_predicts = "F:\\MaskRCNN\\Mask_RCNN\\myproject\\objectDetection\\finalDatasets\\valing\\predicts\\"
# Override the training configurations with a few
# changes for inferencing.
config = InferenceConfig()
DEVICE = "/cpu:0" # /cpu:0 or /gpu:0
# Inspect the model in training or inference modes
# values: 'inference' or 'training'
# TODO: code for 'training' test mode not ready yet
TEST_MODE = "inference"
class_names = ['background','building_roof', 'ground_cars', 'building_facade', 'ground_cars', 'building_roof']
# Create model in inference mode
with tf.device(DEVICE):
model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR,
config=config)
weights_path = model.find_last()
# Load weights
print("Loading weights ", weights_path)
model.load_weights(weights_path, by_name=True)
names = [x for x in os.listdir(data_DIR_images) if ".jpg" in x] #new
for name in names:
name = name.split(".")[0]
image = skimage.io.imread(data_DIR_images + name+".jpg")
thermal = skimage.io.imread(data_DIR_thermals + name+".jpg")
image = np.concatenate((image, thermal), axis=2)
gt_image = cv2.imread(data_DIR_lables+name+".png")
# Run object detection
results = model.detect([image], verbose=1)
# Display results
r = results[0]
pred_image = visualize.return_save(image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores'], title="Predictions")
gt_image = cv2.cvtColor(gt_image, cv2.COLOR_BGR2RGB)
pred_image = pred_image[:, :, ::-1]
# pred_image = np.array(pred_image,dtype=np.uint8)
# pred_image = cv2.cvtColor(pred_image, cv2.COLOR_BGR2RGB)
plt.imshow(pred_image)
plt.show()
plt.imshow(image)
plt.show()
plt.imshow(gt_image)
plt.show()
print(gt_image[900,400])
print(pred_image[1000,400])
# cv2.imwrite(data_DIR_predicts+name+".png", pred_image)
skimage.io.imsave(data_DIR_predicts+name+".png", pred_image)
| [
11748,
28686,
201,
198,
11748,
25064,
201,
198,
11748,
4738,
201,
198,
11748,
10688,
201,
198,
11748,
302,
201,
198,
11748,
640,
201,
198,
11748,
299,
32152,
355,
45941,
201,
198,
11748,
11192,
273,
11125,
355,
48700,
201,
198,
11748,
2... | 2.552885 | 1,664 |
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
# FUNDAMENTALS STRINGS HASHES DATA STRUCTURES
import unittest
import allure
from utils.log_func import print_log
from kyu_6.count_letters_in_string.count_letters_in_string import letter_count
@allure.epic('6 kyu')
@allure.parent_suite('Novice')
@allure.suite("Data Structures")
@allure.sub_suite("Unit Tests")
@allure.feature("String")
@allure.story('Count letters in string')
@allure.tag('FUNDAMENTALS', 'STRINGS', 'HASHES', 'DATA STRUCTURES')
@allure.link(url='',
name='Source/Kata')
class CountLettersInStringTestCase(unittest.TestCase):
"""
Testing 'letter_count' function
"""
def test_count_letters_in_string(self):
"""
Testing 'letter_count' function
:return:
"""
allure.dynamic.title("Testing 'letter_count' function")
allure.dynamic.severity(allure.severity_level.NORMAL)
allure.dynamic.description_html('<h3>Codewars badge:</h3>'
'<img src="https://www.codewars.com/users/myFirstCode'
'/badges/large">'
'<h3>Test Description:</h3>'
"<p></p>")
with allure.step("Enter test string and verify the output"):
string = "codewars"
expected = {"a": 1, "c": 1, "d": 1, "e": 1,
"o": 1, "r": 1, "s": 1, "w": 1}
print_log(string=string, expected=expected)
self.assertEqual(expected, letter_count(string))
with allure.step("Enter test string and verify the output"):
string = "activity"
expected = {"a": 1, "c": 1, "i": 2, "t": 2,
"v": 1, "y": 1}
print_log(string=string, expected=expected)
self.assertEqual(expected, letter_count(string))
with allure.step("Enter test string and verify the output"):
string = "arithmetics"
expected = {"a": 1, "c": 1, "e": 1, "h": 1,
"i": 2, "m": 1, "r": 1, "s": 1, "t": 2}
print_log(string=string, expected=expected)
self.assertEqual(expected, letter_count(string))
with allure.step("Enter test string and verify the output"):
string = "traveller"
expected = {"a": 1, "e": 2, "l": 2,
"r": 2, "t": 1, "v": 1}
print_log(string=string, expected=expected)
self.assertEqual(expected, letter_count(string))
with allure.step("Enter test string and verify the output"):
string = "daydreamer"
expected = {"a": 2, "d": 2, "e": 2,
"m": 1, "r": 2, "y": 1}
print_log(string=string, expected=expected)
self.assertEqual(expected, letter_count(string))
| [
2,
220,
15622,
416,
412,
7053,
509,
455,
272,
13,
198,
2,
220,
21722,
25,
3740,
1378,
12567,
13,
785,
14,
1134,
455,
272,
198,
2,
220,
27133,
25,
3740,
1378,
2503,
13,
25614,
259,
13,
785,
14,
259,
14,
1533,
273,
12,
74,
455,
... | 2.028159 | 1,456 |
import torch
from functools import wraps
@wraps(torch._nested_tensor)
# TODO: This entire class is not really necessary now that NestedTensor lives
# in tree; before it lived out of tree and there was no way to conveniently
# override the string printing behavior. Now that we are in tree, we can
# directly override _tensor_str to capture this behavior, and the wrapper subclass
# is not necessary. See also https://github.com/pytorch/pytorch/issues/73506
| [
11748,
28034,
198,
6738,
1257,
310,
10141,
1330,
27521,
628,
198,
31,
29988,
862,
7,
13165,
354,
13557,
77,
7287,
62,
83,
22854,
8,
628,
198,
2,
16926,
46,
25,
770,
2104,
1398,
318,
407,
1107,
3306,
783,
326,
399,
7287,
51,
22854,
... | 3.696 | 125 |
# coding=utf-8
"""
stop.py
divia_api is a Python library that allows to retrieve the timetable
of Divia’s bus and tramways straight from a Python script.
Copyright (C) 2021 Firmin Launay
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from browser import ajax
from datetime import datetime, timedelta
two_minutes = timedelta(minutes=2)
one_day = timedelta(days=1)
| [
2,
19617,
28,
40477,
12,
23,
198,
198,
37811,
198,
11338,
13,
9078,
198,
198,
7146,
544,
62,
15042,
318,
257,
11361,
5888,
326,
3578,
284,
19818,
262,
40021,
198,
1659,
4777,
544,
447,
247,
82,
1323,
290,
29957,
1322,
3892,
422,
257... | 3.679688 | 256 |
import functools
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
import pika
import ujson
from django.conf import settings
from typing import Callable, Any, Optional, List
"""
BB = Bitrix24 Bridge
"""
def get_var(name) -> Callable[[], Optional[Any]]:
"""
Safe wraper over settings
:param name:
:return: Callable[[], Optional[Any]] - get param from settings if it defined, else return None
"""
return functools.partial(getattr, settings, name, None)
@dataclass
@dataclass
| [
11748,
1257,
310,
10141,
198,
6738,
450,
66,
1330,
9738,
11,
12531,
24396,
198,
6738,
4818,
330,
28958,
1330,
4818,
330,
31172,
11,
2214,
198,
198,
11748,
279,
9232,
198,
11748,
334,
17752,
198,
6738,
42625,
14208,
13,
10414,
1330,
6460... | 3.092486 | 173 |
import os
import sys
import warnings
import unittest
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
from setuptools.command.test import test as TestCommand
"""
https://packaging.python.org/guides/making-a-pypi-friendly-readme/
check the README.rst works on pypi as the
long_description with:
twine check dist/*
"""
long_description = open('README.rst').read()
cur_path, cur_script = os.path.split(sys.argv[0])
os.chdir(os.path.abspath(cur_path))
install_requires = [
"colorlog",
"coverage",
"flake8",
"matplotlib",
"numpy",
"pandas",
"pep8",
"pipenv",
"pycodestyle",
"pylint",
"recommonmark",
"requests",
"seaborn",
"sphinx",
"sphinx-autobuild",
"sphinx_rtd_theme",
"spylunking",
"tox",
"tqdm",
"unittest2",
"mock"
]
if sys.version_info < (3, 5):
warnings.warn(
"Less than Python 3.5 is not supported.",
DeprecationWarning)
# Do not import antinex_client module here, since deps may not be installed
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "antinex_client"))
setup(
name="antinex-client",
cmdclass={"test": PyTest},
version="1.3.6",
description=("AntiNex Python client"),
long_description_content_type='text/x-rst',
long_description=long_description,
author="Jay Johnson",
author_email="jay.p.h.johnson@gmail.com",
url="https://github.com/jay-johnson/antinex-client",
packages=[
"antinex_client",
"antinex_client.scripts",
"antinex_client.log"
],
package_data={},
install_requires=install_requires,
test_suite="setup.antinex_client_test_suite",
tests_require=[
"pytest"
],
scripts=[
"./antinex_client/scripts/ai",
"./antinex_client/scripts/ai_env_predict.py",
"./antinex_client/scripts/ai_get_prepared_dataset.py",
"./antinex_client/scripts/ai_get_job.py",
"./antinex_client/scripts/ai_get_results.py",
"./antinex_client/scripts/ai_prepare_dataset.py",
"./antinex_client/scripts/ai_train_dnn.py"
],
use_2to3=True,
classifiers=[
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Software Development :: Libraries :: Python Modules",
])
| [
11748,
28686,
198,
11748,
25064,
198,
11748,
14601,
198,
11748,
555,
715,
395,
198,
198,
28311,
25,
198,
220,
220,
220,
422,
900,
37623,
10141,
1330,
9058,
198,
16341,
17267,
12331,
25,
198,
220,
220,
220,
422,
1233,
26791,
13,
7295,
... | 2.379186 | 1,105 |
import json
import os
from os import listdir
from os.path import isfile, join
SCRIPT_BUCKET = 'mybucket'
SCRIPT_FOLDER = 'artifacts'
# Copy Glue script files to S3 bucket
script_path = 'artifacts'
#my_bucket = s3.Bucket(SCRIPT_BUCKET)
for path, subdirs, files in os.walk(script_path):
path = path.replace("\\","/")
directory_name = path.replace(script_path, "")
for file in files:
print(SCRIPT_FOLDER + directory_name + '/' + file) | [
11748,
33918,
198,
11748,
28686,
198,
6738,
28686,
1330,
1351,
15908,
198,
6738,
28686,
13,
6978,
1330,
318,
7753,
11,
4654,
198,
198,
6173,
46023,
62,
33,
16696,
2767,
796,
705,
1820,
27041,
316,
6,
198,
6173,
46023,
62,
37,
3535,
14... | 2.705521 | 163 |
# Sekvencia DNA sa skladá zo štyroch typov nukleových báz (A, C, G, T). Relatívna početnosť bázy vyjadruje, aká časť sekvencie je tvorená daným typom bázy (počet výskytov bázy / dĺžka sekvencie). Súčet relatívnej početnosti je teda vždy rovna 1.
# Napíšte definíciu funkcie funkcia3, ktorá zoberie ako parameter sekvenciu DNA a vráti slovník s relatívnou početnosťou nukleových báz. (Poznámka: funkcia pprint v doctestu vypisuje obsah slovníka zoradenu podľa kľúčov, poradie teda nemusíte riešiť. Hodnoty nie je potreba nijak zaokrúhľovať.)
from typing import Dict, List, Tuple
from pprint import pprint
import math
def funkcia3(sekvencia: str) -> Dict[str, float]:
"""Spočítaj relativnu četnosť baz v sekvencii DNA.
>>> pprint(funkcia3('ACGTTTTGAG'))
{'A': 0.2, 'C': 0.1, 'G': 0.3, 'T': 0.4}
>>> pprint(funkcia3('AAA'))
{'A': 1.0, 'C': 0.0, 'G': 0.0, 'T': 0.0}
"""
dlzka = len(sekvencia)
relativna_cetnost = {baza: sekvencia.count(baza) / dlzka for baza in 'ATGC'}
return relativna_cetnost
# # Alternatívne riešenie:
# cetnost = {'A': 0, 'C': 0, 'G': 0, 'T': 0}
# for baza in sekvencia:
# cetnost[baza] += 1
# dlzka = len(sekvencia)
# for baza in cetnost:
# cetnost[baza] /= dlzka
# return cetnost
print(funkcia3('ACGTTTTGAG')) | [
2,
37558,
574,
33743,
7446,
473,
1341,
9435,
6557,
40565,
25370,
94,
774,
305,
354,
2170,
709,
299,
2724,
293,
709,
127,
121,
354,
275,
6557,
89,
357,
32,
11,
327,
11,
402,
11,
309,
737,
4718,
265,
8836,
85,
2616,
745,
46195,
316,... | 1.87037 | 702 |
L = ['apples', 'oranges', 'kiwis', 'pineapples']
print(stdDevOfLengths(L)) | [
198,
43,
796,
37250,
1324,
829,
3256,
705,
273,
6231,
3256,
705,
4106,
86,
271,
3256,
705,
23908,
1324,
829,
20520,
198,
4798,
7,
19282,
13603,
5189,
24539,
82,
7,
43,
4008
] | 2.34375 | 32 |
"""
History: (file) logging for nuqql conversations
"""
import datetime
import logging
import pathlib
import os
from typing import List, Optional, TYPE_CHECKING
import nuqql.config
from .logmessage import LogMessage
if TYPE_CHECKING: # imports for typing
# pylint: disable=cyclic-import
from .conversation import Conversation # noqa
logger = logging.getLogger(__name__)
HISTORY_FILE = "/history"
LASTREAD_FILE = "/lastread"
class History:
"""
Message history
"""
def _get_conv_path(self) -> str:
"""
Get path for conversation history as a string and make sure it exists
"""
# construct directory path
assert self.conv.backend and self.conv.account
conv_dir = str(nuqql.config.get("dir")) + \
(f"/conversation/{self.conv.backend.name}/"
f"{self.conv.account.aid}/{self.conv.name}")
# make sure directory exists
pathlib.Path(conv_dir).mkdir(parents=True, exist_ok=True)
return conv_dir
@staticmethod
def _get_logger(name, file_name: str) -> logging.Logger:
"""
Create a logger for a conversation
"""
# create logger
conv_logger = logging.getLogger(name)
conv_logger.propagate = False
conv_logger.setLevel(logging.DEBUG)
# create handler
fileh = logging.FileHandler(file_name)
fileh.setLevel(logging.DEBUG)
fileh.terminator = "\r\n"
# create formatter
formatter = logging.Formatter(
# fmt="%(asctime)s %(levelname)-5.5s [%(name)s] %(message)s",
fmt="%(message)s",
datefmt="%s")
# add formatter to handler
fileh.setFormatter(formatter)
# add handler to logger
if not conv_logger.hasHandlers():
conv_logger.addHandler(fileh)
# return logger to caller
return conv_logger
def init_logger(self) -> None:
"""
Init logger for a conversation
"""
logger.debug("initializing logger of conversation %s", self.conv.name)
# get log dir and make sure it exists
assert self.conv.backend and self.conv.account
self.conv_path = self._get_conv_path()
# create logger with log name and log file
log_name = (f"nuqql.history.{self.conv.backend.name}."
f"{self.conv.account.aid}.{self.conv.name}")
self.log_file = self.conv_path + HISTORY_FILE
self.logger = self._get_logger(log_name, self.log_file)
@staticmethod
def _parse_log_line(line: str) -> LogMessage:
"""
Parse line from log file and return a LogMessage
"""
# parse line
parts = line.split(sep=" ", maxsplit=3)
# tstamp = parts[0]
direction = parts[1]
is_own = False
if direction == "OUT":
is_own = True
sender = parts[2]
msg = parts[3][:-2]
tstamp = datetime.datetime.fromtimestamp(int(parts[0]))
# create and return LogMessage
log_msg = LogMessage(tstamp, sender, msg, own=is_own)
return log_msg
@staticmethod
def _create_log_line(log_msg: LogMessage) -> str:
"""
Create a line for the log files from a LogMessage
"""
# determine log line contents
tstamp = round(log_msg.tstamp.timestamp())
direction = "IN"
sender = log_msg.sender
if log_msg.own:
direction = "OUT"
sender = "you"
msg = log_msg.msg
return f"{tstamp} {direction} {sender} {msg}"
def get_lastread(self) -> Optional[LogMessage]:
"""
Get last read message from "lastread" file of the conversation
"""
logger.debug("getting lastread of conversation %s", self.conv.name)
lastread_file = self.conv_path + LASTREAD_FILE
try:
with open(lastread_file, encoding='UTF-8',
newline="\r\n") as in_file:
for line in in_file:
log_msg = self._parse_log_line(line)
log_msg.is_read = True
return log_msg
logger.debug("lastread file of conversation %s is empty",
self.conv.name)
return None
except FileNotFoundError:
logger.debug("lastread file of conversation %s not found",
self.conv.name)
return None
def set_lastread(self, log_msg: LogMessage) -> None:
"""
Set last read message in "lastread" file of the conversation
"""
logger.debug("setting lastread of conversation %s", self.conv.name)
# create log line and write it to lastread file
line = self._create_log_line(log_msg) + "\r\n"
lines = []
lines.append(line)
lastread_file = self.conv_path + LASTREAD_FILE
with open(lastread_file, "w+", encoding='UTF-8') as out_file:
out_file.writelines(lines)
def get_last_log_line(self) -> Optional[LogMessage]:
"""
Read last LogMessage from log file
"""
logger.debug("getting last log line of conversation %s",
self.conv.name)
history_file = self.conv_path + HISTORY_FILE
try:
# negative seeking requires binary mode
with open(history_file, "rb") as in_file:
# check if file contains at least 2 bytes
in_file.seek(0, os.SEEK_END)
if in_file.tell() < 3:
logger.debug("log of conversation %s seems to be empty",
self.conv.name)
return None
# try to find last line
in_file.seek(-3, os.SEEK_END)
while in_file.read(2) != b"\r\n":
try:
in_file.seek(-3, os.SEEK_CUR)
except IOError:
in_file.seek(-2, os.SEEK_CUR)
if in_file.tell() == 0:
break
# read and return last line as LogMessage
last_line = in_file.read()
log_msg = self._parse_log_line(last_line.decode())
return log_msg
except FileNotFoundError:
logger.debug("log file of conversation %s not found",
self.conv.name)
return None
def init_log_from_file(self) -> None:
"""
Initialize a conversation's log from the conversation's log file
"""
logger.debug("initializing log of conversation %s from file %s",
self.conv.name, self.log_file)
# get last read log message
last_read = self.get_lastread()
is_read = True
with open(self.log_file, encoding='UTF-8', newline="\r\n") as in_file:
prev_msg = None
for line in in_file:
# parse log line and create log message
log_msg = self._parse_log_line(line)
log_msg.is_read = is_read
# check if date changed between two messages, and print event
if prev_msg and \
prev_msg.tstamp.date() != log_msg.tstamp.date():
date_change_msg = LogMessage(
log_msg.tstamp,
"<event>", (f"<Date changed to "
f"{log_msg.tstamp.date()}>"), own=True)
date_change_msg.is_read = True
self.log.append(date_change_msg)
prev_msg = log_msg
# add log message to the conversation's log
self.log.append(log_msg)
# if this is the last read message, following message will be
# marked as unread
if last_read and last_read.is_equal(log_msg):
is_read = False
if self.log:
# if there were any log messages in the log file, put a marker in
# the log where the new messages start
tstamp = datetime.datetime.now()
tstamp_str = tstamp.strftime("%Y-%m-%d %H:%M:%S")
new_conv_msg = f"<Started new conversation at {tstamp_str}.>"
log_msg = LogMessage(tstamp, "<event>", new_conv_msg, own=True)
log_msg.is_read = True
self.log.append(log_msg)
def log_to_file(self, log_msg: LogMessage) -> None:
"""
Write LogMessage to history log file and set lastread message
"""
logger.debug("logging msg to log file of conversation %s: %s",
self.conv.name, log_msg)
# create line and write it to history
line = self._create_log_line(log_msg)
assert self.logger
self.logger.info(line)
# assume user read all previous messages when user sends a message and
# set lastread accordingly
if log_msg.own:
self.set_lastread(log_msg)
| [
37811,
198,
18122,
25,
357,
7753,
8,
18931,
329,
14364,
80,
13976,
10275,
198,
37811,
198,
198,
11748,
4818,
8079,
198,
11748,
18931,
198,
11748,
3108,
8019,
198,
11748,
28686,
198,
198,
6738,
19720,
1330,
7343,
11,
32233,
11,
41876,
62... | 2.057971 | 4,416 |
#!/usr/bin/python -t
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# Copyright 2005 Duke University
# Parts Copyright 2007 Red Hat, Inc
import rpm
import os
import fcntl
import time
import logging
import types
import sys
from yum.constants import *
from yum import _
import misc
import tempfile
class RPMBaseCallback:
'''
Base class for a RPMTransaction display callback class
'''
def event(self, package, action, te_current, te_total, ts_current, ts_total):
"""
@param package: A yum package object or simple string of a package name
@param action: A yum.constant transaction set state or in the obscure
rpm repackage case it could be the string 'repackaging'
@param te_current: Current number of bytes processed in the transaction
element being processed
@param te_total: Total number of bytes in the transaction element being
processed
@param ts_current: number of processes completed in whole transaction
@param ts_total: total number of processes in the transaction.
"""
raise NotImplementedError()
def scriptout(self, package, msgs):
"""package is the package. msgs is the messages that were
output (if any)."""
pass
# This is ugly, but atm. rpm can go insane and run the "cleanup" phase
# without the "install" phase if it gets an exception in it's callback. The
# following means that we don't really need to know/care about that in the
# display callback functions.
# Note try/except's in RPMTransaction are for the same reason.
| [
2,
48443,
14629,
14,
8800,
14,
29412,
532,
83,
198,
2,
770,
1430,
318,
1479,
3788,
26,
345,
460,
17678,
4163,
340,
290,
14,
273,
13096,
198,
2,
340,
739,
262,
2846,
286,
262,
22961,
3611,
5094,
13789,
355,
3199,
416,
198,
2,
262,
... | 3.102258 | 753 |
import os
import time
import re
import bisect
from collections import OrderedDict
import numpy as np
import tensorflow as tf
import scipy.ndimage
import scipy.misc
import config
import misc
import tfutil
import train
import dataset
#----------------------------------------------------------------------------
# Generate random images or image grids using a previously trained network.
# To run, uncomment the appropriate line in config.py and launch train.py.
#----------------------------------------------------------------------------
# Generate MP4 video of random interpolations using a previously trained network.
# To run, uncomment the appropriate line in config.py and launch train.py.
#----------------------------------------------------------------------------
# Generate MP4 video of training progress for a previous training run.
# To run, uncomment the appropriate line in config.py and launch train.py.
| [
11748,
28686,
198,
11748,
640,
198,
11748,
302,
198,
11748,
47457,
478,
198,
6738,
17268,
1330,
14230,
1068,
35,
713,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
11192,
273,
11125,
355,
48700,
198,
11748,
629,
541,
88,
13,
358,
9060... | 4.914894 | 188 |
import gin
import torch
@gin.configurable
def pow_loss(X, X_true, power=2, **kwargs):
"""Difference between items to a power, avg over dataset, sum over items."""
assert X.shape == X_true.shape, (X.shape, X_true.shape)
abs_diff = torch.abs(X - X_true)
loss = torch.pow(abs_diff, power)
# mean over batches
loss = torch.mean(loss, dim=0)
# sum over the rest
loss = torch.sum(loss)
return loss
@gin.configurable
def ae_loss(autoencoder, X_chw, loss_fcn, **kwargs):
"""Vanilla autoencoder loss."""
reconstructed = autoencoder(X_chw)
value = loss_fcn(X_chw, reconstructed)
return value | [
11748,
39733,
201,
198,
11748,
28034,
201,
198,
201,
198,
31,
1655,
13,
11250,
11970,
201,
198,
4299,
7182,
62,
22462,
7,
55,
11,
1395,
62,
7942,
11,
1176,
28,
17,
11,
12429,
46265,
22046,
2599,
201,
198,
220,
220,
220,
37227,
28813... | 2.359431 | 281 |
# Generated by Django 3.0.6 on 2020-05-22 15:31
from django.db import migrations, models
| [
2,
2980,
515,
416,
37770,
513,
13,
15,
13,
21,
319,
12131,
12,
2713,
12,
1828,
1315,
25,
3132,
198,
198,
6738,
42625,
14208,
13,
9945,
1330,
15720,
602,
11,
4981,
628
] | 2.84375 | 32 |
"""
Basel IV Standardised Approach to Credit Risk.py (b4sacr.py)
----------------
This package encapsulates the Basel Committee on Bank Supervision's finalisation of Basel III
for standardised credit risk.
The text is found at https://www.bis.org/bcbs/publ/d424.htm
This will serve as the foundation of any Basel 4 impact analysis.
-----------------
Blake Stratton
A key objective of the revisions in this document is to reduce excessive variability of risk-
weighted assets (RWAs). The revisions (i) enhance the robustness and risk sensitivity of the
standardised approaches for credit risk and operational risk; (ii) constrain the use of
internally-modelled approaches (particularly for low default exposures such as FIs and large
corporates); and (iii) complement the risk-weighted capital ratio with a finalised leverage
ratio and a standardised RWA capital floor.
A comment on nomenclature: BCBS calls this package of reforms Basel III finalisation however
the industry - atleast for the time being - refers to it as Basel IV. We will refer to these
changes as Basel IV until such a time that it no longer suits.
This package is structured as:
- classes for each of the exposure classes
See Basel4.py script for overarching logic for Basel 4 packages.
"""
"""
Version 0.1 2017-12-12 Written introduction and start on sacr
Version 0.2 2018-01-01
"""
"""
Insert dependencies here
"""
import pandas as pd
class sacr():
"""
"""
"TO INSERT LOOKUPS BASED ON BOOKING ENTITY AND CTPYID ONCE BASEL4.PY BUILT TO GET VALUES LIKE SUPERVISOR____" | [
37811,
198,
15522,
417,
8363,
8997,
1417,
38066,
284,
10504,
19602,
13,
9078,
357,
65,
19,
30584,
81,
13,
9078,
8,
198,
1783,
198,
1212,
5301,
32652,
15968,
262,
6455,
417,
4606,
319,
5018,
3115,
10178,
338,
2457,
5612,
286,
6455,
417... | 3.676815 | 427 |
#!/usr/bin/env python
"""
Copyright 2010-2019 University Of Southern California
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.
Program used to learn how many realizations are needed
for a method to converge.
This program is based on the original bbp_converge script
from Karen Assatourians, Western University
"""
from __future__ import division, print_function
# Import Python modules
import os
import sys
import glob
import math
import curses
import random
import shutil
import argparse
import numpy as np
import matplotlib as mpl
if mpl.get_backend() != 'agg':
mpl.use('Agg') # Disables use of Tk/X11
import pylab
# Import Broadband modules
import bband_utils
import plot_config
DEFAULT_SEED = 123456789
def update_progress_bar(progress, total):
"""
Keeps the progress bar moving
"""
bar_size = 40
completed = int(progress * bar_size / total)
missing = bar_size - completed
progress_bar = "%s%s" % ("*" * completed, "-" * missing)
print("\r Iteration: %s : %d" % (progress_bar, progress), end="")
sys.stdout.flush()
def parse_arguments():
"""
This function takes care of parsing the command-line arguments and
asking the user for any missing parameters that we need
"""
parser = argparse.ArgumentParser(description="Learn how many "
" realizations are needed "
" for methods to converge.")
parser.add_argument("--input_dir", "-i", dest="input_dir",
required=True, help="input directory")
parser.add_argument("-o", "--output",
dest="output_file", required=True,
help="output png file")
parser.add_argument("--limit", "-l", type=float,
dest="limit", default=0.02,
help="difference limit")
parser.add_argument("--ns", type=int, default=10000,
dest="sampling", help="number of sampling")
parser.add_argument("-c", "--codebase", required=True,
dest="codebase",
help="method used for the simulation")
parser.add_argument("--colormap", default="Paired",
dest="colormap",
help="matplotlib colormap to use")
args = parser.parse_args()
return args
def read_input_bias_data(input_dir):
"""
Read the bias data from all realizations
"""
periods = []
data = []
event_label = None
realizations = sorted(os.listdir(input_dir))
for realization in realizations:
basedir = os.path.join(input_dir, realization)
bias_file = glob.glob("%s%s*-rotd50.bias" % (basedir, os.sep))
if len(bias_file) != 1:
raise bband_utils.ProcessingError("Bias file not found for "
"realization %s!" % (realization))
bias_file = bias_file[0]
# Let's capture the event label
if event_label is None:
event_label = os.path.basename(bias_file).split("-")[0]
input_file = open(bias_file, 'r')
cur_periods = []
cur_data = []
for line in input_file:
line = line.strip()
# Skip comments and empty lines
if line.startswith("#") or line.startswith("%") or not line:
continue
tokens = [float(token) for token in line.split()]
cur_periods.append(tokens[0])
cur_data.append(tokens[1])
# Close input_file
input_file.close()
# Keep list of periods if not already done
if not periods:
periods = cur_periods
# And keep data
data.append(cur_data)
bias_data = {}
bias_data["num_periods"] = len(periods)
bias_data["periods"] = periods
bias_data["num_realizations"] = len(realizations)
bias_data["data"] = data
bias_data["event_label"] = event_label
return bias_data
def find_gavg(bias_data):
"""
Calculate averages
"""
gavg = np.zeros(bias_data["num_periods"])
data = bias_data["data"]
num_realizations = float(bias_data["num_realizations"])
for realization in data:
for cur_period in range(0, bias_data["num_periods"]):
gavg[cur_period] = (gavg[cur_period] +
realization[cur_period] / num_realizations)
bias_data["gavg"] = gavg
return bias_data
def calculate_probabilities(bias_data, limit, sampling):
"""
Calculate the probabilities
"""
ratios_by_period = [[] for _ in range(0, bias_data["num_periods"])]
random.seed(DEFAULT_SEED)
for cur_realization in range(1, bias_data["num_realizations"] + 1):
update_progress_bar(cur_realization, bias_data["num_realizations"])
ratio = np.zeros(bias_data["num_periods"])
for _ in range(0, sampling):
avg = np.zeros(bias_data["num_periods"])
for _ in range(0, cur_realization):
random_int = (int(random.random() * bias_data["num_realizations"]))
if random_int > bias_data["num_realizations"]:
random_int = bias_data["num_realizations"]
for nper in range(0, bias_data["num_periods"]):
avg[nper] = (avg[nper] +
bias_data["data"][random_int][nper] / float(cur_realization))
for nper in range(0, bias_data["num_periods"]):
if abs(avg[nper] - bias_data["gavg"][nper]) <= limit:
ratio[nper] = ratio[nper] + 1
ratio = ratio / sampling
# Now re-shuffle so that we split by periods not realizations
for val, dest in zip(ratio, ratios_by_period):
dest.append(val)
# Save calculated data
bias_data["ratios"] = ratios_by_period
print()
return bias_data
def plot_results(bias_data, codebase, colormap, output_file):
"""
Generate plot showing results calculated from all realizations
"""
fig, ax = pylab.plt.subplots()
xlocs = range(1, bias_data["num_periods"] + 1)
ylocs = list(np.full(bias_data["num_periods"],
bias_data["num_realizations"]))
bars = ax.bar(xlocs, ylocs)
ax = bars[0].axes
lim = ax.get_xlim() + ax.get_ylim()
for bar, ratio in zip(bars, bias_data["ratios"]):
rev_ratio = ratio[::-1]
gradient = np.atleast_2d(rev_ratio).T
bar.set_zorder(1)
bar.set_facecolor("none")
x, y = bar.get_xy()
w, h = bar.get_width(), bar.get_height()
im = ax.imshow(gradient, extent=[x, x + w, y, y + h],
cmap=pylab.get_cmap(colormap),
vmin=0.0, vmax=1.0,
aspect="auto", zorder=0)
ax.axis(lim)
fig.colorbar(im)
pylab.xlim(0, bias_data["num_periods"] + 2)
pylab.plt.xticks([val + 0.5 for val in xlocs],
bias_data["periods"],
rotation='vertical', fontsize=6)
#frame1 = pylab.gca()
#frame1.axes.xaxis.set_ticklabels([])
#frame1.axes.yaxis.set_ticklabels([])
pylab.xlabel("Periods")
pylab.ylabel("Number of Realizations")
pylab.title(("Convergence Plot - %s Method - %s" %
(codebase, bias_data["event_label"])),
size=10)
# Save plot
fig.savefig(output_file, format="png",
transparent=False, dpi=plot_config.dpi)
def main():
"""
Figure out how many realizations are needed for methods to
converge
"""
# Parse command-line options
args = parse_arguments()
# Copy options
limit = args.limit
sampling = args.sampling
base_input_dir = args.input_dir
output_file = args.output_file
colormap = args.colormap
codebase = args.codebase
# Read input data
input_dir = os.path.join(base_input_dir, "Sims", "outdata")
bias_data = read_input_bias_data(input_dir)
bias_data = find_gavg(bias_data)
bias_data = calculate_probabilities(bias_data, limit, sampling)
plot_results(bias_data, codebase, colormap, output_file)
if __name__ == "__main__":
main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
37811,
198,
15269,
3050,
12,
23344,
2059,
3226,
8050,
3442,
198,
198,
26656,
15385,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
5832,
743,
407,
7... | 2.24922 | 3,844 |
from .abstract_is_admin import AbstractIsAdmin
from .abstract_is_examiner import AbstractIsExaminer
from .abstract_is_candidate import AbstractIsCandidate
from .basenode import BaseNode
from .subject import Subject
from .period import Period, PeriodApplicationKeyValue
from .period_tag import PeriodTag
from .relateduser import RelatedExaminer, RelatedStudent, RelatedStudentKeyValue
from .assignment import Assignment
from .pointrange_to_grade import PointRangeToGrade
from .pointrange_to_grade import PointToGradeMap
from .assignment_group import AssignmentGroup, AssignmentGroupTag
from .assignment_group_history import AssignmentGroupHistory
from .delivery import Delivery
from .deadline import Deadline
from .candidate import Candidate
from .static_feedback import StaticFeedback, StaticFeedbackFileAttachment
from .filemeta import FileMeta
from .devilryuserprofile import DevilryUserProfile
from .examiner import Examiner
from .groupinvite import GroupInvite
from .examiner_candidate_group_history import ExaminerAssignmentGroupHistory, CandidateAssignmentGroupHistory
__all__ = ("AbstractIsAdmin", "AbstractIsExaminer", "AbstractIsCandidate",
"BaseNode", "Subject", "Period", "PeriodTag", 'RelatedExaminer', 'RelatedStudent',
"RelatedStudentKeyValue", "Assignment", "AssignmentGroup",
"AssignmentGroupTag", "Delivery", "Deadline", "Candidate", "StaticFeedback",
"FileMeta", "DevilryUserProfile", 'PeriodApplicationKeyValue', 'Examiner',
'GroupInvite', 'StaticFeedbackFileAttachment', 'PointRangeToGrade',
'PointToGradeMap', 'AssignmentGroupHistory', 'ExaminerAssignmentGroupHistory',
'CandidateAssignmentGroupHistory')
| [
6738,
764,
397,
8709,
62,
271,
62,
28482,
1330,
27741,
3792,
46787,
198,
6738,
764,
397,
8709,
62,
271,
62,
1069,
32086,
1330,
27741,
3792,
3109,
32086,
198,
6738,
764,
397,
8709,
62,
271,
62,
46188,
20540,
1330,
27741,
3792,
41572,
2... | 3.484663 | 489 |
# coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
# TEST SCENARIO COVERAGE
# ----------------------
# Methods Total : 26
# Methods Covered : 26
# Examples Total : 26
# Examples Tested : 20
# Coverage % : 77
# ----------------------
# Current Operation Coverage:
# Operations: 1/1
# Redis: 10/13
# FirewallRules: 4/4
# PatchSchedules: 4/4
# LinkedServer: 1/4
import time
import unittest
import azure.mgmt.redis
from devtools_testutils import AzureMgmtTestCase, RandomNameResourceGroupPreparer
AZURE_LOCATION = 'eastus'
#------------------------------------------------------------------------------
if __name__ == '__main__':
unittest.main()
| [
2,
19617,
25,
3384,
69,
12,
23,
198,
198,
2,
10097,
45537,
198,
2,
15069,
357,
66,
8,
5413,
10501,
13,
1439,
2489,
10395,
13,
198,
2,
49962,
739,
262,
17168,
13789,
13,
4091,
13789,
13,
14116,
287,
262,
1628,
6808,
329,
198,
2,
... | 3.799197 | 249 |
from .base import GnuRecipe
| [
6738,
764,
8692,
1330,
18509,
84,
37523,
628
] | 3.625 | 8 |
from bitstring import Bits
from baseconvert import base
from src.funcionalidades import Funcionalidad
| [
6738,
1643,
8841,
1330,
44733,
198,
6738,
2779,
1102,
1851,
1330,
2779,
198,
6738,
12351,
13,
20786,
1538,
312,
2367,
1330,
11138,
66,
1538,
32482,
628,
628,
628,
198
] | 3.724138 | 29 |
import Bot # This is the local Python Module that we made
# Initialization
bot_1 = Bot.Bot("ya boi", "just got bamboozled", "Bot_1")
# Find Functionality
find_input = {
"function_name": "One_Stock",
"parameters": [
"FIS"
]
}
find_output = bot_1.Find(find_input)
# Finance Functionality
finance_input = {
"function_name": "Set",
"parameters": [
10, # 10 dollars
False # 10 dollars infinitely... If it was False, then it would be limited to 10 dollars
]
}
"""
finance_input = {
"function_name": "Set",
"parameters": [
10, # 10 dollars
True # 10 dollars infinitely... If it was False, then it would be limited to 10 dollars
]
}
"""
finance_output = bot_1.Finance(finance_input)
# Algorithm Functionality
algorithm_input = {
"function_name": "Gates",
"parameters": [
find_output,
finance_output
]
}
bot_1.Algorithm(algorithm_input)
"""
ways for this to work:
1.
import all functions in the beginning... and have the application.py file run the logic explicitely...
2.
import programmatically based on name... then allow json entry to decide the parameters of the other functions...
____
find fuctions return json...
finance fuctions return json...
algorithm function is in a while true loop that runs depending on:
- find json
- finance json
- any additionals parameters
... some algorithms will not need find json or finance json
""" | [
11748,
18579,
1303,
770,
318,
262,
1957,
11361,
19937,
326,
356,
925,
198,
198,
2,
20768,
1634,
198,
13645,
62,
16,
796,
18579,
13,
20630,
7203,
3972,
1489,
72,
1600,
366,
3137,
1392,
275,
22651,
8590,
992,
1600,
366,
20630,
62,
16,
... | 2.906375 | 502 |
from pathlib import Path
import pytest
@pytest.fixture | [
6738,
3108,
8019,
1330,
10644,
198,
11748,
12972,
9288,
628,
198,
31,
9078,
9288,
13,
69,
9602
] | 3.294118 | 17 |
#!/usr/bin/env python2.7
import numpy as np
import sys
import cv2
import tf
import pdb
import yaml
import rosbag
import rospy
from sensor_msgs.msg import Image
from nav_msgs.msg import Odometry
from message_filters import ApproximateTimeSynchronizer, Subscriber
from cv_bridge import CvBridge
from apriltag_tracker._AprilTagTracker import AprilTagTracker
from apriltag_tracker.msg import Apriltags
from geometry import SE3, se3
datatype = np.float32
np.set_printoptions(precision=4, suppress=True)
config_file = '../config/extrinsics_calib.yaml'
with open(config_file, 'r') as f:
file_node = yaml.load(f)
node = file_node['apriltag_tracker_params']
tag_size = node['tag_size']
s = tag_size/2.0
K = np.array(node['K']).reshape(3, 3)
path = file_node['extrinsics_calib_params']['bag_file']
tracker = AprilTagTracker(config_file)
rospy.init_node('broadcaster')
bridge = CvBridge()
broadcaster = tf.TransformBroadcaster()
img_pub = rospy.Publisher('debug_img', Image)
data_tuples = []
use_bag = True
visualize = True
buffer_size = 100
topics_to_parse = ['/kinect2/qhd/image_color_rect',
'/kinect_one/vicon_odom', '/apriltag_27_board/vicon_odom']
subs = []
subs.append(Subscriber(topics_to_parse[0], Image))
subs.append(Subscriber(topics_to_parse[1], Odometry))
subs.append(Subscriber(topics_to_parse[2], Odometry))
synchronizer = ApproximateTimeSynchronizer(subs, 10, 0.05)
synchronizer.registerCallback(got_tuple)
if use_bag:
with rosbag.Bag(path, 'r') as bag:
counter = 0
for topic, msg, t in bag.read_messages(topics_to_parse):
if topic in topics_to_parse:
index = topics_to_parse.index(topic)
subs[index].signalMessage(msg)
counter += 1
if counter%1000 == 0:
print 'Read {0} tuples'.format(counter)
# Try to use a black box optimizer
print 'Starting optimization...'
from scipy.optimize import minimize
initial_guess = np.array([0,0,0,0,0,0,-0.1]) # Since initial guess is pretty close to unity
result = minimize(cost_function_tuple_offset, initial_guess, bounds=np.array([[-1,1],[-1,1],[-1,1],[-1,1],[-1,1],[-1,1], [-1, 1]]))
print 'Done, results is'
print result
print SE3.group_from_algebra(se3.algebra_from_vector(result.x[:6]))
print result.x[6]
pdb.set_trace()
else:
rospy.Subscriber(topics_to_parse[0], Image,
lambda msg: subs[0].signalMessage(msg))
rospy.Subscriber(topics_to_parse[1], Odometry,
lambda msg: subs[1].signalMessage(msg))
rospy.Subscriber(topics_to_parse[2], Odometry,
lambda msg: subs[2].signalMessage(msg))
rospy.spin()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
17,
13,
22,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
25064,
198,
11748,
269,
85,
17,
198,
11748,
48700,
198,
11748,
279,
9945,
198,
11748,
331,
43695,
198,
198,
11748,
686,
82,
21454... | 2.295151 | 1,196 |
import os
import configparser
from .client import RestAPI
from .lib.server import Server
from .lib.server_group import ServerGroup
from .lib.volume import Volume
from .lib.flavor import Flavor
from .lib.floating_ip import FloatingIp
from .lib.image import Image
from .lib.region import Region
from .lib.network import Network
from .lib.subnet import Subnet
from .lib.objects_user import ObjectsUser
from .error import CloudscaleException, CloudscaleApiException # noqa F401
from .version import __version__
APP_NAME = 'cloudscale-cli'
CLOUDSCALE_API_ENDPOINT = 'https://api.cloudscale.ch/v1'
CLOUDSCALE_CONFIG = 'cloudscale.ini'
| [
11748,
28686,
198,
11748,
4566,
48610,
198,
6738,
764,
16366,
1330,
8324,
17614,
198,
6738,
764,
8019,
13,
15388,
1330,
9652,
198,
6738,
764,
8019,
13,
15388,
62,
8094,
1330,
9652,
13247,
198,
6738,
764,
8019,
13,
29048,
1330,
14701,
19... | 3.290155 | 193 |
from unittest.mock import patch
from requests.exceptions import ConnectionError
from zulip_bots.test_lib import BotTestCase, DefaultTests, StubBotHandler
from zulip_bots.bots.google_translate.google_translate import TranslateError
help_text = '''
Google translate bot
Please format your message like:
`@-mention "<text_to_translate>" <target-language> <source-language(optional)>`
Visit [here](https://cloud.google.com/translate/docs/languages) for all languages
'''
| [
6738,
555,
715,
395,
13,
76,
735,
1330,
8529,
198,
6738,
7007,
13,
1069,
11755,
1330,
26923,
12331,
198,
198,
6738,
1976,
377,
541,
62,
42478,
13,
9288,
62,
8019,
1330,
18579,
14402,
20448,
11,
15161,
51,
3558,
11,
41135,
20630,
25060... | 3.35 | 140 |
class Opp(object):
"""docstring for MC"""
| [
4871,
9385,
7,
15252,
2599,
198,
197,
37811,
15390,
8841,
329,
13122,
37811,
198,
197,
197,
198,
197
] | 2.611111 | 18 |
import pandas as pd
from sqlalchemy import create_engine, exc
from load_transform import extract_from_mongodb, extract_data_from_json
from bert_model import load_bert_model, sentiment_prediction
from logo_detection_model import logo_detection
import time
import logging
from config import POSTGRES, TAG
# Postgres connection
PG = create_engine(POSTGRES)
# Remove duplicates in Postgres
QUERY = f""" DELETE FROM {TAG} T1
USING {TAG} T2
WHERE T1.ctid < T2.ctid
AND T1.date_time = T2.date_time;
"""
def sentiment_analysis_on_scraped_data(df):
"""
Analyse the sentiment of the cleaned caption in the dataframe using the
BERT sentiment analysis model and fill the sentiment column with the results.
return: dataframe with sentiment analysis of the posts
"""
df_analyse = df[(df['language'] == 'en') & (df['clean_text_en'] != None)] # Only the English captions
df_analyse['sentiment'] = df_analyse['clean_text_en'].apply(sentiment_prediction)
df['sentiment'][df_analyse.index] = df_analyse['sentiment']
return df
if __name__ == '__main__':
while True:
# Extract
posts = extract_from_mongodb()
if posts:
total_post = len(posts['items']) + len(posts['ranked_items'])
logging.critical(f"{total_post} posts have been extracted from mongodb")
# Transform
df = extract_data_from_json(posts)
logging.critical("Sentiment analysis on the clean text has been started")
df_analized = sentiment_analysis_on_scraped_data(df)
logging.critical("Sentiment analysis is finished")
logging.critical("Logo detection on the images has been started")
df_analized['logos'] = df_analized['urls'].apply(logo_detection)
logging.critical("Logo detection is finished")
# Load
logging.critical("Uploading data to AWS database")
df_analized.to_sql(f'{TAG}', PG, if_exists='append')
PG.execute(QUERY) # removing the duplicates
logging.critical("Waiting for 10 minutes...")
time.sleep(600)
| [
11748,
19798,
292,
355,
279,
67,
201,
198,
6738,
44161,
282,
26599,
1330,
2251,
62,
18392,
11,
2859,
201,
198,
6738,
3440,
62,
35636,
1330,
7925,
62,
6738,
62,
31059,
375,
65,
11,
7925,
62,
7890,
62,
6738,
62,
17752,
201,
198,
6738,... | 2.422489 | 916 |
from CanonizerBase import Page
from Identifiers import HelpIdentifiers
| [
6738,
19507,
7509,
14881,
1330,
7873,
198,
6738,
11440,
13350,
1330,
10478,
33234,
13350,
628,
628,
198
] | 4.411765 | 17 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2021-01-05 02:27
from __future__ import unicode_literals
from django.db import migrations, models
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
2980,
515,
416,
37770,
352,
13,
1157,
13,
1959,
319,
33448,
12,
486,
12,
2713,
7816,
25,
1983,
198,
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198,... | 2.754386 | 57 |
# -*- coding: utf-8 -*-
from mock import patch, MagicMock
import os
import six
import shutil
import sys
import testtools
from doc8.main import main, doc8
# Location to create test files
TMPFS_DIR_NAME = ".tmp"
# Expected output
OUTPUT_CMD_NO_QUIET = """\
Scanning...
Validating...
{path}/invalid.rst:1: D002 Trailing whitespace
{path}/invalid.rst:1: D005 No newline at end of file
========
Total files scanned = 1
Total files ignored = 0
Total accumulated errors = 2
Detailed error counts:
- doc8.checks.CheckCarriageReturn = 0
- doc8.checks.CheckIndentationNoTab = 0
- doc8.checks.CheckMaxLineLength = 0
- doc8.checks.CheckNewlineEndOfFile = 1
- doc8.checks.CheckTrailingWhitespace = 1
- doc8.checks.CheckValidity = 0
"""
OUTPUT_CMD_QUIET = """\
{path}/invalid.rst:1: D002 Trailing whitespace
{path}/invalid.rst:1: D005 No newline at end of file
"""
OUTPUT_CMD_VERBOSE = """\
Scanning...
Selecting '{path}/invalid.rst'
Validating...
Validating {path}/invalid.rst (ascii, 10 chars, 1 lines)
Running check 'doc8.checks.CheckValidity'
Running check 'doc8.checks.CheckTrailingWhitespace'
- {path}/invalid.rst:1: D002 Trailing whitespace
Running check 'doc8.checks.CheckIndentationNoTab'
Running check 'doc8.checks.CheckCarriageReturn'
Running check 'doc8.checks.CheckMaxLineLength'
Running check 'doc8.checks.CheckNewlineEndOfFile'
- {path}/invalid.rst:1: D005 No newline at end of file
========
Total files scanned = 1
Total files ignored = 0
Total accumulated errors = 2
Detailed error counts:
- doc8.checks.CheckCarriageReturn = 0
- doc8.checks.CheckIndentationNoTab = 0
- doc8.checks.CheckMaxLineLength = 0
- doc8.checks.CheckNewlineEndOfFile = 1
- doc8.checks.CheckTrailingWhitespace = 1
- doc8.checks.CheckValidity = 0
"""
OUTPUT_API_REPORT = """\
{path}/invalid.rst:1: D002 Trailing whitespace
{path}/invalid.rst:1: D005 No newline at end of file
========
Total files scanned = 1
Total files ignored = 0
Total accumulated errors = 2
Detailed error counts:
- doc8.checks.CheckCarriageReturn = 0
- doc8.checks.CheckIndentationNoTab = 0
- doc8.checks.CheckMaxLineLength = 0
- doc8.checks.CheckNewlineEndOfFile = 1
- doc8.checks.CheckTrailingWhitespace = 1
- doc8.checks.CheckValidity = 0"""
class Capture(object):
"""
Context manager to capture output on stdout and stderr
"""
class TmpFs(object):
"""
Context manager to create and clean a temporary file area for testing
"""
def mock(self):
"""
Create a file which fails on a LineCheck and a ContentCheck
"""
self.create_file("invalid.rst", "D002 D005 ")
def expected(self, template):
"""
Insert the path into a template to generate an expected test value
"""
return template.format(path=self.path)
class FakeResult(object):
"""
Minimum valid result returned from doc8
"""
total_errors = 0
class TestCommandLine(testtools.TestCase):
"""
Test command line invocation
"""
class TestApi(testtools.TestCase):
"""
Test direct code invocation
"""
class TestArguments(testtools.TestCase):
"""
Test that arguments are parsed correctly
"""
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
6738,
15290,
1330,
8529,
11,
6139,
44,
735,
198,
11748,
28686,
198,
11748,
2237,
198,
11748,
4423,
346,
198,
11748,
25064,
198,
11748,
1332,
31391,
198,
198,
6738,
... | 2.738617 | 1,186 |
from .models import Brand,Size,BrandColor,Category,Master_Page
from django import forms
from django import forms
| [
6738,
764,
27530,
1330,
13512,
11,
10699,
11,
38416,
10258,
11,
27313,
11,
18254,
62,
9876,
198,
6738,
42625,
14208,
1330,
5107,
198,
6738,
42625,
14208,
1330,
5107,
628,
220,
220,
220,
220,
220,
220,
220,
198,
220,
220,
220,
220,
220... | 2.869565 | 46 |
# Copyright 2019 NREL
# 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
# speROSCO_cific language governing permissions and limitations under the License.
import numpy as np
from ROSCO_toolbox import turbine as ROSCO_turbine
import matplotlib.pyplot as plt
import sys
# Some useful constants
deg2rad = np.deg2rad(1)
rad2deg = np.rad2deg(1)
rpm2RadSec = 2.0*(np.pi)/60.0
class Sim():
"""
Simple controller simulation interface for a wind turbine.
- Currently runs a 1DOF simple rotor model based on an OpenFAST model
Note: Due to the complex nature of the wind speed estimators implemented in ROSCO,
using them for simulations is known to cause problems for the simple simulator.
We suggesting using WE_Mode = 0 for the simulator
Methods:
--------
sim_ws_series
Parameters:
-----------
turbine: class
Turbine class containing wind turbine information from OpenFAST model
controller_int: class
Controller interface class to run compiled controller binary
"""
def __init__(self, turbine, controller_int):
"""
Setup the simulator
"""
self.turbine = turbine
self.controller_int = controller_int
def sim_ws_series(self,t_array,ws_array,rotor_rpm_init=10,init_pitch=0.0, make_plots=True):
'''
Simulate simplified turbine model using a complied controller (.dll or similar).
- currently a 1DOF rotor model
Parameters:
-----------
t_array: float
Array of time steps, (s)
ws_array: float
Array of wind speeds, (s)
rotor_rpm_init: float, optional
initial rotor speed, (rpm)
init_pitch: float, optional
initial blade pitch angle, (deg)
make_plots: bool, optional
True: generate plots, False: don't.
'''
print('Running simulation for %s wind turbine.' % self.turbine.TurbineName)
# Store turbine data for conveniente
dt = t_array[1] - t_array[0]
R = self.turbine.rotor_radius
GBRatio = self.turbine.Ng
# Declare output arrays
bld_pitch = np.ones_like(t_array) * init_pitch
rot_speed = np.ones_like(t_array) * rotor_rpm_init * rpm2RadSec # represent rot speed in rad / s
gen_speed = np.ones_like(t_array) * rotor_rpm_init * GBRatio * rpm2RadSec # represent gen speed in rad/s
aero_torque = np.ones_like(t_array) * 1000.0
gen_torque = np.ones_like(t_array) # * trq_cont(turbine_dict, gen_speed[0])
gen_power = np.ones_like(t_array) * 0.0
# Loop through time
for i, t in enumerate(t_array):
if i == 0:
continue # Skip the first run
ws = ws_array[i]
# Load current Cq data
tsr = rot_speed[i-1] * self.turbine.rotor_radius / ws
cq = self.turbine.Cq.interp_surface([bld_pitch[i-1]],tsr)
# Update the turbine state
# -- 1DOF model: rotor speed and generator speed (scaled by Ng)
aero_torque[i] = 0.5 * self.turbine.rho * (np.pi * R**2) * cq * R * ws**2
rot_speed[i] = rot_speed[i-1] + (dt/self.turbine.J)*(aero_torque[i] * self.turbine.GenEff/100 - self.turbine.Ng * gen_torque[i-1])
gen_speed[i] = rot_speed[i] * self.turbine.Ng
# Call the controller
gen_torque[i], bld_pitch[i] = self.controller_int.call_controller(t,dt,bld_pitch[i-1],gen_torque[i-1],gen_speed[i],self.turbine.GenEff/100,rot_speed[i],ws)
# Calculate the power
gen_power[i] = gen_speed[i] * gen_torque[i]
# Save these values
self.bld_pitch = bld_pitch
self.rot_speed = rot_speed
self.gen_speed = gen_speed
self.aero_torque = aero_torque
self.gen_torque = gen_torque
self.gen_power = gen_power
self.t_array = t_array
self.ws_array = ws_array
# Close shared library when finished
self.controller_int.kill_discon()
if make_plots:
fig, axarr = plt.subplots(4,1,sharex=True,figsize=(6,10))
ax = axarr[0]
ax.plot(self.t_array,self.ws_array)
ax.set_ylabel('Wind Speed (m/s)')
ax.grid()
ax = axarr[1]
ax.plot(self.t_array,self.rot_speed)
ax.set_ylabel('Rot Speed (rad/s)')
ax.grid()
ax = axarr[2]
ax.plot(self.t_array,self.gen_torque)
ax.set_ylabel('Gen Torque (N)')
ax.grid()
ax = axarr[3]
ax.plot(self.t_array,self.bld_pitch*rad2deg)
ax.set_ylabel('Bld Pitch (deg)')
ax.set_xlabel('Time (s)')
ax.grid()
| [
2,
15069,
13130,
399,
16448,
198,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
345,
743,
407,
779,
198,
2,
428,
2393,
2845,
287,
11846,
351,
262,
13789,
13,
921,
743,
7330,
257,
4866,
... | 2.149533 | 2,461 |
#!/usr/bin/python3
import sys, getopt
import plistlib
from optparse import OptionParser
from sys import version_info
if __name__ == "__main__":
main(sys.argv[1:])
| [
2,
48443,
14629,
14,
8800,
14,
29412,
18,
198,
198,
11748,
25064,
11,
651,
8738,
198,
11748,
458,
396,
8019,
198,
6738,
2172,
29572,
1330,
16018,
46677,
198,
6738,
25064,
1330,
2196,
62,
10951,
628,
628,
628,
198,
361,
11593,
3672,
83... | 2.761905 | 63 |
import torch
import numpy as np
from deep_privacy import torch_utils
from deep_privacy.visualization import utils as vis_utils
import os
from deep_privacy.inference import infer
from deep_privacy.data_tools.dataloaders import load_dataset_files, cut_bounding_box
import matplotlib.pyplot as plt
if __name__ == "__main__":
generator, _, _, _, _ = infer.read_args()
imsize = generator.current_imsize
images, bounding_boxes, landmarks = load_dataset_files("data/fdf", imsize,
load_fraction=True)
batch_size = 128
savedir = os.path.join(".debug","test_examples", "pose_sensitivity_experiment")
os.makedirs(savedir, exist_ok=True)
num_iterations = 20
ims_to_save = []
percentages = [0] + list(np.linspace(-0.3, 0.3, num_iterations-1))
z = generator.generate_latent_variable(1, "cuda", torch.float32).zero_()
for idx in range(-5, -1):
orig = images[idx]
orig_pose = landmarks[idx:idx+1]
bbox = bounding_boxes[idx].clone()
assert orig.dtype == np.uint8
to_save = orig.copy()
to_save = np.tile(to_save, (2, 1, 1))
truncation_levels = np.linspace(0.00, 3, num_iterations)
for i in range(num_iterations):
im = orig.copy()
orig_to_save = im.copy()
p = percentages[i]
pose = orig_pose.clone()
rand = torch.rand_like(pose) - 0.5
rand = (rand / 0.5) * p
pose += rand
im = cut_bounding_box(im, bbox, generator.transition_value)
keypoints = (pose*imsize).long()
keypoints = infer.keypoint_to_numpy(keypoints)
orig_to_save = vis_utils.draw_faces_with_keypoints(
orig_to_save, None, [keypoints],
radius=3)
im = torch_utils.image_to_torch(im, cuda=True, normalize_img=True)
im = generator(im, pose, z.clone())
im = torch_utils.image_to_numpy(im.squeeze(), to_uint8=True, denormalize=True)
im = np.concatenate((orig_to_save.astype(np.uint8), im), axis=0)
to_save = np.concatenate((to_save, im), axis=1)
ims_to_save.append(to_save)
savepath = os.path.join(savedir, f"result_image.jpg")
ims_to_save = np.concatenate(ims_to_save, axis=0)
plt.imsave(savepath, ims_to_save)
print("Results saved to:", savedir) | [
11748,
28034,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
2769,
62,
13776,
1590,
1330,
28034,
62,
26791,
198,
6738,
2769,
62,
13776,
1590,
13,
41464,
1634,
1330,
3384,
4487,
355,
1490,
62,
26791,
198,
11748,
28686,
198,
6738,
2769,
6... | 2.098958 | 1,152 |
import os
inputfile = "c:\ip.txt"
inputfile='c:\column.bmp'
outputfile = 'c:\ip_result.txt'
outputfile2 = 'c:\ip_result2.txt'
import sys
if __name__ == '__main__':
if (len(sys.argv)) != 2:
print 'Input filepath'
exit(1)
f_input = sys.argv[1]
print f_input
travsedir(f_input)
| [
11748,
28686,
201,
198,
15414,
7753,
796,
366,
66,
7479,
541,
13,
14116,
1,
201,
198,
15414,
7753,
11639,
66,
7479,
28665,
13,
65,
3149,
6,
201,
198,
22915,
7753,
796,
705,
66,
7479,
541,
62,
20274,
13,
14116,
6,
201,
198,
22915,
... | 2.054054 | 148 |
import json
import os
from json import JSONDecodeError
import magic
import requests
from PyPDF2 import PdfFileReader
from django.http import Http404
from config.configuration import django_backend_service_api_url, verify_certificate
from eatb.utils.fileutils import read_file_content, find_files
from util.djangoutils import get_user_api_token
| [
11748,
33918,
198,
11748,
28686,
198,
6738,
33918,
1330,
19449,
10707,
1098,
12331,
198,
198,
11748,
5536,
198,
11748,
7007,
198,
6738,
9485,
20456,
17,
1330,
350,
7568,
8979,
33634,
198,
6738,
42625,
14208,
13,
4023,
1330,
367,
29281,
26... | 3.441176 | 102 |
import os
import matplotlib.pyplot as plt
import matplotlib
import pandas as pd
import numpy as np
import logging
import sys
from sklearn.metrics import mean_absolute_error
import seaborn
from .common import INSOLES_FILE_NAME, LABELS_FILE_NAME
seaborn.set()
matplotlib.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}']
plt.rc('text', usetex=True)
TARGET_FRAME_RATE = 60
STEP_FORCE_THRESHOLD = 0.2
LIFT_FORCE_THRESHOLD = 0.17
logging.basicConfig(format='%(message)s', level=logging.DEBUG)
#reprocess_all_soles_data()
#optimize_thresholds()
| [
11748,
28686,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
11748,
2603,
29487,
8019,
198,
11748,
19798,
292,
355,
279,
67,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
18931,
198,
11748,
25064,
198,
198,
6738,
1... | 2.555556 | 225 |
# Copyright 2021 The FACEGOOD 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.
# ==============================================================================
import numpy as np
import os
project_dir = r'D:\audio2bs\shirley_1119'
bs_name = np.load(os.path.join(project_dir,'shirley_1119_bs_name.npy'))
dataSet_dir = os.path.join(project_dir,'dataSet16')
# 参与训练的数据
# name_list = ['1_01','1_02','2_01','2_02','2_03','2_04'] #dataSet1
# name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','3_15','3_16'] #dataSet2
# name_list = ['2_02','2_03','2_04','3_15','3_16'] #dataSet3:修改后的2_02和2_04
# name_list = ['2_02','2_03','2_04','3_15','3_16'] #dataSet4:修改后的2_02和2_04
# name_list = ['1_01','1_02','2_02','2_03','2_04'] #dataSet5:修改后的1_01、1_02、2_02和2_04
# name_list = ['1_01','1_02','2_02','2_03','2_04','3_15','3_16'] #dataSet6:修改后的1_01、1_02、2_02和2_04
# name_list = ['1_01','1_02','2_02','2_03','2_04'] #dataSet7:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3
# name_list = ['1_01','1_02','2_02','2_03','2_04','3_15','3_16'] #dataSet8:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3
# name_list = ['1_01','1_02','2_02','2_03','2_04'] #dataSet9:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3;删除单音节和词语一半的0帧
# name_list = ['1_01','1_02','2_02','2_03','2_04','3_15','3_16'] #dataSet10:修改后的1_01、1_02、2_02和2_04;1_01、1_02张嘴等系数*1.3;删除单音节和词语一半的0帧
# name_list = ['1_01','1_02','2_01','2_02','2_03','2_04'] #dataSet11:修改后的1_01、1_02、2_01、2_02和2_04
# name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','3_15','3_16'] #dataSet12:修改后的1_01、1_02、2_01、2_02和2_04
# name_list = ['1_01','1_02','2_01','2_02','2_03','2_04'] #dataSet11:修改后的1_01、1_02、2_01、2_02和2_04;删除单音节和词语一半的0帧
# name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','3_15','3_16'] #dataSet12:修改后的1_01、1_02、2_01、2_02和2_04;删除单音节和词语一半的0帧
name_list = ['1_01','1_02','2_01','2_02','2_03','2_04','2_05','3_15','3_16'] #dataSet16:all_付
data_path_list = [os.path.join(project_dir,'lpc','lpc_1114_' + i + '.npy') for i in name_list]
label_path_list = [os.path.join(project_dir,'bs_value','bs_value_1114_' + i + '.npy') for i in name_list]
data = np.zeros((1, 32, 64, 1))
label = np.zeros((1, 116))
for i in range(len(data_path_list)):
data_temp = np.load(data_path_list[i])
label_temp = np.load(label_path_list[i])
if data_path_list[i][-8] == '1' or data_path_list[i][-8] == '2':
label_temp_sum = label_temp.sum(axis=1)
zero_index = np.where(label_temp_sum == 0)[0]
half_zero_index = [zero_index[i] for i in range(0,len(zero_index),2)]
select_index = [i for i in range(label_temp.shape[0]) if i not in half_zero_index]
data_temp = data_temp[select_index]
label_temp = label_temp[select_index]
data = np.vstack((data,data_temp))
label = np.vstack((label,label_temp))
data = data[1:]
label = label[1:]
print(data.shape)
print(label.shape)
# label1 = np.zeros((label.shape[0],label.shape[1]))
# bs_name_index = [0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 94, 93, 95, 96, 97, 98, 99, 100, 101, 102, 103, 105, 104, 106, 107, 108, 109, 110, 111, 112, 113, 114, 1, 115]
# for i in range(len(bs_name_index)):
# label1[:,i] = label[:,bs_name_index[i]]
# label = label1
############### select ###############
# # bs的相关性计算
# import pandas as pd
# df = pd.DataFrame(label,columns=bs_name)
# corr = df.corr() #计算相关系数
# data = corr.values
# print(data.shape)
# bs_value_dict = {} # key:bs原始索引;value:与key的bs相关的min(bs_index)
# for i in range(len(bs_name)):
# bs_name_corr = corr[(corr[bs_name[i]]==1)].index.tolist() #与bs_name[i]极相关的bs_name。 0.99-0.995 33个;0.999 37个;0.9999 38个;1 41个
# if len(bs_name_corr)==0:
# bs_value_dict[i] = i
# else:
# ndx = np.asarray([np.nonzero(bs_name == bs_name0)[0][0] for bs_name0 in bs_name_corr]) #返回索引
# bs_value_dict[i] = min(ndx)
# print(bs_value_dict)
# bs_index = list(set(list(bs_value_dict.values())))
# print('uncorr_bs_index: ',bs_index)
# print('uncorr_bs_num: ',len(bs_index))
# # 筛选常值bs和变值bs
# bs_max_value = np.amax(label, axis=0) #每个BS的最大值
# bs_min_value = np.amin(label, axis=0) #每个BS的最小值
# # print('bs_max_value: ',bs_max_value)
# # print('bs_min_value: ',bs_min_value)
# const_bs_index = np.where(bs_max_value-bs_min_value==0) #常数BS的索引
# const_bs_index = list(const_bs_index[0])
# print('const_bs_index: ',const_bs_index)
# var_bs_index = [x for x in range(len(bs_name)) if x not in const_bs_index] #变值BS的索引
# print('var_bs_index: ',var_bs_index)
# print('var_bs_index_len: ',len(var_bs_index))
# const_bs_value = label[0][const_bs_index] #值不变的BS其值
# print('const_bs_value: ',const_bs_value)
# bs_name_1119_v1
# const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 38, 45, 46, 47, 48, 49, 54, 55, 60, 61, 64, 69, 70, 71, 72, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115]
# var_bs_index = [9, 12, 13, 14, 17, 32, 36, 37, 39, 40, 41, 42, 43, 44, 50, 51, 52, 53, 56, 57, 58, 59, 62, 63, 65, 66, 67, 68, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83]
# const_bs_value = [0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.]
# bs_name_1015_v1
# const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 39, 46, 47, 48, 49, 50, 55, 56, 61, 62, 65, 70, 71, 72, 73, 83, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115]
# var_bs_index = [10, 13, 14, 15, 18, 33, 38, 40, 41, 42, 43, 44, 45, 51, 52, 53, 54, 57, 58, 59, 60, 63, 64, 66, 67, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84]
# const_bs_value = [0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.]
# bs_name_1119_v2
# const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 15, 16, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 33, 34, 35, 38, 45, 46, 47, 48, 49, 54, 55, 60, 61, 64, 69, 70, 71, 72, 82, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115]
# var_bs_index = [9, 12, 13, 14, 17, 32, 36, 37, 39, 40, 41, 42, 43, 44, 50, 51, 52, 53, 56, 57, 58, 59, 62, 63, 65, 66, 67, 68, 73, 74, 75, 76, 77, 78, 79, 80, 81, 83]
# const_bs_value = [0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.]
# bs_name_1015_v2
const_bs_index = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 16, 17, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 34, 35, 36, 37, 39, 46, 47, 48, 49, 50, 55, 56, 61, 62, 65, 70, 71, 72, 73, 83, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115]
var_bs_index = [10, 13, 14, 15, 18, 33, 38, 40, 41, 42, 43, 44, 45, 51, 52, 53, 54, 57, 58, 59, 60, 63, 64, 66, 67, 68, 69, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84]
const_bs_value = [0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,-0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.,-0.,0.]
# 保存训练数据
train_data = data
val_data = data[-1000:]
train_label_var = label[:,var_bs_index]
val_label_var = label[-1000:,var_bs_index]
print(train_data.shape)
print(val_data.shape)
print(train_label_var.shape)
print(val_label_var.shape)
np.save(os.path.join(dataSet_dir,'train_data.npy'),train_data)
np.save(os.path.join(dataSet_dir,'val_data.npy'),val_data)
np.save(os.path.join(dataSet_dir,'train_label_var.npy'),train_label_var)
np.save(os.path.join(dataSet_dir,'val_label_var.npy'),val_label_var)
| [
2,
15069,
33448,
383,
44216,
7156,
22808,
46665,
13,
1439,
6923,
33876,
13,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
743,
407,
779,
428,
2393,
2845,
287,
11846... | 1.857055 | 4,876 |
"""
Given two binary trees, write a function to check
if they are equal or not.
Two binary trees are considered equal if they are
structurally identical and the nodes have the same value.
"""
# Time Complexity O(min(N,M))
# where N and M are the number of nodes for the trees.
# Space Complexity O(min(height1, height2))
# levels of recursion is the mininum height between the two trees.
| [
37811,
198,
15056,
734,
13934,
7150,
11,
3551,
257,
2163,
284,
2198,
198,
361,
484,
389,
4961,
393,
407,
13,
198,
198,
7571,
13934,
7150,
389,
3177,
4961,
611,
484,
389,
198,
7249,
20221,
10411,
290,
262,
13760,
423,
262,
976,
1988,
... | 3.605505 | 109 |
from flask import Flask, render_template, jsonify, send_file
import random, json, base64, os
# import my_utils as utils
import opt_db
# 获取server.py当前路径,以及父路径、祖父路径
current_dir = os.path.dirname(__file__)
parent_dir = os.path.dirname(current_dir) # 获得current_dir所在的目录,
grandparent_dir = os.path.dirname(parent_dir)
print("current_dir: ", current_dir)
# print("parent_dir: ", parent_dir)
# print("grandparent_dir: ", grandparent_dir)
app = Flask(
__name__,
static_folder = parent_dir + "/client/static",
template_folder = parent_dir + "/client/templates"
)
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
data0 = [
{'name': 'root', 'value': 10086,'children':[
{'name': 'A', 'value': 1, 'children': [{'name': 'C', 'value': 3}, {'name': 'D', 'value': 4}]},
{'name': 'B', 'value': 2, 'children': [{'name': 'E', 'value': 5}, {'name': 'F', 'value': 6}]}
]}]
# dataIndex = [data0, data1, data2, data3]
map_data0 = [{"lon": 122.226654,"lat": 31.210672}]
map_data1 = [{"lon": 122.226654,"lat": 31.210672}, {"lon": 122.226654,"lat": 31.410672}]
map_data2 = [{"lon": 122.226654,"lat": 31.210672}, {"lon": 122.226654,"lat": 31.410672}, {"lon": 122.426654,"lat": 31.210672}]
map_data = [map_data0, map_data1, map_data2]
# 根路由,首页页面
@app.route("/")
# 英语版本的首页页面
@app.route("/en_version")
# 网站入口
@app.route("/index")
@app.route("/demo")
# 初始加载的树数据,可删除之
@app.route("/tree")
# 获取最新的仿真树data
@app.route("/tree/first")
# 获取最新的仿真树data
@app.route("/tree/lastest")
# 从数据库中查询指定TREEID的data并返回
@app.route("/tree/<treeid>")
@app.route("/map")
# 从数据库中查询指定VMID的data并返回
@app.route("/vm/<vmid>")
@app.route("/img/<imageid>")
@app.route("/sangji")
if __name__ == "__main__":
app.run(debug=True) | [
6738,
42903,
1330,
46947,
11,
8543,
62,
28243,
11,
33918,
1958,
11,
3758,
62,
7753,
198,
11748,
4738,
11,
33918,
11,
2779,
2414,
11,
28686,
198,
2,
1330,
616,
62,
26791,
355,
3384,
4487,
198,
11748,
2172,
62,
9945,
628,
198,
2,
5525... | 1.870763 | 944 |
##########################################################################
# NSAp - Copyright (C) CEA, 2016
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for details.
##########################################################################
# System import
import unittest
import sys
# COMPATIBILITY: since python 3.3 mock is included in unittest module
python_version = sys.version_info
if python_version[:2] <= (3, 3):
import mock
from mock import patch
mock_builtin = "__builtin__"
else:
import unittest.mock as mock
from unittest.mock import patch
mock_builtin = "builtins"
# Package import
from pyconnectome.utils.filetools import fslreorient2std, apply_mask
class Fslreorient2std(unittest.TestCase):
""" Test the FSL reorient the image to standard:
'pyconnectome.utils.filetools.fslreorient2std'
"""
def setUp(self):
""" Run before each test - the mock_popen will be available and in the
right state in every test<something> function.
"""
# Mocking popen
self.popen_patcher = patch("pyconnectome.wrapper.subprocess.Popen")
self.mock_popen = self.popen_patcher.start()
mock_process = mock.Mock()
attrs = {
"communicate.return_value": ("mock_OK", "mock_NONE"),
"returncode": 0
}
mock_process.configure_mock(**attrs)
self.mock_popen.return_value = mock_process
# Mocking set environ
self.env_patcher = patch(
"pyconnectome.wrapper.FSLWrapper._fsl_version_check")
self.mock_env = self.env_patcher.start()
self.mock_env.return_value = {}
# Define function parameters
self.kwargs = {
"input_image": "/my/path/mock_input_image",
"output_image": "/my/path/mock_output_image",
"save_trf": True,
"fslconfig": "/my/path/mock_shfile",
}
def tearDown(self):
""" Run after each test.
"""
self.popen_patcher.stop()
self.env_patcher.stop()
@mock.patch("pyconnectome.utils.filetools.os.path.isfile")
def test_badfileerror_raise(self, mock_isfile):
"""Bad input file -> raise valueError.
"""
# Set the mocked functions returned values
mock_isfile.side_effect = [False]
# Test execution
self.assertRaises(ValueError, fslreorient2std, **self.kwargs)
@mock.patch("{0}.open".format(mock_builtin))
@mock.patch("numpy.savetxt")
@mock.patch("pyconnectome.utils.filetools.flirt2aff")
@mock.patch("pyconnectome.utils.filetools.glob.glob")
@mock.patch("pyconnectome.utils.filetools.os.path.isfile")
def test_normal_execution(self, mock_isfile, mock_glob, mock_aff,
mock_savetxt, mock_open):
""" Test the normal behaviour of the function.
"""
# Set the mocked function returned values.
mock_isfile.side_effect = [True]
mock_glob.return_value = ["/my/path/mock_output"]
mock_context_manager = mock.Mock()
mock_open.return_value = mock_context_manager
mock_file = mock.Mock()
mock_file.read.return_value = "WRONG"
mock_enter = mock.Mock()
mock_enter.return_value = mock_file
mock_exit = mock.Mock()
setattr(mock_context_manager, "__enter__", mock_enter)
setattr(mock_context_manager, "__exit__", mock_exit)
mock_aff.flirt2aff.return_value = ""
# Test execution
fslreorient2std(**self.kwargs)
self.assertEqual([
mock.call(["which", "fslreorient2std"],
env={}, stderr=-1, stdout=-1),
mock.call(["fslreorient2std",
self.kwargs["input_image"],
self.kwargs["output_image"] + ".nii.gz"],
cwd=None, env={}, stderr=-1, stdout=-1),
mock.call(["which", "fslreorient2std"],
env={}, stderr=-1, stdout=-1),
mock.call(["fslreorient2std",
self.kwargs["input_image"]],
cwd=None, env={}, stderr=-1, stdout=-1)],
self.mock_popen.call_args_list)
self.assertEqual(len(self.mock_env.call_args_list), 1)
class FslApplyMask(unittest.TestCase):
""" Test the FSL apply mask:
'pyconnectome.utils.filetools.apply_mask'
"""
def setUp(self):
""" Run before each test - the mock_popen will be available and in the
right state in every test<something> function.
"""
# Mocking popen
self.popen_patcher = patch("pyconnectome.wrapper.subprocess.Popen")
self.mock_popen = self.popen_patcher.start()
mock_process = mock.Mock()
attrs = {
"communicate.return_value": ("mock_OK", "mock_NONE"),
"returncode": 0
}
mock_process.configure_mock(**attrs)
self.mock_popen.return_value = mock_process
# Mocking set environ
self.env_patcher = patch(
"pyconnectome.wrapper.FSLWrapper._fsl_version_check")
self.mock_env = self.env_patcher.start()
self.mock_env.return_value = {}
# Define function parameters
self.kwargs = {
"input_file": "/my/path/mock_input_file",
"mask_file": "/my/path/mock_mask_file",
"output_fileroot": "/my/path/mock_output_fileroot",
"fslconfig": "/my/path/mock_shfile",
}
def tearDown(self):
""" Run after each test.
"""
self.popen_patcher.stop()
self.env_patcher.stop()
def test_badfileerror_raise(self):
"""Bad input file -> raise valueError.
"""
# Test execution
self.assertRaises(ValueError, apply_mask, **self.kwargs)
@mock.patch("pyconnectome.utils.filetools.glob.glob")
@mock.patch("pyconnectome.utils.filetools.os.path.isfile")
def test_normal_execution(self, mock_isfile, mock_glob):
""" Test the normal behaviour of the function.
"""
# Set the mocked function returned values.
mock_isfile.side_effect = [True, True]
mock_glob.return_value = ["/my/path/mock_output"]
# Test execution
apply_mask(**self.kwargs)
self.assertEqual([
mock.call(["which", "fslmaths"],
env={}, stderr=-1, stdout=-1),
mock.call(["fslmaths",
self.kwargs["input_file"],
"-mas", self.kwargs["mask_file"],
self.kwargs["output_fileroot"]],
cwd=None, env={}, stderr=-1, stdout=-1)],
self.mock_popen.call_args_list)
self.assertEqual(len(self.mock_env.call_args_list), 1)
if __name__ == "__main__":
unittest.main()
| [
29113,
29113,
7804,
2235,
198,
2,
10551,
79,
532,
15069,
357,
34,
8,
327,
16412,
11,
1584,
198,
2,
4307,
6169,
739,
262,
2846,
286,
262,
20101,
34,
8267,
12,
33,
5964,
11,
355,
3199,
416,
198,
2,
262,
327,
16412,
12,
34,
41256,
... | 2.15657 | 3,219 |
import json
from os.path import abspath, dirname
import discord
import os
from discord.ext import commands
from discord.ext.commands import Bot
from cogs.Utils import Utils
with open(dirname(abspath(__file__)) + '/data/locales.json') as f:
locales = json.load(f)
with open(dirname(abspath(__file__)) + '/data/config.json') as f:
config = json.load(f)
bot = Bot(command_prefix=config['default_prefix'], help_command=None)
filepath = dirname(abspath(__file__))
@bot.event
@bot.event
bot.run(config['token'])
| [
11748,
33918,
198,
6738,
28686,
13,
6978,
1330,
2352,
6978,
11,
26672,
3672,
198,
198,
11748,
36446,
198,
11748,
28686,
198,
6738,
36446,
13,
2302,
1330,
9729,
198,
6738,
36446,
13,
2302,
13,
9503,
1746,
1330,
18579,
198,
198,
6738,
269... | 2.764398 | 191 |
'''
Copyright (c) 2019 Aria-K-Alethia@github.com
Description:
embedding class supporting multiple features
and customized merge method
Licence:
MIT
THE USER OF THIS CODE AGREES TO ASSUME ALL LIABILITY FOR THE USE OF THIS CODE.
Any use of this code should display all the info above.
'''
import torch
import torch.nn as nn
from embedding import Embedding
from mlp import MLP
class MultiFeatureEmbedding(nn.Module):
"""
overview:
for nlp, support multiple feature
and customized merge methods
params:
vocab_sizes: vocab size for each feature
embedding_dims: embedding dim for each feature
merge_methods: merge method for each feature
currently support 'cat', 'sum'
out_method: support 'none', 'linear', 'mlp'
out_dim: output dimension
"""
def forward(self, x):
'''
overview:
forward method
params:
x: [#batch, #len, #n_feature]
'''
# get embedding for each feature
outs = []
for emb, f in enumerate(zip(self.emb_list, x.split(1, -1))):
outs.append(emb(f.squeeze(-1)))
# merge
# cat
cat = [emb for index, emb in enumerate(outs)\
if self.merge_methods[index] == 'cat']
out = torch.cat(cat, -1)
# sum
sum_ = [emb for index, emb in enumerate(outs)\
if self.merge_methods[index] == 'sum']
[out.add_(item) for item in sum_]
if self.output_method != 'none':
out = self.out_module(out)
return out
@property
@property
@property
@property
@property
@property
@property
@property
| [
7061,
6,
197,
201,
198,
197,
15269,
357,
66,
8,
13130,
6069,
64,
12,
42,
12,
37474,
31079,
31,
12567,
13,
785,
201,
198,
197,
201,
198,
197,
11828,
25,
201,
198,
197,
197,
20521,
12083,
1398,
6493,
3294,
3033,
201,
198,
197,
197,
... | 2.416409 | 646 |
# Generated by Django 2.2 on 2019-06-06 09:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
| [
2,
2980,
515,
416,
37770,
362,
13,
17,
319,
13130,
12,
3312,
12,
3312,
7769,
25,
2999,
198,
198,
6738,
42625,
14208,
13,
10414,
1330,
6460,
198,
6738,
42625,
14208,
13,
9945,
1330,
15720,
602,
11,
4981,
198,
11748,
42625,
14208,
13,
... | 3.1 | 50 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import abc
from scipy.ndimage import gaussian_filter
import numpy as np
class CropDiagonal(AffinityRefinementOperation):
"""Crop the diagonal.
Replace diagonal element by the max value of row.
We do this because the diagonal will bias Gaussian blur and normalization.
"""
class GaussianBlur(AffinityRefinementOperation):
"""Apply Gaussian blur."""
class RowWiseThreshold(AffinityRefinementOperation):
"""Apply row wise thresholding."""
class Symmetrize(AffinityRefinementOperation):
"""The Symmetrization operation."""
class Diffuse(AffinityRefinementOperation):
"""The diffusion operation."""
class RowWiseNormalize(AffinityRefinementOperation):
"""The row wise max normalization operation."""
| [
6738,
11593,
37443,
834,
1330,
4112,
62,
11748,
198,
6738,
11593,
37443,
834,
1330,
7297,
198,
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
198,
11748,
450,
66,
198,
6738,
629,
541,
88,
13,
358,
9060,
1330,
31986,
31562,
62,
24... | 3.504098 | 244 |
"""
analyze EEG data
Created by Dirk van Moorselaar on 10-03-2015.
Copyright (c) 2015 DvM. All rights reserved.
"""
import mne
import os
import logging
import itertools
import pickle
import copy
import glob
import sys
import time
import itertools
import numpy as np
import scipy as sp
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import cm
from scipy.stats import zscore
from typing import Optional, Generic, Union, Tuple, Any
from termios import tcflush, TCIFLUSH
from eeg_analyses.EYE import *
from math import sqrt
from IPython import embed
from support.FolderStructure import *
from scipy.stats.stats import pearsonr
from mne.viz.epochs import plot_epochs_image
from mne.filter import filter_data
from mne.preprocessing import ICA
from mne.preprocessing import create_eog_epochs, create_ecg_epochs
from math import ceil, floor
from autoreject import Ransac, AutoReject
class RawBDF(mne.io.edf.edf.RawEDF, FolderStructure):
'''
Child originating from MNE built-in RawEDF, such that new methods can be added to this built in class
'''
def report_raw(self, report, events, event_id):
'''
'''
# report raw
report.add_raw(self, title='raw EEG', psd=True )
# and events
events = events[np.in1d(events[:,2], event_id)]
report.add_events(events, title = 'detected events', sfreq = self.info['sfreq'])
return report
def replaceChannel(self, sj, session, replace):
'''
Replace bad electrodes by electrodes that were used during recording as a replacement
Arguments
- - - - -
raw (object): raw mne eeg object
sj (int): subject_nr
session (int): eeg session number
replace (dict): dictionary containing to be replaced electrodes per subject and session
Returns
- - - -
self(object): raw object with bad electrodes replaced
'''
sj = str(sj)
session = 'session_{}'.format(session)
if sj in replace.keys():
if session in replace[sj].keys():
to_replace = replace[sj][session].keys()
for e in to_replace:
self._data[self.ch_names.index(e), :] = self._data[
self.ch_names.index(replace[sj][session][e]), :]
# print('Electrode {0} replaced by
# {1}'.format(e,replace[sj][session][e]))
def reReference(self, ref_channels=['EXG5', 'EXG6'], vEOG=['EXG1', 'EXG2'], hEOG=['EXG3', 'EXG4'], changevoltage=True, to_remove = ['EXG7','EXG8']):
'''
Rereference raw data to reference channels. By default data is rereferenced to the mastoids.
Also EOG data is rerefenced. Subtraction of VEOG and HEOG results in a VEOG and an HEOG channel.
After rereferencing redundant channels are removed. Functions assumes that there are 2 vEOG and 2
hEOG channels.
Arguments
- - - - -
self(object): RawBDF object
ref_channels (list): list with channels for rerefencing
vEOG (list): list with vEOG channels
hEOG (list): list with hEOG channels
changevoltage (bool):
remove(bool): Specify whether channels need to be removed
Returns
- - - -
self (object): Rereferenced raw eeg data
'''
# change data format from Volts to microVolts
if changevoltage:
self._data[:-1, :] *= 1e6
print('Volts changed to microvolts')
logging.info('Volts changed to microvolts')
# rereference all EEG channels to reference channels
self.set_eeg_reference(ref_channels=ref_channels)
to_remove += ref_channels
print('EEG data was rereferenced to channels {}'.format(ref_channels))
logging.info(
'EEG data was rereferenced to channels {}'.format(ref_channels))
# select eog channels
eog = self.copy().pick_types(eeg=False, eog=True)
# # rerefence EOG data (vertical and horizontal)
# idx_v = [eog.ch_names.index(vert) for vert in vEOG]
# idx_h = [eog.ch_names.index(hor) for hor in hEOG]
# if len(idx_v) == 2:
# eog._data[idx_v[0]] -= eog._data[idx_v[1]]
# if len(idx_h) == 2:
# eog._data[idx_h[0]] -= eog._data[idx_h[1]]
# print(
# 'EOG data (VEOG, HEOG) rereferenced with subtraction and renamed EOG channels')
# logging.info(
# 'EOG data (VEOG, HEOG) rereferenced with subtraction and renamed EOG channels')
# # add rereferenced vEOG and hEOG data to self
# ch_mapping = {vEOG[0]: 'VEOG', hEOG[0]: 'HEOG'}
# eog.rename_channels(ch_mapping)
# eog.drop_channels([vEOG[1], hEOG[1]])
# #self.add_channels([eog])
# drop ref chans
self.drop_channels(to_remove)
print('Reference channels and empty channels removed')
logging.info('Reference channels and empty channels removed')
def setMontage(self, montage='biosemi64', ch_remove = []):
'''
Uses mne function to set the specified montage. Also changes channel labels from A, B etc
naming scheme to standard naming conventions and removes specified channels.
At the same time changes the name of EOG electrodes (assumes an EXG naming scheme)
Arguments
- - - - -
raw (object): raw mne eeg object
montage (str): used montage during recording
ch_remove (list): channels that you want to exclude from analysis (e.g heart rate)
Returns
- - - -
self(object): raw object with changed channel names following biosemi 64 naming scheme (10 - 20 system)
'''
# drop channels and get montage
self.drop_channels(ch_remove)
# create mapping dictionary
idx = 0
ch_mapping = {}
if self.ch_names[0] == 'A1':
for hemi in ['A', 'B']:
for electr in range(1, 33):
ch_mapping.update(
{'{}{}'.format(hemi, electr): montage.ch_names[idx]})
idx += 1
self.rename_channels(ch_mapping)
self.set_montage(montage=montage)
print('Channels renamed to 10-20 system, and montage added')
logging.info('Channels renamed to 10-20 system, and montage added')
def eventSelection(self, trigger, binary=0, consecutive=False, min_duration=0.003):
'''
Returns array of events necessary for epoching.
Arguments
- - - - -
raw (object): raw mne eeg object
binary (int): is subtracted from stim channel to control for spoke triggers (e.g. subtracts 3840)
Returns
- - - -
events(array): numpy array with trigger events (first column contains the event time in samples and the third column contains the event id)
'''
self._data[-1, :] -= binary # Make universal
events = mne.find_events(self, stim_channel=None, consecutive=consecutive, min_duration=min_duration)
# Check for consecutive
if not consecutive:
spoke_idx = []
for i in range(events[:-1,2].size):
if events[i,2] == events[i + 1,2] and events[i,2] in trigger:
spoke_idx.append(i)
events = np.delete(events,spoke_idx,0)
logging.info('{} spoke events removed from event file'.format(len(spoke_idx)))
return events
def matchBeh(self, sj, session, events, event_id, trigger_header = 'trigger', headers = []):
'''
Alligns bdf file with csv file with experimental variables
Arguments
- - - - -
raw (object): raw mne eeg object
sj (int): sj number
session(int): session number
events(array): event file from eventSelection (last column contains trigger values)
trigger(list|array): trigger values used for epoching
headers (list): relevant column names from behavior file
Returns
- - - -
beh (object): panda object with behavioral data (triggers are alligned)
missing (araray): array of missing trials (can be used when selecting eyetracking data)
'''
# read in data file
beh_file = self.FolderTracker(extension=[
'beh', 'raw'], filename='subject-{}_session_{}.csv'.format(sj, session))
# get triggers logged in beh file
beh = pd.read_csv(beh_file)
beh = beh[headers]
if 'practice' in headers:
beh = beh[beh['practice'] == 'no']
beh = beh.drop(['practice'], axis=1)
beh_triggers = beh[trigger_header].values
# get triggers bdf file
if type(event_id) == dict:
event_id = [event_id[key] for key in event_id.keys()]
idx_trigger = [idx for idx, tr in enumerate(events[:,2]) if tr in event_id]
bdf_triggers = events[idx_trigger,2]
# log number of unique triggers
unique = np.unique(bdf_triggers)
logging.info('{} detected unique triggers (min = {}, max = {})'.
format(unique.size, unique.min(), unique.max()))
# make sure trigger info between beh and bdf data matches
missing_trials = []
nr_miss = beh_triggers.size - bdf_triggers.size
logging.info('{} trials will be removed from beh file'.format(nr_miss))
# check whether trial info is present in beh file
if nr_miss > 0 and 'nr_trials' not in beh.columns:
raise ValueError('Behavior file does not contain a column with trial info named nr_trials. Please adjust')
while nr_miss > 0:
stop = True
# continue to remove beh trials until data files are lined up
for i, tr in enumerate(bdf_triggers):
if tr != beh_triggers[i]: # remove trigger from beh_file
miss = beh['nr_trials'].iloc[i]
#print miss
missing_trials.append(miss)
logging.info('Removed trial {} from beh file,because no matching trigger exists in bdf file'.format(miss))
beh.drop(beh.index[i], inplace=True)
beh_triggers = np.delete(beh_triggers, i, axis = 0)
nr_miss -= 1
stop = False
break
# check whether there are missing trials at end of beh file
if beh_triggers.size > bdf_triggers.size and stop:
# drop the last items from the beh file
missing_trials = np.hstack((missing_trials, beh['nr_trials'].iloc[-nr_miss:].values))
beh.drop(beh.index[-nr_miss:], inplace=True)
logging.info('Removed last {} trials because no matches detected'.format(nr_miss))
nr_miss = 0
# keep track of missing trials to allign eye tracking data (if available)
missing = np.array(missing_trials)
# log number of matches between beh and bdf
logging.info('{} matches between beh and epoched data out of {}'.
format(sum(beh[trigger_header].values == bdf_triggers), bdf_triggers.size))
return beh, missing
class Epochs(mne.Epochs, FolderStructure):
'''
Child originating from MNE built-in Epochs, such that new methods can be added to this built in class
'''
def align_behavior(self, events: np.array, trigger_header: str = 'trigger', headers: list = [], bdf_remove: np.array = None):
"""
Aligns bdf file with csv file with experimental variables. In case there are more behavioral trials than eeg trials
(e.g., because trigger was not properly sent/detected), trials are removed from the raw behavioral data such that
both datasets are aligned. Information about this process can be found in individual preprocessing log files.
Args:
events (np.array): event info as returned by RAW.event_selection
trigger_header (str, optional): Column in raw behavior that contains trigger values used for epoching. Defaults to 'trigger'.
headers (list, optional): List of headers that should be linked to eeg data. Defaults to [].
bdf_remove (np.array, optional): Indices of trigger events that need to be removed. Only specify when to many trials are recorded.
Raises:
ValueError: In case behavior and eeg data do not align (i.e., contain different trial numbers). If there are more behavior trials than epochs,
raises an error in case there is no column 'nr_trials', which prevents informed alignment of eeg and behavior. Also raises an error if there are
too many epochs and automatic allignment fails
Returns:
beh (pd.DataFrame): Behavior data after aligning to eeg data (index is reset)
missing (np.array): array with trials that are removed from beh because no matching trigger was detected. Is used
when aligning eyetracker data (where it is assumed that eyetracking data and raw behavior contain the same number of trials)
"""
print('Linking behavior to eeg data')
report_str = ''
# read in data file
beh_file = self.FolderTracker(extension=[
'beh', 'raw'], filename='subject-{}_session_{}.csv'.format(self.sj, self.session))
# get triggers logged in beh file
beh = pd.read_csv(beh_file)
beh = beh[headers]
if 'practice' in headers:
print('{} practice trials removed from behavior'.format(beh[beh.practice == 'yes'].shape[0]))
#logging.info('{} practice trials removed from behavior'.format(beh[beh.practice == 'yes'].shape[0]))
beh = beh[beh.practice == 'no']
beh = beh.drop(['practice'], axis=1)
beh_triggers = beh[trigger_header].values
# get eeg triggers in epoched order ()
bdf_triggers = events[self.selection, 2]
if bdf_remove is not None:
self.drop(bdf_remove)
report_str += '{} bdf triggers removed as specified by the user \n'.format(bdf_remove.size)
#logging.info('{} bdf triggers and epochs removed as specified by the user'.format(bdf_remove.size))
bdf_triggers = np.delete(bdf_triggers, bdf_remove)
# log number of unique triggers
#unique = np.unique(bdf_triggers)
#logging.info('{} detected unique triggers (min = {}, max = {})'.
# format(unique.size, unique.min(), unique.max()))
# make sure trigger info between beh and bdf data matches
missing_trials = []
nr_miss = beh_triggers.size - bdf_triggers.size
#logging.info(f'{nr_miss} trials will be removed from beh file')
if nr_miss > 0:
report_str += f'Behavior has {nr_miss} more trials than detected events. The following trial numbers \
will be removed in attempt to fix this: \n'
# check whether trial info is present in beh file
if nr_miss > 0 and 'nr_trials' not in beh.columns:
raise ValueError('Behavior file does not contain a column with trial info named nr_trials. Please adjust')
elif nr_miss < 0:
report_str += 'EEG events are removed in an attempt to align the data. Please inspect your data carefully! \n'
while nr_miss < 0:
# continue to remove bdf triggers until data files are lined up
for i, tr in enumerate(beh_triggers):
if tr != bdf_triggers[i]: # remove trigger from eeg_file
bdf_triggers = np.delete(bdf_triggers, i, axis = 0)
nr_miss += 1
# check file sizes
if sum(beh_triggers == bdf_triggers) < bdf_triggers.size:
raise ValueError('Behavior and eeg cannot be linked as too many eeg triggers received. Please pass indices of trials to be removed \
to subject_info dict with key bdf_remove')
while nr_miss > 0:
stop = True
# continue to remove beh trials until data files are lined up
for i, tr in enumerate(bdf_triggers):
if tr != beh_triggers[i]: # remove trigger from beh_file
miss = beh['nr_trials'].iloc[i]
missing_trials.append(i)
report_str += f'{miss}, '
#logging.info(f'Removed trial {miss} from beh file,because no matching trigger exists in bdf file')
beh.drop(beh.index[i], inplace=True)
beh_triggers = np.delete(beh_triggers, i, axis = 0)
nr_miss -= 1
stop = False
break
# check whether there are missing trials at end of beh file
if beh_triggers.size > bdf_triggers.size and stop:
# drop the last items from the beh file
missing_trials = np.hstack((missing_trials, beh['nr_trials'].iloc[-nr_miss:].values))
beh.drop(beh.index[-nr_miss:], inplace=True)
#logging.info('Removed last {} trials because no matches detected'.format(nr_miss))
report_str += f'\n Removed final {nr_miss} trials from behavior to allign data. Please inspect your data carefully!'
nr_miss = 0
# keep track of missing trials to allign eye tracking data (if available)
missing = np.array(missing_trials)
beh.reset_index(inplace = True)
# add behavior to epochs object
self.metadata = beh
# log number of matches between beh and bdf
#logging.info('{} matches between beh and epoched data out of {}'.
# format(sum(beh[trigger_header].values == bdf_triggers), bdf_triggers.size))
report_str += '\n {} matches between beh and epoched data out of {}'.format(sum(beh[trigger_header].values == bdf_triggers), bdf_triggers.size)
return missing, report_str
def autoRepair(self):
'''
'''
# select eeg channels
picks = mne.pick_types(self.info, meg=False, eeg=True, stim=False, eog=False,
include=[], exclude=[])
# initiate parameters p and k
n_interpolates = np.array([1, 4, 32])
consensus_percs = np.linspace(0, 1.0, 11)
ar = AutoReject(n_interpolates, consensus_percs, picks=picks,
thresh_method='random_search', random_state=42)
self, reject_log = ar.fit_transform(self, return_log=True)
def apply_ransac(self):
'''
Implements RAndom SAmple Consensus (RANSAC) method to detect bad channels.
Returns
- - - -
self.info['bads']: list with all bad channels detected by the RANSAC algorithm
'''
# select channels to display
picks = mne.pick_types(self.info, eeg=True, exclude='bads')
# use Ransac, interpolating bads and append bad channels to self.info['bads']
ransac = Ransac(verbose=False, picks=picks, n_jobs=1)
epochs_clean = ransac.fit_transform(self)
print('The following electrodes are selected as bad by Ransac:')
print('\n'.join(ransac.bad_chs_))
return ransac.bad_chs_
def selectBadChannels(self, run_ransac = True, channel_plots=True, inspect=True, n_epochs=10, n_channels=32, RT = None):
'''
'''
logging.info('Start selection of bad channels')
#matplotlib.style.use('classic')
# select channels to display
picks = mne.pick_types(self.info, eeg=True, exclude='bads')
# plot epoched data
if channel_plots:
for ch in picks:
# plot evoked responses across channels
try: # handle bug in mne for plotting undefined x, y coordinates
plot_epochs_image(self.copy().crop(self.tmin + self.flt_pad,self.tmax - self.flt_pad), ch, show=False, overlay_times = RT)
plt.savefig(self.FolderTracker(extension=[
'preprocessing', 'subject-{}'.format(self.sj), self.session, 'channel_erps'], filename='{}.pdf'.format(self.ch_names[ch])))
plt.close()
except:
plt.savefig(self.FolderTracker(extension=[
'preprocessing', 'subject-{}'.format(self.sj), self.session,'channel_erps'], filename='{}.pdf'.format(self.ch_names[ch])))
plt.close()
self.plot_psd(picks = [ch], show = False)
plt.savefig(self.FolderTracker(extension=[
'preprocessing', 'subject-{}'.format(self.sj), self.session,'channel_erps'], filename='_psd_{}'.format(self.ch_names[ch])))
plt.close()
# plot power spectra topoplot to detect any clear bad electrodes
self.plot_psd_topomap(bands=[(0, 4, 'Delta'), (4, 8, 'Theta'), (8, 12, 'Alpha'), (
12, 30, 'Beta'), (30, 45, 'Gamma'), (45, 100, 'High')], show=False)
plt.savefig(self.FolderTracker(extension=[
'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='psd_topomap.pdf'))
plt.close()
if run_ransac:
self.applyRansac()
if inspect:
# display raw eeg with 50mV range
self.plot(block=True, n_epochs=n_epochs,
n_channels=n_channels, picks=picks, scalings=dict(eeg=50))
if self.info['bads'] != []:
with open(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj),
self.session], filename='marked_bads.txt'), 'wb') as handle:
pickle.dump(self.info['bads'], handle)
else:
try:
with open(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj),
self.session], filename='marked_bads.txt'), 'rb') as handle:
self.info['bads'] = pickle.load(handle)
print('The following channals were read in as bads from a txt file: {}'.format(
self.info['bads']))
except:
print('No bad channels selected')
logging.info('{} channels marked as bad: {}'.format(
len(self.info['bads']), self.info['bads']))
def automatic_artifact_detection(self, z_thresh=4, band_pass=[110, 140], plot=True, inspect=True):
""" Detect artifacts> modification of FieldTrip's automatic artifact detection procedure
(https://www.fieldtriptoolbox.org/tutorial/automatic_artifact_rejection/).
Artifacts are detected in three steps:
1. Filtering the data within specified frequency range
2. Z-transforming the filtered data across channels and normalize it over channels
3. Threshold the accumulated z-score
Counter to fieldtrip the z_threshold is ajusted based on the noise level within the data
Note: all data included for filter padding is now taken into consideration to calculate z values
Afer running this function, Epochs contains information about epeochs marked as bad (self.marked_epochs)
Arguments:
Keyword Arguments:
z_thresh {float|int} -- Value that is added to difference between median
and min value of accumulated z-score to obtain z-threshold
band_pass {list} -- Low and High frequency cutoff for band_pass filter
plot {bool} -- If True save detection plots (overview of z scores across epochs,
raw signal of channel with highest z score, z distributions,
raw signal of all electrodes)
inspect {bool} -- If True gives the opportunity to overwrite selected components
"""
embed()
# select data for artifact rejection
sfreq = self.info['sfreq']
self_copy = self.copy()
self_copy.pick_types(eeg=True, exclude='bads')
#filter data and apply Hilbert
self_copy.filter(band_pass[0], band_pass[1], fir_design='firwin', pad='reflect_limited')
#self_copy.filter(band_pass[0], band_pass[1], method='iir', iir_params=dict(order=6, ftype='butter'))
self_copy.apply_hilbert(envelope=True)
# get the data and apply box smoothing
data = self_copy.get_data()
nr_epochs = data.shape[0]
for i in range(data.shape[0]):
data[i] = self.boxSmoothing(data[i])
# get the data and z_score over electrodes
data = data.swapaxes(0,1).reshape(data.shape[1],-1)
z_score = zscore(data, axis = 1) # check whether axis is correct!!!!!!!!!!!
# normalize z_score
z_score = z_score.sum(axis = 0)/sqrt(data.shape[0])
#z_score = filter_data(z_score, self.info['sfreq'], None, 4, pad='reflect_limited')
# adjust threshold (data driven)
z_thresh += np.median(z_score) + abs(z_score.min() - np.median(z_score))
# transform back into epochs
z_score = z_score.reshape(nr_epochs, -1)
# control for filter padding
if self.flt_pad > 0:
idx_ep = self.time_as_index([self.tmin + self.flt_pad, self.tmax - self.flt_pad])
z_score = z_score[:, slice(*idx_ep)]
# mark bad epochs
bad_epochs = []
cnt = 0
for ep, X in enumerate(z_score):
noise_smp = np.where(X > z_thresh)[0]
if noise_smp.size > 0:
bad_epochs.append(ep)
if inspect:
print('This interactive window selectively shows epochs marked as bad. You can overwrite automatic artifact detection by clicking on selected epochs')
bad_eegs = self[bad_epochs]
idx_bads = bad_eegs.selection
# display bad eegs with 50mV range
bad_eegs.plot(
n_epochs=5, n_channels=data.shape[1], scalings=dict(eeg = 50))
plt.show()
plt.close()
missing = np.array([list(idx_bads).index(idx) for idx in idx_bads if idx not in bad_eegs.selection],dtype = int)
logging.info('Manually ignored {} epochs out of {} automatically selected({}%)'.format(
missing.size, len(bad_epochs),100 * round(missing.size / float(len(bad_epochs)), 2)))
bad_epochs = np.delete(bad_epochs, missing)
if plot:
plt.figure(figsize=(10, 10))
with sns.axes_style('dark'):
plt.subplot(111, xlabel='samples', ylabel='z_value',
xlim=(0, z_score.size), ylim=(-20, 40))
plt.plot(np.arange(0, z_score.size), z_score.flatten(), color='b')
plt.plot(np.arange(0, z_score.size),
np.ma.masked_less(z_score.flatten(), z_thresh), color='r')
plt.axhline(z_thresh, color='r', ls='--')
plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(
self.sj), self.session], filename='automatic_artdetect.pdf'))
plt.close()
# drop bad epochs and save list of dropped epochs
self.drop_beh = bad_epochs
np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(
self.sj), self.session], filename='noise_epochs.txt'), bad_epochs)
print('{} epochs dropped ({}%)'.format(len(bad_epochs),
100 * round(len(bad_epochs) / float(len(self)), 2)))
logging.info('{} epochs dropped ({}%)'.format(
len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2)))
self.drop(np.array(bad_epochs), reason='art detection ecg')
logging.info('{} epochs left after artifact detection'.format(len(self)))
np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='automatic_artdetect.txt'),
['Artifact detection z threshold set to {}. \n{} epochs dropped ({}%)'.
format(round(z_thresh, 1), len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))], fmt='%.100s')
return z_thresh
def artifactDetectionOLD(self, z_cutoff=4, band_pass=[110, 140], min_dur = 0.05, min_nr_art = 1, run = True, plot=True, inspect=True):
""" Detect artifacts based on FieldTrip's automatic artifact detection.
Artifacts are detected in three steps:
1. Filtering the data (6th order butterworth filter)
2. Z-transforming the filtered data and normalize it over channels
3. Threshold the accumulated z-score
False-positive transient peaks are prevented by low-pass filtering the resulting z-score time series at 4 Hz.
Afer running this function, Epochs contains information about epeochs marked as bad (self.marked_epochs)
Arguments:
Keyword Arguments:
z_cuttoff {int} -- Value that is added to difference between median
nd min value of accumulated z-score to obtain z-threshold
band_pass {list} -- Low and High frequency cutoff for band_pass filter
min_dur {float} -- minimum duration of detected artefects to be considered an artefact
min_nr_art {int} -- minimum number of artefacts that may be present in an epoch (irrespective of min_dur)
run {bool} -- specifies whether analysis is run a new or whether bad epochs are read in from memory
plot {bool} -- If True save detection plots (overview of z scores across epochs,
raw signal of channel with highest z score, z distributions,
raw signal of all electrodes)
inspect {bool} -- If True gives the opportunity to overwrite selected components
time {tuple} -- Time window used for decoding
tr_header {str} -- Name of column that contains training labels
te_header {[type]} -- Name of column that contains testing labels
"""
# select channels for artifact detection
picks = mne.pick_types(self.info, eeg=True, exclude='bads')
nr_channels = picks.size
sfreq = self.info['sfreq']
# control for filter padding
if self.flt_pad > 0:
idx_ep = self.time_as_index([self.tmin + self.flt_pad, self.tmax - self.flt_pad])
timings = self.times[idx_ep[0]:idx_ep[1]]
ep_data = []
# STEP 1: filter each epoch data, apply hilbert transform and boxsmooth
# the resulting data before removing filter padds
if run:
print('Started artifact detection')
logging.info('Started artifact detection')
for epoch, X in enumerate(self):
# CHECK IF THIS IS CORRECT ORDER IN FIELDTRIP CODE / ALSO CHANGE
# FILTER TO MNE 0.14 STANDARD
X = filter_data(X[picks, :], sfreq, band_pass[0], band_pass[
1], method='iir', iir_params=dict(order=6, ftype='butter'))
X = np.abs(sp.signal.hilbert(X))
X = self.boxSmoothing(X)
X = X[:, idx_ep[0]:idx_ep[1]]
ep_data.append(X)
# STEP 2: Z-transform data
epoch = np.hstack(ep_data)
avg_data = epoch.mean(axis=1).reshape(-1, 1)
std_data = epoch.std(axis=1).reshape(-1, 1)
z_data = [(ep - avg_data) / std_data for ep in ep_data]
# STEP 3 threshold z-score per epoch
z_accumel = np.hstack(z_data).sum(axis=0) / sqrt(nr_channels)
z_accumel_ep = [np.array(z.sum(axis=0) / sqrt(nr_channels))
for z in z_data]
z_thresh = np.median(
z_accumel) + abs(z_accumel.min() - np.median(z_accumel)) + z_cutoff
# split noise epochs based on start and end time
# and select bad epochs based on specified criteria
bad_epochs = []
for ep, X in enumerate(z_accumel_ep):
noise_smp = np.where((X > z_thresh) == True)[0]
noise_smp = np.split(noise_smp, np.where(np.diff(noise_smp) != 1)[0]+1)
time_inf = [timings[smp[-1]] - timings[smp[0]] for smp in noise_smp
if smp.size > 0]
if len(time_inf) > 0:
if max(time_inf) > min_dur or len(time_inf) > min_nr_art:
bad_epochs.append(ep)
if plot:
plt.figure(figsize=(10, 10))
with sns.axes_style('dark'):
plt.subplot(111, xlabel='samples', ylabel='z_value',
xlim=(0, z_accumel.size), ylim=(-20, 40))
plt.plot(np.arange(0, z_accumel.size), z_accumel, color='b')
plt.plot(np.arange(0, z_accumel.size),
np.ma.masked_less(z_accumel, z_thresh), color='r')
plt.axhline(z_thresh, color='r', ls='--')
plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(
self.sj), self.session], filename='automatic_artdetect.pdf'))
plt.close()
bad_epochs = np.array(bad_epochs)
else:
logging.info('Bad epochs read in from file')
bad_epochs = np.loadtxt(self.FolderTracker(extension=[
'preprocessing', 'subject-{}'.format(self.sj), self.session],
filename='noise_epochs.txt'))
if inspect:
print('You can now overwrite automatic artifact detection by clicking on epochs selected as bad')
bad_eegs = self[bad_epochs]
idx_bads = bad_eegs.selection
# display bad eegs with 50mV range
bad_eegs.plot(
n_epochs=5, n_channels=picks.size, picks=picks, scalings=dict(eeg = 50))
plt.show()
plt.close()
missing = np.array([list(idx_bads).index(idx) for idx in idx_bads if idx not in bad_eegs.selection], dtype = int)
logging.info('Manually ignored {} epochs out of {} automatically selected({}%)'.format(
missing.size, bad_epochs.size,100 * round(missing.size / float(bad_epochs.size), 2)))
bad_epochs = np.delete(bad_epochs, missing)
# drop bad epochs and save list of dropped epochs
np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(
self.sj), self.session], filename='noise_epochs.txt'), bad_epochs)
print('{} epochs dropped ({}%)'.format(len(bad_epochs),
100 * round(len(bad_epochs) / float(len(self)), 2)))
logging.info('{} epochs dropped ({}%)'.format(
len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2)))
self.drop(np.array(bad_epochs), reason='art detection ecg')
logging.info('{} epochs left after artifact detection'.format(len(self)))
if run:
np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='automatic_artdetect.txt'),
['Artifact detection z threshold set to {}. \n{} epochs dropped ({}%)'.
format(round(z_thresh, 1), len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))], fmt='%.100s')
def boxSmoothing(self, data, box_car=0.2):
'''
doc string boxSmoothing
'''
pad = int(round(box_car * self.info['sfreq']))
if pad % 2 == 0:
# the kernel should have an odd number of samples
pad += 1
kernel = np.ones(pad) / pad
pad = int(ceil(pad / 2))
pre_pad = int(min([pad, floor(data.shape[1]) / 2.0]))
edge_left = data[:, :pre_pad].mean(axis=1)
edge_right = data[:, -pre_pad:].mean(axis=1)
data = np.concatenate((np.tile(edge_left.reshape(data.shape[0], 1), pre_pad), data, np.tile(
edge_right.reshape(data.shape[0], 1), pre_pad)), axis=1)
data_smooth = sp.signal.convolve2d(
data, kernel.reshape(1, kernel.shape[0]), 'same')
data = data_smooth[:, pad:(data_smooth.shape[1] - pad)]
return data
def detectEye(self, missing, events, nr_events, time_window, threshold=20, windowsize=100, windowstep=10, channel='HEOG', tracker_shift = 0, start_event = '', extension = 'asc', eye_freq = 500, screen_res = (1680, 1050), viewing_dist = 60, screen_h = 29):
'''
Marking epochs containing step-like activity that is greater than a given threshold
Arguments
- - - - -
self(object): Epochs object
missing
events (array):
nr_events (int):
time_window (tuple): start and end time in seconds
threshold (int): range of amplitude in microVolt
windowsize (int): total moving window width in ms. So each window's width is half this value
windowsstep (int): moving window step in ms
channel (str): name of HEOG channel
tracker_shift (float): specifies difference in ms between onset trigger and event in eyetracker data
start_event (str): marking onset of trial in eyetracker data
extension (str): type of eyetracker file (now supports .asc/ .tsv)
eye_freq (int): sampling rate of the eyetracker
Returns
- - - -
'''
self.eye_bins = True
sac_epochs = []
# CODE FOR HEOG DATA
idx_ch = self.ch_names.index(channel)
idx_s, idx_e = tuple([np.argmin(abs(self.times - t))
for t in time_window])
windowstep /= 1000 / self.info['sfreq']
windowsize /= 1000 / self.info['sfreq']
for i in range(len(self)):
up_down = 0
for j in np.arange(idx_s, idx_e - windowstep, windowstep):
w1 = np.mean(self._data[i, idx_ch, int(
j):int(j + windowsize / 2) - 1])
w2 = np.mean(self._data[i, idx_ch, int(
j + windowsize / 2):int(j + windowsize) - 1])
if abs(w1 - w2) > threshold:
up_down += 1
if up_down == 2:
sac_epochs.append(i)
break
logging.info('Detected {0} epochs ({1:.2f}%) with a saccade based on HEOG'.format(
len(sac_epochs), len(sac_epochs) / float(len(self)) * 100))
# CODE FOR EYETRACKER DATA
EO = EYE(sfreq = eye_freq, viewing_dist = viewing_dist,
screen_res = screen_res, screen_h = screen_h)
# do binning based on eye-tracking data (if eyetracker data exists)
eye_bins, window_bins, trial_nrs = EO.eyeBinEEG(self.sj, int(self.session),
int((self.tmin + self.flt_pad + tracker_shift)*1000), int((self.tmax - self.flt_pad + tracker_shift)*1000),
drift_correct = (-200,0), start_event = start_event, extension = extension)
if eye_bins.size > 0:
logging.info('Window method detected {} epochs exceeding 0.5 threshold'.format(window_bins.size))
# remove trials that could not be linked to eeg trigger
if missing.size > 0:
eye_bins = np.delete(eye_bins, missing)
dropped = trial_nrs[missing]
logging.info('{} trials removed from eye data to align to eeg. Correspond to trial_nr {} in beh'.format(missing.size, dropped))
# remove trials that have been deleted from eeg
eye_bins = np.delete(eye_bins, self.drop_beh)
# log eyetracker info
unique_bins = np.array(np.unique(eye_bins), dtype = np.float64)
for eye_bin in np.unique(unique_bins[~np.isnan(unique_bins)]):
logging.info('{0:.1f}% of trials exceed {1} degree of visual angle'.format(sum(eye_bins> eye_bin) / eye_bins.size*100, eye_bin))
# save array of deviation bins
np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(
self.sj), self.session], filename='eye_bins.txt'), eye_bins)
# # correct for missing data (if eye recording is stopped during experiment)
# if eye_bins.size > 0 and eye_bins.size < self.nr_events:
# # create array of nan values for all epochs (UGLY CODING!!!)
# temp = np.empty(self.nr_events) * np.nan
# temp[trial_nrs - 1] = eye_bins
# eye_bins = temp
# temp = (np.empty(self.nr_events) * np.nan)
# temp[trial_nrs - 1] = trial_nrs
# trial_nrs = temp
# elif eye_bins.size == 0:
# eye_bins = np.empty(self.nr_events + missing.size) * np.nan
# trial_nrs = np.arange(self.nr_events + missing.size) + 1
def applyICA(self, raw, ica_fit, method='extended-infomax', decim=None, fit_params = None, inspect = True):
'''
Arguments
- - - - -
self(object): Epochs object
raw (object):
n_components ():
method (str):
decim ():
Returns
- - - -
self
'''
# make sure that bad electrodes and 'good' epochs match between both data sets
ica_fit.info['bads'] = self.info['bads']
if str(type(ica_fit))[-3] == 's':
print('fitting data on epochs object')
to_drop = [i for i, v in enumerate(ica_fit.selection) if v not in self.selection]
ica_fit.drop(to_drop)
# initiate ica
logging.info('Started ICA')
picks = mne.pick_types(self.info, eeg=True, exclude='bads')
ica = ICA(n_components=picks.size, method=method, fit_params = fit_params)
# ica is fitted on epoched data
ica.fit(ica_fit, picks=picks, decim=decim)
# plot the components
ica.plot_components(colorbar=True, picks=range(picks.size), show=False)
plt.savefig(self.FolderTracker(extension=[
'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='components.pdf'))
plt.close()
# advanced artifact detection
eog_epochs = create_eog_epochs(raw, baseline=(None, None))
eog_inds_a, scores = ica.find_bads_eog(eog_epochs)
ica.plot_scores(scores, exclude=eog_inds_a, show=False)
plt.savefig(self.FolderTracker(extension=[
'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='ica_scores.pdf'))
plt.close()
# diagnostic plotting
ica.plot_sources(self, show_scrollbars=False, show=False)
if inspect:
plt.show()
else:
plt.savefig(self.FolderTracker(extension=[
'preprocessing', 'subject-{}'.format(self.sj), self.session], filename='sources.pdf'))
plt.close()
# double check selected component with user input
time.sleep(5)
tcflush(sys.stdin, TCIFLUSH)
print('You are preprocessing subject {}, session {}'.format(self.sj, self.session))
conf = input(
'Advanced detection selected component(s) {}. Do you agree (y/n)'.format(eog_inds_a))
if conf == 'y':
eog_inds = eog_inds_a
else:
eog_inds = []
nr_comp = input(
'How many components do you want to select (<10)?')
for i in range(int(nr_comp)):
eog_inds.append(
int(input('What is component nr {}?'.format(i + 1))))
for i, cmpt in enumerate(eog_inds):
ica.plot_properties(self, picks=cmpt, psd_args={
'fmax': 35.}, image_args={'sigma': 1.}, show=False)
plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(
self.sj), self.session], filename='property{}.pdf'.format(cmpt)))
plt.close()
ica.plot_overlay(raw, exclude=eog_inds, picks=[self.ch_names.index(e) for e in [
'Fp1', 'Fpz', 'Fp2', 'AF7', 'AF3', 'AFz', 'AF4', 'AF8']], show = False)
plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(
self.sj), self.session], filename='ica-frontal.pdf'))
plt.close()
ica.plot_overlay(raw, exclude=eog_inds, picks=[self.ch_names.index(e) for e in [
'PO7', 'PO8', 'PO3', 'PO4', 'O1', 'O2', 'POz', 'Oz','Iz']], show = False)
plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(
self.sj), self.session], filename='ica-posterior.pdf'))
plt.close()
# remove selected component
ica.apply(self, exclude=eog_inds)
logging.info(
'The following components were removed from raw eeg with ica: {}'.format(eog_inds))
def link_behavior(self, beh: pd.DataFrame, combine_sessions: bool = True):
"""
Saves linked eeg and behavior data. Preprocessed eeg is saved in the folder processed and behavior is saved
in a processed subfolder of beh.
Args:
beh (pd.DataFrame): behavioral dataframe containing parameters of interest
combine_sessions (bool, optional):If experiment contains seperate sessions, these are combined into a single datafile that
is saved alongside the individual sessions. Defaults to True.
"""
# update beh dict after removing noise trials
beh.drop(self.drop_beh, axis = 'index', inplace = True)
# also include eye binned data
if hasattr(self, 'eye_bins'):
eye_bins = np.loadtxt(self.FolderTracker(extension=[
'preprocessing', 'subject-{}'.format(self.sj), self.session],
filename='eye_bins.txt'))
else:
eye_bins = np.nan
beh['eye_bins'] = pd.Series(eye_bins)
# save behavior as pickle
beh_dict = beh.to_dict(orient = 'list')
with open(self.FolderTracker(extension=['beh', 'processed'],
filename='subject-{}_ses-{}.pickle'.format(self.sj, self.session)), 'wb') as handle:
pickle.dump(beh_dict, handle)
# save eeg
self.save(self.FolderTracker(extension=[
'processed'], filename='subject-{}_ses-{}-epo.fif'.format(self.sj, self.session)),
split_size='2GB', overwrite = True)
# update preprocessing information
logging.info('Nr clean trials is {0}'.format(beh.shape[0]))
if 'condition' in beh.index:
cnd = beh['condition'].values
min_cnd, cnd = min([sum(cnd == c) for c in np.unique(cnd)]), np.unique(cnd)[
np.argmin([sum(cnd == c) for c in np.unique(cnd)])]
logging.info(
'Minimum condition ({}) number after cleaning is {}'.format(cnd, min_cnd))
else:
logging.info('no condition found in beh file')
logging.info('EEG data linked to behavior file')
# check whether individual sessions need to be combined
if combine_sessions and int(self.session) != 1:
# combine eeg and beh files of seperate sessions
all_beh = []
all_eeg = []
nr_events = []
for i in range(int(self.session)):
with open(self.FolderTracker(extension=['beh', 'processed'],
filename='subject-{}_ses-{}.pickle'.format(self.sj, i + 1)), 'rb') as handle:
all_beh.append(pickle.load(handle))
all_eeg.append(mne.read_epochs(self.FolderTracker(extension=[
'processed'], filename='subject-{}_ses-{}-epo.fif'.format(self.sj, i + 1))))
# do actual combining
for key in beh_dict.keys():
beh_dict.update(
{key: np.hstack([beh[key] for beh in all_beh])})
with open(self.FolderTracker(extension=['beh', 'processed'],
filename='subject-{}_all.pickle'.format(self.sj)), 'wb') as handle:
pickle.dump(beh_dict, handle)
all_eeg = mne.concatenate_epochs(all_eeg)
all_eeg.save(self.FolderTracker(extension=[
'processed'], filename='subject-{}_all-epo.fif'.format(self.sj)),
split_size='2GB', overwrite = True)
logging.info('EEG sessions combined')
class ArtefactReject(object):
""" Multiple (automatic artefact rejection procedures)
Work in progress
"""
@blockPrinting
def apply_hilbert(self, epochs: mne.Epochs, lower_band: int = 110, upper_band: int = 140) -> np.array:
"""
Takes an mne epochs object as input and returns the eeg data after Hilbert transform
Args:
epochs (mne.Epochs): mne epochs object before muscle artefact detection
lower_band (int, optional): Lower limit of the bandpass filter. Defaults to 110.
upper_band (int, optional): Upper limit of the bandpass filter. Defaults to 140.
Returns:
X (np.array): eeg data after applying hilbert transform within the given frequency band
"""
# exclude channels that are marked as overall bad
epochs_ = epochs.copy()
epochs_.pick_types(eeg=True, exclude='bads')
# filter data and apply Hilbert
epochs_.filter(lower_band, upper_band, fir_design='firwin', pad='reflect_limited')
epochs_.apply_hilbert(envelope=True)
# get data
X = epochs_.get_data()
del epochs_
return X
def filt_pad(self, X: np.array, pad_length: int) -> np.array:
"""
performs padding (using local mean method) on the data, i.e., adds samples before and after the data
TODO: MOVE to signal processing folder (see https://github.com/fieldtrip/fieldtrip/blob/master/preproc/ft_preproc_padding.m))
Args:
X (np.array): 2-dimensional array [nr_elec X nr_time]
pad_length (int): number of samples that will be padded
Returns:
X (np.array): 2-dimensional array with padded data [nr_elec X nr_time]
"""
# set number of pad samples
pre_pad = int(min([pad_length, floor(X.shape[1]) / 2.0]))
# get local mean on both sides
edge_left = X[:, :pre_pad].mean(axis=1)
edge_right = X[:, -pre_pad:].mean(axis=1)
# pad data
X = np.concatenate((np.tile(edge_left.reshape(X.shape[0], 1), pre_pad), X, np.tile(
edge_right.reshape(X.shape[0], 1), pre_pad)), axis=1)
return X
def box_smoothing(self, X: np.array, sfreq: float, boxcar: float = 0.2) -> np.array:
"""
performs boxcar smoothing with specified length. Modified version of ft_preproc_smooth as
implemented in the FieldTrip toolbox (https://www.fieldtriptoolbox.org)
Args:
X (np.array): 3-dimensional array [nr_epoch X nr_elec X nr_time]
sfreq (float): sampling frequency
boxcar (float, optional): parameter that determines the length of the filter kernel. Defaults to 0.2 (optimal accrding to fieldtrip documentation).
Returns:
np.array: [description]
"""
# create smoothing kernel
pad = int(round(boxcar * sfreq))
# make sure that kernel has an odd number of samples
if pad % 2 == 0:
pad += 1
kernel = np.ones(pad) / pad
# padding and smoothing functions expect 2-d input (nr_elec X nr_time)
pad_length = int(ceil(pad / 2))
for i, x in enumerate(X):
# pad the data
x = self.filt_pad(x, pad_length = pad_length)
# smooth the data
x_smooth = sp.signal.convolve2d(
x, kernel.reshape(1, kernel.shape[0]), 'same')
X[i] = x_smooth[:, pad_length:(x_smooth.shape[1] - pad_length)]
return X
def z_score_data(self, X: np.array, z_thresh: int = 4, mask: np.array = None, filter_z: tuple = (False, 512)) -> Tuple[np.array, np.array, float]:
"""
Z scores input data over the second dimension (i.e., electrodes). The z threshold, which is used to mark artefact segments,
is then calculated using a data driven approach, where the upper limit of the 'bandwith' of obtained z scores is added
to the provided default threshold. Also returns z scored data per electrode which can be used during iterative automatic cleaning
procedure.
Args:
X (np.array): 3-dimensional array of [trial repeats by electrodes by time points].
z_thresh (int, optional): starting z value cut off. Defaults to 4.
mask (np.array, optional): a boolean array that masks out time points such that they are excluded during z scoring. Note these datapoints are
still returned in Z_n and elecs_z (see below).
filter_z (tuple, optional): prevents false-positive transient peaks by low-pass filtering
the resulting z-score time series at 4 Hz. Note: Should never be used without filter padding the data.
Second argument in the tuple specifies the sampling frequency. Defaults to False, i.e., no filtering.
Returns:
Z_n (np.array): 2-dimensional array of normalized z scores across electrodes[trial repeats by time points].
elecs_z (np.array): 3-dimensional array of z scores data per sample [trial repeats by electrodes by time points].
z_thresh (float): z_score theshold used to mark segments of muscle artefacts
"""
# set params
nr_epoch, nr_elec, nr_time = X.shape
# get the data and z_score over electrodes
X = X.swapaxes(0,1).reshape(nr_elec,-1)
X_z = zscore(X, axis = 1)
if mask is not None:
mask = np.tile(mask, nr_epoch)
X_z[:, mask] = zscore(X[:,mask], axis = 1)
# reshape to get get epoched data in terms of z scores
elecs_z = X_z.reshape(nr_elec, nr_epoch,-1).swapaxes(0,1)
# normalize z_score
Z_n = X_z.sum(axis = 0)/sqrt(nr_elec)
if mask is not None:
Z_n[mask] = X_z[:,mask].sum(axis = 0)/sqrt(nr_elec)
if filter_z[0]:
Z_n = filter_data(Z_n, filter_z[1], None, 4, pad='reflect_limited')
# adjust threshold (data driven)
if mask is None:
mask = np.ones(Z_n.size, dtype = bool)
z_thresh += np.median(Z_n[mask]) + abs(Z_n[mask].min() - np.median(Z_n[mask]))
# transform back into epochs
Z_n = Z_n.reshape(nr_epoch, -1)
return Z_n, elecs_z, z_thresh
def mark_bads(self, Z: np.array, z_thresh: float, times: np.array) -> list:
"""
Marks which epochs contain samples that exceed the data driven z threshold (as set by z_score_data).
Outputs a list with marked epochs. Per marked epoch alongside the index, a slice of the artefact, the start and end point and the duration
of the artefact are saved
Args:
Z (np.array): 2-dimensional array of normalized z scores across electrodes [trial repeats by time points]
z_thresh (float): z_score theshold used to mark segments of muscle artefacts
times (np.array): sample time points
Returns:
noise_events (list): indices of marked epochs. Per epoch time information of each artefact is logged
[idx, (artefact slice, start_time, end_time, duration)]
"""
# start with empty list
noise_events = []
# loop over each epoch
for ep, x in enumerate(Z):
# mask noise samples
noise_mask = abs(x) > z_thresh
# get start and end point of continuous noise segments
starts = np.argwhere((~noise_mask[:-1] & noise_mask[1:]))
if noise_mask[0]:
starts = np.insert(starts, 0, 0)
ends = np.argwhere((noise_mask[:-1] & ~noise_mask[1:])) + 1
# update noise_events
if starts.size > 0:
starts = np.hstack(starts)
if ends.size == 0:
ends = np.array([times.size-1])
else:
ends = np.hstack(ends)
ep_noise = [ep] + [(slice(s, e), times[s],times[e], abs(times[e] - times[s])) for s,e in zip(starts, ends)]
noise_events.append(ep_noise)
return noise_events
def automatic_artifact_detection(self, z_thresh=4, band_pass=[110, 140], plot=True, inspect=True):
""" Detect artifacts> modification of FieldTrip's automatic artifact detection procedure
(https://www.fieldtriptoolbox.org/tutorial/automatic_artifact_rejection/).
Artifacts are detected in three steps:
1. Filtering the data within specified frequency range
2. Z-transforming the filtered data across channels and normalize it over channels
3. Threshold the accumulated z-score
Counter to fieldtrip the z_threshold is ajusted based on the noise level within the data
Note: all data included for filter padding is now taken into consideration to calculate z values
Afer running this function, Epochs contains information about epeochs marked as bad (self.marked_epochs)
Arguments:
Keyword Arguments:
z_thresh {float|int} -- Value that is added to difference between median
and min value of accumulated z-score to obtain z-threshold
band_pass {list} -- Low and High frequency cutoff for band_pass filter
plot {bool} -- If True save detection plots (overview of z scores across epochs,
raw signal of channel with highest z score, z distributions,
raw signal of all electrodes)
inspect {bool} -- If True gives the opportunity to overwrite selected components
"""
# select data for artifact rejection
sfreq = self.info['sfreq']
self_copy = self.copy()
self_copy.pick_types(eeg=True, exclude='bads')
#filter data and apply Hilbert
self_copy.filter(band_pass[0], band_pass[1], fir_design='firwin', pad='reflect_limited')
#self_copy.filter(band_pass[0], band_pass[1], method='iir', iir_params=dict(order=6, ftype='butter'))
self_copy.apply_hilbert(envelope=True)
# get the data and apply box smoothing
data = self_copy.get_data()
nr_epochs = data.shape[0]
for i in range(data.shape[0]):
data[i] = self.boxSmoothing(data[i])
# get the data and z_score over electrodes
data = data.swapaxes(0,1).reshape(data.shape[1],-1)
z_score = zscore(data, axis = 1) # check whether axis is correct!!!!!!!!!!!
# z score per electrode and time point (adjust number of electrodes)
elecs_z = z_score.reshape(nr_epochs, 64, -1)
# normalize z_score
z_score = z_score.sum(axis = 0)/sqrt(data.shape[0])
#z_score = filter_data(z_score, self.info['sfreq'], None, 4, pad='reflect_limited')
# adjust threshold (data driven)
z_thresh += np.median(z_score) + abs(z_score.min() - np.median(z_score))
# transform back into epochs
z_score = z_score.reshape(nr_epochs, -1)
# control for filter padding
if self.flt_pad > 0:
idx_ep = self.time_as_index([self.tmin + self.flt_pad, self.tmax - self.flt_pad])
z_score = z_score[:, slice(*idx_ep)]
elecs_z
# mark bad epochs
bad_epochs = []
noise_events = []
cnt = 0
for ep, X in enumerate(z_score):
# get start, endpoint and duration in ms per continuous artefact
noise_mask = X > z_thresh
starts = np.argwhere((~noise_mask[:-1] & noise_mask[1:]))
ends = np.argwhere((noise_mask[:-1] & ~noise_mask[1:])) + 1
ep_noise = [(slice(s[0], e[0]), self.times[s][0],self.times[e][0], abs(self.times[e][0] - self.times[s][0])) for s,e in zip(starts, ends)]
noise_events.append(ep_noise)
noise_smp = np.where(X > z_thresh)[0]
if noise_smp.size > 0:
bad_epochs.append(ep)
if inspect:
print('This interactive window selectively shows epochs marked as bad. You can overwrite automatic artifact detection by clicking on selected epochs')
bad_eegs = self[bad_epochs]
idx_bads = bad_eegs.selection
# display bad eegs with 50mV range
bad_eegs.plot(
n_epochs=5, n_channels=data.shape[1], scalings=dict(eeg = 50))
plt.show()
plt.close()
missing = np.array([list(idx_bads).index(idx) for idx in idx_bads if idx not in bad_eegs.selection],dtype = int)
logging.info('Manually ignored {} epochs out of {} automatically selected({}%)'.format(
missing.size, len(bad_epochs),100 * round(missing.size / float(len(bad_epochs)), 2)))
bad_epochs = np.delete(bad_epochs, missing)
if plot:
plt.figure(figsize=(10, 10))
with sns.axes_style('dark'):
plt.subplot(111, xlabel='samples', ylabel='z_value',
xlim=(0, z_score.size), ylim=(-20, 40))
plt.plot(np.arange(0, z_score.size), z_score.flatten(), color='b')
plt.plot(np.arange(0, z_score.size),
np.ma.masked_less(z_score.flatten(), z_thresh), color='r')
plt.axhline(z_thresh, color='r', ls='--')
plt.savefig(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(
self.sj), self.session], filename='automatic_artdetect.pdf'))
plt.close()
# drop bad epochs and save list of dropped epochs
self.drop_beh = bad_epochs
np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(
self.sj), self.session], filename='noise_epochs.txt'), bad_epochs)
print('{} epochs dropped ({}%)'.format(len(bad_epochs),
100 * round(len(bad_epochs) / float(len(self)), 2)))
logging.info('{} epochs dropped ({}%)'.format(
len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2)))
self.drop(np.array(bad_epochs), reason='art detection ecg')
logging.info('{} epochs left after artifact detection'.format(len(self)))
np.savetxt(self.FolderTracker(extension=['preprocessing', 'subject-{}'.format(self.sj), self.session], filename='automatic_artdetect.txt'),
['Artifact detection z threshold set to {}. \n{} epochs dropped ({}%)'.
format(round(z_thresh, 1), len(bad_epochs), 100 * round(len(bad_epochs) / float(len(self)), 2))], fmt='%.100s')
return z_thresh
if __name__ == '__main__':
print('Please run preprocessing via a project script')
| [
37811,
198,
38200,
2736,
48749,
1366,
198,
198,
41972,
416,
42761,
5719,
31451,
741,
64,
283,
319,
838,
12,
3070,
12,
4626,
13,
198,
15269,
357,
66,
8,
1853,
360,
85,
44,
13,
1439,
2489,
10395,
13,
198,
37811,
198,
198,
11748,
285,
... | 2.192681 | 29,157 |
import FWCore.ParameterSet.Config as cms
process = cms.Process("FedCablingBuilder")
process.MessageLogger = cms.Service("MessageLogger",
debugModules = cms.untracked.vstring(''),
cablingBuilder = cms.untracked.PSet(
threshold = cms.untracked.string('INFO')
),
destinations = cms.untracked.vstring('cablingBuilder.log')
)
process.source = cms.Source("EmptySource",
numberEventsInRun = cms.untracked.uint32(1),
firstRun = cms.untracked.uint32(1)
)
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(1)
)
process.load("CalibTracker.SiStripESProducers.SiStripFedCablingFakeESSource_cfi")
process.PoolDBOutputService = cms.Service("PoolDBOutputService",
BlobStreamerName = cms.untracked.string('TBufferBlobStreamingService'),
DBParameters = cms.PSet(
messageLevel = cms.untracked.int32(2),
authenticationPath = cms.untracked.string('/afs/cern.ch/cms/DB/conddb')
),
timetype = cms.untracked.string('runnumber'),
connect = cms.string('sqlite_file:dummy2.db'),
toPut = cms.VPSet(cms.PSet(
record = cms.string('SiStripFedCablingRcd'),
tag = cms.string('SiStripFedCabling_30X')
))
)
process.load("Configuration.StandardSequences.Geometry_cff")
process.TrackerDigiGeometryESModule.applyAlignment = False
process.SiStripConnectivity = cms.ESProducer("SiStripConnectivity")
process.SiStripRegionConnectivity = cms.ESProducer("SiStripRegionConnectivity",
EtaDivisions = cms.untracked.uint32(20),
PhiDivisions = cms.untracked.uint32(20),
EtaMax = cms.untracked.double(2.5)
)
process.fedcablingbuilder = cms.EDAnalyzer("SiStripFedCablingBuilder",
PrintFecCabling = cms.untracked.bool(True),
PrintDetCabling = cms.untracked.bool(True),
PrintRegionCabling = cms.untracked.bool(True)
)
process.p1 = cms.Path(process.fedcablingbuilder)
| [
11748,
48849,
14055,
13,
36301,
7248,
13,
16934,
355,
269,
907,
198,
198,
14681,
796,
269,
907,
13,
18709,
7203,
42268,
34,
11716,
32875,
4943,
198,
198,
14681,
13,
12837,
11187,
1362,
796,
269,
907,
13,
16177,
7203,
12837,
11187,
1362,... | 2.085189 | 1,033 |
import os
import mobase
from ..basic_features import BasicGameSaveGameInfo
from ..basic_game import BasicGame
| [
11748,
28686,
201,
198,
201,
198,
11748,
7251,
589,
201,
198,
201,
198,
6738,
11485,
35487,
62,
40890,
1330,
14392,
8777,
16928,
8777,
12360,
201,
198,
6738,
11485,
35487,
62,
6057,
1330,
14392,
8777,
201,
198,
201,
198
] | 3.157895 | 38 |
#! /usr/bin/python
# -*- coding: utf-8 -*-
# Simple Python OpenSCAD Code Generator
# Copyright (C) 2009 Philipp Tiefenbacher <wizards23@gmail.com>
# Amendments & additions, (C) 2011 Evan Jones <evan_t_jones@mac.com>
#
# License: LGPL 2.1 or later
#
import os, sys, re
import inspect
openscad_builtins = [
# 2D primitives
{'name': 'polygon', 'args': ['points', 'paths'], 'kwargs': []} ,
{'name': 'circle', 'args': [], 'kwargs': ['r', 'segments']} ,
{'name': 'square', 'args': [], 'kwargs': ['size', 'center']} ,
# 3D primitives
{'name': 'sphere', 'args': [], 'kwargs': ['r', 'segments']} ,
{'name': 'cube', 'args': [], 'kwargs': ['size', 'center']} ,
{'name': 'cylinder', 'args': [], 'kwargs': ['r','h','r1', 'r2', 'center', 'segments']} ,
{'name': 'polyhedron', 'args': ['points', 'triangles' ], 'kwargs': ['convexity']} ,
# Boolean operations
{'name': 'union', 'args': [], 'kwargs': []} ,
{'name': 'intersection', 'args': [], 'kwargs': []} ,
{'name': 'difference', 'args': [], 'kwargs': []} ,
# Transforms
{'name': 'translate', 'args': [], 'kwargs': ['v']} ,
{'name': 'scale', 'args': [], 'kwargs': ['v']} ,
{'name': 'rotate', 'args': [], 'kwargs': ['a', 'v']} ,
{'name': 'mirror', 'args': ['v'], 'kwargs': []},
{'name': 'multmatrix', 'args': ['m'], 'kwargs': []},
{'name': 'color', 'args': ['c'], 'kwargs': []},
{'name': 'minkowski', 'args': [], 'kwargs': []},
{'name': 'hull', 'args': [], 'kwargs': []},
{'name': 'render', 'args': [], 'kwargs': ['convexity']},
# 2D to 3D transitions
{'name': 'linear_extrude', 'args': [], 'kwargs': ['height', 'center', 'convexity', 'twist','slices']} ,
{'name': 'rotate_extrude', 'args': [], 'kwargs': ['convexity']} ,
{'name': 'dxf_linear_extrude', 'args': ['file'], 'kwargs': ['layer', 'height', 'center', 'convexity', 'twist', 'slices']} ,
{'name': 'projection', 'args': [], 'kwargs': ['cut']} ,
{'name': 'surface', 'args': ['file'], 'kwargs': ['center','convexity']} ,
# Import/export
{'name': 'import_stl', 'args': ['filename'], 'kwargs': ['convexity']} ,
# Modifiers; These are implemented by calling e.g.
# obj.set_modifier( '*') or
# obj.set_modifier('disable')
# on an existing object.
# {'name': 'background', 'args': [], 'kwargs': []}, # %{}
# {'name': 'debug', 'args': [], 'kwargs': []} , # #{}
# {'name': 'root', 'args': [], 'kwargs': []} , # !{}
# {'name': 'disable', 'args': [], 'kwargs': []} , # *{}
{'name': 'intersection_for', 'args': ['n'], 'kwargs': []} , # e.g.: intersection_for( n=[1..6]){}
# Unneeded
{'name': 'assign', 'args': [], 'kwargs': []} # Not really needed for Python. Also needs a **args argument so it accepts anything
]
# Some functions need custom code in them; put that code here
builtin_literals = {
'polygon': '''class polygon( openscad_object):
def __init__( self, points, paths=None):
if not paths:
paths = [ range( len( points))]
openscad_object.__init__( self, 'polygon', {'points':points, 'paths': paths})
'''
}
# ===============
# = Including OpenSCAD code =
# ===============
# use() & include() mimic OpenSCAD's use/include mechanics.
# -- use() makes methods in scad_file_path.scad available to
# be called.
# --include() makes those methods available AND executes all code in
# scad_file_path.scad, which may have side effects.
# Unless you have a specific need, call use().
def use( scad_file_path, use_not_include=True):
'''
TODO: doctest needed
'''
# Opens scad_file_path, parses it for all usable calls,
# and adds them to caller's namespace
try:
module = open( scad_file_path)
contents = module.read()
module.close()
except Exception, e:
raise Exception( "Failed to import SCAD module '%(scad_file_path)s' with error: %(e)s "%vars())
# Once we have a list of all callables and arguments, dynamically
# add openscad_object subclasses for all callables to the calling module's
# namespace.
symbols_dicts = extract_callable_signatures( scad_file_path)
for sd in symbols_dicts:
class_str = new_openscad_class_str( sd['name'], sd['args'], sd['kwargs'], scad_file_path, use_not_include)
exec class_str in calling_module().__dict__
return True
# =========================================
# = Rendering Python code to OpenSCAD code=
# =========================================
# =========================
# = Internal Utilities =
# =========================
class included_openscad_object( openscad_object):
'''
Identical to openscad_object, but each subclass of included_openscad_object
represents imported scad code, so each instance needs to store the path
to the scad file it's included from.
'''
def calling_module():
'''
Returns the module *2* back in the frame stack. That means:
code in module A calls code in module B, which asks calling_module()
for module A.
Got that?
'''
frm = inspect.stack()[2]
calling_mod = inspect.getmodule( frm[0])
return calling_mod
# ===========
# = Parsing =
# ===========
def parse_scad_callables( scad_code_str):
""">>> test_str = '''module hex (width=10, height=10,
... flats= true, center=false){}
... function righty (angle=90) = 1;
... function lefty( avar) = 2;
... module more( a=[something, other]) {}
... module pyramid(side=10, height=-1, square=false, centerHorizontal=true, centerVertical=false){}
... module no_comments( arg=10, //test comment
... other_arg=2, /* some extra comments
... on empty lines */
... last_arg=4){}
... module float_arg( arg=1.0){}
... '''
>>> parse_scad_callables( test_str)
[{'args': [], 'name': 'hex', 'kwargs': ['width', 'height', 'flats', 'center']}, {'args': [], 'name': 'righty', 'kwargs': ['angle']}, {'args': ['avar'], 'name': 'lefty', 'kwargs': []}, {'args': [], 'name': 'more', 'kwargs': ['a']}, {'args': [], 'name': 'pyramid', 'kwargs': ['side', 'height', 'square', 'centerHorizontal', 'centerVertical']}, {'args': [], 'name': 'no_comments', 'kwargs': ['arg', 'other_arg', 'last_arg']}, {'args': [], 'name': 'float_arg', 'kwargs': ['arg']}]
>>> """
callables = []
# Note that this isn't comprehensive; tuples or nested data structures in
# a module definition will defeat it.
# Current implementation would throw an error if you tried to call a(x, y)
# since Python would expect a( x); OpenSCAD itself ignores extra arguments,
# but that's not really preferable behavior
# TODO: write a pyparsing grammar for OpenSCAD, or, even better, use the yacc parse grammar
# used by the language itself. -ETJ 06 Feb 2011
no_comments_re = r'(?mxs)(//.*?\n|/\*.*?\*/)'
# Also note: this accepts: 'module x(arg) =' and 'function y(arg) {', both of which are incorrect syntax
mod_re = r'(?mxs)^\s*(?:module|function)\s+(?P<callable_name>\w+)\s*\((?P<all_args>.*?)\)\s*(?:{|=)'
# This is brittle. To get a generally applicable expression for all arguments,
# we'd need a real parser to handle nested-list default args or parenthesized statements.
# For the moment, assume a maximum of one square-bracket-delimited list
args_re = r'(?mxs)(?P<arg_name>\w+)(?:\s*=\s*(?P<default_val>[\w.-]+|\[.*\]))?(?:,|$)'
# remove all comments from SCAD code
scad_code_str = re.sub(no_comments_re,'', scad_code_str)
# get all SCAD callables
mod_matches = re.finditer( mod_re, scad_code_str)
for m in mod_matches:
callable_name = m.group('callable_name')
args = []
kwargs = []
all_args = m.group('all_args')
if all_args:
arg_matches = re.finditer( args_re, all_args)
for am in arg_matches:
arg_name = am.group('arg_name')
if am.group('default_val'):
kwargs.append( arg_name)
else:
args.append( arg_name)
callables.append( { 'name':callable_name, 'args': args, 'kwargs':kwargs})
return callables
# Dynamically add all builtins to this namespace on import
for sym_dict in openscad_builtins:
# entries in 'builtin_literals' override the entries in 'openscad_builtins'
if sym_dict['name'] in builtin_literals:
class_str = builtin_literals[ sym_dict['name']]
else:
class_str = new_openscad_class_str( sym_dict['name'], sym_dict['args'], sym_dict['kwargs'])
exec class_str
| [
2,
0,
1220,
14629,
14,
8800,
14,
29412,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
2,
220,
220,
220,
17427,
11361,
4946,
6173,
2885,
6127,
35986,
198,
2,
220,
220,
220,
15069,
357,
34,
8,
3717,
220,... | 2.242505 | 4,136 |
from contextlib import contextmanager
import datetime
import unittest
import diagnose
from diagnose import probes
diagnose.manager.instrument_classes.setdefault(
"test", diagnose.instruments.ProbeTestInstrument
)
| [
6738,
4732,
8019,
1330,
4732,
37153,
198,
11748,
4818,
8079,
198,
11748,
555,
715,
395,
198,
198,
11748,
37489,
198,
6738,
37489,
1330,
33124,
198,
198,
47356,
577,
13,
37153,
13,
259,
43872,
62,
37724,
13,
2617,
12286,
7,
198,
220,
2... | 3.666667 | 60 |
from django.conf.urls import url, include
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns = [
url(r'^blog/', include('blogtools.tests.test_blog.urls', app_name='blogtools', namespace='test_blog')),
]
| [
6738,
42625,
14208,
13,
10414,
13,
6371,
82,
1330,
19016,
11,
2291,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
12708,
16624,
13,
6371,
82,
1330,
9037,
16624,
62,
6371,
33279,
82,
198,
198,
6371,
33279,
82,
796,
685,
198,
220,
220,
... | 2.890244 | 82 |
# Generated by Django 2.0 on 2019-12-09 08:54
from django.db import migrations
| [
2,
2980,
515,
416,
37770,
362,
13,
15,
319,
13130,
12,
1065,
12,
2931,
8487,
25,
4051,
198,
198,
6738,
42625,
14208,
13,
9945,
1330,
15720,
602,
628
] | 2.892857 | 28 |
import numpy as np
from sklearn.metrics import fbeta_score
from keras import backend as K
def FScore2(y_true, y_pred):
'''
The F score, beta=2
'''
B2 = K.variable(4)
OnePlusB2 = K.variable(5)
pred = K.round(y_pred)
tp = K.sum(K.cast(K.less(K.abs(pred - K.clip(y_true, .5, 1.)), 0.01), 'float32'), -1)
fp = K.sum(K.cast(K.greater(pred - y_true, 0.1), 'float32'), -1)
fn = K.sum(K.cast(K.less(pred - y_true, -0.1), 'float32'), -1)
f2 = OnePlusB2 * tp / (OnePlusB2 * tp + B2 * fn + fp)
return K.mean(f2)
| [
11748,
299,
32152,
355,
45941,
198,
198,
6738,
1341,
35720,
13,
4164,
10466,
1330,
277,
31361,
62,
26675,
198,
6738,
41927,
292,
1330,
30203,
355,
509,
198,
198,
4299,
376,
26595,
17,
7,
88,
62,
7942,
11,
331,
62,
28764,
2599,
198,
... | 2.018382 | 272 |
import json
from django.conf import settings
from rest_framework import status
from rest_framework.response import Response
from iiif_api_services.models.QueueModel import Queue
from iiif_api_services.models.ActivityModel import Activity
if settings.QUEUE_RUNNER=="THREAD":
from threading import Thread as Runner
else:
from multiprocessing import Process as Runner
| [
11748,
33918,
198,
6738,
42625,
14208,
13,
10414,
1330,
6460,
198,
6738,
1334,
62,
30604,
1330,
3722,
198,
6738,
1334,
62,
30604,
13,
26209,
1330,
18261,
198,
6738,
21065,
361,
62,
15042,
62,
30416,
13,
27530,
13,
34991,
17633,
1330,
46... | 3.373913 | 115 |
import stat
from os import stat as os_stat
from os.path import join, exists
from tempfile import TemporaryDirectory
import pytest
from jinja2 import UndefinedError, TemplateSyntaxError
from mlvtools.exception import MlVToolException
from mlvtools.helper import extract_type, to_dvc_meta_filename, to_instructions_list, \
write_python_script, write_template, to_sanitized_path
from mlvtools.helper import to_cmd_param, to_method_name, to_bash_variable, to_script_name, to_dvc_cmd_name
def test_should_convert_to_command_param():
"""
Test convert to command parameter
"""
assert to_cmd_param('my_param_One') == 'my-param-One'
def test_should_convert_to_bash_variable():
"""
Test convert to bash variable
"""
assert to_bash_variable('my-param-one') == 'MY_PARAM_ONE'
def test_should_convert_to_method_name():
"""
Test convert file name without extension to a python method name
"""
assert to_method_name('01my-Meth$odk++ Name.truc') == 'mlvtools_01my_meth_odk_name_truc'
def test_should_convert_to_script_name():
"""
Test convert file name to script name
"""
assert to_script_name('My notebook.ipynb') == 'mlvtools_my_notebook.py'
def test_should_convert_to_dvc_meta_filename():
"""
Test convert notebook path to dvc meta filename
"""
assert to_dvc_meta_filename('./toto/truc/My notebook.ipynb') == 'my_notebook.dvc'
def test_should_convert_to_instructions_list():
"""
Test convert a string of several instructions into a list of instructions
"""
assert to_instructions_list('\nimport os\na = 45\n') == ['import os', 'a = 45']
def test_should_extract_python_str_and_int():
"""
Test extract python str and int types
"""
type_info = extract_type('str ')
assert type_info.type_name == 'str'
assert not type_info.is_list
type_info = extract_type(' int')
assert type_info.type_name == 'int'
assert not type_info.is_list
def test_should_return_none_if_extract_python_of_no_type():
"""
Test extract python return None if empty type
"""
type_info = extract_type('')
assert not type_info.type_name
assert not type_info.is_list
type_info = extract_type(None)
assert not type_info.type_name
assert not type_info.is_list
def test_should_extract_python_list_type():
"""
Test extract python list type
"""
type_info = extract_type('list')
assert type_info.type_name == 'str'
assert type_info.is_list
type_info = extract_type('List')
assert type_info.type_name == 'str'
assert type_info.is_list
type_info = extract_type('list[str]')
assert type_info.type_name == 'str'
assert type_info.is_list
type_info = extract_type('List[int]')
assert type_info.type_name == 'int'
assert type_info.is_list
def test_should_convert_to_dvc_cmd_name():
"""
Test convert script name to dvc command name
"""
assert to_dvc_cmd_name('my_notebook.py') == 'my_notebook_dvc'
def test_should_sanitize_path():
"""
Test should add ./ to path if does not start wiht / or ./
"""
assert to_sanitized_path('toto.py') == './toto.py'
def test_sanitize_should_not_change_absolute_path():
"""
Test sanitize should not change absolute path
"""
absolute_path = '/absolut/path/toto.py'
assert to_sanitized_path(absolute_path) == absolute_path
def test_sanitize_should_not_change_path_starting_with_dot_slash():
"""
Test sanitize should not change path starting with dot slash
"""
path = './toto.py'
assert to_sanitized_path(path) == path
@pytest.fixture
def test_should_write_template(work_dir, valid_template_path):
"""
Test write an executable file from a given template and data
"""
output_path = join(work_dir, 'my_exe.sh')
write_template(output_path, valid_template_path, given_data='test')
assert exists(output_path)
assert stat.S_IMODE(os_stat(output_path).st_mode) == 0o755
with open(output_path, 'r') as fd:
assert fd.read() == 'a_value=test'
def test_should_create_directory_to_write_template(work_dir, valid_template_path):
"""
Test create directory and write template
"""
output_path = join(work_dir, 'a_dir', 'my_exe.sh')
write_template(output_path, valid_template_path, given_data='test')
assert exists(join(work_dir, 'a_dir'))
assert exists(output_path)
def test_write_template_should_raise_if_template_does_not_exist(work_dir):
"""
Test write_template raise an MlVToolException if the template file does not exist
"""
template_path = join(work_dir, 'not_existing_template.tpl')
check_write_template_error_case(template_path, data={}, exp_error=IOError)
def test_write_template_should_raise_if_template_format_error(work_dir):
"""
Test write_template raise an MlVToolException if the template is wrongly formatted
"""
template_data = 'a_value={{ t_data'
template_path = join(work_dir, 'template_wrong_format.tpl')
with open(template_path, 'w') as fd:
fd.write(template_data)
check_write_template_error_case(template_path, data={'t_data': 'test'}, exp_error=TemplateSyntaxError)
@pytest.mark.parametrize('missing_pattern', (('{{ printed_var }}',
'{% for val in iterated_var %}{% endfor %}',
'{{ accessed.var }}')))
def test_write_template_should_raise_if_missing_template_data(work_dir, missing_pattern):
"""
Test write_template raise an MlVToolException if there is an undefined template variable
Case of :
- print
- iteration
- other access
"""
template_data = f'a_value={missing_pattern}'
template_path = join(work_dir, 'template.tpl')
with open(template_path, 'w') as fd:
fd.write(template_data)
check_write_template_error_case(template_path, data={}, exp_error=UndefinedError)
def test_write_template_should_raise_if_can_not_write_executable_output(work_dir, mocker, valid_template_path):
"""
Test write_template raise an MlVToolException if the executable output cannot be written
"""
output_path = join(work_dir, 'output.sh')
mocker.patch('builtins.open', side_effect=IOError)
with pytest.raises(MlVToolException) as e:
write_template(output_path, valid_template_path, given_data='test')
assert isinstance(e.value.__cause__, IOError)
def test_should_write_formatted_python_script(work_dir):
"""
Test write formatted and executable python script
"""
script_content = 'my_var=4\nmy_list=[1,2,3]'
script_path = join(work_dir, 'test.py')
write_python_script(script_content, script_path)
assert exists(script_path)
assert stat.S_IMODE(os_stat(script_path).st_mode) == 0o755
with open(script_path, 'r') as fd:
assert fd.read() == 'my_var = 4\nmy_list = [1, 2, 3]\n'
def test_should_create_directory_to_write_formatted_python_script(work_dir):
"""
Test create directory and write formatted and executable python script
"""
script_content = 'my_var=4'
script_path = join(work_dir, 'a_dir', 'test.py')
write_python_script(script_content, script_path)
assert exists(join(work_dir, 'a_dir'))
assert exists(script_path)
def test_write_python_script_should_raise_if_cannot_write_executable_script(work_dir, mocker):
"""
Test write_python_script raise an MlVToolException if can not write executable output
"""
script_content = 'my_var=4\nmy_list=[1,2,3]'
script_path = join(work_dir, 'test.py')
mocker.patch('builtins.open', side_effect=IOError)
with pytest.raises(MlVToolException) as e:
write_python_script(script_content, script_path)
assert isinstance(e.value.__cause__, IOError)
def test_write_python_script_should_raise_if_python_syntax_error(work_dir):
"""
Test write_python_script raise an MlVToolException if python syntax error
"""
script_content = 'my_var :=: 4'
script_path = join(work_dir, 'test.py')
with pytest.raises(MlVToolException) as e:
write_python_script(script_content, script_path)
assert isinstance(e.value.__cause__, SyntaxError)
| [
11748,
1185,
198,
6738,
28686,
1330,
1185,
355,
28686,
62,
14269,
198,
6738,
28686,
13,
6978,
1330,
4654,
11,
7160,
198,
6738,
20218,
7753,
1330,
46042,
43055,
198,
198,
11748,
12972,
9288,
198,
6738,
474,
259,
6592,
17,
1330,
13794,
18... | 2.562136 | 3,259 |
import os
import json
import time
import datetime
import tablo
from lib import backgroundthread
from .util import logger
SAVE_VERSION = 1
INTERVAL_HOURS = 2
INTERVAL_TIMEDELTA = datetime.timedelta(hours=INTERVAL_HOURS)
PENDING_UPDATE = {}
| [
11748,
28686,
198,
11748,
33918,
198,
11748,
640,
198,
11748,
4818,
8079,
198,
198,
11748,
7400,
5439,
198,
198,
6738,
9195,
1330,
4469,
16663,
198,
6738,
764,
22602,
1330,
49706,
198,
198,
4090,
6089,
62,
43717,
796,
352,
198,
41358,
2... | 3 | 82 |
#!/usr/bin/env python
import argparse
import csv
from pyplot_helper import barchart
from matplotlib import pyplot
from palettable.colorbrewer.qualitative import Paired_12 as Colors
parser = argparse.ArgumentParser(description='Plot benchmark results.')
parser.add_argument('--inputs', type=str, required=True, nargs='+',
help='Input files')
parser.add_argument('--output', type=str,
help='Output file')
parser.add_argument('--delimiter', default='\t', type=str,
help='CSV delimiter')
parser.add_argument('--fontsize', default=20, type=int,
help='Font size')
parser.add_argument('--colorshift', default=1, type=int)
parser.add_argument('--parameters', type=str, nargs='+', required=True,
help='Parameters to evaluate')
parser.add_argument('--names', type=str, default=None, nargs="+",
help='Names')
parser.add_argument('--filter_load', type=str, default=None, nargs='+')
parser.add_argument('--filter_length', type=str, default=None, nargs='+')
parser.add_argument('--filter_number', type=str, default=None, nargs='+')
parser.add_argument('--filter_nesting', type=str, default=None, nargs='+')
parser.add_argument('--filter_sharing', type=str, default=None, nargs='+')
parser.add_argument('--absolute', action='store_true')
parser.add_argument('--stackfailed', action='store_true')
parser.add_argument('--failed', action='store_true')
args = parser.parse_args()
charts = dict()
i = 0
for param in args.parameters:
name = param
if args.names is not None:
name = args.names[i]
ylabel = ""
charts[param] = barchart.BarChart(ylabel=ylabel, xlabel=name,
title="",
width=1,
rotation=0,
colors=Colors.mpl_colors,
colorshift=args.colorshift,
xticksize=args.fontsize,
labelsize=args.fontsize,
legend_loc="upper right",
legend_cols=len(args.parameters)+1,
legend_anchor=(1,1.2),
legendsize=args.fontsize)
i += 1
fig, axes = pyplot.subplots(1, len(charts), figsize=(6*len(charts),5))
i = 0
for param in charts:
data = read_data(param)
for group in data:
values = list()
for cat in data[group]:
if args.absolute:
if args.stackfailed:
val = [data[group][cat]['failed'], data[group][cat]['good']]
elif args.failed:
val = data[group][cat]['failed']
else:
val = data[group][cat]['good']
else:
good = data[group][cat]['good']
total = data[group][cat]['total']
failed = data[group][cat]['failed']
if args.stackfailed:
val = [failed * 100 / total, good * 100 / total]
elif args.failed:
val = failed * 100 / total
else:
val = good * 100 / total
values.append((cat, val))
charts[param].add_group_data(group, values)
if args.filter_load is not None:
for load in args.filter_load:
charts[param].add_category(load, load +"% Load")
else:
charts[param].add_category("60", "60% Load")
charts[param].add_category("80", "80% Load")
charts[param].add_category("90", "90% Load")
charts[param].add_category("95", "95% Load")
charts[param].add_category("98", "98% Load")
charts[param].add_category("99", "99% Load")
charts[param].add_category("100", "100% Load")
charts[param].plot(axes[i], stacked=False, sort=False)
i += 1
for ax in axes:
ax.set_yticks([20, 40, 60, 80, 100])
ax.set_yticklabels(list())
axes[0].set_yticklabels(["20%", "40%", "60%", "80%", "100%"], fontsize=args.fontsize)
pyplot.rcParams.update({'font.size': args.fontsize})
# output
if args.output is not None:
# fig.subplots_adjust(top=0.5, bottom=0.15)
pyplot.tight_layout(rect=(0, -0.05, 1, 0.95))
pyplot.savefig(args.output)
else:
pyplot.show()
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
11748,
1822,
29572,
198,
11748,
269,
21370,
198,
198,
6738,
12972,
29487,
62,
2978,
525,
1330,
275,
998,
433,
198,
6738,
2603,
29487,
8019,
1330,
12972,
29487,
198,
198,
6738,
6340,
3087... | 2.235071 | 1,842 |
# -*- coding: utf-8 -*- #
# Copyright 2019 Google LLC. 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.
"""API utilities for gcloud compute vpn-gateways commands."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from googlecloudsdk.api_lib.compute.operations import poller
from googlecloudsdk.api_lib.util import waiter
import six
class VpnGatewayHelper(object):
"""Helper for VPN gateway service in the Compute API."""
def __init__(self, holder):
"""Initializes the helper for VPN Gateway operations.
Args:
holder: Object representing the Compute API holder instance.
"""
self._compute_client = holder.client
self._resources = holder.resources
@property
@property
@property
def GetVpnGatewayForInsert(self, name, description, network,
vpn_interfaces_with_interconnect_attachments,
stack_type):
"""Returns the VpnGateway message for an insert request.
Args:
name: String representing the name of the VPN Gateway resource.
description: String representing the description for the VPN Gateway
resource.
network: String representing the network URL the VPN gateway resource
belongs to.
vpn_interfaces_with_interconnect_attachments: Dict representing pairs
interface id and interconnected attachment associated with vpn gateway on
this interface.
stack_type: Enum presenting the stack type of the vpn gateway resource.
Returns:
The VpnGateway message object that can be used in an insert request.
"""
if vpn_interfaces_with_interconnect_attachments is not None:
vpn_interfaces = []
for key, value in sorted(
vpn_interfaces_with_interconnect_attachments.items()):
vpn_interfaces.append(
self._messages.VpnGatewayVpnGatewayInterface(
id=int(key), interconnectAttachment=six.text_type(value)))
if stack_type is not None:
return self._messages.VpnGateway(
name=name,
description=description,
network=network,
vpnInterfaces=vpn_interfaces,
stackType=self._messages.VpnGateway.StackTypeValueValuesEnum(
stack_type))
else:
return self._messages.VpnGateway(
name=name,
description=description,
network=network,
vpnInterfaces=vpn_interfaces)
else:
if stack_type is not None:
return self._messages.VpnGateway(
name=name,
description=description,
network=network,
stackType=self._messages.VpnGateway.StackTypeValueValuesEnum(
stack_type))
else:
return self._messages.VpnGateway(
name=name, description=description, network=network)
def WaitForOperation(self, vpn_gateway_ref, operation_ref, wait_message):
"""Waits for the specified operation to complete and returns the target.
Args:
vpn_gateway_ref: The VPN Gateway reference object.
operation_ref: The operation reference object to wait for.
wait_message: String representing the wait message to display while the
operation is in progress.
Returns:
The resulting resource object after the operation completes.
"""
operation_poller = poller.Poller(self._service, vpn_gateway_ref)
return waiter.WaitFor(operation_poller, operation_ref, wait_message)
def Create(self, ref, vpn_gateway):
"""Sends an Insert request for a VPN Gateway and returns the operation.
Args:
ref: The VPN Gateway reference object.
vpn_gateway: The VPN Gateway message object to use in the insert request.
Returns:
The operation reference object for the insert request.
"""
request = self._messages.ComputeVpnGatewaysInsertRequest(
project=ref.project, region=ref.region, vpnGateway=vpn_gateway)
operation = self._service.Insert(request)
return self._resources.Parse(
operation.selfLink, collection='compute.regionOperations')
def Describe(self, ref):
"""Sends a Get request for a VPN Gateway and returns the resource.
Args:
ref: The VPN Gateway reference object.
Returns:
The VPN Gateway resource object.
"""
request = self._messages.ComputeVpnGatewaysGetRequest(
project=ref.project, region=ref.region, vpnGateway=ref.Name())
return self._service.Get(request)
def Delete(self, ref):
"""Sends a Delete request for a VPN Gateway and returns the operation.
Args:
ref: The VPN Gateway reference object.
Returns:
The operation reference object for the delete request.
"""
request = self._messages.ComputeVpnGatewaysDeleteRequest(
project=ref.project, region=ref.region, vpnGateway=ref.Name())
operation = self._service.Delete(request)
return self._resources.Parse(
operation.selfLink, collection='compute.regionOperations')
def List(self, project, filter_expr):
"""Yields a VPN Gateway resource from the list of VPN Gateways.
Sends an AggregatedList request to obtain the list of VPN Gateways and
yields the next VPN Gateway in this list.
Args:
project: String representing the project to use for the request.
filter_expr: The expression used to filter the results.
"""
next_page_token = None
while True:
request = self._messages.ComputeVpnGatewaysAggregatedListRequest(
project=project, filter=filter_expr, pageToken=next_page_token)
response = self._service.AggregatedList(request)
next_page_token = response.nextPageToken
for scoped_vpn_gateways in response.items.additionalProperties:
for vpn_gateway in scoped_vpn_gateways.value.vpnGateways:
yield vpn_gateway
if not next_page_token:
break
def SetLabels(self, ref, existing_label_fingerprint, new_labels):
"""Sends a SetLabels request for a VPN Gateway and returns the operation.
Args:
ref: The VPN Gateway reference object.
existing_label_fingerprint: The existing label fingerprint.
new_labels: List of new label key, value pairs.
Returns:
The operation reference object for the SetLabels request.
"""
set_labels_request = self._messages.RegionSetLabelsRequest(
labelFingerprint=existing_label_fingerprint, labels=new_labels)
request = self._messages.ComputeVpnGatewaysSetLabelsRequest(
project=ref.project,
region=ref.region,
resource=ref.Name(),
regionSetLabelsRequest=set_labels_request)
operation = self._service.SetLabels(request)
return self._resources.Parse(
operation.selfLink, collection='compute.regionOperations')
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
1303,
198,
2,
15069,
13130,
3012,
11419,
13,
1439,
6923,
33876,
13,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198... | 2.822624 | 2,599 |
import numpy as np
import pyamg
#the function must be called solve and take (A,b) as inputs
| [
198,
11748,
299,
32152,
355,
45941,
198,
11748,
12972,
321,
70,
198,
198,
2,
1169,
2163,
1276,
307,
1444,
8494,
290,
1011,
357,
32,
11,
65,
8,
355,
17311,
198
] | 3.133333 | 30 |
#!/usr/bin/env python
# coding=utf-8
"""
This is a script for downloading and converting the pascal voc 2012 dataset
and the berkely extended version.
# original PASCAL VOC 2012
# wget http://host.robots.ox.ac.uk/pascal/VOC/voc2012/VOCtrainval_11-May-2012.tar # 2 GB
# berkeley augmented Pascal VOC
# wget http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz # 1.3 GB
This can be run as an independent executable to download
the dataset or be imported by scripts used for larger experiments.
If you aren't sure run this to do a full download + conversion setup of the dataset:
./data_pascal_voc.py pascal_voc_setup
"""
from __future__ import division, print_function, unicode_literals
from sacred import Ingredient, Experiment
import sys
import numpy as np
from PIL import Image
from collections import defaultdict
import os
from keras.utils import get_file
# from tf_image_segmentation.recipes import datasets
from tf_image_segmentation.utils.tf_records import write_image_annotation_pairs_to_tfrecord
from tf_image_segmentation.utils import pascal_voc
import tarfile
# ============== Ingredient 2: dataset =======================
data_pascal_voc = Experiment("dataset")
@data_pascal_voc.config
@data_pascal_voc.capture
@data_pascal_voc.command
@data_pascal_voc.command
@data_pascal_voc.config
@data_pascal_voc.command
@data_pascal_voc.command
@data_pascal_voc.command
@data_pascal_voc.automain | [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
19617,
28,
40477,
12,
23,
198,
37811,
198,
1212,
318,
257,
4226,
329,
22023,
290,
23202,
262,
279,
27747,
12776,
2321,
27039,
198,
392,
262,
18157,
365,
306,
7083,
2196,
13,
628,
... | 3.096033 | 479 |
from django.db import models
| [
6738,
42625,
14208,
13,
9945,
1330,
4981,
198
] | 3.625 | 8 |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
def load_CHEMorPO(station, inputDir, CHEMorPO="CHEM", fromSource=True):
"""
Import the concentration file into a DataFrame
Parameters
----------
stationName: str, the name of the station
inputDir: str, the path of file
CHEMorPO: str, {"CHEM","PO"}
fromSource: bool, default True
whith CHEMorPO == "CHEM", chose if the CHEM file is from source or from
raw chemistry.
Output
------
df: a panda DataFrame
"""
if CHEMorPO == "CHEM":
if fromSource:
nameFile = "_ContributionsMass_positive.csv"
else:
nameFile = "CHEM_conc.csv"
elif CHEMorPO == "PO":
nameFile = "PO.csv"
else:
print("Error: CHEMorPO must be 'CHEM' or 'PO'")
return
df = pd.read_csv(inputDir+station+"/"+station+nameFile,
index_col="date", parse_dates=["date"])
df.name = station
return df
def setSourcesCategories(df):
"""
Return the DataFrame df with a renamed columns.
The renaming axes set the source's name to its category, i.e
Road traffic → Vehicular
VEH → Vehicular
Secondary bio → Secondary_bio
BB → Bio_burning
Biomass burning → Bio_burning
etc.
"""
possible_sources ={
"Vehicular": "Vehicular",
"VEH": "Vehicular",
"VEH ind": "Vehicular_ind",
"VEH dir": "Vehicular_dir",
"Oil/Vehicular": "Vehicular",
"Road traffic": "Vehicular",
"Bio. burning": "Bio_burning",
"Bio burning": "Bio_burning",
"BB": "Bio_burning",
"BB1": "Bio_burning1",
"BB2": "Bio_burning2",
"Sulfate-rich": "Sulfate_rich",
"Nitrate-rich": "Nitrate_rich",
"Sulfate rich": "Sulfate_rich",
"Nitrate rich": "Nitrate_rich",
"Secondaire": "Secondary_bio",
"Secondary bio": "Secondary_bio",
"Secondary biogenic": "Secondary_bio",
"Marine biogenic/HFO": "Marine_bio/HFO",
"Marine bio/HFO": "Marine_bio/HFO",
"Marin bio/HFO": "Marine_bio/HFO",
"Marine secondary": "Marine_bio",
"Marin secondaire": "Marine_bio",
"HFO": "HFO",
"Marin": "Marine",
"Sea/road salt": "Salt",
"Sea salt": "Salt",
"Aged sea salt": "Aged_salt",
"Aged seasalt": "Aged_salt",
"Primary bio": "Primary_bio",
"Primary biogenic": "Primary_bio",
"Biogenique": "Primary_bio",
"Biogenic": "Primary_bio",
"Mineral dust": "Dust",
"Resuspended dust": "Dust",
"Dust": "Dust",
"Dust (mineral)": "Dust",
"AOS/dust": "Dust",
"Industrial": "Industrial",
"Industry/vehicular": "Indus._veh.",
"Arcellor": "Industrial",
"Siderurgie": "Industrial",
"Débris végétaux": "Plant_debris",
"Chlorure": "Chloride",
"PM other": "Other"
}
return df.rename(columns=possible_sources)
| [
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
19798,
292,
355,
279,
67,
628,
198,
4299,
3440,
62,
3398,
3620,
273,
16402,
7,
17529,
11,
5128,
35277,
11,
5870,
3620,
273,
16402... | 2.096708 | 1,458 |
import datetime
import numpy as np
import pandas as pd
import pymc3 as pm
import scipy
import scipy.stats
from bb_utils.ids import BeesbookID
from bb_utils.meta import BeeMetaInfo
| [
11748,
4818,
8079,
198,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
19798,
292,
355,
279,
67,
198,
11748,
279,
4948,
66,
18,
355,
9114,
198,
11748,
629,
541,
88,
198,
11748,
629,
541,
88,
13,
34242,
198,
198,
6738,
275,
65,
62,
... | 2.904762 | 63 |
import spatialHeterogeneity as sh
import pickle as pk
import os
import matplotlib.pyplot as plt
hdf = '/Users/art/Documents/spatial-omics/spatialOmics.hdf5'
f = '/Users/art/Documents/spatial-omics/spatialOmics.pkl'
# so = SpatialOmics.form_h5py(f)
with open(f, 'rb') as f:
so = pk.load(f)
# with open(f, 'wb') as file:
# pk.dump(so, file)
so.h5py_file = hdf
so.spl_keys = list(so.X.keys())
spl = so.spl_keys[0]
sh.pl.spatial(so,spl, 'meta_id')
sh.pl.spatial(so,spl, 'meta_id', mode='mask')
fig, ax = plt.subplots()
sh.pl.spatial(so,spl, 'meta_id', mode='mask', ax=ax)
fig.show()
sh.pl.spatial(so,spl, 'EGFR')
sh.pl.spatial(so,spl, 'EGFR', mode='mask')
sh.pl.spatial(so,spl, 'meta_id', edges=True)
sh.pl.spatial(so,spl, 'meta_id', mode='mask', edges=True)
# %%
sh.pl.napari_viewer(so, spl, ['DNA2', 'EGFR', 'H3'], add_masks='cellmask')
#%%
import numpy as np
import napari
from skimage import data
viewer = napari.view_image(data.astronaut(), rgb=True)
img = [so.images[spl][i,...] for i in [8,39]]
a0 = np.stack(img, axis=0)
a2 = np.stack(img, axis=2)
img = so.images[spl][[8,39]]
mask = so.masks[spl]['cellmask']
viewer = napari.view_image(img[0,], name='adsf')
labels_layer = viewer.add_labels(mask, name='assd')
viewer = napari.Viewer()
viewer.add_image(img, channel_axis=0, name=['Ich', 'Du'])
labels_layer = viewer.add_labels(mask, name='assd')
with napari.gui_qt():
viewer = napari.Viewer()
viewer.add_image(data.astronaut())
| [
11748,
21739,
39,
2357,
37477,
355,
427,
198,
11748,
2298,
293,
355,
279,
74,
198,
11748,
28686,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
198,
71,
7568,
796,
31051,
14490,
14,
433,
14,
38354,
14,
2777,
34961,... | 2.238897 | 653 |
import importA
my_drive = importA.HasConstants(importA.HasConstants.DRIVE)
| [
11748,
1330,
32,
198,
198,
1820,
62,
19472,
796,
1330,
32,
13,
19242,
34184,
1187,
7,
11748,
32,
13,
19242,
34184,
1187,
13,
7707,
9306,
8,
198
] | 2.814815 | 27 |
# Copyright 2007-2009 by Peter Cock. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
import os
import unittest
from Bio import SeqIO
from Bio.Alphabet import single_letter_alphabet
from Bio.Seq import Seq, MutableSeq
from Bio.SeqRecord import SeqRecord
from Bio.SeqUtils import GC, seq1, seq3, GC_skew
from Bio.SeqUtils.lcc import lcc_simp, lcc_mult
from Bio.SeqUtils.CheckSum import crc32, crc64, gcg, seguid
from Bio.SeqUtils.CodonUsage import CodonAdaptationIndex
if __name__ == "__main__":
runner = unittest.TextTestRunner(verbosity=2)
unittest.main(testRunner=runner)
| [
2,
15069,
4343,
12,
10531,
416,
5613,
23769,
13,
220,
1439,
2489,
10395,
13,
198,
2,
770,
2438,
318,
636,
286,
262,
8436,
404,
7535,
6082,
290,
21825,
416,
663,
198,
2,
5964,
13,
220,
4222,
766,
262,
38559,
24290,
2393,
326,
815,
... | 2.959514 | 247 |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from context import bbfsa
#read csv file
spectra = pd.read_csv('./tests/workflow/input/700cow.csv', delimiter=',', names= ['wn', 'ab'])
# cristallinity index
s = bbfsa.slice(spectra,700,400) #slice for baseline
b = bbfsa.baseline(s) #baseline
s2 = bbfsa.slice(b,620,530) #slice for peak picking
pp = bbfsa.peakpickMin (s2) #needs test if 2 values
pn = bbfsa.peakpickMin (s2) #needs test if 1 value
#nearest peak
NV = pp['ab'].where (pp['a'].abs(500)==min(pp['a'].abs(500)))
print (NV)
plotmeX = s2.wn
plotmeY = s2.ab
plt.plot(plotmeX, plotmeY)
plt.plot(pp.wn, pp.ab,'ro')
plt.xlim(max(plotmeX)+100, min(plotmeX)-100)
plt.ylim(min(plotmeY), max(plotmeY)+0.1)
#plt.show()
| [
11748,
299,
32152,
355,
45941,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
11748,
19798,
292,
355,
279,
67,
198,
198,
6738,
4732,
1330,
275,
65,
9501,
64,
198,
198,
2,
961,
269,
21370,
2393,
198,
4443,
430,
79... | 2.217009 | 341 |
from typing import Callable, Optional, Union
from dataclasses import dataclass
import hashlib
import hodgepodge.types
from hodgepodge.serialization import Serializable
DEFAULT_FILE_IO_BLOCK_SIZE = 8192
MD5 = 'md5'
SHA1 = 'sha1'
SHA256 = 'sha256'
SHA512 = 'sha512'
HASH_ALGORITHMS = [MD5, SHA1, SHA256, SHA512]
@dataclass(frozen=True)
@dataclass(frozen=True)
| [
6738,
19720,
1330,
4889,
540,
11,
32233,
11,
4479,
198,
6738,
4818,
330,
28958,
1330,
4818,
330,
31172,
198,
198,
11748,
12234,
8019,
198,
11748,
289,
9728,
79,
9728,
13,
19199,
198,
6738,
289,
9728,
79,
9728,
13,
46911,
1634,
1330,
2... | 2.57931 | 145 |
#!/usr/bin/env python3
# Web client, html parsing
import aiohttp
from lxml import html
from bs4 import BeautifulSoup as BS
# Web driver, browser/network interaction
from seleniumwire import webdriver
from selenium.webdriver.firefox.options import Options
# Downloading, compressing images
from PIL import Image
import numpy as np
from numpy import asarray
import blosc
#PYMONGO
import asyncio
import gzip
import os
import re
from random import randint
from subprocess import run
import time
class Main:
"""
Source property data from trulia real estate.
Main.dispatch() controls the execution of tasks at a high level.
functions called through dispatch() will comprise of multiple enclosures to optimize refactorability.
"""
base_url = "https://www.trulia.com/" # Gather grab cookies and headers for requests
sitemap = "https://www.trulia.com/sitemaps/xml/p/index.xml" #XML list of gz compressed urls for all properties.
urls = [] # Empty placeholder for urls
image_requests = [] # Placeholder for urls to static images
pages_visited = 0 # Placeholder. Every 50 pages visited call switch proxy
sleep_time = randint(1,5) # Randomized sleep/wait. Increase range for slower but sneakier crawl.
proxy_wait_time = randint(3,5) # Give expressvpn time to connect to a different relay.
async def fetch_urls(self, session, gzip_url) -> list:
"""
Fetch listings wrapper.
Uses nested functions as there is room to implement more control flows in pipeline.
For example extracting urls from rental-properties sitemap.
"""
async def load_in_urls(filename) -> dict:
"""
Read streamed gzip files from local dir.
Cannot be done on the fly.
Yield a dict {filename: lines}
"""
with gzip.open(filename, 'rb') as f:
xml_content = f.readlines()
await self.parse_xml(str(xml_content))
print(f"{len(self.urls)} urls extracted. \n {self.urls}")
async def prep_fetch() -> str:
"""
Get urls to listings.
Stream gzip compressed files and write to local dir.
"""
async with session.get(gzip_url) as resp:
chunk_size = 10 # Set chunk for streaming
# Name files based on url basename
filename = "./urls/" + str(os.path.basename(gzip_url)) # .strip(".gz"))
print(filename) # Debug
with open(filename, 'wb') as fd: # Save in urls dir
while True: #Stream to files
chunk = await resp.content.read(chunk_size)
if not chunk:
break
fd.write(chunk) # Write
print(f"File {filename} has been saved to urls/")
await load_in_urls(filename) # Call helper to extract/load urls
await prep_fetch()
async def extract_listing(self, session, listing_url) -> dict:
"""
Extract data from listings.
"""
# Track pages visted and switch proxies/vpn relay every 50 pages.
self.pages_visited += 1
if self.pages_visited % 50 == 0:
switch_proxy() # Blocking call to prevent dns leak during rotation.
def switch_proxy(): #NOTE: Blocking call all requests will halt until new relay connection.
"""
For dev testing purposes. This function will be refactored as a script imported via docker-compose.
Run vpn_routing.sh to interact with expressvpn CLI.
All outbound requests will pause during this transition.
"""
# Vpn aliases
vpn_aliases = ["hk2", "usny","uswd", "usse", "usda2", "usda", "usla", "ussf",
"sgju","in","cato","camo","defr1","ukdo","uklo","nlam","nlam2",
"esba","mx","ch2","frpa1","itmi"]
# Randomize rotation.
random_alias = dict(enumerate(vpn_aliases))[randint(0, int(len(vpn_aliases)))]
# Run the vpn_routing script pass in the alias
run(["./vpn_routing.sh", f"{random_alias}"])
time.sleep(self.proxy_wait_time) # Give expressvpn time to connect
async def interceptor() -> list:
"""
Intercepts and modifies requests on the fly.
View network requests for api data and static imageset urls.
Return a list of request urls' to thumbnail imagesets of listing.
"""
# Concatenate this str to url to view modal lightbox triggering imageset of thumbnails to load (Fetched from graphql api).
modal_box = "?mid=0#lil-mediaTab" # Replace '-mediaTab' for different requests/data ie '-crime' returns requests to api for crime stats/rate.
async with driver.get(str(listing_url) + str(modal_box)) as response: # Load modal and imageset requests with 'response'
_requests = await response.requests # List of requests. Parse for imagset urls.
requests = re.find_all(_requests, ("/pictures/thumbs_5/zillowstatic")) # Parse list of network connections for thumbnail image urls.
self.image_requests.append(requests)
async def download_images():
"""
Download images from trulia listings and insert into mongodb.
Note that the images are compressed bianries.
"""
async with session.get(image_request) as resp:
# Output of resp image will be binary, No need to compress again.
#TODO Use blosc to put binary into array for MongoClient insert.
_image = await resp
#compressed_image = Image.from #TODO
pass # TODO INSERT DATA
async def parse_html() -> dict:
"""
Provided html, parse for data points.
Need to use xpath as classnames are dynamically generated/change frequently.
"""
# xpaths to data points. These will most likely change which sucks.
temp_sale_tag = "/html/body/div[2]/div[2]/div/div[2]/div[1]/div/div/div[2]/div[1]/span/text()"
temp_address = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[1]/h1/span[1]/text()"
temp_state_zip = " /html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[1]/h1/span[2]/text()"
temp_price = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[2]/div/h3/div/text()"
temp_beds = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[2]/div/h3/div/text()"
temp_baths = " /html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[2]/div[1]/div/ul/li[2]/div/div/text()"
temp_sqft = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[1]/div/div/div[1]/div[2]/div[1]/div/ul/li[3]/div/div/text()"
temp_hoa_fee = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[4]/div[2]/div/div[4]/div/div/div[3]text()"
temp_heating = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[4]/div[2]/div/div[5]/div/div/div[3]/text()"
temp_cooling = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[4]/div[2]/div/div[6]/div/div/div[3]/text()"
temp_description = "/html/body/div[2]/div[2]/div/div[2]/div[2]/div[1]/div[1]/div[4]/div[2]/div/text()"
# Use lxml to parse xpath from soup.
tree = html.fromstring(html_content) # Create element tree.
sale_tag = tree.xpath(temp_sale_tag)
address = tree.xpath(temp_address)
state_zip = tree.xpath(temp_state_zip)
price = tree.xpath(temp_price)
beds = tree.xpath(temp_beds)
baths = tree.xpath(temp_baths)
sqft = tree.xpath(temp_sqft)
hoa_fee = tree.xpath(temp_hoa_fee)
heating = tree.xpath(temp_heating)
cooling = tree.xpath(temp_cooling)
description = tree.xpath(temp_descrption)
# Extract Listings
# Initiate webdriver.
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options,executable_path=r"geckodriver") # Make sure the driver is an exe. Intended to be run in linux vm.
# Get listing response
async with session.get(listing_url) as resp:
html_content = resp.text()
await asyncio.sleep(self.sleep_time) # Sleep a few second between every request. Be nice to the trulia graphql api backend!
await html_content
datapoints = await parse_html()
# Get listing images' urls with webdriver
imageset_requests = await interceptor() # Call interceptor. Aggregates all requests for property images.
images_task = [download_images() for image_url in imageset_requests]
get_images = await asyncio.gather(*images_task)
# Load into DB
async def parse_xml(self, xml_content) -> list:
"""Return a list of urls from sitemaps' xml content"""
urls = [] #Temp storage in mem
soup = BS(xml_content, "lxml") # Pass xml content and parser into soup
for url in soup.find_all('loc'):
urls.append(url.get_text())
self.urls = urls
assert len(self.urls) > 10 # We should have way more. Better end to end testing will be implemented in the store_data.py module. '
async def dispatch(self, loop) -> dict:
"""
Init ClientSession().
Dispatch urls to unzip/decompress.
Return dict of all datapoints including status of db insert:Bool.
"""
# headers
headers = ({'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36',
'Accept-Language': 'en-US, en;q=0.5'})
# Wrap method calls in ClientSession() context manager.
async with aiohttp.ClientSession(loop=loop) as session:
# Get xml page containg urls to active property sitemaps
async with session.get(self.sitemap) as resp:
xml_content = await resp.text()
await self.parse_xml(xml_content)
print(f"Collected {len(self.urls)} urls. \n {self.urls}")
assert len(self.urls) > 10
# Fetch Listing sitemaps. Extract/Read gzip urls to file
tasks = [self.fetch_urls(session, gzip_url) for gzip_url in self.urls]
results = asyncio.gather(*tasks)
await results
# Fetch Extracted listing urls & parse html
tasks = [self.extract_listing(session, listing_url, random_alias) for listing_url in self.urls]
results = asyncio.gather(*tasks)
await results
if __name__ == '__main__':
m = Main()
loop = asyncio.get_event_loop()
results = loop.run_until_complete(m.dispatch(loop))
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
198,
2,
5313,
5456,
11,
27711,
32096,
198,
11748,
257,
952,
4023,
198,
6738,
300,
19875,
1330,
27711,
198,
6738,
275,
82,
19,
1330,
23762,
50,
10486,
355,
24218,
198,
198,
2,
531... | 2.208804 | 5,043 |
import zmq
from getpass import getpass
if __name__ == '__main__':
main()
| [
11748,
1976,
76,
80,
198,
6738,
651,
6603,
1330,
651,
6603,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
220,
1388,
3419,
198
] | 2.6 | 30 |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Ke Sun (sunk@mail.ustc.edu.cn)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from yacs.config import CfgNode as CN
# high_resoluton_net related params for segmentation
HIGH_RESOLUTION_NET = CN()
HIGH_RESOLUTION_NET.PRETRAINED_LAYERS = ['*']
HIGH_RESOLUTION_NET.STEM_INPLANES = 64
HIGH_RESOLUTION_NET.FINAL_CONV_KERNEL = 1
HIGH_RESOLUTION_NET.WITH_HEAD = True
HIGH_RESOLUTION_NET.STAGE1 = CN()
HIGH_RESOLUTION_NET.STAGE1.NUM_MODULES = 1
HIGH_RESOLUTION_NET.STAGE1.NUM_BRANCHES = 1
HIGH_RESOLUTION_NET.STAGE1.NUM_BLOCKS = [4]
HIGH_RESOLUTION_NET.STAGE1.NUM_CHANNELS = [32]
HIGH_RESOLUTION_NET.STAGE1.BLOCK = 'BASIC'
HIGH_RESOLUTION_NET.STAGE1.FUSE_METHOD = 'SUM'
HIGH_RESOLUTION_NET.STAGE2 = CN()
HIGH_RESOLUTION_NET.STAGE2.NUM_MODULES = 1
HIGH_RESOLUTION_NET.STAGE2.NUM_BRANCHES = 2
HIGH_RESOLUTION_NET.STAGE2.NUM_BLOCKS = [4, 4]
HIGH_RESOLUTION_NET.STAGE2.NUM_CHANNELS = [32, 64]
HIGH_RESOLUTION_NET.STAGE2.BLOCK = 'BASIC'
HIGH_RESOLUTION_NET.STAGE2.FUSE_METHOD = 'SUM'
HIGH_RESOLUTION_NET.STAGE3 = CN()
HIGH_RESOLUTION_NET.STAGE3.NUM_MODULES = 1
HIGH_RESOLUTION_NET.STAGE3.NUM_BRANCHES = 3
HIGH_RESOLUTION_NET.STAGE3.NUM_BLOCKS = [4, 4, 4]
HIGH_RESOLUTION_NET.STAGE3.NUM_CHANNELS = [32, 64, 128]
HIGH_RESOLUTION_NET.STAGE3.BLOCK = 'BASIC'
HIGH_RESOLUTION_NET.STAGE3.FUSE_METHOD = 'SUM'
HIGH_RESOLUTION_NET.STAGE4 = CN()
HIGH_RESOLUTION_NET.STAGE4.NUM_MODULES = 1
HIGH_RESOLUTION_NET.STAGE4.NUM_BRANCHES = 4
HIGH_RESOLUTION_NET.STAGE4.NUM_BLOCKS = [4, 4, 4, 4]
HIGH_RESOLUTION_NET.STAGE4.NUM_CHANNELS = [32, 64, 128, 256]
HIGH_RESOLUTION_NET.STAGE4.BLOCK = 'BASIC'
HIGH_RESOLUTION_NET.STAGE4.FUSE_METHOD = 'SUM'
MODEL_EXTRAS = {
'seg_hrnet': HIGH_RESOLUTION_NET,
}
| [
2,
16529,
26171,
201,
198,
2,
15069,
357,
66,
8,
5413,
201,
198,
2,
49962,
739,
262,
17168,
13789,
13,
201,
198,
2,
22503,
416,
3873,
3825,
357,
82,
2954,
31,
4529,
13,
436,
66,
13,
15532,
13,
31522,
8,
201,
198,
2,
16529,
26171... | 2.256952 | 899 |
# coding=utf-8
"""Given the multifuture trajectory output, compute NLL"""
import argparse
import os
import pickle
import numpy as np
from tqdm import tqdm
parser = argparse.ArgumentParser()
parser.add_argument("gt_path")
parser.add_argument("prediction_file")
parser.add_argument("--scene_h", type=int, default=18)
parser.add_argument("--scene_w", type=int, default=32)
parser.add_argument("--video_h", type=int, default=1080)
parser.add_argument("--video_w", type=int, default=1920)
def softmax(x, axis=None):
"""Stable softmax."""
x = x - x.max(axis=axis, keepdims=True)
y = np.exp(x)
return y / y.sum(axis=axis, keepdims=True)
if __name__ == "__main__":
args = parser.parse_args()
args.w_gap = args.video_w*1.0/args.scene_w
args.h_gap = args.video_h*1.0/args.scene_h
with open(args.prediction_file, "rb") as f:
predictions = pickle.load(f) # traj_id -> [1, beam_size, T, h*W]
# T ~ [14, 25]
time_list = [0, 1, 2, 3, 4] # 5 frame, 2second and 10 frame 4 second length prediction
# NLL for each sample
nlls = {}
for timestep in time_list:
nlls["T=%d" % (timestep+1)] = []
for traj_id in tqdm(predictions):
camera = traj_id.split("_")[-1] # cam4 ...
gt_file = os.path.join(args.gt_path, "%s.p" % traj_id)
with open(gt_file, "rb") as f:
gt = pickle.load(f) # annotation_key -> x_agent_traj
# [1, beam_size, T, H*W] and beam_size of prob
beams, logprobs = predictions[traj_id]
# normalize the prob first
logprobs = softmax(np.squeeze(logprobs))
beams = softmax(np.squeeze(beams), axis=-1)
assert beams.shape[-1] == args.scene_h * args.scene_w
# time_list number of h*w
grid_probs = [get_hw_prob(beams, logprobs, t) for t in time_list]
for i, timestep in enumerate(time_list):
gt_xys = []
for future_id in gt:
if len(gt[future_id]["x_agent_traj"]) <= timestep:
continue
x, y = gt[future_id]["x_agent_traj"][timestep][2:]
gt_xys.append([x, y])
if not gt_xys:
continue
# a list of indices between 1 and h*w
gt_indexes = xys_to_indexes(np.asarray(gt_xys), args)
nll = compute_nll(grid_probs[i], gt_indexes)
nlls["T=%d" % (timestep+1)].append(nll)
print([len(nlls[k]) for k in nlls])
print("NLL:")
keys = sorted(nlls.keys())
print(" ".join(keys))
print(" ".join(["%s" % np.mean(nlls[k])
for k in keys]))
| [
2,
19617,
28,
40477,
12,
23,
198,
37811,
15056,
262,
43543,
1832,
22942,
5072,
11,
24061,
399,
3069,
37811,
198,
198,
11748,
1822,
29572,
198,
11748,
28686,
198,
11748,
2298,
293,
198,
11748,
299,
32152,
355,
45941,
198,
198,
6738,
256,... | 2.229493 | 1,085 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
vi $HOME/.LoginAccount.txt
[mailClient]
host = smtp.qq.com
port = 25
user = ***
pass = ***
fr = xxxxxx@qq.com
to = xxxxxx@gmail.com
debuglevel = True
login = False
starttls = False
'''
__all__ = ['get_smtp_client', 'sendmail']
import os, sys
from ConfigParser import ConfigParser
from ConfigParser import NoOptionError
from smtplib import SMTP
from smtplib import SMTPAuthenticationError
from email import Encoders
from email.base64MIME import encode as encode_base64
from email.MIMEBase import MIMEBase
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
if __name__ == '__main__':
from optparse import OptionParser
usage = '%prog [-e addr] [-a] args...'
parser = OptionParser(usage=usage)
parser.add_option('-e', '--addr', dest='addr',
help='receive email address', metavar='address')
parser.add_option('-a', '--atta', dest='atta',
action='store_true', default=False,
help='attachment flag')
(options, args) = parser.parse_args()
if not args:
parser.print_usage()
sys.exit(1)
fn(options, args)
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
7061,
6,
198,
8903,
720,
39069,
11757,
47790,
30116,
13,
14116,
198,
58,
4529,
11792,
60,
198,
4774,
796,
895,
3... | 2.49375 | 480 |
import re
import struct
from django import forms
from django.core.validators import RegexValidator
from django.db import models, connection
from django.utils import six
from django.utils.translation import ugettext_lazy as _
__all__ = ["HexadecimalField", "HexIntegerField"]
hex_re = re.compile(r"^[0-9A-f]+$")
postgres_engines = [
"django.db.backends.postgresql_psycopg2",
"django.contrib.gis.db.backends.postgis",
]
class HexadecimalField(forms.CharField):
"""
A form field that accepts only hexadecimal numbers
"""
class HexIntegerField(models.CharField):
"""
This field stores a hexadecimal *string* of up to 64 bits as an unsigned integer
on *all* backends including postgres.
Reasoning: Postgres only supports signed bigints. Since we don't care about
signedness, we store it as signed, and cast it to unsigned when we deal with
the actual value (with struct)
On sqlite and mysql, native unsigned bigint types are used. In all cases, the
value we deal with in python is always in hex.
"""
# def db_type(self, connection):
# engine = connection.settings_dict["ENGINE"]
# if "mysql" in engine:
# return "bigint unsigned"
# elif "sqlite" in engine:
# return "TEXT"
# else:
# return super(HexIntegerField, self).db_type(connection=connection)
| [
11748,
302,
198,
11748,
2878,
198,
6738,
42625,
14208,
1330,
5107,
198,
6738,
42625,
14208,
13,
7295,
13,
12102,
2024,
1330,
797,
25636,
47139,
1352,
198,
6738,
42625,
14208,
13,
9945,
1330,
4981,
11,
4637,
198,
6738,
42625,
14208,
13,
... | 2.779116 | 498 |
import os
import sys
input = sys.argv[1]
output = sys.argv[2]
f1 = open(input, 'r')
f2 = open('temp.txt', 'w')
start = 0
for line in f1:
start += 1
if start < 3:
f2.write(line)
continue
parts = line.split()
if float(parts[2]) > 1e-3:
f2.write(line)
f1.close()
f2.close()
command = 'cp temp.txt' + ' ' + output
print('command: ', command)
os.system(command)
os.system('rm -rf temp.txt')
| [
11748,
28686,
198,
11748,
25064,
198,
15414,
796,
25064,
13,
853,
85,
58,
16,
60,
198,
22915,
796,
25064,
13,
853,
85,
58,
17,
60,
198,
198,
69,
16,
796,
1280,
7,
15414,
11,
705,
81,
11537,
198,
69,
17,
796,
1280,
10786,
29510,
... | 2.161616 | 198 |
import jax.numpy as jnp
import jaxlib
from arraytainers import Jaxtainer
from main_tests.test_class import ArraytainerTests
| [
11748,
474,
897,
13,
77,
32152,
355,
474,
37659,
201,
198,
11748,
474,
897,
8019,
201,
198,
6738,
7177,
3153,
364,
1330,
13790,
742,
10613,
201,
198,
6738,
1388,
62,
41989,
13,
9288,
62,
4871,
1330,
15690,
3153,
263,
51,
3558,
201
] | 3.02381 | 42 |
# -*- coding: utf-8 -*-
# Function to evaluate Post Fix expression
#Calculation function for different opeartors
#Printing the Menu
print ""
print ""
print ""
print ""
menu = {}
menu['1']="What are infix postfix and prefix notations?"
menu['2']="Infix to Postfix Expression Conversion"
menu['3']="Evaluation of Postfix expression"
menu['4']="Exit"
while True:
options=menu.keys()
options.sort()
print""
print " MENU"
print"============================================="
for entry in options:
print entry, menu[entry]
print""
selection=raw_input("Please Select:")
print""
print ""
if selection =='1':
print "Infix notation : X + Y - Operators are written in-between their operands. "
print "Postfix notation : X Y + - Operators are written after their operands. "
print "Prefix notation : + X Y - Operators are written before their operands. "
print ""
print ""
elif selection == '2' :
print ""
print ""
print ""
print " Infix to Postfix Convertor"
print " ------------------------------------"
print " Enter your In-Fix expression to be converted "
infix = raw_input( " Example of In-Fix exprtession could be (2 + 3) - 7 / 9 :")
print " ----------------------------------------------------------"
postfix = infixtopostfix(infix)
print ""
print " Post Fix expression of ",infix, " is : "+' '.join(postfix) #to convert list into string
print ""
print ""
print ""
choice = raw_input(" Do you want to evaluate the value of your Post Fix expression (Y/N) : ")
if choice == 'Y' or 'y' :
result = evalPostfix(' '.join(postfix))
print " Value of Post Fix expression is :",result
print " ----------------------------------------------------------------------------"
print ""
print ""
else :
continue
elif selection == '3' :
print ""
print ""
print ""
print " Postfix Value Convertor"
print " ------------------------------------"
print " Enter your Post-Fix expression to be converted "
postfix = raw_input( " Example of Post-Fix exprtession could be 2 3 + 7 9 / - :")
print " ----------------------------------------------------------------------------"
result = evalPostfix(' '.join(postfix))
#print "Value of Post Fix expression ",postfix," is :"+' '.join(result)
print " Value of Post Fix expression is :",result
print " "
print ""
elif selection == '4':
break
else:
print "Unknown Option Selected!"
print "--------------------------"
print ""
print ""
print "" | [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
628,
198,
198,
2,
15553,
284,
13446,
2947,
13268,
5408,
198,
220,
220,
220,
220,
220,
220,
220,
220,
220,
198,
2,
9771,
14902,
2163,
329,
1180,
267,
431,
433,
669,
198,
2... | 2.315441 | 1,360 |
import argparse
import numpy as np
import os
import pandas as pd
import time
import torch
from data import (
eval_collate_fn,
EvalDataset,
TrainCollator,
TrainDataset,
)
from evaluate import predict, make_word_outputs_final
from transformers import (
AdamW,
AutoConfig,
AutoModelWithLMHead,
AutoTokenizer,
get_linear_schedule_with_warmup,
set_seed,
)
from torch.utils.data import DataLoader
parser = argparse.ArgumentParser()
parser.add_argument('--train-src', type=str, required=True)
parser.add_argument('--train-tgt', type=str, required=True)
parser.add_argument('--dev-src', type=str, required=True)
parser.add_argument('--dev-tgt', type=str, required=True)
parser.add_argument('--dev-hter', type=str)
parser.add_argument('--dev-tags', type=str)
parser.add_argument('--block-size', type=int, default=256)
parser.add_argument('--eval-block-size', type=int, default=512)
parser.add_argument('--wwm', action='store_true')
parser.add_argument('--mlm-probability', type=float, default=0.15)
parser.add_argument('--batch-size', type=int, default=16)
parser.add_argument('--update-cycle', type=int, default=8)
parser.add_argument('--eval-batch-size', type=int, default=8)
parser.add_argument('--train-steps', type=int, default=100000)
parser.add_argument('--eval-steps', type=int, default=1000)
parser.add_argument('--learning-rate', type=float, default=5e-5)
parser.add_argument('--pretrained-model-path', type=str, required=True)
parser.add_argument('--save-model-path', type=str, required=True)
parser.add_argument('--seed', type=int, default=42)
args = parser.parse_args()
print(args)
set_seed(args.seed)
device = torch.device('cuda')
torch.cuda.set_device(0)
config = AutoConfig.from_pretrained(args.pretrained_model_path, cache_dir=None)
tokenizer = AutoTokenizer.from_pretrained(args.pretrained_model_path, cache_dir=None, use_fast=False, do_lower_case=False)
model = AutoModelWithLMHead.from_pretrained(args.pretrained_model_path, config=config, cache_dir=None)
model.resize_token_embeddings(len(tokenizer))
model.to(device)
train_dataset = TrainDataset(
src_path=args.train_src,
tgt_path=args.train_tgt,
tokenizer=tokenizer,
block_size=args.block_size,
wwm=args.wwm,
)
train_dataloader = DataLoader(
dataset=train_dataset,
batch_size=args.batch_size,
shuffle=True,
collate_fn=TrainCollator(tokenizer=tokenizer, mlm_probability=args.mlm_probability),
)
dev_dataset = EvalDataset(
src_path=args.dev_src,
tgt_path=args.dev_tgt,
tokenizer=tokenizer,
block_size=args.eval_block_size,
wwm=args.wwm,
N=7,
M=1,
)
dev_dataloader = DataLoader(
dataset=dev_dataset,
batch_size=args.eval_batch_size,
shuffle=False,
collate_fn=eval_collate_fn,
)
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{
'params':
[p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
'weight_decay':
0.01
},
{
'params':
[p for n, p in param_optimizer if any(nd in n for nd in no_decay)],
'weight_decay':
0.0
}]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate)
lr_scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=args.train_steps)
dirs = ['checkpoint_best', 'checkpoint_last']
files_to_copy = ['config.json', 'tokenizer.json', 'tokenizer_config.json', 'vocab.txt']
for d in dirs:
os.system('mkdir -p %s' % os.path.join(args.save_model_path, d))
for f in files_to_copy:
os.system('cp %s %s' % (
os.path.join(args.pretrained_model_path, f),
os.path.join(args.save_model_path, d, f)
))
print('Configuration files copied')
total_minibatches = len(train_dataloader)
best_score = 0.0
num_steps = 1
model.train()
model.zero_grad()
epoch = 1
total_loss = 0.0
current_time = time.time()
while True:
for i, inputs in enumerate(train_dataloader):
n_minibatches = i + 1
output = model(
input_ids=inputs['input_ids'].to(device),
token_type_ids=inputs['token_type_ids'].to(device),
attention_mask=inputs['attention_mask'].to(device),
labels=inputs['labels'].to(device),
)
loss = output.loss / float(args.update_cycle)
total_loss += float(loss)
loss.backward()
if (n_minibatches == total_minibatches) or (n_minibatches % args.update_cycle == 0):
optimizer.step()
lr_scheduler.step()
model.zero_grad()
old_time = current_time
current_time = time.time()
print('epoch = %d, step = %d, loss = %.6f (%.3fs)' % (epoch, num_steps, total_loss, current_time - old_time))
if (num_steps == args.train_steps) or (num_steps % args.eval_steps == 0):
print('Evaluating...')
preds, preds_prob = predict(
eval_dataloader=dev_dataloader,
model=model,
device=device,
tokenizer=tokenizer,
N=7,
M=1,
mc_dropout=False,
)
eval_score = make_word_outputs_final(preds, args.dev_tgt, tokenizer, threshold_tune=args.dev_tags)[-1]
word_scores_prob = make_word_outputs_final(preds_prob, args.dev_tgt, tokenizer, threshold=0.5)[0]
sent_outputs = pd.Series([float(np.mean(w)) for w in word_scores_prob])
fhter = open(args.dev_hter, 'r', encoding='utf-8')
hter = pd.Series([float(x.strip()) for x in fhter])
fhter.close()
pearson = float(sent_outputs.corr(hter))
print('Pearson: %.6f' % pearson)
eval_score += pearson
print('Validation Score: %.6f, Previous Best Score: %.6f' % (eval_score, best_score))
if eval_score > best_score:
save_model(model, os.path.join(args.save_model_path, 'checkpoint_best/pytorch_model.bin'))
best_score = eval_score
save_model(model, os.path.join(args.save_model_path, 'checkpoint_last/pytorch_model.bin'))
if num_steps >= args.train_steps:
exit(0)
num_steps += 1
total_loss = 0.0
epoch += 1
| [
11748,
1822,
29572,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
28686,
198,
11748,
19798,
292,
355,
279,
67,
198,
11748,
640,
198,
11748,
28034,
198,
198,
6738,
1366,
1330,
357,
198,
220,
220,
220,
5418,
62,
26000,
378,
62,
22184,
... | 2.163896 | 3,008 |
import modules.open_file as of
# read in the file downloaded from the run archive, in this partcular case https://www.ncbi.nlm.nih.gov/Traces/study/?query_key=1&WebEnv=MCID_6178e8ee92f0234b8354c36f&o=acc_s%3Aa (may not be functional)
# SraRunTable.txt
# Contains Metadata for all samples
# check for each line if it contains "HMP_" -> that is the tissue
# Check is_affected or is_tumor for extra subcategories in later versions of this script (but initially ignore these)
# we select the first element from each line except the first line: the Run identifier
# we select the element HMP_ which represnets the category
# we ignore all lines that do not contain HMP_
# then we load teh file https://trace.ncbi.nlm.nih.gov/Traces/sra/?run= >>Run identifier here <<
# a basic frequency table is stored in the function "oTaxAnalysisData"
# From this function we collect "name" and "percent"
# This is stored as a file RunIdentifier.txt in the directory that carries the name of the category
#main
if __name__ == '__main__':
main()
| [
11748,
13103,
13,
9654,
62,
7753,
355,
286,
628,
198,
2,
1100,
287,
262,
2393,
15680,
422,
262,
1057,
15424,
11,
287,
428,
636,
10440,
1339,
3740,
1378,
2503,
13,
10782,
8482,
13,
21283,
76,
13,
37373,
13,
9567,
14,
2898,
2114,
14,
... | 3.243077 | 325 |
from jsonobject import JsonObject, StringProperty
from taxjar.data.iterable import TaxJarIterable
| [
6738,
33918,
15252,
1330,
449,
1559,
10267,
11,
10903,
21746,
198,
6738,
1687,
9491,
13,
7890,
13,
2676,
540,
1330,
9241,
47511,
29993,
540,
198
] | 3.92 | 25 |
from api.models import ClassTypeEnum
from api.parser.registrar import Registrar | [
6738,
40391,
13,
27530,
1330,
5016,
6030,
4834,
388,
198,
6738,
40391,
13,
48610,
13,
2301,
396,
20040,
1330,
46439
] | 3.95 | 20 |
from flask import render_template
from flask_assets import Environment, Bundle
from flask_compress import Compress
from factory import create_app
app = create_app(__name__)
app.config.from_object("config.DevelopmentConfig")
assets = Environment(app)
Compress(app)
testing_site = app.config["TESTING_SITE"]
app.jinja_env.filters["circle_num"] = circle_num_from_jinja_loop
app.jinja_env.filters["taste"] = taste
app.jinja_env.filters["price"] = price
@app.errorhandler(404)
@app.after_request
# Define static asset bundles to be minimized and deployed
bundles = {
"parryc_css": Bundle(
"css/marx.min.css",
"css/style_parryc.css",
"css/fonts/ptsans/fonts.css",
filters="cssmin",
output="gen/parryc.css",
),
"khachapuri_css": Bundle(
"css/marx.min.css",
"css/style_khachapuri.css",
"css/fonts/ptsans/fonts.css",
filters="cssmin",
output="gen/khachapuri.css",
),
"corbin_css": Bundle(
"css/marx.min.css",
"css/style_corbin.css",
"css/fonts/cormorant/fonts.css",
filters="cssmin",
output="gen/corbin.css",
),
"leflan_css": Bundle(
"css/marx.min.css",
"css/style_leflan.css",
"css/fonts/source-code-pro/source-code-pro.css",
"css/fonts/cmu/fonts.css",
"css/fonts/bpg-ingiri/bpg-ingiri.css",
"css/fonts/mayan/fonts.css",
filters="cssmin",
output="gen/leflan.css",
),
}
assets.register(bundles)
from mod_parryc.controllers import mod_parryc
app.register_blueprint(mod_parryc)
from mod_leflan.controllers import mod_leflan
app.register_blueprint(mod_leflan)
from mod_corbin.controllers import mod_corbin
app.register_blueprint(mod_corbin)
from mod_khachapuri.controllers import mod_khachapuri
app.register_blueprint(mod_khachapuri)
from avar_rocks.flask.controllers import mod_avar
app.register_blueprint(mod_avar)
from mod_zmnebi.controllers import mod_zmnebi
app.register_blueprint(mod_zmnebi)
| [
6738,
42903,
1330,
8543,
62,
28243,
198,
6738,
42903,
62,
19668,
1330,
9344,
11,
25282,
198,
6738,
42903,
62,
5589,
601,
1330,
3082,
601,
198,
6738,
8860,
1330,
2251,
62,
1324,
198,
198,
1324,
796,
2251,
62,
1324,
7,
834,
3672,
834,
... | 2.245556 | 900 |
################################################################################
##
## This library is free software; you can redistribute it and/or
## modify it under the terms of the GNU Lesser General Public
## License as published by the Free Software Foundation; either
## version 2.1 of the License, or (at your option) any later version.
##
## This library is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
## Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public
## License along with this library; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
##
## (C) Copyrights Dr. Michel F. Sanner and TSRI 2016
##
################################################################################
#############################################################################
#
# Author: Ruth Huey, Michel F. SANNER
#
# Copyright: M. Sanner TSRI 2014
#
#############################################################################
#
# $Header: /mnt/raid/services/cvs/PmvApp/deleteCmds.py,v 1.8.4.1 2017/07/13 20:55:28 annao Exp $
#
# $Id: deleteCmds.py,v 1.8.4.1 2017/07/13 20:55:28 annao Exp $
#
"""
This Module implements commands to delete items from the MoleculeViewer:
for examples:
Delete Molecule
"""
from PmvApp.Pmv import Event, AfterDeleteAtomsEvent, DeleteAtomsEvent, \
BeforeDeleteMoleculeEvent, AfterDeleteMoleculeEvent, RefreshDisplayEvent
from PmvApp.Pmv import BeforeDeleteMoleculeEvent, AfterDeleteMoleculeEvent
from PmvApp.selectionCmds import SelectionEvent
from PmvApp.Pmv import MVCommand
from AppFramework.App import DeleteObjectEvent
from MolKit2.selection import Selection, SelectionSet
from MolKit2.molecule import Molecule, MoleculeSet
from PmvApp.selectionCmds import SelectionEvent
class DeleteMolecule(MVCommand):
"""Command to delete molecule from the MoleculeViewer \n
Package : PmvApp \n
Module : deleteCmds \n
Class : DeleteMolecule \n
Command : deleteMolecule \n
Synopsis:\n
None<---deleteMolecule(molSel, **kw) \n
"""
def checkArguments(self, molSel):
"""None <- deleteMolecules(nodes, **kw) \n
nodes: TreeNodeSet holding the current selection.
"""
assert molSel
return (molSel,), {}
class DeleteAtoms(MVCommand):
""" Command to remove an AtomSet from the MoleculeViewer \n
Package : PmvApp \n
Module : deleteCmds \n
Class : DeleteAtoms \n
Command : deleteAtoms \n
Synopsis:\n
None<---deleteAtoms(atoms)\n
Required Arguments:\n
atoms --- AtomSet to be deleted.\n
"""
def checkArguments(self, selection):
"""None <- deleteAtoms(atoms) \n
atoms: AtomSet to be deleted."""
assert selection
return (selection,), {}
def doit(self, selection):
""" Function to delete all the references to each atom of a
AtomSet."""
# Remove the atoms of the molecule you are deleting from the
# the AtomSet self.app().allAtoms
mol = selection.getAtomGroup().getMolecule()
app = self.app()
if len(selection)==len(mol._ag):
app.deleteMolecule(mol)
return
# delete the atoms
mol.deleteAtoms(selection)
event = DeleteAtomsEvent(deletedAtoms=selection)
self.app().eventHandler.dispatchEvent(event)
event = RefreshDisplayEvent(molecule=mol)
self.app().eventHandler.dispatchEvent(event)
class DeleteCurrentSelection(DeleteAtoms):
""" Command to remove an AtomSet from the MoleculeViewer \n
Package : PmvApp \n
Module : deleteCmds \n
Class : DeleteCurrentSelection \n
Command : deleteCurrentSelection \n
Synopsis:\n
None<---deleteCurrentSelection()\n
Required Arguments:\n
None
"""
def checkArguments(self):
"""None <- deleteCurrentSelection()
"""
return (), {}
def doit(self):
""" Function to delete all the references to each atom of a
the currentSelection."""
atoms = old = self.app().activeSelection.get()[:] # make copy of selection
ats = self.app().expandNodes(atoms)
if not len(ats):
return
ats = ats.findType(Atom)
self.app().clearSelection(log=0)
DeleteAtoms.doit(self, ats)
class DeleteHydrogens(DeleteAtoms):
""" Command to remove hydrogen atoms from the MoleculeViewer \n
Package : PmvApp
Module : deleteCmds \n
Class : DeleteHydrogens \n
Command : deleteHydrogens \n
Synopsis:\n
None<---deleteHydrogens(atoms)\n
Required Arguments:\n
atoms --- Hydrogens found in this atom set are deleted.\n
"""
def checkArguments(self, atoms):
"""None <- deleteHydrogents(atoms) \n
atoms: set of atoms, from which hydrogens are to be deleted."""
if isinstance(atoms, str):
self.nodeLogString = "'"+atoms+"'"
ats = self.app().expandNodes(atoms)
assert ats
return (ats,), {}
commandClassFromName = {
'deleteMolecule' : [DeleteMolecule, None],
'deleteAtoms' : [DeleteAtoms, None ],
#'deleteMolecules' : [DeleteMolecules, None],
#'deleteAllMolecules' : [DeleteAllMolecules, None],
#'deleteCurrentSelection' : [DeleteCurrentSelection, None ],
#'deleteHydrogens' : [DeleteHydrogens, None],
#'restoreMol' : [RestoreMolecule, None],
}
| [
29113,
29113,
14468,
198,
2235,
198,
2235,
770,
5888,
318,
1479,
3788,
26,
345,
460,
17678,
4163,
340,
290,
14,
273,
198,
2235,
13096,
340,
739,
262,
2846,
286,
262,
22961,
12892,
263,
3611,
5094,
198,
2235,
13789,
355,
3199,
416,
262... | 2.702218 | 2,119 |
import pytest
from starlette.testclient import TestClient
from .fastapi_app import app, deps, Inner, ContextLoaded
@pytest.fixture
| [
11748,
12972,
9288,
198,
6738,
3491,
21348,
13,
9288,
16366,
1330,
6208,
11792,
198,
198,
6738,
764,
7217,
15042,
62,
1324,
1330,
598,
11,
390,
862,
11,
24877,
11,
30532,
8912,
276,
628,
628,
198,
198,
31,
9078,
9288,
13,
69,
9602,
... | 3.181818 | 44 |
#!/usr/bin/python
# Allen Daniel Yesa
# Aditya Subramanian Muralidaran
import sys
curr_key = None
curr_val = 0
for key_val in sys.stdin:
key,str_val = key_val.split("\t",1)
try:
val = int(str_val)
except:
continue
if(curr_key==key):
curr_val=curr_val+val;
else:
if(curr_key is not None):
print(curr_key+"\t"+str(curr_val))
curr_key=key;
curr_val=val;
print(curr_key+"\t"+str(curr_val))
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
198,
2,
9659,
7806,
3363,
64,
198,
2,
1215,
414,
64,
3834,
859,
38336,
337,
1523,
312,
19173,
198,
198,
11748,
25064,
198,
198,
22019,
81,
62,
2539,
796,
6045,
198,
22019,
81,
62,
2100,
7... | 1.976526 | 213 |
from ..base import HaravanResource
| [
6738,
11485,
8692,
1330,
2113,
12421,
26198,
628
] | 4.5 | 8 |
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from boto.exception import S3ResponseError
from pydoc import locate
import json
import redis
from provider.utils import unicode_encode
# TODO : replace with better implementation - e.g. use Redis/Elasticache
| [
6738,
275,
2069,
13,
82,
18,
13,
38659,
1330,
311,
18,
32048,
198,
6738,
275,
2069,
13,
82,
18,
13,
2539,
1330,
7383,
198,
6738,
275,
2069,
13,
1069,
4516,
1330,
311,
18,
31077,
12331,
198,
6738,
279,
5173,
420,
1330,
17276,
198,
... | 3.321839 | 87 |
#!/usr/bin/env python
#
# Common lint functions applicable to multiple types of files.
from __future__ import print_function
import re
def VerifyLineLength(filename, lines, max_length):
"""Checks to make sure the file has no lines with lines exceeding the length
limit.
Args:
filename: the file under consideration as string
lines: contents of the file as string array
max_length: maximum acceptable line length as number
Returns:
A list of tuples with format [(filename, line number, msg), ...] with any
violations found.
"""
lint = []
line_num = 1
for line in lines:
length = len(line.rstrip('\n'))
if length > max_length:
lint.append((filename, line_num,
'Line exceeds %d chars (%d)' % (max_length, length)))
line_num += 1
return lint
def VerifyTabs(filename, lines):
"""Checks to make sure the file has no tab characters.
Args:
filename: the file under consideration as string
lines: contents of the file as string array
Returns:
A list of tuples with format [(line_number, msg), ...] with any violations
found.
"""
lint = []
tab_re = re.compile(r'\t')
line_num = 1
for line in lines:
if tab_re.match(line.rstrip('\n')):
lint.append((filename, line_num, 'Tab found instead of whitespace'))
line_num += 1
return lint
def VerifyTrailingWhitespace(filename, lines):
"""Checks to make sure the file has no lines with trailing whitespace.
Args:
filename: the file under consideration as string
lines: contents of the file as string array
Returns:
A list of tuples with format [(filename, line number, msg), ...] with any
violations found.
"""
lint = []
trailing_whitespace_re = re.compile(r'\s+$')
line_num = 1
for line in lines:
if trailing_whitespace_re.match(line.rstrip('\n')):
lint.append((filename, line_num, 'Trailing whitespace'))
line_num += 1
return lint
def RunLintOverAllFiles(linter, filenames):
"""Runs linter over the contents of all files.
Args:
lint: subclass of BaseLint, implementing RunOnFile()
filenames: list of all files whose contents will be linted
Returns:
A list of tuples with format [(filename, line number, msg), ...] with any
violations found.
"""
lint = []
for filename in filenames:
file = open(filename, 'r')
if not file:
print('Cound not open %s' % filename)
continue
lines = file.readlines()
lint.extend(linter.RunOnFile(filename, lines))
return lint
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
198,
2,
8070,
300,
600,
5499,
9723,
284,
3294,
3858,
286,
3696,
13,
198,
198,
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
11748,
302,
198,
198,
4299,
49899,
13949,
24539,
... | 2.910345 | 870 |
# pip install pdfminer.six docx2txt
# to install win32com use the pywin32install.py script
import shutil
import sys
from pathlib import Path
from pprint import pprint
import docx2txt
from pdfminer.high_level import extract_text
if sys.platform == "win32":
import win32com.client as win32
from win32com.client import constants
filenames, parent_path = collect_all_document_files()
convert_to_txt(parent_path)
| [
2,
7347,
2721,
37124,
1084,
263,
13,
19412,
2205,
87,
17,
14116,
198,
2,
284,
2721,
1592,
2624,
785,
779,
262,
12972,
5404,
2624,
17350,
13,
9078,
4226,
198,
198,
11748,
4423,
346,
198,
11748,
25064,
198,
6738,
3108,
8019,
1330,
10644... | 3.086957 | 138 |
#!/usr/bin/env python2.7
#
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Base class for the handlers used in the portable server."""
import os
import sys
import traceback
import tornado.web
import portable_globe
class BaseHandler(tornado.web.RequestHandler):
"""Historically, the base class for local and remote servers.
Remote servers are no longer supported.
"""
def WriteFile(self, path):
"""Return a simple file as content."""
# If local override is on, return the local file if it exists.
if (tornado.web.globe_.config_.LocalOverride() and
os.path.isfile("./local/%s" % path)):
print "Using local file:", path
return self.WriteLocalFile(path)
# Write the file from the package.
try:
self.write(tornado.web.globe_.ReadFile(path))
return True
except portable_globe.UnableToFindException as e:
return False
def WriteLocalFile(self, path):
"""Return a simple local file as content."""
path = path.replace("..", "__")
# Write the file from the package.
try:
fp = open("./local/%s" % path, "rb")
self.write(fp.read())
fp.close()
return True
except portable_globe.UnableToFindException as e:
print e.message
return False
def ShowUri(self, host):
"""Show the uri that was requested."""
# Comment out next line to increase performance.
if tornado.web.globe_.config_.Debug():
print "Host: %s Request: %s" % (host, self.request.uri)
def IsLocalhost(self):
"""Checks if request is from localhost."""
host = self.request.headers["Host"]
try:
(server, server_port) = host.split(":")
except:
server = host
# Accept localhost requests
if server == "localhost" or server == "127.0.0.1":
return True
return False
def IsValidLocalRequest(self):
"""Make sure that the request looks good before processing.
Returns:
Whether request should be processed.
"""
host = self.request.headers["Host"]
try:
(caller_host, _) = host.split(":")
except:
caller_host = host
# Accept all localhost requests
if caller_host == "localhost" or caller_host == "127.0.0.1":
self.ShowUri(host)
return True
return False
def IsValidRequest(self):
"""Makes sure that the request looks valid.
Returns:
Whether request should be processed.
"""
return self.IsBroadcasting() or self.IsValidLocalRequest()
class LocalDocsHandler(BaseHandler):
"""Class for returning the content of files directly from disk."""
def get(self, path):
"""Handle GET request for some local file.
For example it is used for setup pages.
Args:
path: Path to file to be returned.
"""
if not self.IsValidRequest():
raise tornado.web.HTTPError(404)
if path[-3:].lower() == "gif":
self.set_header("Content-Type", "image/gif")
elif path[-3:].lower() == "png":
self.set_header("Content-Type", "image/png")
elif path[-3:].lower() == "css":
self.set_header("Content-Type", "text/css")
else:
self.set_header("Content-Type", "text/html")
self.WriteLocalFile(path)
class ExtHandler(BaseHandler):
"""Class for passing control to externally defined routines."""
def get(self, path):
"""Handle GET request for some external request.
Args:
path: Path relative to the ext directory.
"""
try:
tornado.web.local_server_.ext_service_.ExtGetHandler(self, path)
except:
if self.get_argument("debug", "") or tornado.web.globe_.config_.Debug():
e = sys.exc_info()
self.set_header("Content-Type", "text/html")
self.write("<pre>%s</pre>" % "".join(
traceback.format_exception(e[0], e[1], e[2])
))
else:
self.set_header("Content-Type", "text/html")
self.write("GET service failed or is undefined.")
def post(self, path):
"""Handle POST request for some external request.
Args:
path: Path relative to the ext directory.
"""
try:
tornado.web.local_server_.ext_service_.ExtPostHandler(self, path)
except:
if self.get_argument("debug", "") or tornado.web.globe_.config_.Debug():
e = sys.exc_info()
self.set_header("Content-Type", "text/html")
self.write("<pre>%s</pre>" % "".join(
traceback.format_exception(e[0], e[1], e[2])
))
else:
self.set_header("Content-Type", "text/html")
self.write("POST service failed or is undefined.")
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
17,
13,
22,
198,
2,
198,
2,
15069,
2177,
3012,
3457,
13,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
743,
407,
77... | 2.728932 | 1,863 |
import sys
sys.path.insert(0, "./")
import os
from Scripts import *
if __name__ == "__main__":
if len(sys.argv) <= 1:
usage()
else:
module = "Scripts." + sys.argv[1]
if module in sys.modules:
sys.modules[module].start()
else:
print("No module named {}".format("Scripts." + sys.argv[1]))
usage()
| [
11748,
25064,
198,
17597,
13,
6978,
13,
28463,
7,
15,
11,
366,
19571,
4943,
198,
11748,
28686,
198,
198,
6738,
12327,
82,
1330,
1635,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
628,
220,
220,
220,
611,
18896,
... | 2.054945 | 182 |
"""Unit test for treadmill.scheduler.
"""
# Disable too many lines in module warning.
#
# pylint: disable=C0302
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import datetime
import itertools
import sys
import time
import unittest
import mock
import numpy as np
import six
# Disable W0611: Unused import
import treadmill.tests.treadmill_test_skip_windows # pylint: disable=W0611
from treadmill import scheduler
from treadmill import utils
_TRAITS = dict()
# Helper functions to convert user readable traits to bit mask.
def app_list(count, name, *args, **kwargs):
"""Return list of apps."""
return [scheduler.Application(name + '-' + str(idx),
*args, affinity=name, **kwargs)
for idx in range(0, count)]
class OpsTest(unittest.TestCase):
"""Test comparison operators."""
# Disable warning accessing protected members.
#
# pylint: disable=W0212
def test_ops(self):
"""Test comparison operators."""
self.assertTrue(scheduler._all_gt([3, 3], [2, 2]))
self.assertTrue(scheduler._any_gt([3, 2], [2, 2]))
self.assertFalse(scheduler._all_gt([3, 2], [2, 2]))
self.assertTrue(scheduler._all_lt([2, 2], [3, 3]))
class AllocationTest(unittest.TestCase):
"""treadmill.scheduler.Allocation tests."""
def test_utilization(self):
"""Test utilization calculation."""
alloc = scheduler.Allocation([10, 10])
alloc.add(scheduler.Application('app1', 100, [1, 1], 'app1'))
alloc.add(scheduler.Application('app2', 100, [2, 2], 'app1'))
alloc.add(scheduler.Application('app3', 100, [3, 3], 'app1'))
# First element is rank.
util_q = list(alloc.utilization_queue([20, 20]))
self.assertEqual(100, util_q[0][0])
self.assertEqual(100, util_q[1][0])
self.assertEqual(100, util_q[2][0])
# Second and third elememts is before / after utilization.
self.assertEqual(-10 / (10. + 20), util_q[0][1])
self.assertEqual(-9 / (10. + 20), util_q[0][2])
self.assertEqual(-7 / (10. + 20), util_q[1][2])
self.assertEqual(-9 / (10. + 20), util_q[1][1])
self.assertEqual(-4 / (10. + 20), util_q[2][2])
self.assertEqual(-7 / (10. + 20), util_q[2][1])
# Applications are sorted by priority.
alloc = scheduler.Allocation([10, 10])
alloc.add(scheduler.Application('app1', 10, [1, 1], 'app1'))
alloc.add(scheduler.Application('app2', 50, [2, 2], 'app1'))
alloc.add(scheduler.Application('app3', 100, [3, 3], 'app1'))
util_q = list(alloc.utilization_queue([20., 20.]))
self.assertEqual(-10 / (10. + 20), util_q[0][1])
self.assertEqual(-7 / (10. + 20), util_q[0][2])
self.assertEqual(-7 / (10. + 20), util_q[1][1])
self.assertEqual(-5 / (10. + 20), util_q[1][2])
self.assertEqual(-5 / (10. + 20), util_q[2][1])
self.assertEqual(-4 / (10. + 20), util_q[2][2])
def test_running_order(self):
"""Test apps are ordered by status (running first) for same prio."""
alloc = scheduler.Allocation([10, 10])
alloc.add(scheduler.Application('app1', 5, [1, 1], 'app1'))
alloc.add(scheduler.Application('app2', 5, [2, 2], 'app1'))
alloc.add(scheduler.Application('app3', 5, [3, 3], 'app1'))
queue = list(alloc.utilization_queue([20., 20.]))
self.assertEqual(alloc.apps['app1'], queue[0][-1])
alloc.apps['app2'].server = 'abc'
queue = list(alloc.utilization_queue([20., 20.]))
self.assertEqual(alloc.apps['app2'], queue[0][-1])
def test_utilization_max(self):
"""Tests max utilization cap on the allocation."""
alloc = scheduler.Allocation([3, 3])
alloc.add(scheduler.Application('app1', 1, [1, 1], 'app1'))
alloc.add(scheduler.Application('app2', 1, [2, 2], 'app1'))
alloc.add(scheduler.Application('app3', 1, [3, 3], 'app1'))
self.assertEqual(3, len(list(alloc.utilization_queue([20., 20.]))))
# Now set max_utilization to 1
alloc.max_utilization = 1
# XXX: Broken test. Needs upgrade to V3
# XXX:
# XXX: self.assertEqual(
# XXX: 2,
# XXX: len(list(alloc.utilization_queue([20., 20.])))
# XXX: )
alloc.set_max_utilization(None)
self.assertEqual(3, len(list(alloc.utilization_queue([20., 20.]))))
def test_priority_zero(self):
"""Tests priority zero apps."""
alloc = scheduler.Allocation([3, 3])
alloc.add(scheduler.Application('app1', 1, [1, 1], 'app1'))
alloc.add(scheduler.Application('app2', 0, [2, 2], 'app1'))
# default max_utilization still lets prio 0 apps through
queue = alloc.utilization_queue([20., 20.])
self.assertEqual([100, 100], [item[0] for item in queue])
alloc.set_max_utilization(100)
# setting max_utilization will cut off prio 0 apps
queue = alloc.utilization_queue([20., 20.])
self.assertEqual(
[100, sys.maxsize],
[item[0] for item in queue]
)
def test_rank_adjustment(self):
"""Test rank adjustment"""
alloc = scheduler.Allocation()
alloc.update([3, 3], 100, 10)
alloc.add(scheduler.Application('app1', 1, [1, 1], 'app1'))
alloc.add(scheduler.Application('app2', 1, [2, 2], 'app1'))
alloc.add(scheduler.Application('app3', 1, [3, 3], 'app1'))
queue = list(alloc.utilization_queue([20., 20.]))
self.assertEqual(90, queue[0][0])
self.assertEqual(90, queue[1][0])
self.assertEqual(100, queue[2][0])
def test_zerovector(self):
"""Test updating allocation with allocation vector containing 0's"""
alloc = scheduler.Allocation(None)
alloc.update([1, 0], None, None)
self.assertEqual(1.0, alloc.reserved[0])
self.assertEqual(0, alloc.reserved[1])
def test_utilization_no_reservation(self):
"""Checks that any utilization without reservation is VERY large."""
alloc = scheduler.Allocation(None)
alloc.add(scheduler.Application('app1', 1, [1., 1.], 'app1'))
queue = list(alloc.utilization_queue(np.array([10., 10.])))
self.assertEqual(0 / 10, queue[0][1])
self.assertEqual(1 / 10, queue[0][2])
def test_duplicate(self):
"""Checks behavior when adding duplicate app."""
alloc = scheduler.Allocation(None)
alloc.add(scheduler.Application('app1', 0, [1, 1], 'app1'))
self.assertEqual(
1, len(list(alloc.utilization_queue(np.array([5., 5.])))))
alloc.add(scheduler.Application('app1', 0, [1, 1], 'app1'))
self.assertEqual(
1, len(list(alloc.utilization_queue(np.array([5., 5.])))))
def test_sub_allocs(self):
"""Test utilization calculation with sub-allocs."""
alloc = scheduler.Allocation([3, 3])
self.assertEqual(3, alloc.total_reserved()[0])
queue = list(alloc.utilization_queue([20., 20.]))
sub_alloc_a = scheduler.Allocation([5, 5])
alloc.add_sub_alloc('a1/a', sub_alloc_a)
self.assertEqual(8, alloc.total_reserved()[0])
sub_alloc_a.add(scheduler.Application('1a', 3, [2, 2], 'app1'))
sub_alloc_a.add(scheduler.Application('2a', 2, [3, 3], 'app1'))
sub_alloc_a.add(scheduler.Application('3a', 1, [5, 5], 'app1'))
queue = list(alloc.utilization_queue([20., 20.]))
_rank, _util_b, util_a, _pending, _order, app = queue[0]
self.assertEqual('1a', app.name)
self.assertEqual((2 - (5 + 3)) / (20 + (5 + 3)), util_a)
sub_alloc_b = scheduler.Allocation([10, 10])
alloc.add_sub_alloc('a1/b', sub_alloc_b)
sub_alloc_b.add(scheduler.Application('1b', 3, [2, 2], 'app1'))
sub_alloc_b.add(scheduler.Application('2b', 2, [3, 3], 'app1'))
sub_alloc_b.add(scheduler.Application('3b', 1, [5, 5], 'app1'))
queue = list(alloc.utilization_queue([20., 20.]))
self.assertEqual(6, len(queue))
self.assertEqual(18, alloc.total_reserved()[0])
# For each sub-alloc (and self) the least utilized app is 1.
# The sub_allloc_b is largest, so utilization smallest, 1b will be
# first.
_rank, _util_b, util_a, _pending, _order, app = queue[0]
self.assertEqual('1b', app.name)
self.assertEqual((2 - 18) / (20 + 18), util_a)
# Add prio 0 app to each, make sure they all end up last.
alloc.add(scheduler.Application('1-zero', 0, [2, 2], 'app1'))
sub_alloc_b.add(scheduler.Application('b-zero', 0, [5, 5], 'app1'))
sub_alloc_a.add(scheduler.Application('a-zero', 0, [5, 5], 'app1'))
queue = list(alloc.utilization_queue([20., 20.]))
self.assertIn('1-zero', [item[-1].name for item in queue[-3:]])
self.assertIn('a-zero', [item[-1].name for item in queue[-3:]])
self.assertIn('b-zero', [item[-1].name for item in queue[-3:]])
# Check that utilization of prio 0 apps is always max float.
self.assertEqual(
[float('inf')] * 3,
[
util_b
for (_rank,
util_b,
_util_a,
_pending,
_order,
_app) in queue[-3:]
]
)
def test_sub_alloc_reservation(self):
"""Test utilization calculation is fair between sub-allocs."""
alloc = scheduler.Allocation()
sub_alloc_poor = scheduler.Allocation()
alloc.add_sub_alloc('poor', sub_alloc_poor)
sub_alloc_poor.add(scheduler.Application('p1', 1, [1, 1], 'app1'))
sub_alloc_rich = scheduler.Allocation([5, 5])
sub_alloc_rich.add(scheduler.Application('r1', 1, [5, 5], 'app1'))
sub_alloc_rich.add(scheduler.Application('r2', 1, [5, 5], 'app1'))
alloc.add_sub_alloc('rich', sub_alloc_rich)
queue = list(alloc.utilization_queue([20., 20.]))
self.assertEqual('r1', queue[0][-1].name)
self.assertEqual('p1', queue[1][-1].name)
self.assertEqual('r2', queue[2][-1].name)
def test_visitor(self):
"""Test queue visitor"""
alloc = scheduler.Allocation()
sub_alloc_a = scheduler.Allocation()
sub_alloc_a.add(scheduler.Application('a1', 1, [1, 1], 'app1'))
alloc.add_sub_alloc('a', sub_alloc_a)
sub_alloc_b = scheduler.Allocation()
sub_alloc_b.add(scheduler.Application('b1', 1, [5, 5], 'app1'))
sub_alloc_b.add(scheduler.Application('b2', 1, [5, 5], 'app1'))
alloc.add_sub_alloc('b', sub_alloc_b)
result = []
list(alloc.utilization_queue([20., 20.],
visitor=_visitor))
self.assertEqual(6, len(result))
class TraitSetTest(unittest.TestCase):
"""treadmill.scheduler.TraitSet tests."""
def test_traits(self):
"""Test trait inheritance."""
trait_a = int('0b0000001', 2)
trait_x = int('0b0000100', 2)
trait_y = int('0b0001000', 2)
trait_z = int('0b0010000', 2)
fset_a = scheduler.TraitSet(trait_a)
fset_xz = scheduler.TraitSet(trait_x | trait_z)
fset_xy = scheduler.TraitSet(trait_x | trait_y)
self.assertTrue(fset_a.has(trait_a))
fset_a.add('xy', fset_xy.traits)
self.assertTrue(fset_a.has(trait_a))
self.assertTrue(fset_a.has(trait_x))
self.assertTrue(fset_a.has(trait_y))
fset_a.add('xz', fset_xz.traits)
self.assertTrue(fset_a.has(trait_x))
self.assertTrue(fset_a.has(trait_y))
self.assertTrue(fset_a.has(trait_z))
fset_a.remove('xy')
self.assertTrue(fset_a.has(trait_x))
self.assertFalse(fset_a.has(trait_y))
self.assertTrue(fset_a.has(trait_z))
fset_a.remove('xz')
self.assertFalse(fset_a.has(trait_x))
self.assertFalse(fset_a.has(trait_y))
self.assertFalse(fset_a.has(trait_z))
class NodeTest(unittest.TestCase):
"""treadmill.scheduler.Allocation tests."""
def test_bucket_capacity(self):
"""Tests adjustment of bucket capacity up and down."""
parent = scheduler.Bucket('top')
bucket = scheduler.Bucket('b')
parent.add_node(bucket)
srv1 = scheduler.Server('n1', [10, 5], valid_until=500)
bucket.add_node(srv1)
self.assertTrue(np.array_equal(bucket.free_capacity,
np.array([10., 5.])))
self.assertTrue(np.array_equal(parent.free_capacity,
np.array([10., 5.])))
srv2 = scheduler.Server('n2', [5, 10], valid_until=500)
bucket.add_node(srv2)
self.assertTrue(np.array_equal(bucket.free_capacity,
np.array([10., 10.])))
self.assertTrue(np.array_equal(parent.free_capacity,
np.array([10., 10.])))
srv3 = scheduler.Server('n3', [3, 3], valid_until=500)
bucket.add_node(srv3)
self.assertTrue(np.array_equal(bucket.free_capacity,
np.array([10., 10.])))
self.assertTrue(np.array_equal(parent.free_capacity,
np.array([10., 10.])))
bucket.remove_node_by_name('n3')
self.assertTrue(np.array_equal(bucket.free_capacity,
np.array([10., 10.])))
self.assertTrue(np.array_equal(parent.free_capacity,
np.array([10., 10.])))
bucket.remove_node_by_name('n1')
self.assertTrue(np.array_equal(bucket.free_capacity,
np.array([5., 10.])))
self.assertTrue(np.array_equal(parent.free_capacity,
np.array([5., 10.])))
def test_app_node_placement(self):
"""Tests capacity adjustments for app placement."""
parent = scheduler.Bucket('top')
bucket = scheduler.Bucket('a_bucket')
parent.add_node(bucket)
srv1 = scheduler.Server('n1', [10, 5], valid_until=500)
bucket.add_node(srv1)
srv2 = scheduler.Server('n2', [10, 5], valid_until=500)
bucket.add_node(srv2)
self.assertTrue(np.array_equal(bucket.free_capacity,
np.array([10., 5.])))
self.assertTrue(np.array_equal(parent.free_capacity,
np.array([10., 5.])))
self.assertTrue(np.array_equal(bucket.size(None),
np.array([20., 10.])))
# Create 10 identical apps.
apps = app_list(10, 'app', 50, [1, 2])
self.assertTrue(srv1.put(apps[0]))
# Capacity of buckets should not change, other node is intact.
self.assertTrue(np.array_equal(bucket.free_capacity,
np.array([10., 5.])))
self.assertTrue(np.array_equal(parent.free_capacity,
np.array([10., 5.])))
self.assertTrue(srv1.put(apps[1]))
self.assertTrue(srv2.put(apps[2]))
self.assertTrue(np.array_equal(bucket.free_capacity,
np.array([9., 3.])))
self.assertTrue(np.array_equal(parent.free_capacity,
np.array([9., 3.])))
def test_bucket_placement(self):
"""Tests placement strategies."""
top = scheduler.Bucket('top')
a_bucket = scheduler.Bucket('a_bucket')
top.add_node(a_bucket)
b_bucket = scheduler.Bucket('b_bucket')
top.add_node(b_bucket)
a1_srv = scheduler.Server('a1_srv', [10, 10], valid_until=500)
a_bucket.add_node(a1_srv)
a2_srv = scheduler.Server('a2_srv', [10, 10], valid_until=500)
a_bucket.add_node(a2_srv)
b1_srv = scheduler.Server('b1_srv', [10, 10], valid_until=500)
b_bucket.add_node(b1_srv)
b2_srv = scheduler.Server('b2_srv', [10, 10], valid_until=500)
b_bucket.add_node(b2_srv)
# bunch of apps with the same affinity
apps1 = app_list(10, 'app1', 50, [1, 1])
apps2 = app_list(10, 'app2', 50, [1, 1])
# Default strategy is spread, so placing 4 apps1 will result in each
# node having one app.
self.assertTrue(top.put(apps1[0]))
self.assertTrue(top.put(apps1[1]))
self.assertTrue(top.put(apps1[2]))
self.assertTrue(top.put(apps1[3]))
# from top level, it will spread between a and b buckets, so first
# two apps go to a1_srv, b1_srv respectively.
#
# 3rd app - buckets rotate, and a bucket is preferred again. Inside the
# bucket, next node is chosed. Same for 4th app.
#
# Result is the after 4 placements they are spread evenly.
#
self.assertEqual(1, len(a1_srv.apps))
self.assertEqual(1, len(a2_srv.apps))
self.assertEqual(1, len(b1_srv.apps))
self.assertEqual(1, len(b2_srv.apps))
a_bucket.set_affinity_strategy('app2', scheduler.PackStrategy)
self.assertTrue(top.put(apps2[0]))
self.assertTrue(top.put(apps2[1]))
self.assertTrue(top.put(apps2[2]))
self.assertTrue(top.put(apps2[3]))
# B bucket still uses spread strategy.
self.assertEqual(2, len(b1_srv.apps))
self.assertEqual(2, len(b2_srv.apps))
# Without predicting exact placement, apps will be placed on one of
# the servers in A bucket but not the other, as they use pack strateg.
self.assertNotEqual(len(a1_srv.apps), len(a2_srv.apps))
def test_valid_times(self):
"""Tests node valid_until calculation."""
top = scheduler.Bucket('top', traits=_traits2int(['top']))
left = scheduler.Bucket('left', traits=_traits2int(['left']))
right = scheduler.Bucket('right', traits=_traits2int(['right']))
srv_a = scheduler.Server('a', [10, 10], traits=_traits2int(['a', '0']),
valid_until=1)
srv_b = scheduler.Server('b', [10, 10], traits=_traits2int(['b', '0']),
valid_until=2)
srv_y = scheduler.Server('y', [10, 10], traits=_traits2int(['y', '1']),
valid_until=3)
srv_z = scheduler.Server('z', [10, 10], traits=_traits2int(['z', '1']),
valid_until=4)
top.add_node(left)
top.add_node(right)
left.add_node(srv_a)
left.add_node(srv_b)
right.add_node(srv_y)
right.add_node(srv_z)
self.assertEqual(top.valid_until, 4)
self.assertEqual(left.valid_until, 2)
self.assertEqual(right.valid_until, 4)
left.remove_node_by_name('a')
self.assertEqual(top.valid_until, 4)
self.assertEqual(left.valid_until, 2)
self.assertEqual(right.valid_until, 4)
right.remove_node_by_name('z')
self.assertEqual(top.valid_until, 3)
self.assertEqual(left.valid_until, 2)
self.assertEqual(right.valid_until, 3)
def test_node_traits(self):
"""Tests node trait inheritance."""
top = scheduler.Bucket('top', traits=_traits2int(['top']))
left = scheduler.Bucket('left', traits=_traits2int(['left']))
right = scheduler.Bucket('right', traits=_traits2int(['right']))
srv_a = scheduler.Server('a', [10, 10], traits=_traits2int(['a', '0']),
valid_until=500)
srv_b = scheduler.Server('b', [10, 10], traits=_traits2int(['b', '0']),
valid_until=500)
srv_y = scheduler.Server('y', [10, 10], traits=_traits2int(['y', '1']),
valid_until=500)
srv_z = scheduler.Server('z', [10, 10], traits=_traits2int(['z', '1']),
valid_until=500)
top.add_node(left)
top.add_node(right)
left.add_node(srv_a)
left.add_node(srv_b)
right.add_node(srv_y)
right.add_node(srv_z)
self.assertTrue(top.traits.has(_trait2int('a')))
self.assertTrue(top.traits.has(_trait2int('b')))
self.assertTrue(top.traits.has(_trait2int('0')))
self.assertTrue(top.traits.has(_trait2int('y')))
self.assertTrue(top.traits.has(_trait2int('z')))
self.assertTrue(top.traits.has(_trait2int('1')))
self.assertTrue(left.traits.has(_trait2int('a')))
self.assertTrue(left.traits.has(_trait2int('b')))
self.assertTrue(left.traits.has(_trait2int('0')))
self.assertFalse(left.traits.has(_trait2int('y')))
self.assertFalse(left.traits.has(_trait2int('z')))
self.assertFalse(left.traits.has(_trait2int('1')))
left.remove_node_by_name('a')
self.assertFalse(left.traits.has(_trait2int('a')))
self.assertTrue(left.traits.has(_trait2int('b')))
self.assertTrue(left.traits.has(_trait2int('0')))
self.assertFalse(top.traits.has(_trait2int('a')))
self.assertTrue(top.traits.has(_trait2int('b')))
self.assertTrue(top.traits.has(_trait2int('0')))
left.remove_node_by_name('b')
self.assertFalse(left.traits.has(_trait2int('b')))
self.assertFalse(left.traits.has(_trait2int('0')))
self.assertFalse(top.traits.has(_trait2int('b')))
self.assertFalse(top.traits.has(_trait2int('0')))
def test_app_trait_placement(self):
"""Tests placement of app with traits."""
top = scheduler.Bucket('top', traits=_traits2int(['top']))
left = scheduler.Bucket('left', traits=_traits2int(['left']))
right = scheduler.Bucket('right', traits=_traits2int(['right']))
srv_a = scheduler.Server('a', [10, 10], traits=_traits2int(['a', '0']),
valid_until=500)
srv_b = scheduler.Server('b', [10, 10], traits=_traits2int(['b', '0']),
valid_until=500)
srv_y = scheduler.Server('y', [10, 10], traits=_traits2int(['y', '1']),
valid_until=500)
srv_z = scheduler.Server('z', [10, 10], traits=_traits2int(['z', '1']),
valid_until=500)
top.add_node(left)
top.add_node(right)
left.add_node(srv_a)
left.add_node(srv_b)
right.add_node(srv_y)
right.add_node(srv_z)
alloc_a = scheduler.Allocation(traits=_traits2int(['a']))
apps_a = app_list(10, 'app_a', 50, [2, 2])
for app in apps_a:
alloc_a.add(app)
# srv_a is the only one with trait 'a'.
self.assertTrue(top.put(apps_a[0]))
self.assertTrue(top.put(apps_a[1]))
self.assertIn(apps_a[0].name, srv_a.apps)
self.assertIn(apps_a[1].name, srv_a.apps)
apps_b = app_list(10, 'app_b', 50, [2, 2], traits=_traits2int(['b']))
# srv_b is the only one with trait 'b'.
self.assertTrue(top.put(apps_b[0]))
self.assertTrue(top.put(apps_b[1]))
self.assertIn(apps_b[0].name, srv_b.apps)
self.assertIn(apps_b[1].name, srv_b.apps)
apps_ab = app_list(10, 'app_ab', 50, [2, 2], traits=_traits2int(['b']))
for app in apps_ab:
alloc_a.add(app)
# there is no server with both 'a' and 'b' traits.
self.assertFalse(top.put(apps_ab[0]))
self.assertFalse(top.put(apps_ab[1]))
alloc_0 = scheduler.Allocation(traits=_traits2int(['0']))
apps_0 = app_list(10, 'app_0', 50, [2, 2])
for app in apps_0:
alloc_0.add(app)
# '0' trait - two servers, will spread by default.
self.assertTrue(top.put(apps_0[0]))
self.assertTrue(top.put(apps_0[1]))
self.assertIn(apps_0[0].name, srv_a.apps)
self.assertIn(apps_0[1].name, srv_b.apps)
apps_a0 = app_list(10, 'app_a0', 50, [2, 2], traits=_traits2int(['a']))
for app in apps_a0:
alloc_0.add(app)
# srv_a is the only one with traits 'a' and '0'.
self.assertTrue(top.put(apps_a0[0]))
self.assertTrue(top.put(apps_a0[1]))
self.assertIn(apps_a0[0].name, srv_a.apps)
self.assertIn(apps_a0[1].name, srv_a.apps)
# Prev implementation propagated traits from parent to children,
# so "right" trait propagated to leaf servers.
#
# This behavior is removed, so placing app with "right" trait will
# fail.
#
# alloc_r1 = scheduler.Allocation(traits=_traits2int(['right', '1']))
# apps_r1 = app_list(10, 'app_r1', 50, [2, 2])
# for app in apps_r1:
# alloc_r1.add(app)
# self.assertTrue(top.put(apps_r1[0]))
# self.assertTrue(top.put(apps_r1[1]))
# self.assertIn(apps_r1[0].name, srv_y.apps)
# self.assertIn(apps_r1[1].name, srv_z.apps)
apps_nothing = app_list(10, 'apps_nothing', 50, [1, 1])
# All nodes fit. Spead first between buckets, then between nodes.
# top
# left right
# a b y z
self.assertTrue(top.put(apps_nothing[0]))
self.assertTrue(top.put(apps_nothing[1]))
self.assertTrue(
(
apps_nothing[0].server in ['a', 'b'] and
apps_nothing[1].server in ['y', 'z']
) or
(
apps_nothing[0].server in ['y', 'z'] and
apps_nothing[1].server in ['a', 'b']
)
)
self.assertTrue(top.put(apps_nothing[2]))
self.assertTrue(top.put(apps_nothing[3]))
self.assertTrue(
(
apps_nothing[2].server in ['a', 'b'] and
apps_nothing[3].server in ['y', 'z']
) or
(
apps_nothing[2].server in ['y', 'z'] and
apps_nothing[3].server in ['a', 'b']
)
)
def test_size_and_members(self):
"""Tests recursive size calculation."""
top = scheduler.Bucket('top', traits=_traits2int(['top']))
left = scheduler.Bucket('left', traits=_traits2int(['left']))
right = scheduler.Bucket('right', traits=_traits2int(['right']))
srv_a = scheduler.Server('a', [1, 1], traits=_traits2int(['a', '0']),
valid_until=500)
srv_b = scheduler.Server('b', [1, 1], traits=_traits2int(['b', '0']),
valid_until=500)
srv_y = scheduler.Server('y', [1, 1], traits=_traits2int(['y', '1']),
valid_until=500)
srv_z = scheduler.Server('z', [1, 1], traits=_traits2int(['z', '1']),
valid_until=500)
top.add_node(left)
top.add_node(right)
left.add_node(srv_a)
left.add_node(srv_b)
right.add_node(srv_y)
right.add_node(srv_z)
# pylint: disable=W0212
self.assertTrue(scheduler._all_isclose(srv_a.size(None), [1, 1]))
self.assertTrue(scheduler._all_isclose(left.size(None), [2, 2]))
self.assertTrue(scheduler._all_isclose(top.size(None), [4, 4]))
self.assertEqual(
{
'a': srv_a,
'b': srv_b,
'y': srv_y,
'z': srv_z
},
top.members()
)
def test_affinity_counters(self):
"""Tests affinity counters."""
top = scheduler.Bucket('top', traits=_traits2int(['top']))
left = scheduler.Bucket('left', traits=_traits2int(['left']))
right = scheduler.Bucket('right', traits=_traits2int(['right']))
srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500)
srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500)
srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500)
srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500)
top.add_node(left)
top.add_node(right)
left.add_node(srv_a)
left.add_node(srv_b)
right.add_node(srv_y)
right.add_node(srv_z)
apps_a = app_list(10, 'app_a', 50, [1, 1])
self.assertTrue(srv_a.put(apps_a[0]))
self.assertEqual(1, srv_a.affinity_counters['app_a'])
self.assertEqual(1, left.affinity_counters['app_a'])
self.assertEqual(1, top.affinity_counters['app_a'])
srv_z.put(apps_a[0])
self.assertEqual(1, srv_z.affinity_counters['app_a'])
self.assertEqual(1, left.affinity_counters['app_a'])
self.assertEqual(2, top.affinity_counters['app_a'])
srv_a.remove(apps_a[0].name)
self.assertEqual(0, srv_a.affinity_counters['app_a'])
self.assertEqual(0, left.affinity_counters['app_a'])
self.assertEqual(1, top.affinity_counters['app_a'])
class CellTest(unittest.TestCase):
"""treadmill.scheduler.Cell tests."""
def test_emtpy(self):
"""Simple test to test empty bucket"""
cell = scheduler.Cell('top')
empty = scheduler.Bucket('empty', traits=0)
cell.add_node(empty)
bucket = scheduler.Bucket('bucket', traits=0)
srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500)
bucket.add_node(srv_a)
cell.add_node(bucket)
cell.schedule()
def test_labels(self):
"""Test scheduling with labels."""
cell = scheduler.Cell('top')
left = scheduler.Bucket('left', traits=0)
right = scheduler.Bucket('right', traits=0)
srv_a = scheduler.Server('a_xx', [10, 10], valid_until=500, label='xx')
srv_b = scheduler.Server('b', [10, 10], valid_until=500)
srv_y = scheduler.Server('y_xx', [10, 10], valid_until=500, label='xx')
srv_z = scheduler.Server('z', [10, 10], valid_until=500)
cell.add_node(left)
cell.add_node(right)
left.add_node(srv_a)
left.add_node(srv_b)
right.add_node(srv_y)
right.add_node(srv_z)
app1 = scheduler.Application('app1', 4, [1, 1], 'app')
app2 = scheduler.Application('app2', 3, [2, 2], 'app')
app3 = scheduler.Application('app_xx_3', 2, [3, 3], 'app')
app4 = scheduler.Application('app_xx_4', 1, [4, 4], 'app')
cell.partitions[None].allocation.add(app1)
cell.partitions[None].allocation.add(app2)
cell.partitions['xx'].allocation.add(app3)
cell.partitions['xx'].allocation.add(app4)
cell.schedule()
self.assertIn(app1.server, ['b', 'z'])
self.assertIn(app2.server, ['b', 'z'])
self.assertIn(app3.server, ['a_xx', 'y_xx'])
self.assertIn(app4.server, ['a_xx', 'y_xx'])
def test_simple(self):
"""Simple placement test."""
# pylint - too many lines.
#
# pylint: disable=R0915
cell = scheduler.Cell('top')
left = scheduler.Bucket('left', traits=0)
right = scheduler.Bucket('right', traits=0)
srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500)
srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500)
srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500)
srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500)
cell.add_node(left)
cell.add_node(right)
left.add_node(srv_a)
left.add_node(srv_b)
right.add_node(srv_y)
right.add_node(srv_z)
app1 = scheduler.Application('app1', 4, [1, 1], 'app')
app2 = scheduler.Application('app2', 3, [2, 2], 'app')
app3 = scheduler.Application('app3', 2, [3, 3], 'app')
app4 = scheduler.Application('app4', 1, [4, 4], 'app')
cell.partitions[None].allocation.add(app1)
cell.partitions[None].allocation.add(app2)
cell.partitions[None].allocation.add(app3)
cell.partitions[None].allocation.add(app4)
cell.schedule()
self.assertEqual(
set([app1.server, app2.server, app3.server, app4.server]),
set(['a', 'y', 'b', 'z'])
)
srv1 = app1.server
srv2 = app2.server
srv3 = app3.server
srv4 = app4.server
# Add high priority app that needs entire cell
app_prio50 = scheduler.Application('prio50', 50, [10, 10], 'app')
cell.partitions[None].allocation.add(app_prio50)
cell.schedule()
# The queue is ordered by priority:
# - prio50, app1, app2, app3, app4
#
# As placement not found for prio50, app4 will be evicted first.
#
# As result, prio50 will be placed on 'z', and app4 (evicted) will be
# placed on "next" server, which is 'a'.
self.assertEqual(app_prio50.server, srv4)
self.assertEqual(app4.server, srv1)
app_prio51 = scheduler.Application('prio51', 51, [10, 10], 'app')
cell.partitions[None].allocation.add(app_prio51)
cell.schedule()
# app4 is now colocated with app1. app4 will still be evicted first,
# then app3, at which point there will be enough capacity to place
# large app.
#
# app3 will be rescheduled to run on "next" server - 'y', and app4 will
# be restored to 'a'.
self.assertEqual(app_prio51.server, srv3)
self.assertEqual(app_prio50.server, srv4)
self.assertEqual(app4.server, srv1)
app_prio49_1 = scheduler.Application('prio49_1', 49, [10, 10], 'app')
app_prio49_2 = scheduler.Application('prio49_2', 49, [9, 9], 'app')
cell.partitions[None].allocation.add(app_prio49_1)
cell.partitions[None].allocation.add(app_prio49_2)
cell.schedule()
# 50/51 not moved. from the end of the queue,
self.assertEqual(app_prio51.server, srv3)
self.assertEqual(app_prio50.server, srv4)
self.assertEqual(
set([app_prio49_1.server, app_prio49_2.server]),
set([srv1, srv2])
)
# Only capacity left for small [1, 1] app.
self.assertIsNotNone(app1.server)
self.assertIsNone(app2.server)
self.assertIsNone(app3.server)
self.assertIsNone(app4.server)
def test_max_utilization(self):
"""Test max-utilization is handled properly when priorities change"""
cell = scheduler.Cell('top')
left = scheduler.Bucket('left', traits=0)
right = scheduler.Bucket('right', traits=0)
srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500)
srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500)
srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500)
srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500)
cell.add_node(left)
cell.add_node(right)
left.add_node(srv_a)
left.add_node(srv_b)
right.add_node(srv_y)
right.add_node(srv_z)
app1 = scheduler.Application('app1', 4, [1, 1], 'app')
app2 = scheduler.Application('app2', 3, [2, 2], 'app')
app3 = scheduler.Application('app3', 2, [3, 3], 'app')
app4 = scheduler.Application('app4', 1, [4, 4], 'app')
cell.partitions[None].allocation.add(app1)
cell.partitions[None].allocation.add(app2)
cell.partitions[None].allocation.add(app3)
cell.partitions[None].allocation.add(app4)
cell.partitions[None].allocation.set_reserved([6, 6])
cell.partitions[None].allocation.set_max_utilization(1)
cell.schedule()
self.assertIsNotNone(app1.server)
self.assertIsNotNone(app2.server)
self.assertIsNotNone(app3.server)
self.assertIsNone(app4.server)
app4.priority = 5
cell.schedule()
self.assertIsNotNone(app1.server)
self.assertIsNone(app2.server)
self.assertIsNone(app3.server)
self.assertIsNotNone(app4.server)
def test_affinity_limits_bunker(self):
"""Simple placement test with bunker in level"""
cell = scheduler.Cell('top')
bunker1 = scheduler.Bucket('bunker1', traits=0)
bunker2 = scheduler.Bucket('bunker2', traits=0)
b1_left = scheduler.Bucket('b1_left', traits=0)
b1_right = scheduler.Bucket('b1_right', traits=0)
b2 = scheduler.Bucket('b2', traits=0)
srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500)
srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500)
srv_c = scheduler.Server('c', [10, 10], traits=0, valid_until=500)
srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500)
srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500)
cell.add_node(bunker1)
cell.add_node(bunker2)
bunker1.add_node(b1_left)
bunker1.add_node(b1_right)
bunker2.add_node(b2)
b1_left.add_node(srv_a)
b1_left.add_node(srv_b)
b1_right.add_node(srv_c)
b2.add_node(srv_y)
b2.add_node(srv_z)
bunker1.level = 'bunker'
bunker2.level = 'bunker'
b1_left.level = 'rack'
b1_right.level = 'rack'
b2.level = 'rack'
apps = app_list(10, 'app', 50, [1, 1],
affinity_limits={'server': 1, 'bunker': 1})
cell.add_app(cell.partitions[None].allocation, apps[0])
cell.add_app(cell.partitions[None].allocation, apps[1])
cell.add_app(cell.partitions[None].allocation, apps[2])
cell.add_app(cell.partitions[None].allocation, apps[3])
cell.schedule()
self.assertIsNotNone(apps[0].server)
self.assertIsNotNone(apps[1].server)
self.assertIsNone(apps[2].server)
self.assertIsNone(apps[3].server)
apps = app_list(10, 'app', 50, [1, 1],
affinity_limits={'server': 1, 'rack': 1, 'bunker': 2})
for app in apps:
cell.remove_app(app.name)
cell.add_app(cell.partitions[None].allocation, apps[0])
cell.add_app(cell.partitions[None].allocation, apps[1])
cell.add_app(cell.partitions[None].allocation, apps[2])
cell.add_app(cell.partitions[None].allocation, apps[3])
cell.schedule()
self.assertIsNotNone(apps[0].server)
self.assertIsNotNone(apps[1].server)
self.assertIsNotNone(apps[2].server)
self.assertIsNone(apps[3].server)
def test_affinity_limits_levels(self):
"""Simple placement test with 2 layer of bucket"""
# pylint: disable=too-many-statements
cell = scheduler.Cell('top')
group1 = scheduler.Bucket('group1', traits=0)
group2 = scheduler.Bucket('group2', traits=0)
g1_left = scheduler.Bucket('g1_left', traits=0)
g1_right = scheduler.Bucket('g1_right', traits=0)
g2_left = scheduler.Bucket('g2_left', traits=0)
g2_right = scheduler.Bucket('g2_right', traits=0)
srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500)
srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500)
srv_c = scheduler.Server('c', [10, 10], traits=0, valid_until=500)
srv_x = scheduler.Server('x', [10, 10], traits=0, valid_until=500)
srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500)
srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500)
cell.add_node(group1)
cell.add_node(group2)
group1.add_node(g1_left)
group1.add_node(g1_right)
group2.add_node(g2_left)
group2.add_node(g2_right)
g1_left.add_node(srv_a)
g1_left.add_node(srv_b)
g1_right.add_node(srv_c)
g2_left.add_node(srv_x)
g2_right.add_node(srv_y)
g2_right.add_node(srv_z)
g1_left.level = 'rack'
g1_right.level = 'rack'
g2_left.level = 'rack'
g2_right.level = 'rack'
apps = app_list(10, 'app', 50, [1, 1],
affinity_limits={'server': 1})
cell.add_app(cell.partitions[None].allocation, apps[0])
cell.add_app(cell.partitions[None].allocation, apps[1])
cell.add_app(cell.partitions[None].allocation, apps[2])
cell.add_app(cell.partitions[None].allocation, apps[3])
cell.add_app(cell.partitions[None].allocation, apps[4])
cell.add_app(cell.partitions[None].allocation, apps[5])
cell.add_app(cell.partitions[None].allocation, apps[6])
cell.schedule()
self.assertIsNotNone(apps[0].server)
self.assertIsNotNone(apps[1].server)
self.assertIsNotNone(apps[2].server)
self.assertIsNotNone(apps[3].server)
self.assertIsNotNone(apps[4].server)
self.assertIsNotNone(apps[5].server)
self.assertIsNone(apps[6].server)
for app in apps:
cell.remove_app(app.name)
apps = app_list(10, 'app', 50, [1, 1],
affinity_limits={'server': 1, 'rack': 1})
cell.add_app(cell.partitions[None].allocation, apps[0])
cell.add_app(cell.partitions[None].allocation, apps[1])
cell.add_app(cell.partitions[None].allocation, apps[2])
cell.add_app(cell.partitions[None].allocation, apps[3])
cell.add_app(cell.partitions[None].allocation, apps[4])
cell.add_app(cell.partitions[None].allocation, apps[5])
cell.schedule()
self.assertIsNotNone(apps[0].server)
self.assertIsNotNone(apps[1].server)
self.assertIsNotNone(apps[2].server)
self.assertIsNotNone(apps[3].server)
self.assertIsNone(apps[4].server)
self.assertIsNone(apps[5].server)
apps = app_list(10, 'app', 50, [1, 1],
affinity_limits={'server': 1, 'rack': 2, 'cell': 3})
for app in apps:
cell.remove_app(app.name)
cell.add_app(cell.partitions[None].allocation, apps[0])
cell.add_app(cell.partitions[None].allocation, apps[1])
cell.add_app(cell.partitions[None].allocation, apps[2])
cell.add_app(cell.partitions[None].allocation, apps[3])
cell.schedule()
self.assertIsNotNone(apps[0].server)
self.assertIsNotNone(apps[1].server)
self.assertIsNotNone(apps[2].server)
self.assertIsNone(apps[3].server)
def test_affinity_limits(self):
"""Simple placement test."""
cell = scheduler.Cell('top')
left = scheduler.Bucket('left', traits=0)
right = scheduler.Bucket('right', traits=0)
srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500)
srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500)
srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500)
srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500)
cell.add_node(left)
cell.add_node(right)
left.add_node(srv_a)
left.add_node(srv_b)
right.add_node(srv_y)
right.add_node(srv_z)
left.level = 'rack'
right.level = 'rack'
apps = app_list(10, 'app', 50, [1, 1],
affinity_limits={'server': 1})
cell.add_app(cell.partitions[None].allocation, apps[0])
cell.add_app(cell.partitions[None].allocation, apps[1])
cell.add_app(cell.partitions[None].allocation, apps[2])
cell.add_app(cell.partitions[None].allocation, apps[3])
cell.add_app(cell.partitions[None].allocation, apps[4])
cell.schedule()
self.assertIsNotNone(apps[0].server)
self.assertIsNotNone(apps[1].server)
self.assertIsNotNone(apps[2].server)
self.assertIsNotNone(apps[3].server)
self.assertIsNone(apps[4].server)
for app in apps:
cell.remove_app(app.name)
apps = app_list(10, 'app', 50, [1, 1],
affinity_limits={'server': 1, 'rack': 1})
cell.add_app(cell.partitions[None].allocation, apps[0])
cell.add_app(cell.partitions[None].allocation, apps[1])
cell.add_app(cell.partitions[None].allocation, apps[2])
cell.add_app(cell.partitions[None].allocation, apps[3])
cell.schedule()
self.assertIsNotNone(apps[0].server)
self.assertIsNotNone(apps[1].server)
self.assertIsNone(apps[2].server)
self.assertIsNone(apps[3].server)
for app in apps:
cell.remove_app(app.name)
apps = app_list(10, 'app', 50, [1, 1],
affinity_limits={'server': 1, 'rack': 2, 'cell': 3})
cell.add_app(cell.partitions[None].allocation, apps[0])
cell.add_app(cell.partitions[None].allocation, apps[1])
cell.add_app(cell.partitions[None].allocation, apps[2])
cell.add_app(cell.partitions[None].allocation, apps[3])
cell.schedule()
self.assertIsNotNone(apps[0].server)
self.assertIsNotNone(apps[1].server)
self.assertIsNotNone(apps[2].server)
self.assertIsNone(apps[3].server)
@mock.patch('time.time', mock.Mock(return_value=0))
def test_data_retention_levels(self):
"""Tests data retention."""
cell = scheduler.Cell('top')
group1 = scheduler.Bucket('group1', traits=0)
group2 = scheduler.Bucket('group2', traits=0)
g1_left = scheduler.Bucket('g1_left', traits=0)
g1_right = scheduler.Bucket('g1_right', traits=0)
g2 = scheduler.Bucket('g2', traits=0)
srvs = {
'a': scheduler.Server('a', [10, 10], traits=0, valid_until=500),
'b': scheduler.Server('b', [10, 10], traits=0, valid_until=500),
'c': scheduler.Server('c', [10, 10], traits=0, valid_until=500),
'y': scheduler.Server('y', [10, 10], traits=0, valid_until=500),
'z': scheduler.Server('z', [10, 10], traits=0, valid_until=500),
}
cell.add_node(group1)
cell.add_node(group2)
group1.add_node(g1_left)
group1.add_node(g1_right)
group2.add_node(g2)
g1_left.add_node(srvs['a'])
g1_left.add_node(srvs['b'])
g1_right.add_node(srvs['c'])
g2.add_node(srvs['y'])
g2.add_node(srvs['z'])
g1_left.level = 'rack'
g1_right.level = 'rack'
g2.level = 'rack'
time.time.return_value = 100
sticky_apps = app_list(10, 'sticky', 50, [1, 1],
affinity_limits={'server': 1, 'rack': 1},
data_retention_timeout=30)
unsticky_app = scheduler.Application('unsticky', 10, [1., 1.],
'unsticky',
data_retention_timeout=0)
cell.partitions[None].allocation.add(sticky_apps[0])
cell.partitions[None].allocation.add(unsticky_app)
cell.schedule()
# Both apps having different affinity, will be on same node.
first_srv = sticky_apps[0].server
self.assertEqual(sticky_apps[0].server, unsticky_app.server)
# Mark srv_a as down, unsticky app migrates right away,
# sticky stays.
srvs[first_srv].state = scheduler.State.down
cell.schedule()
self.assertEqual(sticky_apps[0].server, first_srv)
self.assertNotEqual(unsticky_app.server, first_srv)
self.assertEqual(cell.next_event_at, 130)
time.time.return_value = 110
cell.schedule()
self.assertEqual(sticky_apps[0].server, first_srv)
self.assertNotEqual(unsticky_app.server, first_srv)
self.assertEqual(cell.next_event_at, 130)
time.time.return_value = 130
cell.schedule()
self.assertNotEqual(sticky_apps[0].server, first_srv)
self.assertNotEqual(unsticky_app.server, first_srv)
self.assertEqual(cell.next_event_at, np.inf)
@mock.patch('time.time', mock.Mock(return_value=0))
def test_data_retention(self):
"""Tests data retention."""
# Disable pylint's too many statements warning.
#
# pylint: disable=R0915
cell = scheduler.Cell('top')
left = scheduler.Bucket('left', traits=0)
right = scheduler.Bucket('right', traits=0)
srvs = {
'a': scheduler.Server('a', [10, 10], traits=0, valid_until=500),
'b': scheduler.Server('b', [10, 10], traits=0, valid_until=500),
'y': scheduler.Server('y', [10, 10], traits=0, valid_until=500),
'z': scheduler.Server('z', [10, 10], traits=0, valid_until=500),
}
cell.add_node(left)
cell.add_node(right)
left.add_node(srvs['a'])
left.add_node(srvs['b'])
right.add_node(srvs['y'])
right.add_node(srvs['z'])
left.level = 'rack'
right.level = 'rack'
time.time.return_value = 100
sticky_apps = app_list(10, 'sticky', 50, [1, 1],
affinity_limits={'server': 1, 'rack': 1},
data_retention_timeout=30)
unsticky_app = scheduler.Application('unsticky', 10, [1., 1.],
'unsticky',
data_retention_timeout=0)
cell.partitions[None].allocation.add(sticky_apps[0])
cell.partitions[None].allocation.add(unsticky_app)
cell.schedule()
# Both apps having different affinity, will be on same node.
first_srv = sticky_apps[0].server
self.assertEqual(sticky_apps[0].server, unsticky_app.server)
# Mark srv_a as down, unsticky app migrates right away,
# sticky stays.
srvs[first_srv].state = scheduler.State.down
cell.schedule()
self.assertEqual(sticky_apps[0].server, first_srv)
self.assertNotEqual(unsticky_app.server, first_srv)
self.assertEqual(cell.next_event_at, 130)
time.time.return_value = 110
cell.schedule()
self.assertEqual(sticky_apps[0].server, first_srv)
self.assertNotEqual(unsticky_app.server, first_srv)
self.assertEqual(cell.next_event_at, 130)
time.time.return_value = 130
cell.schedule()
self.assertNotEqual(sticky_apps[0].server, first_srv)
self.assertNotEqual(unsticky_app.server, first_srv)
self.assertEqual(cell.next_event_at, np.inf)
second_srv = sticky_apps[0].server
# Mark srv_a as up, srv_y as down.
srvs[first_srv].state = scheduler.State.up
srvs[second_srv].state = scheduler.State.down
cell.schedule()
self.assertEqual(sticky_apps[0].server, second_srv)
self.assertNotEqual(unsticky_app.server, second_srv)
self.assertEqual(cell.next_event_at, 160)
# Schedule one more sticky app. As it has rack affinity limit 1, it
# can't to to right (x,y) rack, rather will end up in left (a,b) rack.
#
# Other sticky apps will be pending.
time.time.return_value = 135
cell.partitions[None].allocation.add(sticky_apps[1])
cell.partitions[None].allocation.add(sticky_apps[2])
cell.schedule()
# Original app still on 'y', timeout did not expire
self.assertEqual(sticky_apps[0].server, second_srv)
# next sticky app is on (a,b) rack.
# self.assertIn(sticky_apps[1].server, ['a', 'b'])
# The 3rd sticky app pending, as rack affinity taken by currently
# down node y.
self.assertIsNone(sticky_apps[2].server)
srvs[second_srv].state = scheduler.State.up
cell.schedule()
# Original app still on 'y', timeout did not expire
self.assertEqual(sticky_apps[0].server, second_srv)
# next sticky app is on (a,b) rack.
# self.assertIn(sticky_apps[1].server, ['a', 'b'])
# The 3rd sticky app pending, as rack affinity taken by currently
# app[0] on node y.
self.assertIsNone(sticky_apps[2].server)
def test_serialization(self):
"""Tests cell serialization."""
# Disable pylint's too many statements warning.
#
# pylint: disable=R0915
cell = scheduler.Cell('top')
left = scheduler.Bucket('left', traits=0)
right = scheduler.Bucket('right', traits=0)
srv_a = scheduler.Server('a', [10, 10], traits=0, valid_until=500)
srv_b = scheduler.Server('b', [10, 10], traits=0, valid_until=500)
srv_y = scheduler.Server('y', [10, 10], traits=0, valid_until=500)
srv_z = scheduler.Server('z', [10, 10], traits=0, valid_until=500)
cell.add_node(left)
cell.add_node(right)
left.add_node(srv_a)
left.add_node(srv_b)
right.add_node(srv_y)
right.add_node(srv_z)
left.level = 'rack'
right.level = 'rack'
apps = app_list(10, 'app', 50, [1, 1],
affinity_limits={'server': 1, 'rack': 1})
cell.add_app(cell.partitions[None].allocation, apps[0])
cell.add_app(cell.partitions[None].allocation, apps[1])
cell.add_app(cell.partitions[None].allocation, apps[2])
cell.add_app(cell.partitions[None].allocation, apps[3])
cell.schedule()
# TODO: need to implement serialization.
#
# data = scheduler.dumps(cell)
# cell1 = scheduler.loads(data)
def test_identity(self):
"""Tests scheduling apps with identity."""
cell = scheduler.Cell('top')
for idx in range(0, 10):
server = scheduler.Server(str(idx), [10, 10], traits=0,
valid_until=time.time() + 1000)
cell.add_node(server)
cell.configure_identity_group('ident1', 3)
apps = app_list(10, 'app', 50, [1, 1], identity_group='ident1')
for app in apps:
cell.add_app(cell.partitions[None].allocation, app)
self.assertTrue(apps[0].acquire_identity())
self.assertEqual(set([1, 2]), apps[0].identity_group_ref.available)
self.assertEqual(set([1, 2]), apps[1].identity_group_ref.available)
cell.schedule()
self.assertEqual(apps[0].identity, 0)
self.assertEqual(apps[1].identity, 1)
self.assertEqual(apps[2].identity, 2)
for idx in range(3, 10):
self.assertIsNone(apps[idx].identity, None)
# Removing app will release the identity, and it will be aquired by
# next app in the group.
cell.remove_app('app-2')
cell.schedule()
self.assertEqual(apps[3].identity, 2)
# Increase ideneity group count to 5, expect 5 placed apps.
cell.configure_identity_group('ident1', 5)
cell.schedule()
self.assertEqual(
5,
len([app for app in apps if app.server is not None])
)
cell.configure_identity_group('ident1', 3)
cell.schedule()
self.assertEqual(
3,
len([app for app in apps if app.server is not None])
)
def test_schedule_once(self):
"""Tests schedule once trait on server down."""
cell = scheduler.Cell('top')
for idx in range(0, 10):
server = scheduler.Server(str(idx), [10, 10], traits=0,
valid_until=time.time() + 1000)
cell.add_node(server)
apps = app_list(2, 'app', 50, [6, 6], schedule_once=True)
for app in apps:
cell.add_app(cell.partitions[None].allocation, app)
cell.schedule()
self.assertNotEqual(apps[0].server, apps[1].server)
self.assertFalse(apps[0].evicted)
self.assertFalse(apps[0].evicted)
cell.children_by_name[apps[0].server].state = scheduler.State.down
cell.remove_node_by_name(apps[1].server)
cell.schedule()
self.assertIsNone(apps[0].server)
self.assertTrue(apps[0].evicted)
self.assertIsNone(apps[1].server)
self.assertTrue(apps[1].evicted)
def test_schedule_once_eviction(self):
"""Tests schedule once trait with eviction."""
cell = scheduler.Cell('top')
for idx in range(0, 10):
server = scheduler.Server(str(idx), [10, 10], traits=0,
valid_until=time.time() + 1000)
cell.add_node(server)
# Each server has capacity 10.
#
# Place two apps - capacity 1, capacity 8, they will occupy entire
# server.
#
# Try and place app with demand of 2. First it will try to evict
# small app, but it will not be enough, so it will evict large app.
#
# Check that evicted flag is set only for large app, and small app
# will be restored.
small_apps = app_list(10, 'small', 50, [1, 1], schedule_once=True)
for app in small_apps:
cell.add_app(cell.partitions[None].allocation, app)
large_apps = app_list(10, 'large', 60, [8, 8], schedule_once=True)
for app in large_apps:
cell.add_app(cell.partitions[None].allocation, app)
placement = cell.schedule()
# Check that all apps are placed.
app2server = {app: after for app, _, _, after, _ in placement
if after is not None}
self.assertEqual(len(app2server), 20)
# Add one app, higher priority than rest, will force eviction.
medium_apps = app_list(1, 'medium', 70, [5, 5])
for app in medium_apps:
cell.add_app(cell.partitions[None].allocation, app)
cell.schedule()
self.assertEqual(len([app for app in small_apps if app.evicted]), 0)
self.assertEqual(len([app for app in small_apps if app.server]), 10)
self.assertEqual(len([app for app in large_apps if app.evicted]), 1)
self.assertEqual(len([app for app in large_apps if app.server]), 9)
# Remove app, make sure the evicted app is not placed again.
cell.remove_app(medium_apps[0].name)
cell.schedule()
self.assertEqual(len([app for app in small_apps if app.evicted]), 0)
self.assertEqual(len([app for app in small_apps if app.server]), 10)
self.assertEqual(len([app for app in large_apps if app.evicted]), 1)
self.assertEqual(len([app for app in large_apps if app.server]), 9)
@mock.patch('time.time', mock.Mock(return_value=100))
def test_eviction_server_down(self):
"""Tests app restore."""
cell = scheduler.Cell('top')
large_server = scheduler.Server('large', [10, 10], traits=0,
valid_until=10000)
cell.add_node(large_server)
small_server = scheduler.Server('small', [3, 3], traits=0,
valid_until=10000)
cell.add_node(small_server)
# Create two apps one with retention other without. Set priority
# so that app with retention is on the right of the queue, when
# placement not found for app without retention, it will try to
# evict app with retention.
app_no_retention = scheduler.Application('a1', 100, [4, 4], 'app')
app_with_retention = scheduler.Application('a2', 1, [4, 4], 'app',
data_retention_timeout=3000)
cell.add_app(cell.partitions[None].allocation, app_no_retention)
cell.add_app(cell.partitions[None].allocation, app_with_retention)
cell.schedule()
# At this point, both apps are on large server, as small server does
# not have capacity.
self.assertEqual('large', app_no_retention.server)
self.assertEqual('large', app_with_retention.server)
# Mark large server down. App with retention will remain on the server.
# App without retention should be pending.
large_server.state = scheduler.State.down
cell.schedule()
self.assertEqual(None, app_no_retention.server)
self.assertEqual('large', app_with_retention.server)
@mock.patch('time.time', mock.Mock(return_value=100))
def test_restore(self):
"""Tests app restore."""
cell = scheduler.Cell('top')
large_server = scheduler.Server('large', [10, 10], traits=0,
valid_until=200)
cell.add_node(large_server)
small_server = scheduler.Server('small', [3, 3], traits=0,
valid_until=1000)
cell.add_node(small_server)
apps = app_list(1, 'app', 50, [6, 6], lease=50)
for app in apps:
cell.add_app(cell.partitions[None].allocation, app)
# 100 sec left, app lease is 50, should fit.
time.time.return_value = 100
cell.schedule()
self.assertEqual(apps[0].server, 'large')
time.time.return_value = 190
apps_not_fit = app_list(1, 'app-not-fit', 90, [6, 6], lease=50)
for app in apps_not_fit:
cell.add_app(cell.partitions[None].allocation, app)
cell.schedule()
self.assertIsNone(apps_not_fit[0].server)
self.assertEqual(apps[0].server, 'large')
@mock.patch('time.time', mock.Mock(return_value=10))
def test_renew(self):
"""Tests app restore."""
cell = scheduler.Cell('top')
server_a = scheduler.Server('a', [10, 10], traits=0,
valid_until=1000)
cell.add_node(server_a)
apps = app_list(1, 'app', 50, [6, 6], lease=50)
for app in apps:
cell.add_app(cell.partitions[None].allocation, app)
cell.schedule()
self.assertEqual(apps[0].server, 'a')
self.assertEqual(apps[0].placement_expiry, 60)
time.time.return_value = 100
cell.schedule()
self.assertEqual(apps[0].server, 'a')
self.assertEqual(apps[0].placement_expiry, 60)
time.time.return_value = 200
apps[0].renew = True
cell.schedule()
self.assertEqual(apps[0].server, 'a')
self.assertEqual(apps[0].placement_expiry, 250)
self.assertFalse(apps[0].renew)
# fast forward to 975, close to server 'a' expiration, app will
# migratoe to 'b' on renew.
server_b = scheduler.Server('b', [10, 10], traits=0,
valid_until=2000)
cell.add_node(server_b)
time.time.return_value = 975
apps[0].renew = True
cell.schedule()
self.assertEqual(apps[0].server, 'b')
self.assertEqual(apps[0].placement_expiry, 1025)
self.assertFalse(apps[0].renew)
# fast forward to 1975, when app can't be renewed on server b, but
# there is not alternative placement.
time.time.return_value = 1975
apps[0].renew = True
cell.schedule()
self.assertEqual(apps[0].server, 'b')
# Placement expiry did not change, as placement was not found.
self.assertEqual(apps[0].placement_expiry, 1025)
# Renew flag is not cleared, as new placement was not found.
self.assertTrue(apps[0].renew)
def test_partition_server_down(self):
"""Test placement when server in the partition goes down."""
cell = scheduler.Cell('top')
srv_x1 = scheduler.Server('s_x1', [10, 10], valid_until=500, label='x')
srv_x2 = scheduler.Server('s_x2', [10, 10], valid_until=500, label='x')
srv_y1 = scheduler.Server('s_y1', [10, 10], valid_until=500, label='y')
srv_y2 = scheduler.Server('s_y2', [10, 10], valid_until=500, label='y')
cell.add_node(srv_x1)
cell.add_node(srv_x2)
cell.add_node(srv_y1)
cell.add_node(srv_y2)
app_x1 = scheduler.Application('a_x1', 1, [1, 1], 'app')
app_x2 = scheduler.Application('a_x2', 1, [1, 1], 'app')
app_y1 = scheduler.Application('a_y1', 1, [1, 1], 'app')
app_y2 = scheduler.Application('a_y2', 1, [1, 1], 'app')
cell.partitions['x'].allocation.add(app_x1)
cell.partitions['x'].allocation.add(app_x2)
cell.partitions['y'].allocation.add(app_y1)
cell.partitions['y'].allocation.add(app_y2)
placement = cell.schedule()
self.assertEqual(len(placement), 4)
# Default strategy will distribute two apps on each of the servers
# in the partition.
#
# For future test it is important that each server has an app, so
# we assert on that.
self.assertEqual(len(srv_x1.apps), 1)
self.assertEqual(len(srv_x2.apps), 1)
self.assertEqual(len(srv_y1.apps), 1)
self.assertEqual(len(srv_y2.apps), 1)
# Verify that all apps are placed in the returned placement.
for (_app, before, _exp_before, after, _exp_after) in placement:
self.assertIsNone(before)
self.assertIsNotNone(after)
# Bring server down in each partition.
srv_x1.state = scheduler.State.down
srv_y1.state = scheduler.State.down
placement = cell.schedule()
self.assertEqual(len(placement), 4)
# Check that in the updated placement before and after are not None.
for (_app, before, _exp_before, after, _exp_after) in placement:
self.assertIsNotNone(before)
self.assertIsNotNone(after)
def test_placement_shortcut(self):
"""Test no placement tracker."""
cell = scheduler.Cell('top')
srv_1 = scheduler.Server('s1', [10, 10], valid_until=500, label='x')
srv_2 = scheduler.Server('s2', [10, 10], valid_until=500, label='x')
cell.add_node(srv_1)
cell.add_node(srv_2)
app_large_dim1 = scheduler.Application('large-1', 100, [7, 1], 'app')
app_large_dim2 = scheduler.Application('large-2', 100, [1, 7], 'app')
cell.partitions['x'].allocation.add(app_large_dim1)
cell.partitions['x'].allocation.add(app_large_dim2)
cell.schedule()
self.assertIsNotNone(app_large_dim1.server)
self.assertIsNotNone(app_large_dim2.server)
# Add lower priority apps - can't be scheduled.
#
# As free size of top level node is 9x9, placement attempt will be
# made.
medium_apps = []
for appid in range(1, 10):
app_med = scheduler.Application(
'medium-%s' % appid, 90, [4, 4], 'app')
cell.partitions['x'].allocation.add(app_med)
medium_apps.append(app_med)
cell.schedule()
for app in medium_apps:
self.assertIsNone(app.server)
class IdentityGroupTest(unittest.TestCase):
"""scheduler IdentityGroup test."""
def test_basic(self):
"""Test basic acquire/release ops."""
ident_group = scheduler.IdentityGroup(3)
self.assertEqual(0, ident_group.acquire())
self.assertEqual(1, ident_group.acquire())
self.assertEqual(2, ident_group.acquire())
self.assertEqual(None, ident_group.acquire())
ident_group.release(1)
self.assertEqual(1, ident_group.acquire())
def test_adjust(self):
"""Test identity group count adjustement."""
ident_group = scheduler.IdentityGroup(5)
ident_group.available = set([1, 3])
ident_group.adjust(7)
self.assertEqual(set([1, 3, 5, 6]), ident_group.available)
ident_group.adjust(3)
self.assertEqual(set([1]), ident_group.available)
def test_adjust_relese(self):
"""Test releasing identity when identity exceeds the count."""
ident_group = scheduler.IdentityGroup(1)
self.assertEqual(0, ident_group.acquire())
self.assertEqual(len(ident_group.available), 0)
ident_group.adjust(0)
ident_group.release(0)
self.assertEqual(len(ident_group.available), 0)
def _time(string):
"""Convert a formatted datetime to a timestamp."""
return time.mktime(time.strptime(string, '%Y-%m-%d %H:%M:%S'))
class RebootSchedulerTest(unittest.TestCase):
"""reboot scheduler test."""
def test_bucket(self):
"""Test RebootBucket."""
bucket = scheduler.RebootBucket(_time('2000-01-03 00:00:00'))
# cost of inserting into empty bucket is zero
server1 = scheduler.Server('s1', [10, 10],
up_since=_time('2000-01-01 00:00:00'))
self.assertEqual(0, bucket.cost(server1))
# insert server into a bucket
bucket.add(server1)
self.assertEqual(bucket.servers, set([server1]))
self.assertTrue(server1.valid_until > 0)
# inserting server into a bucket is idempotent
valid_until = server1.valid_until
bucket.add(server1)
self.assertEqual(bucket.servers, set([server1]))
self.assertEqual(server1.valid_until, valid_until)
# cost of inserting into non-empty bucket is size of bucket
server2 = scheduler.Server('s2', [10, 10],
up_since=_time('2000-01-01 00:00:00'))
self.assertEqual(1, bucket.cost(server2))
# when server would be too old, cost is prohibitive
server3 = scheduler.Server('s3', [10, 10],
up_since=_time('1999-01-01 00:00:00'))
self.assertEqual(float('inf'), bucket.cost(server3))
# when server is too close to reboot date, cost is prohibitive
server4 = scheduler.Server('s1', [10, 10],
up_since=_time('2000-01-02 10:00:00'))
self.assertEqual(float('inf'), bucket.cost(server4))
# remove server from a bucket
bucket.remove(server1)
self.assertEqual(bucket.servers, set([]))
# removing server from a bucket is idempotent
bucket.remove(server1)
def test_reboots(self):
"""Test RebootScheduler."""
partition = scheduler.Partition(now=_time('2000-01-01 00:00:00'))
server1 = scheduler.Server('s1', [10, 10],
up_since=_time('2000-01-01 00:00:00'))
server2 = scheduler.Server('s2', [10, 10],
up_since=_time('2000-01-01 00:00:00'))
server3 = scheduler.Server('s3', [10, 10],
up_since=_time('2000-01-01 00:00:00'))
server4 = scheduler.Server('s4', [10, 10],
up_since=_time('1999-12-24 00:00:00'))
# adding to existing bucket
# pylint: disable=W0212
timestamp = partition._reboot_buckets[0].timestamp
partition.add(server1, timestamp)
self.assertEqual(timestamp,
server1.valid_until)
# adding to non-existsing bucket, results in finding a more
# appropriate bucket
partition.add(server2, timestamp + 600)
self.assertNotEqual(timestamp + 600,
server2.valid_until)
# will get into different bucket than server2, so bucket sizes
# stay low
partition.add(server3)
self.assertNotEqual(server2.valid_until,
server3.valid_until)
# server max_lifetime is respected
partition.add(server4)
self.assertTrue(
server4.valid_until <
server4.up_since + scheduler.DEFAULT_SERVER_UPTIME
)
def test_reboot_dates(self):
"""Test reboot dates generator."""
# Note: 2018/01/01 is a Monday
start_date = datetime.date(2018, 1, 1)
schedule = utils.reboot_schedule('sat,sun')
dates_gen = scheduler.reboot_dates(schedule, start_date)
self.assertEqual(
list(itertools.islice(dates_gen, 2)),
[
_time('2018-01-06 23:59:59'),
_time('2018-01-07 23:59:59'),
]
)
schedule = utils.reboot_schedule('sat,sun/10:30:00')
dates_gen = scheduler.reboot_dates(schedule, start_date)
self.assertEqual(
list(itertools.islice(dates_gen, 2)),
[
_time('2018-01-06 23:59:59'),
_time('2018-01-07 10:30:00'),
]
)
class ShapeTest(unittest.TestCase):
"""App shape test cases."""
def test_affinity_constraints(self):
"""Test affinity constraints."""
aff = scheduler.Affinity('foo', {})
self.assertEqual(('foo',), aff.constraints)
aff = scheduler.Affinity('foo', {'server': 1})
self.assertEqual(('foo', 1,), aff.constraints)
def test_app_shape(self):
"""Test application shape."""
app = scheduler.Application('foo', 11, [1, 1, 1], 'bar')
self.assertEqual(('bar', 0,), app.shape()[0])
app.lease = 5
self.assertEqual(('bar', 5,), app.shape()[0])
app = scheduler.Application('foo', 11, [1, 1, 1], 'bar',
affinity_limits={'server': 1, 'rack': 2})
# Values of the dict return ordered by key, (rack, server).
self.assertEqual(('bar', 1, 2, 0,), app.shape()[0])
app.lease = 5
self.assertEqual(('bar', 1, 2, 5,), app.shape()[0])
def test_placement_tracker(self):
"""Tests placement tracker."""
app = scheduler.Application('foo', 11, [2, 2, 2], 'bar')
placement_tracker = scheduler.PlacementFeasibilityTracker()
placement_tracker.adjust(app)
# Same app.
self.assertFalse(placement_tracker.feasible(app))
# Larger app, same shape.
app = scheduler.Application('foo', 11, [3, 3, 3], 'bar')
self.assertFalse(placement_tracker.feasible(app))
# Smaller app, same shape.
app = scheduler.Application('foo', 11, [1, 1, 1], 'bar')
self.assertTrue(placement_tracker.feasible(app))
# Different affinity.
app = scheduler.Application('foo', 11, [5, 5, 5], 'bar1')
self.assertTrue(placement_tracker.feasible(app))
if __name__ == '__main__':
unittest.main()
| [
37811,
26453,
1332,
329,
49246,
13,
1416,
704,
18173,
13,
198,
37811,
198,
198,
2,
31529,
1165,
867,
3951,
287,
8265,
6509,
13,
198,
2,
198,
2,
279,
2645,
600,
25,
15560,
28,
34,
15,
22709,
198,
198,
6738,
11593,
37443,
834,
1330,
... | 2.051698 | 36,191 |
from flask import Flask
app = Flask(__name__)
@app.route("/")
| [
6738,
42903,
1330,
46947,
198,
1324,
796,
46947,
7,
834,
3672,
834,
8,
198,
31,
1324,
13,
38629,
7203,
14,
4943,
198
] | 2.818182 | 22 |
"""
File: runOstranderCustomer.py
Final Project - Main file
Reads the files of a company, which contain its customers and their orders, and prints the
contents in a comprehendible format.
"""
from ostranderCustomer import OstranderCustomer
# customers is {304: ostranderCustomer.OstranderCustomer object at 0x00...}
if __name__ == "__main__":
main()
| [
37811,
198,
8979,
25,
1057,
46,
2536,
4066,
44939,
13,
9078,
198,
19006,
4935,
532,
8774,
2393,
198,
198,
5569,
82,
262,
3696,
286,
257,
1664,
11,
543,
3994,
663,
4297,
290,
511,
6266,
11,
290,
20842,
262,
198,
3642,
658,
287,
257,
... | 3.490385 | 104 |
import os
import sys
from unittest import mock
import pytest
sys.path.append(
os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir)
)
from fixtures import (
fixture_registry_url,
fixture_repository,
fixture_repositories,
fixture_tags,
fixture_digest,
fixture_tags_url,
fixture_tags_json,
fixture_image_url,
fixture_image_json,
)
from dregcli.dregcli import DRegCliException, Client, Repository, Image
| [
11748,
28686,
198,
11748,
25064,
198,
6738,
555,
715,
395,
1330,
15290,
198,
11748,
12972,
9288,
198,
198,
17597,
13,
6978,
13,
33295,
7,
198,
220,
220,
220,
28686,
13,
6978,
13,
22179,
7,
418,
13,
6978,
13,
15908,
3672,
7,
418,
13,... | 2.573034 | 178 |
from flask import flash, redirect, url_for, abort
from flask_login import current_user
from srcode.models import Permission, User
from functools import wraps
def check_confirmed(func):
'''Checks whether a certain user is confirmed'''
@wraps(func)
return decorated_function | [
6738,
42903,
1330,
7644,
11,
18941,
11,
19016,
62,
1640,
11,
15614,
198,
6738,
42903,
62,
38235,
1330,
1459,
62,
7220,
198,
6738,
12351,
1098,
13,
27530,
1330,
2448,
3411,
11,
11787,
198,
6738,
1257,
310,
10141,
1330,
27521,
628,
198,
... | 3.411765 | 85 |
import TestData
from kol.Session import Session
import unittest
| [
11748,
6208,
6601,
198,
6738,
479,
349,
13,
36044,
1330,
23575,
198,
198,
11748,
555,
715,
395,
198
] | 3.611111 | 18 |
'''
Created on March 21, 2018
@author: Alejandro Molina
'''
from collections import OrderedDict
from enum import Enum
from spn.algorithms.Validity import is_valid
from spn.structure.Base import Product, Sum, rebuild_scopes_bottom_up, assign_ids, Leaf
import numpy as np
_node_to_str = {}
_str_to_spn = OrderedDict()
| [
7061,
6,
198,
41972,
319,
2805,
2310,
11,
2864,
198,
198,
31,
9800,
25,
9300,
47983,
17958,
1437,
198,
7061,
6,
198,
6738,
17268,
1330,
14230,
1068,
35,
713,
198,
6738,
33829,
1330,
2039,
388,
198,
198,
6738,
599,
77,
13,
282,
7727,... | 2.877193 | 114 |